1 //******************************************************************
3 // Copyright 2015 Samsung Electronics 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 "RCSResourceObject.h"
27 #include "RequestHandler.h"
28 #include "AssertUtils.h"
29 #include "AtomicHelper.h"
30 #include "ResourceAttributesConverter.h"
31 #include "ResourceAttributesUtils.h"
32 #include "RCSRequest.h"
35 #include "OCPlatform.h"
37 #define LOG_TAG "RCSResourceObject"
41 using namespace OIC::Service;
43 inline bool hasProperty(uint8_t base, uint8_t target)
45 return (base & target) == target;
48 inline uint8_t makePropertyFlags(uint8_t base, uint8_t target, bool add)
55 return base & ~target;
58 template <typename RESPONSE>
59 OCEntityHandlerResult sendResponse(RCSResourceObject& resource,
60 const std::shared_ptr< OC::OCResourceRequest >& ocRequest, RESPONSE&& response)
62 auto ocResponse = response.getHandler()->buildResponse(resource);
63 ocResponse->setRequestHandle(ocRequest->getRequestHandle());
64 ocResponse->setResourceHandle(ocRequest->getResourceHandle());
68 if (OC::OCPlatform::sendResponse(ocResponse) == OC_STACK_OK)
73 catch (const OC::OCException& e)
75 OC_LOG_V(WARNING, LOG_TAG, "Error (%s)", e.what());
81 RCSResourceAttributes getAttributesFromOCRequest(
82 const std::shared_ptr< OC::OCResourceRequest >& request)
84 return ResourceAttributesConverter::fromOCRepresentation(
85 request->getResourceRepresentation());
88 template< typename HANDLER, typename RESPONSE =
89 typename std::decay<HANDLER>::type::result_type >
90 RESPONSE invokeHandler(RCSResourceAttributes& attrs,
91 const std::shared_ptr< OC::OCResourceRequest >& ocRequest,
92 std::shared_ptr< HANDLER > handler)
96 return (*handler)(RCSRequest{ ocRequest->getResourceUri() }, attrs);
99 return RESPONSE::defaultAction();
102 typedef void (RCSResourceObject::* AutoNotifyFunc)
103 (bool, RCSResourceObject::AutoNotifyPolicy) const;
105 std::function<void()> createAutoNotifyInvoker(AutoNotifyFunc autoNotifyFunc,
106 const RCSResourceObject& resourceObject, const RCSResourceAttributes& resourceAttributes,
107 RCSResourceObject::AutoNotifyPolicy autoNotifyPolicy)
109 if(autoNotifyPolicy == RCSResourceObject::AutoNotifyPolicy::UPDATED)
111 auto&& compareAttributesFunc =
112 std::bind(std::not_equal_to<RCSResourceAttributes>(),
114 std::cref(resourceAttributes));
115 return std::bind(autoNotifyFunc,
116 &resourceObject, std::move(compareAttributesFunc), autoNotifyPolicy);
118 else if(autoNotifyPolicy == RCSResourceObject::AutoNotifyPolicy::ALWAYS)
120 return std::bind(autoNotifyFunc,
121 &resourceObject, true, autoNotifyPolicy);
125 } // unnamed namespace
133 RCSResourceObject::Builder::Builder(const std::string& uri, const std::string& type,
134 const std::string& interface) :
137 m_interface{ interface },
138 m_properties{ OC_DISCOVERABLE | OC_OBSERVABLE },
139 m_resourceAttributes{ }
143 RCSResourceObject::Builder& RCSResourceObject::Builder::setDiscoverable(
146 m_properties = ::makePropertyFlags(m_properties, OC_DISCOVERABLE, discoverable);
150 RCSResourceObject::Builder& RCSResourceObject::Builder::setObservable(
153 m_properties = ::makePropertyFlags(m_properties, OC_OBSERVABLE, observable);
157 RCSResourceObject::Builder& RCSResourceObject::Builder::setAttributes(
158 const RCSResourceAttributes& attrs)
160 m_resourceAttributes = attrs;
164 RCSResourceObject::Builder& RCSResourceObject::Builder::setAttributes(
165 RCSResourceAttributes&& attrs)
167 m_resourceAttributes = std::move(attrs);
171 RCSResourceObject::Ptr RCSResourceObject::Builder::build()
173 OCResourceHandle handle{ nullptr };
175 RCSResourceObject::Ptr server {
176 new RCSResourceObject{ m_properties, std::move(m_resourceAttributes) } };
178 OC::EntityHandler entityHandler{ std::bind(&RCSResourceObject::entityHandler,
179 server.get(), std::placeholders::_1) };
181 typedef OCStackResult (*RegisterResource)(OCResourceHandle&, std::string&,
182 const std::string&, const std::string&, OC::EntityHandler, uint8_t);
184 invokeOCFunc(static_cast<RegisterResource>(OC::OCPlatform::registerResource),
185 handle, m_uri, m_type, m_interface, entityHandler, m_properties);
187 server->m_resourceHandle = handle;
193 RCSResourceObject::RCSResourceObject(uint8_t properties, RCSResourceAttributes&& attrs) :
194 m_properties { properties },
196 m_resourceAttributes{ std::move(attrs) },
197 m_getRequestHandler{ },
198 m_setRequestHandler{ },
199 m_autoNotifyPolicy { AutoNotifyPolicy::UPDATED },
200 m_setRequestHandlerPolicy { SetRequestHandlerPolicy::NEVER },
201 m_attributeUpdatedListeners{ },
204 m_mutexAttributeUpdatedListeners{ }
206 m_lockOwner.reset(new AtomicThreadId);
209 RCSResourceObject::~RCSResourceObject()
211 if (m_resourceHandle)
215 OC::OCPlatform::unregisterResource(m_resourceHandle);
219 OC_LOG(WARNING, LOG_TAG, "Failed to unregister resource.");
224 template< typename K, typename V >
225 void RCSResourceObject::setAttributeInternal(K&& key, V&& value)
227 bool needToNotify = false;
228 bool valueUpdated = false;
231 WeakGuard lock(*this);
233 if (lock.hasLocked())
236 valueUpdated = testValueUpdated(key, value);
239 m_resourceAttributes[std::forward< K >(key)] = std::forward< V >(value);
242 if (needToNotify) autoNotify(valueUpdated);
244 void RCSResourceObject::setAttribute(const std::string& key,
245 const RCSResourceAttributes::Value& value)
247 setAttributeInternal(key, value);
250 void RCSResourceObject::setAttribute(const std::string& key,
251 RCSResourceAttributes::Value&& value)
253 setAttributeInternal(key, std::move(value));
256 void RCSResourceObject::setAttribute(std::string&& key,
257 const RCSResourceAttributes::Value& value)
259 setAttributeInternal(std::move(key), value);
262 void RCSResourceObject::setAttribute(std::string&& key,
263 RCSResourceAttributes::Value&& value)
265 setAttributeInternal(std::move(key), std::move(value));
268 RCSResourceAttributes::Value RCSResourceObject::getAttributeValue(
269 const std::string& key) const
271 WeakGuard lock(*this);
272 return m_resourceAttributes.at(key);
275 bool RCSResourceObject::removeAttribute(const std::string& key)
277 bool needToNotify = false;
280 WeakGuard lock(*this);
282 if (m_resourceAttributes.erase(key))
285 needToNotify = lock.hasLocked();
289 if (needToNotify) autoNotify(true);
294 bool RCSResourceObject::containsAttribute(const std::string& key) const
296 WeakGuard lock(*this);
297 return m_resourceAttributes.contains(key);
300 RCSResourceAttributes& RCSResourceObject::getAttributes()
303 return m_resourceAttributes;
306 const RCSResourceAttributes& RCSResourceObject::getAttributes() const
309 return m_resourceAttributes;
312 void RCSResourceObject::expectOwnLock() const
314 if (getLockOwner() != std::this_thread::get_id())
316 throw NoLockException{ "Must acquire the lock first using LockGuard." };
320 std::thread::id RCSResourceObject::getLockOwner() const noexcept
325 void RCSResourceObject::setLockOwner(std::thread::id&& id) const noexcept
327 m_lockOwner->store(std::move(id));
330 bool RCSResourceObject::isObservable() const
332 return ::hasProperty(m_properties, OC_OBSERVABLE);
335 bool RCSResourceObject::isDiscoverable() const
337 return ::hasProperty(m_properties, OC_DISCOVERABLE);
340 void RCSResourceObject::setGetRequestHandler(GetRequestHandler h)
342 m_getRequestHandler = std::make_shared< GetRequestHandler >(std::move(h));
345 void RCSResourceObject::setSetRequestHandler(SetRequestHandler h)
347 m_setRequestHandler = std::make_shared< SetRequestHandler >(std::move(h));
350 void RCSResourceObject::notify() const
352 typedef OCStackResult (*NotifyAllObservers)(OCResourceHandle);
354 invokeOCFuncWithResultExpect({ OC_STACK_OK, OC_STACK_NO_OBSERVERS },
355 static_cast< NotifyAllObservers >(OC::OCPlatform::notifyAllObservers),
359 void RCSResourceObject::addAttributeUpdatedListener(const std::string& key,
360 AttributeUpdatedListener h)
362 std::lock_guard< std::mutex > lock(m_mutexAttributeUpdatedListeners);
364 m_attributeUpdatedListeners[key] =
365 std::make_shared< AttributeUpdatedListener >(std::move(h));
368 void RCSResourceObject::addAttributeUpdatedListener(std::string&& key,
369 AttributeUpdatedListener h)
371 std::lock_guard< std::mutex > lock(m_mutexAttributeUpdatedListeners);
373 m_attributeUpdatedListeners[std::move(key)] =
374 std::make_shared< AttributeUpdatedListener >(std::move(h));
377 bool RCSResourceObject::removeAttributeUpdatedListener(const std::string& key)
379 std::lock_guard< std::mutex > lock(m_mutexAttributeUpdatedListeners);
381 return m_attributeUpdatedListeners.erase(key) != 0;
384 bool RCSResourceObject::testValueUpdated(const std::string& key,
385 const RCSResourceAttributes::Value& value) const
387 return m_resourceAttributes.contains(key) == false
388 || m_resourceAttributes.at(key) != value;
391 void RCSResourceObject::setAutoNotifyPolicy(AutoNotifyPolicy policy)
393 m_autoNotifyPolicy = policy;
396 RCSResourceObject::AutoNotifyPolicy RCSResourceObject::getAutoNotifyPolicy() const
398 return m_autoNotifyPolicy;
401 void RCSResourceObject::setSetRequestHandlerPolicy(SetRequestHandlerPolicy policy)
403 m_setRequestHandlerPolicy = policy;
406 auto RCSResourceObject::getSetRequestHandlerPolicy() const -> SetRequestHandlerPolicy
408 return m_setRequestHandlerPolicy;
411 void RCSResourceObject::autoNotify(bool isAttributesChanged) const
413 autoNotify(isAttributesChanged, m_autoNotifyPolicy);
416 void RCSResourceObject::autoNotify(
417 bool isAttributesChanged, AutoNotifyPolicy autoNotifyPolicy) const
419 if(autoNotifyPolicy == AutoNotifyPolicy::NEVER) return;
420 if(autoNotifyPolicy == AutoNotifyPolicy::UPDATED &&
421 isAttributesChanged == false) return;
426 OCEntityHandlerResult RCSResourceObject::entityHandler(
427 const std::shared_ptr< OC::OCResourceRequest >& request)
429 OC_LOG(WARNING, LOG_TAG, "entityHandler");
437 if (request->getRequestHandlerFlag() & OC::RequestHandlerFlag::RequestFlag)
439 return handleRequest(request);
442 if (request->getRequestHandlerFlag() & OC::RequestHandlerFlag::ObserverFlag)
444 return handleObserve(request);
447 catch (const std::exception& e)
449 OC_LOG_V(WARNING, LOG_TAG, "Failed to handle request : %s", e.what());
454 OC_LOG(WARNING, LOG_TAG, "Failed to handle request.");
461 OCEntityHandlerResult RCSResourceObject::handleRequest(
462 const std::shared_ptr< OC::OCResourceRequest >& request)
464 assert(request != nullptr);
466 if (request->getRequestType() == "GET")
468 return handleRequestGet(request);
471 if (request->getRequestType() == "PUT")
473 return handleRequestSet(request);
479 OCEntityHandlerResult RCSResourceObject::handleRequestGet(
480 const std::shared_ptr< OC::OCResourceRequest >& request)
482 assert(request != nullptr);
484 auto attrs = getAttributesFromOCRequest(request);
486 return sendResponse(*this, request, invokeHandler(attrs, request, m_getRequestHandler));
489 bool RCSResourceObject::applyAcceptanceMethod(const RCSSetResponse& response,
490 const RCSResourceAttributes& requstAttrs)
492 auto requestHandler = response.getHandler();
494 assert(requestHandler != nullptr);
496 auto replaced = requestHandler->applyAcceptanceMethod(response.getAcceptanceMethod(),
499 OC_LOG_V(WARNING, LOG_TAG, "replaced num %zu", replaced.size());
500 for (const auto& attrKeyValPair : replaced)
502 std::shared_ptr< AttributeUpdatedListener > foundListener;
504 std::lock_guard< std::mutex > lock(m_mutexAttributeUpdatedListeners);
506 auto it = m_attributeUpdatedListeners.find(attrKeyValPair.first);
507 if (it != m_attributeUpdatedListeners.end())
509 foundListener = it->second;
515 (*foundListener)(attrKeyValPair.second, requstAttrs.at(attrKeyValPair.first));
519 return !replaced.empty();
522 OCEntityHandlerResult RCSResourceObject::handleRequestSet(
523 const std::shared_ptr< OC::OCResourceRequest >& request)
525 assert(request != nullptr);
527 auto attrs = getAttributesFromOCRequest(request);
528 auto response = invokeHandler(attrs, request, m_setRequestHandler);
530 auto attrsChanged = applyAcceptanceMethod(response, attrs);
534 autoNotify(attrsChanged, m_autoNotifyPolicy);
535 return sendResponse(*this, request, response);
536 } catch (const RCSPlatformException& e) {
537 OC_LOG_V(ERROR, LOG_TAG, "Error : %s ", e.what());
542 OCEntityHandlerResult RCSResourceObject::handleObserve(
543 const std::shared_ptr< OC::OCResourceRequest >&)
553 RCSResourceObject::LockGuard::LockGuard(const RCSResourceObject::Ptr ptr) :
554 m_resourceObject(*ptr),
555 m_autoNotifyPolicy{ ptr->getAutoNotifyPolicy() },
556 m_isOwningLock{ false }
561 RCSResourceObject::LockGuard::LockGuard(
562 const RCSResourceObject& serverResource) :
563 m_resourceObject(serverResource),
564 m_autoNotifyPolicy{ serverResource.getAutoNotifyPolicy() },
565 m_isOwningLock{ false }
570 RCSResourceObject::LockGuard::LockGuard(
571 const RCSResourceObject::Ptr ptr, AutoNotifyPolicy autoNotifyPolicy) :
572 m_resourceObject(*ptr),
573 m_autoNotifyPolicy { autoNotifyPolicy },
574 m_isOwningLock{ false }
579 RCSResourceObject::LockGuard::LockGuard(
580 const RCSResourceObject& resourceObject, AutoNotifyPolicy autoNotifyPolicy) :
581 m_resourceObject(resourceObject),
582 m_autoNotifyPolicy { autoNotifyPolicy },
583 m_isOwningLock{ false }
588 RCSResourceObject::LockGuard::~LockGuard() noexcept(false)
590 if (!std::uncaught_exception() && m_autoNotifyFunc) m_autoNotifyFunc();
594 m_resourceObject.setLockOwner(std::thread::id{ });
595 m_resourceObject.m_mutex.unlock();
599 void RCSResourceObject::LockGuard::init()
601 if (m_resourceObject.getLockOwner() != std::this_thread::get_id())
603 m_resourceObject.m_mutex.lock();
604 m_resourceObject.setLockOwner(std::this_thread::get_id());
605 m_isOwningLock = true;
607 m_autoNotifyFunc = ::createAutoNotifyInvoker(&RCSResourceObject::autoNotify,
608 m_resourceObject, m_resourceObject.m_resourceAttributes, m_autoNotifyPolicy);
611 RCSResourceObject::WeakGuard::WeakGuard(
612 const RCSResourceObject& resourceObject) :
613 m_isOwningLock{ false },
614 m_resourceObject(resourceObject)
616 if (m_resourceObject.getLockOwner() != std::this_thread::get_id())
618 m_resourceObject.m_mutex.lock();
619 m_resourceObject.setLockOwner(std::this_thread::get_id());
620 m_isOwningLock = true;
624 RCSResourceObject::WeakGuard::~WeakGuard()
628 m_resourceObject.setLockOwner(std::thread::id{ });
629 m_resourceObject.m_mutex.unlock();
633 bool RCSResourceObject::WeakGuard::hasLocked() const
635 return m_isOwningLock;