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 <ResourceAttributesConverter.h>
32 #include <OCPlatform.h>
36 using namespace OIC::Service;
38 constexpr char LOG_TAG[]{ "RCSResourceObject" };
40 inline bool hasProperty(uint8_t base, uint8_t target)
42 return (base & target) == target;
45 inline uint8_t makePropertyFlags(uint8_t base, uint8_t target, bool add)
52 return base & ~target;
55 template <typename RESPONSE>
56 OCEntityHandlerResult sendResponse(RCSResourceObject& resource,
57 std::shared_ptr< OC::OCResourceRequest > ocRequest, RESPONSE&& response)
59 auto ocResponse = response.getHandler()->buildResponse(resource);
60 ocResponse->setRequestHandle(ocRequest->getRequestHandle());
61 ocResponse->setResourceHandle(ocRequest->getResourceHandle());
65 if (OC::OCPlatform::sendResponse(ocResponse) == OC_STACK_OK)
70 catch (const OC::OCException& e)
72 OC_LOG(WARNING, LOG_TAG, e.what());
78 RCSResourceAttributes getAttributesFromOCRequest(
79 std::shared_ptr< OC::OCResourceRequest > request)
81 return ResourceAttributesConverter::fromOCRepresentation(
82 request->getResourceRepresentation());
85 template< typename HANDLER, typename RESPONSE =
86 typename std::decay<HANDLER>::type::result_type >
87 RESPONSE invokeHandler(RCSResourceAttributes& attrs,
88 std::shared_ptr< OC::OCResourceRequest > ocRequest, HANDLER&& handler)
92 return handler(RCSRequest{ ocRequest->getResourceUri() }, attrs);
95 return RESPONSE::defaultAction();
98 typedef void (RCSResourceObject::* AutoNotifyFunc)
99 (bool, RCSResourceObject::AutoNotifyPolicy) const;
101 std::function <void ()> createAutoNotifyInvoker(AutoNotifyFunc autoNotifyFunc,
102 const RCSResourceObject& resourceObject, const RCSResourceAttributes& resourceAttributes,
103 RCSResourceObject::AutoNotifyPolicy autoNotifyPolicy)
105 if(autoNotifyPolicy == RCSResourceObject::AutoNotifyPolicy::UPDATED)
107 auto&& compareAttributesFunc =
108 std::bind(std::not_equal_to<RCSResourceAttributes>(),
110 std::cref(resourceAttributes));
111 return std::bind(autoNotifyFunc,
112 &resourceObject, std::move(compareAttributesFunc), autoNotifyPolicy);
114 else if(autoNotifyPolicy == RCSResourceObject::AutoNotifyPolicy::ALWAYS)
116 return std::bind(autoNotifyFunc,
117 &resourceObject, true, autoNotifyPolicy);
121 } // unnamed namespace
129 RCSResourceObject::Builder::Builder(const std::string& uri, const std::string& type,
130 const std::string& interface) :
133 m_interface{ interface },
134 m_properties{ OC_DISCOVERABLE | OC_OBSERVABLE },
135 m_resourceAttributes{ }
139 RCSResourceObject::Builder& RCSResourceObject::Builder::setDiscoverable(
142 m_properties = ::makePropertyFlags(m_properties, OC_DISCOVERABLE, discoverable);
146 RCSResourceObject::Builder& RCSResourceObject::Builder::setObservable(
149 m_properties = ::makePropertyFlags(m_properties, OC_OBSERVABLE, observable);
153 RCSResourceObject::Builder& RCSResourceObject::Builder::setAttributes(
154 const RCSResourceAttributes& attrs)
156 m_resourceAttributes = attrs;
160 RCSResourceObject::Builder& RCSResourceObject::Builder::setAttributes(
161 RCSResourceAttributes&& attrs)
163 m_resourceAttributes = std::move(attrs);
167 RCSResourceObject::Ptr RCSResourceObject::Builder::build()
169 OCResourceHandle handle{ nullptr };
171 RCSResourceObject::Ptr server {
172 new RCSResourceObject{ m_properties, std::move(m_resourceAttributes) } };
174 OC::EntityHandler entityHandler{ std::bind(&RCSResourceObject::entityHandler,
175 server.get(), std::placeholders::_1) };
177 typedef OCStackResult (*RegisterResource)(OCResourceHandle&, std::string&,
178 const std::string&, const std::string&, OC::EntityHandler, uint8_t);
180 invokeOCFunc(static_cast<RegisterResource>(OC::OCPlatform::registerResource),
181 handle, m_uri, m_type, m_interface, entityHandler, m_properties);
183 server->m_resourceHandle = handle;
189 RCSResourceObject::RCSResourceObject(uint8_t properties, RCSResourceAttributes&& attrs) :
190 m_properties { properties },
192 m_resourceAttributes{ std::move(attrs) },
193 m_getRequestHandler{ },
194 m_setRequestHandler{ },
195 m_autoNotifyPolicy { AutoNotifyPolicy::UPDATED },
196 m_setRequestHandlerPolicy { SetRequestHandlerPolicy::NEVER },
197 m_keyAttributesUpdatedListeners{ },
200 m_mutexKeyAttributeUpdate{ }
204 RCSResourceObject::~RCSResourceObject()
206 if (m_resourceHandle)
210 OC::OCPlatform::unregisterResource(m_resourceHandle);
214 OC_LOG(WARNING, LOG_TAG, "Failed to unregister resource.");
219 template< typename K, typename V >
220 void RCSResourceObject::setAttributeInternal(K&& key, V&& value)
222 bool needToNotify = false;
223 bool valueUpdated = false;
226 WeakGuard lock(*this);
228 if (lock.hasLocked())
231 valueUpdated = testValueUpdated(key, value);
234 m_resourceAttributes[std::forward< K >(key)] = std::forward< V >(value);
237 if (needToNotify) autoNotify(valueUpdated);
239 void RCSResourceObject::setAttribute(const std::string& key,
240 const RCSResourceAttributes::Value& value)
242 setAttributeInternal(key, value);
245 void RCSResourceObject::setAttribute(const std::string& key,
246 RCSResourceAttributes::Value&& value)
248 setAttributeInternal(key, std::move(value));
251 void RCSResourceObject::setAttribute(std::string&& key,
252 const RCSResourceAttributes::Value& value)
254 setAttributeInternal(std::move(key), value);
257 void RCSResourceObject::setAttribute(std::string&& key,
258 RCSResourceAttributes::Value&& value)
260 setAttributeInternal(std::move(key), std::move(value));
263 RCSResourceAttributes::Value RCSResourceObject::getAttributeValue(
264 const std::string& key) const
266 WeakGuard lock(*this);
267 return m_resourceAttributes.at(key);
270 bool RCSResourceObject::removeAttribute(const std::string& key)
272 bool needToNotify = false;
275 WeakGuard lock(*this);
277 if (m_resourceAttributes.erase(key))
280 needToNotify = lock.hasLocked();
284 if (needToNotify) autoNotify(true);
289 bool RCSResourceObject::containsAttribute(const std::string& key) const
291 WeakGuard lock(*this);
292 return m_resourceAttributes.contains(key);
295 RCSResourceAttributes& RCSResourceObject::getAttributes()
298 return m_resourceAttributes;
301 const RCSResourceAttributes& RCSResourceObject::getAttributes() const
304 return m_resourceAttributes;
307 void RCSResourceObject::expectOwnLock() const
309 if (m_lockOwner != std::this_thread::get_id())
311 throw NoLockException{ "Must acquire the lock first using LockGuard." };
315 bool RCSResourceObject::isObservable() const
317 return ::hasProperty(m_properties, OC_OBSERVABLE);
320 bool RCSResourceObject::isDiscoverable() const
322 return ::hasProperty(m_properties, OC_DISCOVERABLE);
325 void RCSResourceObject::setGetRequestHandler(GetRequestHandler h)
327 m_getRequestHandler = std::move(h);
330 void RCSResourceObject::setSetRequestHandler(SetRequestHandler h)
332 m_setRequestHandler = std::move(h);
335 void RCSResourceObject::notify() const
337 typedef OCStackResult (*NotifyAllObservers)(OCResourceHandle);
339 invokeOCFuncWithResultExpect({ OC_STACK_OK, OC_STACK_NO_OBSERVERS },
340 static_cast< NotifyAllObservers >(OC::OCPlatform::notifyAllObservers),
344 void RCSResourceObject::addAttributeUpdatedListener(const std::string& key,
345 AttributeUpdatedListener h)
347 std::lock_guard<std::mutex> lock(m_mutexKeyAttributeUpdate);
348 m_keyAttributesUpdatedListeners[key] = std::move(h);
351 void RCSResourceObject::addAttributeUpdatedListener(std::string&& key,
352 AttributeUpdatedListener h)
354 std::lock_guard<std::mutex> lock(m_mutexKeyAttributeUpdate);
355 m_keyAttributesUpdatedListeners[std::move(key)] = std::move(h);
358 bool RCSResourceObject::removeAttributeUpdatedListener(const std::string& key)
360 std::lock_guard<std::mutex> lock(m_mutexKeyAttributeUpdate);
362 return m_keyAttributesUpdatedListeners.erase(key) != 0;
365 bool RCSResourceObject::testValueUpdated(const std::string& key,
366 const RCSResourceAttributes::Value& value) const
368 return m_resourceAttributes.contains(key) == false
369 || m_resourceAttributes.at(key) != value;
372 void RCSResourceObject::setAutoNotifyPolicy(AutoNotifyPolicy policy)
374 m_autoNotifyPolicy = policy;
377 RCSResourceObject::AutoNotifyPolicy RCSResourceObject::getAutoNotifyPolicy() const
379 return m_autoNotifyPolicy;
382 void RCSResourceObject::setSetRequestHandlerPolicy(SetRequestHandlerPolicy policy)
384 m_setRequestHandlerPolicy = policy;
387 auto RCSResourceObject::getSetRequestHandlerPolicy() const -> SetRequestHandlerPolicy
389 return m_setRequestHandlerPolicy;
392 void RCSResourceObject::autoNotify(bool isAttributesChanged) const
394 autoNotify(isAttributesChanged, m_autoNotifyPolicy);
397 void RCSResourceObject::autoNotify(
398 bool isAttributesChanged, AutoNotifyPolicy autoNotifyPolicy) const
400 if(autoNotifyPolicy == AutoNotifyPolicy::NEVER) return;
401 if(autoNotifyPolicy == AutoNotifyPolicy::UPDATED &&
402 isAttributesChanged == false) return;
407 OCEntityHandlerResult RCSResourceObject::entityHandler(
408 std::shared_ptr< OC::OCResourceRequest > request)
417 if (request->getRequestHandlerFlag() & OC::RequestHandlerFlag::RequestFlag)
419 return handleRequest(request);
422 if (request->getRequestHandlerFlag() & OC::RequestHandlerFlag::ObserverFlag)
424 return handleObserve(request);
427 catch (const std::exception& e)
429 OC_LOG_V(WARNING, LOG_TAG, "Failed to handle request : %s", e.what());
434 OC_LOG(WARNING, LOG_TAG, "Failed to handle request.");
441 OCEntityHandlerResult RCSResourceObject::handleRequest(
442 std::shared_ptr< OC::OCResourceRequest > request)
444 assert(request != nullptr);
446 if (request->getRequestType() == "GET")
448 return handleRequestGet(request);
451 if (request->getRequestType() == "PUT")
453 return handleRequestSet(request);
459 OCEntityHandlerResult RCSResourceObject::handleRequestGet(
460 std::shared_ptr< OC::OCResourceRequest > request)
462 assert(request != nullptr);
464 auto attrs = getAttributesFromOCRequest(request);
466 return sendResponse(*this, request, invokeHandler(attrs, request, m_getRequestHandler));
469 OCEntityHandlerResult RCSResourceObject::handleRequestSet(
470 std::shared_ptr< OC::OCResourceRequest > request)
472 assert(request != nullptr);
474 auto attrs = getAttributesFromOCRequest(request);
475 auto response = invokeHandler(attrs, request, m_setRequestHandler);
476 auto requestHandler = response.getHandler();
478 assert(requestHandler != nullptr);
480 AttrKeyValuePairs replaced = requestHandler->applyAcceptanceMethod(
481 response.getAcceptanceMethod(), *this, attrs);
483 for (const auto& it : replaced)
485 std::lock_guard<std::mutex> lock(m_mutexKeyAttributeUpdate);
487 auto keyAttribute = m_keyAttributesUpdatedListeners.find(it.first);
488 if(keyAttribute != m_keyAttributesUpdatedListeners.end())
490 keyAttribute-> second(it.second, attrs[it.first]);
494 autoNotify(!replaced.empty(), m_autoNotifyPolicy);
495 return sendResponse(*this, request, response);
498 OCEntityHandlerResult RCSResourceObject::handleObserve(
499 std::shared_ptr< OC::OCResourceRequest > request)
501 assert(request != nullptr);
511 RCSResourceObject::LockGuard::LockGuard(const RCSResourceObject::Ptr ptr) :
512 m_resourceObject(*ptr),
513 m_autoNotifyPolicy{ ptr->getAutoNotifyPolicy() },
514 m_isOwningLock{ false }
519 RCSResourceObject::LockGuard::LockGuard(
520 const RCSResourceObject& serverResource) :
521 m_resourceObject(serverResource),
522 m_autoNotifyPolicy{ serverResource.getAutoNotifyPolicy() },
523 m_isOwningLock{ false }
528 RCSResourceObject::LockGuard::LockGuard(
529 const RCSResourceObject::Ptr ptr, AutoNotifyPolicy autoNotifyPolicy) :
530 m_resourceObject(*ptr),
531 m_autoNotifyPolicy { autoNotifyPolicy },
532 m_isOwningLock{ false }
537 RCSResourceObject::LockGuard::LockGuard(
538 const RCSResourceObject& resourceObject, AutoNotifyPolicy autoNotifyPolicy) :
539 m_resourceObject(resourceObject),
540 m_autoNotifyPolicy { autoNotifyPolicy },
541 m_isOwningLock{ false }
546 RCSResourceObject::LockGuard::~LockGuard()
548 if (m_autoNotifyFunc) m_autoNotifyFunc();
552 m_resourceObject.m_lockOwner = std::thread::id{ };
553 m_resourceObject.m_mutex.unlock();
557 void RCSResourceObject::LockGuard::init()
559 if (m_resourceObject.m_lockOwner != std::this_thread::get_id())
561 m_resourceObject.m_mutex.lock();
562 m_resourceObject.m_lockOwner = std::this_thread::get_id();
563 m_isOwningLock = true;
565 m_autoNotifyFunc = ::createAutoNotifyInvoker(&RCSResourceObject::autoNotify,
566 m_resourceObject, m_resourceObject.m_resourceAttributes, m_autoNotifyPolicy);
569 RCSResourceObject::WeakGuard::WeakGuard(
570 const RCSResourceObject& resourceObject) :
571 m_isOwningLock{ false },
572 m_resourceObject(resourceObject)
574 if (resourceObject.m_lockOwner != std::this_thread::get_id())
576 m_resourceObject.m_mutex.lock();
577 m_resourceObject.m_lockOwner = std::this_thread::get_id();
578 m_isOwningLock = true;
582 RCSResourceObject::WeakGuard::~WeakGuard()
586 m_resourceObject.m_lockOwner = std::thread::id{ };
587 m_resourceObject.m_mutex.unlock();
591 bool RCSResourceObject::WeakGuard::hasLocked() const
593 return m_isOwningLock;