summaryrefslogtreecommitdiff
path: root/AudioManagerUtilities
diff options
context:
space:
mode:
Diffstat (limited to 'AudioManagerUtilities')
-rw-r--r--AudioManagerUtilities/include/CAmCommandLineSingleton.h26
-rw-r--r--AudioManagerUtilities/include/CAmCommonAPIWrapper.h421
-rw-r--r--AudioManagerUtilities/include/CAmDbusWrapper.h58
-rw-r--r--AudioManagerUtilities/include/CAmDltWrapper.h299
-rw-r--r--AudioManagerUtilities/include/CAmSerializer.h2201
-rw-r--r--AudioManagerUtilities/include/CAmSocketHandler.h468
-rw-r--r--[-rwxr-xr-x]AudioManagerUtilities/include/CAmWatchdog.h11
-rw-r--r--AudioManagerUtilities/include/TAmPluginTemplate.h46
-rw-r--r--AudioManagerUtilities/src/CAmCommandLineSingleton.cpp47
-rw-r--r--AudioManagerUtilities/src/CAmCommonAPIWrapper.cpp263
-rw-r--r--AudioManagerUtilities/src/CAmDbusWrapper.cpp317
-rw-r--r--AudioManagerUtilities/src/CAmDltWrapper.cpp1366
-rw-r--r--AudioManagerUtilities/src/CAmSocketHandler.cpp916
-rw-r--r--[-rwxr-xr-x]AudioManagerUtilities/src/CAmWatchdog.cpp39
14 files changed, 3443 insertions, 3035 deletions
diff --git a/AudioManagerUtilities/include/CAmCommandLineSingleton.h b/AudioManagerUtilities/include/CAmCommandLineSingleton.h
index 10d92d4..4a1f081 100644
--- a/AudioManagerUtilities/include/CAmCommandLineSingleton.h
+++ b/AudioManagerUtilities/include/CAmCommandLineSingleton.h
@@ -21,7 +21,6 @@
*
*/
-
#ifndef AUDIOMANAGERUTILITIES_INCLUDE_CAMCOMMANDLINESINGLETON_H_
#define AUDIOMANAGERUTILITIES_INCLUDE_CAMCOMMANDLINESINGLETON_H_
@@ -29,21 +28,22 @@
namespace am {
-class CAmCommandLineSingleton {
+class CAmCommandLineSingleton
+{
public:
- static TCLAP::CmdLine* instanciateOnce(const std::string& message,
- const char delimiter = ' ',
- const std::string& version = "none",
- bool helpAndVersion = true);
-
- static TCLAP::CmdLine* instance();
-
- static void deleteInstance();
-
+ static TCLAP::CmdLine *instanciateOnce(const std::string &message,
+ const char delimiter = ' ',
+ const std::string &version = "none",
+ bool helpAndVersion = true);
+
+ static TCLAP::CmdLine *instance();
+
+ static void deleteInstance();
+
private:
- CAmCommandLineSingleton();
- virtual ~CAmCommandLineSingleton();
+ CAmCommandLineSingleton();
+ virtual ~CAmCommandLineSingleton();
};
} /* namespace am */
diff --git a/AudioManagerUtilities/include/CAmCommonAPIWrapper.h b/AudioManagerUtilities/include/CAmCommonAPIWrapper.h
index a83b5b3..a384f33 100644
--- a/AudioManagerUtilities/include/CAmCommonAPIWrapper.h
+++ b/AudioManagerUtilities/include/CAmCommonAPIWrapper.h
@@ -15,7 +15,6 @@
* For further information see http://www.genivi.org/.
*/
-
#ifndef COMMONAPIWRAPPER_H_
#define COMMONAPIWRAPPER_H_
@@ -27,9 +26,9 @@
#include <cassert>
#include <CommonAPI/CommonAPI.hpp>
#ifndef COMMONAPI_INTERNAL_COMPILATION
-#define COMMONAPI_INTERNAL_COMPILATION
-#include <CommonAPI/MainLoopContext.hpp>
-#undef COMMONAPI_INTERNAL_COMPILATION
+# define COMMONAPI_INTERNAL_COMPILATION
+# include <CommonAPI/MainLoopContext.hpp>
+# undef COMMONAPI_INTERNAL_COMPILATION
#endif
#include <CommonAPI/Utils.hpp>
#include "audiomanagerconfig.h"
@@ -48,247 +47,251 @@ class CAmSocketHandler;
class CAmCommonAPIWrapper
{
- void commonPrepareCallback(const sh_pollHandle_t handle, void* userData);
- TAmShPollPrepare<CAmCommonAPIWrapper> pCommonPrepareCallback;
+ void commonPrepareCallback(const sh_pollHandle_t handle, void *userData);
+
+ TAmShPollPrepare<CAmCommonAPIWrapper> pCommonPrepareCallback;
+
+ bool commonDispatchCallback(const sh_pollHandle_t handle, void *userData);
- bool commonDispatchCallback(const sh_pollHandle_t handle, void* userData);
TAmShPollDispatch<CAmCommonAPIWrapper> pCommonDispatchCallback;
- void commonFireCallback(const pollfd pollfd, const sh_pollHandle_t, void*);
+ void commonFireCallback(const pollfd pollfd, const sh_pollHandle_t, void *);
+
TAmShPollFired<CAmCommonAPIWrapper> pCommonFireCallback;
- bool commonCheckCallback(const sh_pollHandle_t handle, void*);
+ bool commonCheckCallback(const sh_pollHandle_t handle, void *);
+
TAmShPollCheck<CAmCommonAPIWrapper> pCommonCheckCallback;
- void commonTimerCallback(sh_timerHandle_t handle, void* userData);
+ void commonTimerCallback(sh_timerHandle_t handle, void *userData);
+
TAmShTimerCallBack<CAmCommonAPIWrapper> pCommonTimerCallback;
- struct timerHandles
+ struct timerHandles
{
sh_timerHandle_t handle;
- CommonAPI::Timeout* timeout;
+ CommonAPI::Timeout *timeout;
};
- CAmSocketHandler *mpSocketHandler; //!< pointer to the sockethandler
+ CAmSocketHandler *mpSocketHandler; //!< pointer to the sockethandler
- std::shared_ptr<CommonAPI::Runtime> mRuntime;
- std::shared_ptr<CommonAPI::MainLoopContext> mContext;
+ std::shared_ptr<CommonAPI::Runtime> mRuntime;
+ std::shared_ptr<CommonAPI::MainLoopContext> mContext;
CommonAPI::DispatchSourceListenerSubscription mDispatchSourceListenerSubscription;
- CommonAPI::WatchListenerSubscription mWatchListenerSubscription;
- CommonAPI::TimeoutSourceListenerSubscription mTimeoutSourceListenerSubscription;
- CommonAPI::WakeupListenerSubscription mWakeupListenerSubscription;
- std::multimap<CommonAPI::DispatchPriority, CommonAPI::DispatchSource*> mRegisteredDispatchSources;
- std::map<int,CommonAPI::Watch*> mMapWatches;
- CommonAPI::Watch* mWatchToCheck;
- std::list<CommonAPI::DispatchSource*> mSourcesToDispatch;
- std::vector<timerHandles> mpListTimerhandles;
-
- void registerDispatchSource(CommonAPI::DispatchSource* dispatchSource, const CommonAPI::DispatchPriority dispatchPriority);
- void deregisterDispatchSource(CommonAPI::DispatchSource* dispatchSource);
- void registerWatch(CommonAPI::Watch* watch, const CommonAPI::DispatchPriority dispatchPriority);
- void deregisterWatch(CommonAPI::Watch* watch);
- void registerTimeout(CommonAPI::Timeout* timeout, const CommonAPI::DispatchPriority dispatchPriority);
- void deregisterTimeout(CommonAPI::Timeout* timeout);
- void wakeup();
+ CommonAPI::WatchListenerSubscription mWatchListenerSubscription;
+ CommonAPI::TimeoutSourceListenerSubscription mTimeoutSourceListenerSubscription;
+ CommonAPI::WakeupListenerSubscription mWakeupListenerSubscription;
+ std::multimap<CommonAPI::DispatchPriority, CommonAPI::DispatchSource *> mRegisteredDispatchSources;
+ std::map<int, CommonAPI::Watch *> mMapWatches;
+ CommonAPI::Watch *mWatchToCheck;
+ std::list<CommonAPI::DispatchSource *> mSourcesToDispatch;
+ std::vector<timerHandles> mpListTimerhandles;
+
+ void registerDispatchSource(CommonAPI::DispatchSource *dispatchSource, const CommonAPI::DispatchPriority dispatchPriority);
+ void deregisterDispatchSource(CommonAPI::DispatchSource *dispatchSource);
+ void registerWatch(CommonAPI::Watch *watch, const CommonAPI::DispatchPriority dispatchPriority);
+ void deregisterWatch(CommonAPI::Watch *watch);
+ void registerTimeout(CommonAPI::Timeout *timeout, const CommonAPI::DispatchPriority dispatchPriority);
+ void deregisterTimeout(CommonAPI::Timeout *timeout);
+ void wakeup();
protected:
- CAmCommonAPIWrapper(CAmSocketHandler* socketHandler, const std::string & applicationName = "") ;
+ CAmCommonAPIWrapper(CAmSocketHandler *socketHandler, const std::string &applicationName = "");
public:
virtual ~CAmCommonAPIWrapper();
- /**
- * \brief Returns an already instantiated object.
- *
- * This method should be called after the instantiateOnce(...) has been called with non null socket handler parameter.
- *
- * @return The common-api wrapper object.
- */
- static CAmCommonAPIWrapper* getInstance();
-
- /**
- * \brief Deletes the instanciated object
- */
- static void deleteInstance();
-
- /**
- * \brief Creates a singleton instance attached to the provided socket handler object.
- *
- * This method should be called only once because it instantiates a single object.
- * Otherwise it will throw an exception.
- * The first call of this method with non null parameter loads the common-api and attaches it to the main loop.
- *
- * @param socketHandler: A pointer to socket handler or NULL
- *
- * @return The common-api wrapper object.
- */
- static CAmCommonAPIWrapper* instantiateOnce(CAmSocketHandler* socketHandler, const std::string & applicationName = "");
-
-
- /**
- * \brief Getter for the socket handler.
- *
- * @return Pointer to the socket handler.
- */
- CAmSocketHandler *getSocketHandler() const { return mpSocketHandler; }
-
- /**
- * \brief Deprecated method. This class is used only in single connection applications and no connectionId is needed. Instead you should use bool registerService(const std::shared_ptr<TStubImp> & shStub, const std::string & domain, const std::string & instance).
- *
- *
- * Example: std::shared_ptr<ConcreteStubClass> aStub;
- * registerService( aStub, "local", "com.your_company.instance_name", "service-name");
- *
- * @param shStub: Shared pointer to a stub instance
- * @param domain: A string with the domain name, usually "local"
- * @param instance: Common-api instance string as example "com.your_company.instance_name"
- * @param connectionId: A string connection id, which is used by CommonAPI to group applications
- *
- */
- template <class TStubImp> bool __attribute__((deprecated)) registerService(const std::shared_ptr<TStubImp> & shStub, const std::string & domain, const std::string & instance, const CommonAPI::ConnectionId_t __attribute__((__unused__)) & /*connectionId*/)
- {
- return mRuntime->registerService(domain, instance, shStub, mContext);
- }
-
- /**
- * \brief Register stub objects.
- *
- * Example: std::shared_ptr<ConcreteStubClass> aStub;
- * registerService( aStub, "local", "com.your_company.instance_name");
- *
- * @param shStub: Shared pointer to a stub instance
- * @param domain: A string with the domain name, usually "local"
- * @param instance: Common-api instance string as example "com.your_company.instance_name"
- *
- */
- template <class TStubImp> bool registerService(const std::shared_ptr<TStubImp> & shStub, const std::string & domain, const std::string & instance)
- {
- return mRuntime->registerService(domain, instance, shStub, mContext);
- }
-
- /**
- * \brief Unregister stub objects.
- *
- * @param domain: A string with the domain name, usually "local"
- * @param interface: Common-api interface string as example "com.your_company.interface_name"
- * @param instance: Common-api instance string as example "com.your_company.instance_name"
- *
- */
- bool unregisterService(const std::string &domain, const std::string &interface, const std::string &instance)
- {
- return mRuntime->unregisterService(domain, interface, instance);
- }
-
- /**
- * \brief Deprecated method. Instead you should use bool registerService(const std::shared_ptr<TStubImp> & shStub, const std::string & domain, const std::string & instance).
- *
- * Register stub objects.
- *
- * Example: std::shared_ptr<ConcreteStubClass> aStub;
- * registerService( aStub, "local:com.your_company.interface_name:com.your_company.instance_name");
- *
- * @param shStub: Shared pointer to a stub instance
- * @param address: Complete common-api address as example "local:com.your_company.interface_name:com.your_company.instance_name"
- *
- */
- template <class TStubImp> bool __attribute__((deprecated)) registerStub(const std::shared_ptr<TStubImp> & shStub, const std::string & address)
- {
- std::vector<std::string> parts = CommonAPI::split(address, ':');
- assert(parts.size()==3);
-
- return registerService(shStub, parts[0], parts[2]);
- }
-
- /**
- * \brief Deprecated method. Instead you should use bool unregisterService(const std::string &domain, const std::string &interface, const std::string &instance).
- *
- * Unregister stub objects.
- *
- * @param address: Complete common-api address as example "local:com.your_company.interface_name:com.your_company.instance_name"
- *
- */
- bool __attribute__((deprecated)) unregisterStub(const std::string & address)
- {
- std::vector<std::string> parts = CommonAPI::split(address, ':');
- assert(parts.size()==3);
-
- return unregisterService(parts[0], parts[1], parts[2]);
- }
-
- /**
- * \brief Deprecated method. This class is used only in single connection applications and no connectionId is needed. Instead you should use buildProxy(const std::string &domain, const std::string &instance).
- *
- * Example: std::shared_ptr<AProxyClass<>> aProxy = buildProxy<AProxyClass>("local", "com.your_company.instance_name", "client-name");
- *
- * @param domain: A string with the domain name, usually "local"
- * @param instance: Common-api instance string as example "com.your_company.instance_name"
- * @param connectionId: A string connection id, which is used by CommonAPI to group applications
- *
- * @return A proxy object.
- */
- template<template<typename ...> class ProxyClass, typename ... AttributeExtensions>
- std::shared_ptr<ProxyClass<AttributeExtensions...>> __attribute__((deprecated)) buildProxy(const std::string &domain, const std::string &instance, const CommonAPI::ConnectionId_t __attribute__((__unused__)) & /*connectionId*/)
- {
- return mRuntime->buildProxy<ProxyClass>(domain, instance, mContext);
- }
-
- /**
- * \brief Build proxy objects.
- *
- * Example: std::shared_ptr<AProxyClass<>> aProxy = buildProxy<AProxyClass>("local", "com.your_company.instance_name");
- *
- * @param domain: A string with the domain name, usually "local"
- * @param instance: Common-api instance string as example "com.your_company.instance_name"
- *
- * @return A proxy object.
- */
- template<template<typename ...> class ProxyClass, typename ... AttributeExtensions>
- std::shared_ptr<ProxyClass<AttributeExtensions...>> buildProxy(const std::string &domain, const std::string &instance)
- {
- return mRuntime->buildProxy<ProxyClass>(domain, instance, mContext);
- }
-
-
- /**
- * \brief Deprecated method. Instead you should use buildProxy(const std::string &domain, const std::string &instance).
- *
- * Build proxy objects.
- * Example: std::shared_ptr<AProxyClass<>> aProxy = buildProxy<AProxyClass>("local:com.your_company.interface_name:com.your_company.instance_name");
- *
- * @param address: Complete common-api address as example "local:com.your_company.interface_name:com.your_company.instance_name"
- *
- * @return A proxy object.
- */
- template<template<typename ...> class ProxyClass, typename ... AttributeExtensions>
- std::shared_ptr<ProxyClass<AttributeExtensions...>> __attribute__((deprecated)) buildProxy(const std::string & address)
- {
- std::vector<std::string> parts=CommonAPI::split(address, ':');
- assert(parts.size()==3);
-
- return buildProxy<ProxyClass>(parts[0], parts[2]);
- }
+ /**
+ * \brief Returns an already instantiated object.
+ *
+ * This method should be called after the instantiateOnce(...) has been called with non null socket handler parameter.
+ *
+ * @return The common-api wrapper object.
+ */
+ static CAmCommonAPIWrapper *getInstance();
+
+ /**
+ * \brief Deletes the instanciated object
+ */
+ static void deleteInstance();
+
+ /**
+ * \brief Creates a singleton instance attached to the provided socket handler object.
+ *
+ * This method should be called only once because it instantiates a single object.
+ * Otherwise it will throw an exception.
+ * The first call of this method with non null parameter loads the common-api and attaches it to the main loop.
+ *
+ * @param socketHandler: A pointer to socket handler or NULL
+ *
+ * @return The common-api wrapper object.
+ */
+ static CAmCommonAPIWrapper *instantiateOnce(CAmSocketHandler *socketHandler, const std::string &applicationName = "");
+
+ /**
+ * \brief Getter for the socket handler.
+ *
+ * @return Pointer to the socket handler.
+ */
+ CAmSocketHandler *getSocketHandler() const { return mpSocketHandler; }
+
+ /**
+ * \brief Deprecated method. This class is used only in single connection applications and no connectionId is needed. Instead you should use bool registerService(const std::shared_ptr<TStubImp> & shStub, const std::string & domain, const std::string & instance).
+ *
+ *
+ * Example: std::shared_ptr<ConcreteStubClass> aStub;
+ * registerService( aStub, "local", "com.your_company.instance_name", "service-name");
+ *
+ * @param shStub: Shared pointer to a stub instance
+ * @param domain: A string with the domain name, usually "local"
+ * @param instance: Common-api instance string as example "com.your_company.instance_name"
+ * @param connectionId: A string connection id, which is used by CommonAPI to group applications
+ *
+ */
+ template <class TStubImp>
+ bool __attribute__((deprecated)) registerService(const std::shared_ptr<TStubImp> &shStub, const std::string &domain, const std::string &instance, const CommonAPI::ConnectionId_t __attribute__((__unused__)) & /*connectionId*/)
+ {
+ return mRuntime->registerService(domain, instance, shStub, mContext);
+ }
+
+ /**
+ * \brief Register stub objects.
+ *
+ * Example: std::shared_ptr<ConcreteStubClass> aStub;
+ * registerService( aStub, "local", "com.your_company.instance_name");
+ *
+ * @param shStub: Shared pointer to a stub instance
+ * @param domain: A string with the domain name, usually "local"
+ * @param instance: Common-api instance string as example "com.your_company.instance_name"
+ *
+ */
+ template <class TStubImp>
+ bool registerService(const std::shared_ptr<TStubImp> &shStub, const std::string &domain, const std::string &instance)
+ {
+ return mRuntime->registerService(domain, instance, shStub, mContext);
+ }
+
+ /**
+ * \brief Unregister stub objects.
+ *
+ * @param domain: A string with the domain name, usually "local"
+ * @param interface: Common-api interface string as example "com.your_company.interface_name"
+ * @param instance: Common-api instance string as example "com.your_company.instance_name"
+ *
+ */
+ bool unregisterService(const std::string &domain, const std::string &interface, const std::string &instance)
+ {
+ return mRuntime->unregisterService(domain, interface, instance);
+ }
+
+ /**
+ * \brief Deprecated method. Instead you should use bool registerService(const std::shared_ptr<TStubImp> & shStub, const std::string & domain, const std::string & instance).
+ *
+ * Register stub objects.
+ *
+ * Example: std::shared_ptr<ConcreteStubClass> aStub;
+ * registerService( aStub, "local:com.your_company.interface_name:com.your_company.instance_name");
+ *
+ * @param shStub: Shared pointer to a stub instance
+ * @param address: Complete common-api address as example "local:com.your_company.interface_name:com.your_company.instance_name"
+ *
+ */
+ template <class TStubImp>
+ bool __attribute__((deprecated)) registerStub(const std::shared_ptr<TStubImp> &shStub, const std::string &address)
+ {
+ std::vector<std::string> parts = CommonAPI::split(address, ':');
+ assert(parts.size() == 3);
+
+ return registerService(shStub, parts[0], parts[2]);
+ }
+
+ /**
+ * \brief Deprecated method. Instead you should use bool unregisterService(const std::string &domain, const std::string &interface, const std::string &instance).
+ *
+ * Unregister stub objects.
+ *
+ * @param address: Complete common-api address as example "local:com.your_company.interface_name:com.your_company.instance_name"
+ *
+ */
+ bool __attribute__((deprecated)) unregisterStub(const std::string &address)
+ {
+ std::vector<std::string> parts = CommonAPI::split(address, ':');
+ assert(parts.size() == 3);
+
+ return unregisterService(parts[0], parts[1], parts[2]);
+ }
+
+ /**
+ * \brief Deprecated method. This class is used only in single connection applications and no connectionId is needed. Instead you should use buildProxy(const std::string &domain, const std::string &instance).
+ *
+ * Example: std::shared_ptr<AProxyClass<>> aProxy = buildProxy<AProxyClass>("local", "com.your_company.instance_name", "client-name");
+ *
+ * @param domain: A string with the domain name, usually "local"
+ * @param instance: Common-api instance string as example "com.your_company.instance_name"
+ * @param connectionId: A string connection id, which is used by CommonAPI to group applications
+ *
+ * @return A proxy object.
+ */
+ template<template<typename...> class ProxyClass, typename... AttributeExtensions>
+ std::shared_ptr<ProxyClass<AttributeExtensions...> > __attribute__((deprecated)) buildProxy(const std::string &domain, const std::string &instance, const CommonAPI::ConnectionId_t __attribute__((__unused__)) & /*connectionId*/)
+ {
+ return mRuntime->buildProxy<ProxyClass>(domain, instance, mContext);
+ }
+
+ /**
+ * \brief Build proxy objects.
+ *
+ * Example: std::shared_ptr<AProxyClass<>> aProxy = buildProxy<AProxyClass>("local", "com.your_company.instance_name");
+ *
+ * @param domain: A string with the domain name, usually "local"
+ * @param instance: Common-api instance string as example "com.your_company.instance_name"
+ *
+ * @return A proxy object.
+ */
+ template<template<typename...> class ProxyClass, typename... AttributeExtensions>
+ std::shared_ptr<ProxyClass<AttributeExtensions...> > buildProxy(const std::string &domain, const std::string &instance)
+ {
+ return mRuntime->buildProxy<ProxyClass>(domain, instance, mContext);
+ }
+
+ /**
+ * \brief Deprecated method. Instead you should use buildProxy(const std::string &domain, const std::string &instance).
+ *
+ * Build proxy objects.
+ * Example: std::shared_ptr<AProxyClass<>> aProxy = buildProxy<AProxyClass>("local:com.your_company.interface_name:com.your_company.instance_name");
+ *
+ * @param address: Complete common-api address as example "local:com.your_company.interface_name:com.your_company.instance_name"
+ *
+ * @return A proxy object.
+ */
+ template<template<typename...> class ProxyClass, typename... AttributeExtensions>
+ std::shared_ptr<ProxyClass<AttributeExtensions...> > __attribute__((deprecated)) buildProxy(const std::string &address)
+ {
+ std::vector<std::string> parts = CommonAPI::split(address, ':');
+ assert(parts.size() == 3);
-};
+ return buildProxy<ProxyClass>(parts[0], parts[2]);
+ }
+};
-//Alias
-extern CAmCommonAPIWrapper* (*getCAPI)();
+// Alias
+extern CAmCommonAPIWrapper *(*getCAPI)();
#ifndef AMCAPI
- #define AMCAPI getCAPI()
+# define AMCAPI getCAPI()
#endif
#ifndef AM_CAPI
- #define AM_CAPI getCAPI()
+# define AM_CAPI getCAPI()
#endif
#ifndef CAPI
- #define CAPI getCAPI()
+# define CAPI getCAPI()
#endif
-
}
#endif /* COMMONAPIWRAPPER_H_ */
diff --git a/AudioManagerUtilities/include/CAmDbusWrapper.h b/AudioManagerUtilities/include/CAmDbusWrapper.h
index 0352c35..37ecf6b 100644
--- a/AudioManagerUtilities/include/CAmDbusWrapper.h
+++ b/AudioManagerUtilities/include/CAmDbusWrapper.h
@@ -37,54 +37,60 @@ namespace am
class CAmDbusWrapper
{
public:
- CAmDbusWrapper(CAmSocketHandler* socketHandler,DBusBusType type=DBUS_BUS_SESSION,
- const std::string& prefix = DBUS_SERVICE_PREFIX, const std::string& objectPath = DBUS_SERVICE_OBJECT_PATH);
+ CAmDbusWrapper(CAmSocketHandler *socketHandler, DBusBusType type = DBUS_BUS_SESSION,
+ const std::string &prefix = DBUS_SERVICE_PREFIX, const std::string &objectPath = DBUS_SERVICE_OBJECT_PATH);
virtual ~CAmDbusWrapper();
- void registerCallback(const DBusObjectPathVTable* vtable, const std::string& path, void* userdata, const std::string& prefix = DBUS_SERVICE_OBJECT_PATH);
- void registerSignalWatch(DBusHandleMessageFunction handler, const std::string& rule, void* userdata);
- void getDBusConnection(DBusConnection*& connection) const;
+ void registerCallback(const DBusObjectPathVTable *vtable, const std::string &path, void *userdata, const std::string &prefix = DBUS_SERVICE_OBJECT_PATH);
+ void registerSignalWatch(DBusHandleMessageFunction handler, const std::string &rule, void *userdata);
+ void getDBusConnection(DBusConnection * &connection) const;
static dbus_bool_t addWatch(DBusWatch *watch, void *userData);
static void removeWatch(DBusWatch *watch, void *userData);
static void toogleWatch(DBusWatch *watch, void *userData);
- static dbus_bool_t addTimeout(DBusTimeout *timeout, void* userData);
- static void removeTimeout(DBusTimeout *timeout, void* userData);
- static void toggleTimeout(DBusTimeout *timeout, void* userData);
+ static dbus_bool_t addTimeout(DBusTimeout *timeout, void *userData);
+ static void removeTimeout(DBusTimeout *timeout, void *userData);
+ static void toggleTimeout(DBusTimeout *timeout, void *userData);
+
+ void dbusPrepareCallback(const sh_pollHandle_t handle, void *userData);
- void dbusPrepareCallback(const sh_pollHandle_t handle, void* userData);
TAmShPollPrepare<CAmDbusWrapper> pDbusPrepareCallback;
- bool dbusDispatchCallback(const sh_pollHandle_t handle, void* userData);
+ bool dbusDispatchCallback(const sh_pollHandle_t handle, void *userData);
+
TAmShPollDispatch<CAmDbusWrapper> pDbusDispatchCallback;
- void dbusFireCallback(const pollfd pollfd, const sh_pollHandle_t handle, void* userData);
+ void dbusFireCallback(const pollfd pollfd, const sh_pollHandle_t handle, void *userData);
+
TAmShPollFired<CAmDbusWrapper> pDbusFireCallback;
- bool dbusCheckCallback(const sh_pollHandle_t handle, void* userData);
+ bool dbusCheckCallback(const sh_pollHandle_t handle, void *userData);
+
TAmShPollCheck<CAmDbusWrapper> pDbusCheckCallback;
- void dbusTimerCallback(sh_timerHandle_t handle, void* userData);
+ void dbusTimerCallback(sh_timerHandle_t handle, void *userData);
+
TAmShTimerCallBack<CAmDbusWrapper> pDbusTimerCallback;
private:
- static CAmDbusWrapper* mpReference; //!< reference to the dbus instance
+ static CAmDbusWrapper *mpReference; //!< reference to the dbus instance
static DBusHandlerResult cbRootIntrospection(DBusConnection *conn, DBusMessage *msg, void *reference);
- dbus_bool_t addWatchDelegate(DBusWatch * watch, void* userData);
+ dbus_bool_t addWatchDelegate(DBusWatch *watch, void *userData);
void removeWatchDelegate(DBusWatch *watch, void *userData);
void toogleWatchDelegate(DBusWatch *watch, void *userData);
- dbus_bool_t addTimeoutDelegate(DBusTimeout *timeout, void* userData);
- void removeTimeoutDelegate(DBusTimeout *timeout, void* userData);
- void toggleTimeoutDelegate(DBusTimeout *timeout, void* userData);
- DBusObjectPathVTable mObjectPathVTable; //!< the vpathtable
- DBusConnection* mpDbusConnection; //!< pointer to the dbus connection used
- DBusError mDBusError; //!< dbuserror
- std::vector<std::string> mListNodes; //!< holds a list of all nodes of the dbus
- std::vector<sh_timerHandle_t*> mpListTimerhandles; //!< pointer to the timer handles
- CAmSocketHandler *mpSocketHandler; //!< pointer to the sockethandler
- std::map<DBusWatch*, sh_pollHandle_t> mMapHandleWatch; //!< map to the handle watches
- DBusBusType mDbusType;
+ dbus_bool_t addTimeoutDelegate(DBusTimeout *timeout, void *userData);
+ void removeTimeoutDelegate(DBusTimeout *timeout, void *userData);
+ void toggleTimeoutDelegate(DBusTimeout *timeout, void *userData);
+
+ DBusObjectPathVTable mObjectPathVTable; //!< the vpathtable
+ DBusConnection *mpDbusConnection; //!< pointer to the dbus connection used
+ DBusError mDBusError; //!< dbuserror
+ std::vector<std::string> mListNodes; //!< holds a list of all nodes of the dbus
+ std::vector<sh_timerHandle_t *> mpListTimerhandles; //!< pointer to the timer handles
+ CAmSocketHandler *mpSocketHandler; //!< pointer to the sockethandler
+ std::map<DBusWatch *, sh_pollHandle_t> mMapHandleWatch; //!< map to the handle watches
+ DBusBusType mDbusType;
};
}
diff --git a/AudioManagerUtilities/include/CAmDltWrapper.h b/AudioManagerUtilities/include/CAmDltWrapper.h
index 4d725d8..b6772d9 100644
--- a/AudioManagerUtilities/include/CAmDltWrapper.h
+++ b/AudioManagerUtilities/include/CAmDltWrapper.h
@@ -29,67 +29,67 @@
#include "audiomanagertypes.h"
#ifdef WITH_DLT
- #include <dlt.h>
+# include <dlt.h>
#else
- #include <stdint.h>
- #include <sstream>
+# include <stdint.h>
+# include <sstream>
- #define DLT_USER_BUF_MAX_SIZE 2048
+# define DLT_USER_BUF_MAX_SIZE 2048
- /**
- * This structure is used for every context used in an application.
- */
- typedef struct
- {
- char contextID[4]; /**< context id */
- int32_t log_level_pos; /**< offset in user-application context field */
- int32_t log_level_user; /** any message above this log level is not logged */
- } DltContext;
+/**
+ * This structure is used for every context used in an application.
+ */
+typedef struct
+{
+ char contextID[4]; /**< context id */
+ int32_t log_level_pos; /**< offset in user-application context field */
+ int32_t log_level_user; /** any message above this log level is not logged */
+} DltContext;
- /**
- * Definition of DLT trace status
- */
- typedef enum
- {
- DLT_TRACE_STATUS_DEFAULT = -1, /**< Default trace status */
- DLT_TRACE_STATUS_OFF = 0x00, /**< Trace status: Off */
- DLT_TRACE_STATUS_ON = 0x01 /**< Trace status: On */
- } DltTraceStatusType;
+/**
+ * Definition of DLT trace status
+ */
+typedef enum
+{
+ DLT_TRACE_STATUS_DEFAULT = -1, /**< Default trace status */
+ DLT_TRACE_STATUS_OFF = 0x00, /**< Trace status: Off */
+ DLT_TRACE_STATUS_ON = 0x01 /**< Trace status: On */
+} DltTraceStatusType;
- /**
- * This structure is used for context data used in an application.
- */
- typedef struct
- {
- DltContext *handle; /**< pointer to DltContext */
- std::stringstream buffer; /**< buffer for building log message*/
- int32_t log_level; /**< log level */
- int32_t trace_status; /**< trace status */
- int32_t args_num; /**< number of arguments for extended header*/
- uint8_t mcnt; /**< message counter */
- char* context_description; /**< description of context */
- } DltContextData;
+/**
+ * This structure is used for context data used in an application.
+ */
+typedef struct
+{
+ DltContext *handle; /**< pointer to DltContext */
+ std::stringstream buffer; /**< buffer for building log message*/
+ int32_t log_level; /**< log level */
+ int32_t trace_status; /**< trace status */
+ int32_t args_num; /**< number of arguments for extended header*/
+ uint8_t mcnt; /**< message counter */
+ char *context_description; /**< description of context */
+} DltContextData;
- /**
- * Definitions of DLT log level
- */
- typedef enum
- {
- DLT_LOG_DEFAULT = -1, /**< Default log level */
- DLT_LOG_OFF = 0x00, /**< Log level off */
- DLT_LOG_FATAL = 0x01, /**< fatal system error */
- DLT_LOG_ERROR = 0x02, /**< error with impact to correct functionality */
- DLT_LOG_WARN = 0x03, /**< warning, correct behaviour could not be ensured */
- DLT_LOG_INFO = 0x04, /**< informational */
- DLT_LOG_DEBUG = 0x05, /**< debug */
- DLT_LOG_VERBOSE = 0x06 /**< highest grade of information */
- } DltLogLevelType;
-
- #define DLT_DEFAULT_LOG_LEVEL DLT_LOG_INFO
- #define DLT_DECLARE_CONTEXT(CONTEXT) \
+/**
+ * Definitions of DLT log level
+ */
+typedef enum
+{
+ DLT_LOG_DEFAULT = -1, /**< Default log level */
+ DLT_LOG_OFF = 0x00, /**< Log level off */
+ DLT_LOG_FATAL = 0x01, /**< fatal system error */
+ DLT_LOG_ERROR = 0x02, /**< error with impact to correct functionality */
+ DLT_LOG_WARN = 0x03, /**< warning, correct behaviour could not be ensured */
+ DLT_LOG_INFO = 0x04, /**< informational */
+ DLT_LOG_DEBUG = 0x05, /**< debug */
+ DLT_LOG_VERBOSE = 0x06 /**< highest grade of information */
+} DltLogLevelType;
+
+# define DLT_DEFAULT_LOG_LEVEL DLT_LOG_INFO
+# define DLT_DECLARE_CONTEXT(CONTEXT) \
DltContext CONTEXT;
- #define DLT_IMPORT_CONTEXT(CONTEXT) \
+# define DLT_IMPORT_CONTEXT(CONTEXT) \
extern DltContext CONTEXT;
#endif // WITH_DLT
@@ -112,13 +112,13 @@ public:
*/
typedef struct
{
- DltContext *handle; /**< pointer to DltContext */
- std::stringstream buffer; /**< buffer for building log message*/
- int32_t log_level; /**< log level */
- int32_t trace_status; /**< trace status */
- int32_t args_num; /**< number of arguments for extended header*/
- uint8_t mcnt; /**< message counter */
- char* context_description; /**< description of context */
+ DltContext *handle; /**< pointer to DltContext */
+ std::stringstream buffer; /**< buffer for building log message*/
+ int32_t log_level; /**< log level */
+ int32_t trace_status; /**< trace status */
+ int32_t args_num; /**< number of arguments for extended header*/
+ uint8_t mcnt; /**< message counter */
+ char *context_description; /**< description of context */
} NoDltContextData;
/*
@@ -126,9 +126,9 @@ public:
*/
enum logDestination
{
- DAEMON=0, //!< logging with the DLT daemon
- COMMAND_LINE=1, //!< logging with commandline
- FILE_OUT =2 //!< logging into a file
+ DAEMON = 0, //!< logging with the DLT daemon
+ COMMAND_LINE = 1, //!< logging with commandline
+ FILE_OUT = 2 //!< logging into a file
};
/**
@@ -140,39 +140,42 @@ public:
* @param Filename the filename with absolute path where the log shall be written. only needed if logDest==FILE_OUT
* @param onlyError if set to true, only errors will be logged. just valid for commandline and file logs, default value = false
*/
- static CAmDltWrapper* instanctiateOnce(const char *appid, const char * description, const bool debugEnabled = true, const logDestination logDest = logDestination::DAEMON, const std::string Filename="",bool onlyError=false);
-
+ static CAmDltWrapper *instanctiateOnce(const char *appid, const char *description, const bool debugEnabled = true, const logDestination logDest = logDestination::DAEMON, const std::string Filename = "", bool onlyError = false);
+
/**
* get the Wrapper Instance
*/
- static CAmDltWrapper* instance();
+ static CAmDltWrapper *instance();
/**
* register a context
*/
- void registerContext(DltContext& handle, const char *contextid, const char * description);
- void registerContext(DltContext& handle, const char *contextid, const char * description, const DltLogLevelType level, const DltTraceStatusType status);
- void unregisterContext(DltContext& handle);
+ void registerContext(DltContext &handle, const char *contextid, const char *description);
+ void registerContext(DltContext &handle, const char *contextid, const char *description, const DltLogLevelType level, const DltTraceStatusType status);
+ void unregisterContext(DltContext &handle);
bool getEnabled();
+
~CAmDltWrapper();
- bool init(DltLogLevelType loglevel, DltContext* context = NULL);
+ bool init(DltLogLevelType loglevel, DltContext *context = NULL);
+
bool checkLogLevel(DltLogLevelType logLevel)
{
#ifdef WITH_DLT
- #ifdef DLT_IS_LOG_LEVEL_ENABLED
+# ifdef DLT_IS_LOG_LEVEL_ENABLED
if (mlogDestination == logDestination::DAEMON)
{
return (dlt_user_is_logLevel_enabled(&mDltContext, logLevel) == DLT_RETURN_TRUE);
}
- #else
+# else
(void)logLevel;
- #endif
+# endif // ifdef DLT_IS_LOG_LEVEL_ENABLED
return true;
-#else
+#else // ifdef WITH_DLT
return (logLevel <= mDltContext.log_level_user);
-#endif
+#endif // ifdef WITH_DLT
}
+
void deinit();
void send();
void append(const int8_t value);
@@ -183,48 +186,51 @@ public:
void append(const uint32_t value);
void append(const uint64_t value);
void append(const int64_t value);
- void append(const std::string& value);
+ void append(const std::string &value);
void append(const bool value);
- void append(const std::vector<uint8_t> & data);
-
- template<class T> void appendNoDLT(T value)
+ void append(const std::vector<uint8_t> &data);
+
+ template<class T>
+ void appendNoDLT(T value)
{
- mNoDltContextData.buffer << value <<" ";
+ mNoDltContextData.buffer << value << " ";
}
// specialization for const char*
- template<typename T = const char*> void append(const char* value)
+ template<typename T = const char *>
+ void append(const char *value)
{
- #ifdef WITH_DLT
- if (mlogDestination == logDestination::DAEMON)
- {
- dlt_user_log_write_string(&mDltContextData, value);
- }
- else
- {
- mNoDltContextData.buffer << std::string(value);
- }
- #else
+#ifdef WITH_DLT
+ if (mlogDestination == logDestination::DAEMON)
+ {
+ dlt_user_log_write_string(&mDltContextData, value);
+ }
+ else
+ {
mNoDltContextData.buffer << std::string(value);
- #endif //WITH_DLT
+ }
+#else // ifdef WITH_DLT
+ mNoDltContextData.buffer << std::string(value);
+#endif // WITH_DLT
}
private:
- static const std::vector<const char*> mStr_error;
- static const std::vector<const char*> mStr_sourceState;
- static const std::vector<const char*> mStr_MuteState;
- static const std::vector<const char*> mStr_DomainState;
- static const std::vector<const char*> mStr_ConnectionState;
- static const std::vector<const char*> mStr_Availability;
- static const std::vector<const char*> mStr_Interrupt;
- static const std::vector<const char*> mStr_Handle;
- static const std::vector<const char*> mStr_NotificationStatus;
+ static const std::vector<const char *> mStr_error;
+ static const std::vector<const char *> mStr_sourceState;
+ static const std::vector<const char *> mStr_MuteState;
+ static const std::vector<const char *> mStr_DomainState;
+ static const std::vector<const char *> mStr_ConnectionState;
+ static const std::vector<const char *> mStr_Availability;
+ static const std::vector<const char *> mStr_Interrupt;
+ static const std::vector<const char *> mStr_Handle;
+ static const std::vector<const char *> mStr_NotificationStatus;
public:
// specialization for const am_Error_e
- template<typename T = const am_Error_e> void append(const am_Error_e value)
+ template<typename T = const am_Error_e>
+ void append(const am_Error_e value)
{
if (static_cast<std::size_t>(value) >= mStr_error.size())
{
@@ -232,11 +238,13 @@ public:
append(static_cast<uint16_t>(value));
return;
}
+
append(mStr_error[value]);
}
// specialization for const am_Error_e
- template<typename T = const am_SourceState_e> void append(const am_SourceState_e value)
+ template<typename T = const am_SourceState_e>
+ void append(const am_SourceState_e value)
{
if (static_cast<std::size_t>(value) >= mStr_sourceState.size())
{
@@ -244,11 +252,12 @@ public:
append(static_cast<uint16_t>(value));
return;
}
+
append(mStr_sourceState[value]);
}
-
- template<typename T = const am_MuteState_e> void append(const am_MuteState_e value)
+ template<typename T = const am_MuteState_e>
+ void append(const am_MuteState_e value)
{
if (static_cast<std::size_t>(value) >= mStr_MuteState.size())
{
@@ -256,10 +265,12 @@ public:
append(static_cast<uint16_t>(value));
return;
}
+
append(mStr_MuteState[value]);
}
- template<typename T = const am_DomainState_e> void append(const am_DomainState_e value)
+ template<typename T = const am_DomainState_e>
+ void append(const am_DomainState_e value)
{
if (static_cast<std::size_t>(value) >= mStr_DomainState.size())
{
@@ -267,10 +278,12 @@ public:
append(static_cast<uint16_t>(value));
return;
}
+
append(mStr_DomainState[value]);
}
- template<typename T = const am_ConnectionState_e> void append(const am_ConnectionState_e value)
+ template<typename T = const am_ConnectionState_e>
+ void append(const am_ConnectionState_e value)
{
if (static_cast<std::size_t>(value) >= mStr_ConnectionState.size())
{
@@ -278,10 +291,12 @@ public:
append(static_cast<uint16_t>(value));
return;
}
+
append(mStr_ConnectionState[value]);
}
- template<typename T = const am_Availability_e> void append(const am_Availability_e value)
+ template<typename T = const am_Availability_e>
+ void append(const am_Availability_e value)
{
if (static_cast<std::size_t>(value) >= mStr_Availability.size())
{
@@ -289,10 +304,12 @@ public:
append(static_cast<uint16_t>(value));
return;
}
+
append(mStr_Availability[value]);
}
- template<typename T = const am_InterruptState_e> void append(const am_InterruptState_e value)
+ template<typename T = const am_InterruptState_e>
+ void append(const am_InterruptState_e value)
{
if (static_cast<std::size_t>(value) >= mStr_Interrupt.size())
{
@@ -300,10 +317,12 @@ public:
append(static_cast<uint16_t>(value));
return;
}
+
append(mStr_Interrupt[value]);
}
- template<typename T = const am_Handle_e> void append(const am_Handle_e value)
+ template<typename T = const am_Handle_e>
+ void append(const am_Handle_e value)
{
if (static_cast<std::size_t>(value) >= mStr_Handle.size())
{
@@ -311,16 +330,19 @@ public:
append(static_cast<uint16_t>(value));
return;
}
+
append(mStr_Handle[value]);
}
-
- template<typename T = const am_Handle_s> void append(const am_Handle_s value)
+
+ template<typename T = const am_Handle_s>
+ void append(const am_Handle_s value)
{
- append (value.handleType);
- append (value.handle);
+ append(value.handleType);
+ append(value.handle);
}
- template<typename T = const am_NotificationStatus_e> void append(const am_NotificationStatus_e value)
+ template<typename T = const am_NotificationStatus_e>
+ void append(const am_NotificationStatus_e value)
{
if (static_cast<std::size_t>(value) >= mStr_NotificationStatus.size())
{
@@ -328,11 +350,13 @@ public:
append(static_cast<uint16_t>(value));
return;
}
+
append(mStr_NotificationStatus[value]);
}
// Template to print unknown pointer types with their address
- template<typename T> void append(T* value)
+ template<typename T>
+ void append(T *value)
{
std::ostringstream ss;
ss << "0x" << std::hex << (uint64_t)value;
@@ -340,7 +364,8 @@ public:
}
// Template to print unknown types
- template<typename T> void append(T value)
+ template<typename T>
+ void append(T value)
{
std::ostringstream ss;
ss << std::dec << value;
@@ -349,7 +374,8 @@ public:
// Template parameter pack to generate recursive code
void append(void) {}
- template<typename T, typename... TArgs> void append(T value, TArgs... args)
+ template<typename T, typename... TArgs>
+ void append(T value, TArgs... args)
{
this->append(value);
this->append(args...);
@@ -359,19 +385,20 @@ private:
/**
* private contructor
*/
- CAmDltWrapper(const char *appid, const char * description, const bool debugEnabled = true, const logDestination logDest = logDestination::DAEMON, const std::string Filename="",bool onlyError=false); //is private because of singleton pattern
- bool initNoDlt(DltLogLevelType loglevel, DltContext* context);
+ CAmDltWrapper(const char *appid, const char *description, const bool debugEnabled = true, const logDestination logDest = logDestination::DAEMON, const std::string Filename = "", bool onlyError = false); // is private because of singleton pattern
+ bool initNoDlt(DltLogLevelType loglevel, DltContext *context);
std::string now();
- DltContext mDltContext; //!< the default context
- DltContextData mDltContextData; //!< contextdata
- NoDltContextData mNoDltContextData; //!<contextdata for std out logging
- std::map<DltContext*,std::string> mMapContext; //!< a Map for all registered context
- bool mDebugEnabled; //!< debug Enabled or not
- logDestination mlogDestination; //!< The log destination
- std::ofstream mFilename; //!< Filename for logging
- bool mOnlyError; //!< Only if Log Level is above Error
- bool mLogOn; //!< Used to keep track if currently logging is on
- static CAmDltWrapper* mpDLTWrapper; //!< pointer to the wrapper instance
+
+ DltContext mDltContext; //!< the default context
+ DltContextData mDltContextData; //!< contextdata
+ NoDltContextData mNoDltContextData; //!< contextdata for std out logging
+ std::map<DltContext *, std::string> mMapContext; //!< a Map for all registered context
+ bool mDebugEnabled; //!< debug Enabled or not
+ logDestination mlogDestination; //!< The log destination
+ std::ofstream mFilename; //!< Filename for logging
+ bool mOnlyError; //!< Only if Log Level is above Error
+ bool mLogOn; //!< Used to keep track if currently logging is on
+ static CAmDltWrapper *mpDLTWrapper; //!< pointer to the wrapper instance
static pthread_mutex_t mMutex;
};
@@ -384,17 +411,19 @@ private:
* @param ...
*/
template<typename T, typename... TArgs>
-void log(DltContext* const context, DltLogLevelType loglevel, T value, TArgs... args)
+void log(DltContext *const context, DltLogLevelType loglevel, T value, TArgs... args)
{
- CAmDltWrapper* inst(CAmDltWrapper::instance());
+ CAmDltWrapper *inst(CAmDltWrapper::instance());
if (!inst->getEnabled())
{
return;
}
+
if (!inst->init(loglevel, context))
{
return;
}
+
inst->append(value);
inst->append(args...);
inst->send();
@@ -430,7 +459,7 @@ void logInfo(T value, TArgs... args)
template<typename T, typename... TArgs>
void logError(T value, TArgs... args)
{
- log(NULL, DLT_LOG_ERROR,value,args...);
+ log(NULL, DLT_LOG_ERROR, value, args...);
}
/**
@@ -441,7 +470,7 @@ void logError(T value, TArgs... args)
template<typename T, typename... TArgs>
void logWarning(T value, TArgs... args)
{
- log(NULL, DLT_LOG_WARN,value,args...);
+ log(NULL, DLT_LOG_WARN, value, args...);
}
/**
@@ -452,7 +481,7 @@ void logWarning(T value, TArgs... args)
template<typename T, typename... TArgs>
void logVerbose(T value, TArgs... args)
{
- log(NULL, DLT_LOG_VERBOSE,value,args...);
+ log(NULL, DLT_LOG_VERBOSE, value, args...);
}
}
diff --git a/AudioManagerUtilities/include/CAmSerializer.h b/AudioManagerUtilities/include/CAmSerializer.h
index fbac255..ad0b2b1 100644
--- a/AudioManagerUtilities/include/CAmSerializer.h
+++ b/AudioManagerUtilities/include/CAmSerializer.h
@@ -29,34 +29,36 @@
/*!
* \brief Helper structures used within std::bind for automatically identification of all placeholders.
*/
-template<std::size_t ... Is>
+template<std::size_t... Is>
struct indices
{
};
-template<std::size_t N, std::size_t ... Is>
-struct build_indices: build_indices<N - 1, N - 1, Is...>
+template<std::size_t N, std::size_t... Is>
+struct build_indices : build_indices<N - 1, N - 1, Is...>
{
};
-template<std::size_t ... Is>
+template<std::size_t... Is>
struct build_indices<0, Is...> : indices<Is...>
{
};
-template<int I> struct placeholder
+template<int I>
+struct placeholder
{
};
namespace std
{
- template<int I>
- struct is_placeholder<::placeholder<I>> : std::integral_constant<int, I>
- {
- };
+template<int I>
+struct is_placeholder<::placeholder<I> > : std::integral_constant<int, I>
+{
+};
+
}
-#if defined(__GNUC__)
+#if defined (__GNUC__)
# define DEPRECATED(MSG) __attribute__ ((__deprecated__((#MSG))))
#else
# define DEPRECATED(MSG)
@@ -64,1154 +66,1195 @@ namespace std
namespace am
{
+/**
+ * magic class that does the serialization of functions calls
+ * The constructor must be called within the main threadcontext, after that using the
+ * overloaded template function call will serialize all calls and call them within the
+ * main thread context.\n
+ * More details can be found here: \ref util
+ * \warning asynchronous calls may be used in the mainthread context, but if you want to use synchronous calls make sure that you use one
+ * instance of this class per thread otherwise you could be lost in never returning calls.\n
+ * Examples of the usage can be found in IAmCommandReceiverShadow of the ControlPlugin or IAmRoutingReceiverShadow of the
+ * PluginRoutingInterfaceAsync.
+ *
+ */
+
+/**
+ * \defgroup Deprecated Obsolete class!
+ * @{
+ */
+
+namespace V1
+{
+class CAmSerializer
+{
+private:
+
/**
- * magic class that does the serialization of functions calls
- * The constructor must be called within the main threadcontext, after that using the
- * overloaded template function call will serialize all calls and call them within the
- * main thread context.\n
- * More details can be found here: \ref util
- * \warning asynchronous calls may be used in the mainthread context, but if you want to use synchronous calls make sure that you use one
- * instance of this class per thread otherwise you could be lost in never returning calls.\n
- * Examples of the usage can be found in IAmCommandReceiverShadow of the ControlPlugin or IAmRoutingReceiverShadow of the
- * PluginRoutingInterfaceAsync.
- *
+ * Prototype for a delegate
*/
+ class CAmDelegate
+ {
+ public:
+
+ typedef enum
+ : bool
+ {
+ SyncCallType = false, AsyncCallType = true
+ } CallType;
+
+ virtual ~CAmDelegate()
+ {
+ }
+
+ virtual CallType call(int *pipe) = 0;
+
+ };
/**
- * \defgroup Deprecated Obsolete class!
- * @{
+ * Prototype for a delegate with variadic template arguments in conjunction with the following class.
*/
+ template<class Class, typename Method, typename Tuple, bool Done, int Total, int... N>
+ class CAmDelegateAsyncImpl : public CAmDelegate
+ {
+ Class mInstance;
+ Method mMethod;
+ Tuple mArguments;
+ public:
+ friend class CAmSerializer;
+ static void call(Class instance, Method method, Tuple &&arguments)
+ {
+ CAmDelegateAsyncImpl<Class, Method, Tuple, Total == 1 + sizeof ... (N), Total, N..., sizeof ... (N)>::call(instance, method, std::forward<Tuple>(arguments));
+ }
+
+ CAmDelegateAsyncImpl(Class instance, Method method, Tuple &&arguments)
+ {
+ mInstance = instance;
+ mMethod = method;
+ mArguments = std::move(arguments);
+ }
+
+ CallType call(int *pipe)
+ {
+ (void)pipe;
+ call(mInstance, mMethod, std::forward<Tuple>(mArguments));
+ return (AsyncCallType);
+ }
+
+ };
- namespace V1
+ /**
+ * Prototype for a delegate with variadic template arguments.
+ */
+ template<class Class, typename Method, typename Tuple, int Total, int... N>
+ class CAmDelegateAsyncImpl<Class, Method, Tuple, true, Total, N...> : public CAmDelegate
{
- class CAmSerializer
+ Class mInstance;
+ Method mMethod;
+ Tuple mArguments;
+ public:
+ friend class CAmSerializer;
+ static void call(Class instance, Method method, Tuple &&t)
{
- private:
+ (*instance.*method)(std::get<N>(std::forward<Tuple>(t)) ...);
+ }
- /**
- * Prototype for a delegate
- */
- class CAmDelegate
- {
- public:
-
- typedef enum
- :bool
- {
- SyncCallType = false, AsyncCallType = true
- } CallType;
-
- virtual ~CAmDelegate()
- {
- }
- ;
- virtual CallType call(int* pipe)=0;
-
- };
-
- /**
- * Prototype for a delegate with variadic template arguments in conjunction with the following class.
- */
- template<class Class, typename Method, typename Tuple, bool Done, int Total, int ... N>
- class CAmDelegateAsyncImpl: public CAmDelegate
- {
- Class mInstance;
- Method mMethod;
- Tuple mArguments;
- public:
- friend class CAmSerializer;
- static void call(Class instance, Method method, Tuple && arguments)
- {
- CAmDelegateAsyncImpl<Class, Method, Tuple, Total == 1 + sizeof...(N), Total, N..., sizeof...(N)>::call(instance, method, std::forward<Tuple>(arguments));
- }
-
- CAmDelegateAsyncImpl(Class instance, Method method, Tuple && arguments)
- {
- mInstance = instance;
- mMethod = method;
- mArguments = std::move(arguments);
- }
-
- CallType call(int* pipe)
- {
- (void) pipe;
- call(mInstance, mMethod, std::forward<Tuple>(mArguments));
- return (AsyncCallType);
- }
- ;
- };
-
- /**
- * Prototype for a delegate with variadic template arguments.
- */
- template<class Class, typename Method, typename Tuple, int Total, int ... N>
- class CAmDelegateAsyncImpl<Class, Method, Tuple, true, Total, N...> : public CAmDelegate
- {
- Class mInstance;
- Method mMethod;
- Tuple mArguments;
- public:
- friend class CAmSerializer;
- static void call(Class instance, Method method, Tuple && t)
- {
- (*instance.*method)(std::get<N>(std::forward<Tuple>(t))...);
- }
-
- CAmDelegateAsyncImpl(Class instance, Method method, Tuple && arguments)
- {
- mInstance = instance;
- mMethod = method;
- mArguments = std::move(arguments);
- }
-
- CallType call(int* pipe)
- {
- (void) pipe;
- call(mInstance, mMethod, std::forward<Tuple>(mArguments));
- return (AsyncCallType);
- }
- ;
- };
-
- /**
- * Prototype for a delegate with variadic template arguments in conjunction with the following class.
- */
- template<class Class, typename Method, typename Return, typename Tuple, bool Done, int Total, int ... N>
- class CAmDelegateSyncImpl: public CAmDelegate
- {
- Class mInstance;
- Method mMethod;
- Tuple mArguments;
- Return mReturn;
- public:
- friend class CAmSerializer;
- static void call(Class instance, Method method, Return & result, Tuple && arguments)
- {
- CAmDelegateSyncImpl<Class, Method, Return, Tuple, Total == 1 + sizeof...(N), Total, N..., sizeof...(N)>::call(instance, method, result, std::forward<Tuple>(arguments));
- }
-
- CAmDelegateSyncImpl(Class instance, Method method, Tuple && arguments)
- {
- mInstance = instance;
- mMethod = method;
- mArguments = std::move(arguments);
- }
-
- CallType call(int* pipe)
- {
- call(mInstance, mMethod, mReturn, std::forward<Tuple>(mArguments));
- ssize_t result(-1);
- result = write(pipe[1], this, sizeof(this));
- if (result == -1)
- logError("CAmSerializer: Problem writing into pipe! Error No:", errno);
- return (SyncCallType);
- }
- ;
- };
-
- /**
- * Prototype for a delegate with variadic template arguments.
- */
- template<class Class, typename Method, typename Return, typename Tuple, int Total, int ... N>
- class CAmDelegateSyncImpl<Class, Method, Return, Tuple, true, Total, N...> : public CAmDelegate
- {
- Class mInstance;
- Method mMethod;
- Tuple mArguments;
- Return mReturn;
- public:
- friend class CAmSerializer;
- static void call(Class instance, Method method, Return & result, Tuple && t)
- {
- result = (*instance.*method)(std::get<N>(t)...);
- }
-
- CAmDelegateSyncImpl(Class instance, Method method, Tuple && arguments)
- {
- mInstance = instance;
- mMethod = method;
- mArguments = std::move(arguments);
- }
-
- CallType call(int* pipe)
- {
- call(mInstance, mMethod, mReturn, std::forward<Tuple>(mArguments));
- ssize_t result(-1);
- result = write(pipe[1], this, sizeof(this));
- if (result == -1)
- logError("CAmSerializer: Problem writing into pipe! Error No:", errno);
- return (SyncCallType);
- }
- ;
- };
-
- typedef CAmDelegate* CAmDelegagePtr; //!< pointer to a delegate
-
- public:
- /**
- * instantiates a async delegate with given arguments and sends the delegate pointer over the pipe
- */
- template<typename Class, typename Method, typename Tuple>
- void doAsyncCall(Class intsance, Method method, Tuple & arguments)
- {
- typedef typename std::decay<Tuple>::type ttype;
- typedef CAmDelegateAsyncImpl<Class, Method, Tuple, 0 == std::tuple_size<ttype>::value, std::tuple_size<ttype>::value> AsyncDelegate;
- AsyncDelegate *pImp = new AsyncDelegate(intsance, method, std::forward<Tuple>(arguments));
- send(pImp);
- //Do not delete the pointer. It will be deleted automatically later.
- }
+ CAmDelegateAsyncImpl(Class instance, Method method, Tuple &&arguments)
+ {
+ mInstance = instance;
+ mMethod = method;
+ mArguments = std::move(arguments);
+ }
- /**
- * instantiates a sync delegate with given arguments and sends the delegate pointer over the pipe
- */
- template<typename Class, typename Method, typename Return, typename Tuple>
- void doSyncCall(Class intsance, Method method, Return & result, Tuple & arguments)
- {
- typedef typename std::decay<Tuple>::type ttype;
- typedef CAmDelegateSyncImpl<Class, Method, Return, Tuple, 0 == std::tuple_size<ttype>::value, std::tuple_size<ttype>::value> SyncDelegate;
- SyncDelegate *pImp = new SyncDelegate(intsance, method, std::forward<Tuple>(arguments));
- send(pImp);
- int numReads;
- SyncDelegate *p = NULL;
- if ((numReads = read(mReturnPipe[0], &p, sizeof(p))) == -1)
- {
- logError("CAmSerializer::doSyncCall could not read pipe!");
- throw std::runtime_error("CAmSerializer Could not read pipe!");
- }
- result = std::move(pImp->mReturn);
- arguments = std::move(pImp->mArguments);
- //Delete the pointer.
- delete pImp;
- }
- private:
+ CallType call(int *pipe)
+ {
+ (void)pipe;
+ call(mInstance, mMethod, std::forward<Tuple>(mArguments));
+ return (AsyncCallType);
+ }
- /**
- * rings the line of the pipe and adds the delegate pointer to the queue
- * @param p delegate pointer
- */
- inline void send(CAmDelegagePtr p)
- {
- if (write(mPipe[1], &p, sizeof(p)) == -1)
- {
- throw std::runtime_error("could not write to pipe !");
- }
- }
+ };
- int mPipe[2]; //!< the pipe
- int mReturnPipe[2]; //!< pipe handling returns
- sh_pollHandle_t mHandle;
- CAmSocketHandler* mpSocketHandler;
- std::deque<CAmDelegagePtr> mListDelegatePoiters; //!< intermediate queue to store the pipe results
+ /**
+ * Prototype for a delegate with variadic template arguments in conjunction with the following class.
+ */
+ template<class Class, typename Method, typename Return, typename Tuple, bool Done, int Total, int... N>
+ class CAmDelegateSyncImpl : public CAmDelegate
+ {
+ Class mInstance;
+ Method mMethod;
+ Tuple mArguments;
+ Return mReturn;
+ public:
+ friend class CAmSerializer;
+ static void call(Class instance, Method method, Return &result, Tuple &&arguments)
+ {
+ CAmDelegateSyncImpl<Class, Method, Return, Tuple, Total == 1 + sizeof ... (N), Total, N..., sizeof ... (N)>::call(instance, method, result, std::forward<Tuple>(arguments));
+ }
- public:
+ CAmDelegateSyncImpl(Class instance, Method method, Tuple &&arguments)
+ {
+ mInstance = instance;
+ mMethod = method;
+ mArguments = std::move(arguments);
+ }
- /**
- * get the size of delegate pointers
- */
- int getListDelegatePoiters()
+ CallType call(int *pipe)
+ {
+ call(mInstance, mMethod, mReturn, std::forward<Tuple>(mArguments));
+ ssize_t result(-1);
+ result = write(pipe[1], this, sizeof(this));
+ if (result == -1)
{
- return mListDelegatePoiters.size();
+ logError("CAmSerializer: Problem writing into pipe! Error No:", errno);
}
- /**
- * calls a function with variadic arguments threadsafe
- * @param instance the instance of the class that shall be called
- * @param function the function that shall be called as member function pointer.
- * @param output variable.
- * @tparam TClass the type of the Class to be called
- * @tparam TRet the type of the result
- * @tparam TArgs argument list
- * \section ex Example:
- * @code
- * class MyGreatClass
- * {
- * public:
- * int AGreatMethod(int x);
- * }
- * CAmSerializer serial(&Sockethandler);
- * MyGreatClass anInstance;
- * int result;
- * serial.syncCall<MyGreatClass, int, int>(&anInstance,&MyGreatClass::AGreatMethod, result, 100);
- * @endcode
- */
- template<class TClass, class TRet, class ... TArgs>
- void syncCall(TClass* instance, TRet (TClass::*method)(TArgs ...), TRet & result, TArgs & ... arguments)
- {
- auto t = std::make_tuple(arguments...);
- doSyncCall(instance, method, result, t);
- std::tie(arguments...) = t;
- }
+ return (SyncCallType);
+ }
- /**
- * calls a function with variadic arguments threadsafe
- * @param instance the instance of the class that shall be called
- * @param function the function that shall be called as member function pointer.
- * @tparam TClass the type of the Class to be called
- * @tparam TRet the type of the result
- * @tparam TArgs argument list
- * \section ex Example:
- * @code
- * class MyGreatClass
- * {
- * public:
- * int AGreatMethod(int x);
- * }
- * CAmSerializer serial(&Sockethandler);
- * MyGreatClass anInstance;
- * serial.asyncCall<MyGreatClass, void, int>(&anInstance,&MyGreatClass::AGreatMethod, 100);
- * @endcode
- */
- template<class TClass, class TRet, class ... TArgs>
- void asyncCall(TClass* instance, TRet (TClass::*method)(TArgs ...), TArgs & ... arguments)
- {
- auto t = std::make_tuple(arguments...);
- doAsyncCall(instance, method, t);
- }
+ };
- /**
- * calls a function with no arguments threadsafe
- * @param instance the instance of the class that shall be called
- * @param function the function that shall be called as memberfunction pointer.
- * @tparam TClass1 the type of the Class to be called
- * \section ex Example:
- * @code
- * class myClass
- * {
- * public:
- * void myfunction();
- * }
- * CAmSerializer serial(&Sockethandler);
- * myClass instanceMyClass;
- * serial<CommandSender>(&instanceMyClass,&myClass::myfunction);
- * @endcode
- */
- template<class TClass>
- void asyncCall(TClass* instance, void (TClass::*function)())
- {
- auto t = std::make_tuple();
- doAsyncCall(instance, function, t);
- }
+ /**
+ * Prototype for a delegate with variadic template arguments.
+ */
+ template<class Class, typename Method, typename Return, typename Tuple, int Total, int... N>
+ class CAmDelegateSyncImpl<Class, Method, Return, Tuple, true, Total, N...> : public CAmDelegate
+ {
+ Class mInstance;
+ Method mMethod;
+ Tuple mArguments;
+ Return mReturn;
+ public:
+ friend class CAmSerializer;
+ static void call(Class instance, Method method, Return &result, Tuple &&t)
+ {
+ result = (*instance.*method)(std::get<N>(t) ...);
+ }
- /**
- * calls a function with one arguments asynchronously threadsafe
- * @param instance the instance of the class that shall be called
- * @param function the function that shall be called as memberfunction pointer.
- * @param argument the argument
- * @tparam TClass1 the type of the Class to be called
- * @tparam Targ the type of the argument to be called
- * \section ex Example:
- * @code
- * class myClass
- * {
- * public:
- * void myfunction(int k);
- * }
- * CAmSerializer serial(&Sockethandler);
- * myClass instanceMyClass;
- * serial<CommandSender,int>(&instanceMyClass,&myClass::myfunction,k);
- * @endcode
- *
- */
- template<class TClass1, class Targ>
- void asyncCall(TClass1* instance, void (TClass1::*function)(Targ), Targ argument)
- {
- auto t = std::make_tuple(argument);
- doAsyncCall(instance, function, t);
- }
+ CAmDelegateSyncImpl(Class instance, Method method, Tuple &&arguments)
+ {
+ mInstance = instance;
+ mMethod = method;
+ mArguments = std::move(arguments);
+ }
- /**
- * calls a function with one argument called by reference asynchronously threadsafe
- * @param instance the instance of the class that shall be called
- * @param function the function that shall be called as memberfunction pointer.
- * @param argument the argument
- * @tparam TClass1 the type of the Class to be called
- * @tparam Targ the type of the argument to be called
- * \section ex Example:
- * @code
- * class myClass
- * {
- * public:
- * void myfunction(int k);
- * }
- * CAmSerializer serial(&Sockethandler);
- * myClass instanceMyClass;
- * serial<CommandSender,int>(&instanceMyClass,&myClass::myfunction,k);
- * @endcode
- *
- */
- template<class TClass1, class Targ>
- void asyncCall(TClass1* instance, void (TClass1::*function)(Targ&), Targ& argument)
+ CallType call(int *pipe)
+ {
+ call(mInstance, mMethod, mReturn, std::forward<Tuple>(mArguments));
+ ssize_t result(-1);
+ result = write(pipe[1], this, sizeof(this));
+ if (result == -1)
{
- auto t = std::make_tuple(argument);
- doAsyncCall(instance, function, t);
+ logError("CAmSerializer: Problem writing into pipe! Error No:", errno);
}
- /**
- * calls a function with two arguments asynchronously threadsafe. for more see asyncCall with one argument
- * @param instance pointer to the instance of the class
- * @param function memberfunction poitner
- * @param argument the first argument
- * @param argument1 the second argument
- * @tparam TClass1 the type of the Class to be called
- * @tparam Targ the type of the argument to be called
- * @tparam Targ1 the type of the first argument to be called
- */
- template<class TClass1, class Targ, class Targ1>
- void asyncCall(TClass1* instance, void (TClass1::*function)(Targ argument, Targ1 argument1), Targ argument, Targ1 argument1)
- {
- auto t = std::make_tuple(argument, argument1);
- doAsyncCall(instance, function, t);
- }
+ return (SyncCallType);
+ }
- /**
- * calls a function with two arguments asynchronously threadsafe, first argument is a reference. for more see asyncCall with one argument
- * @param instance pointer to the instance of the class
- * @param function memberfunction poitner
- * @param argument the first argument
- * @param argument1 the second argument
- * @tparam TClass1 the type of the Class to be called
- * @tparam Targ the type of the argument to be called
- * @tparam Targ1 the type of the first argument to be called
- */
- template<class TClass1, class Targ, class Targ1>
- void asyncCall(TClass1* instance, void (TClass1::*function)(Targ& argument, Targ1 argument1), Targ& argument, Targ1 argument1)
- {
- auto t = std::make_tuple(argument, argument1);
- doAsyncCall(instance, function, t);
- }
+ };
- /**
- * calls a function with two arguments asynchronously threadsafe, second argument is a reference. for more see asyncCall with one argument
- * @param instance pointer to the instance of the class
- * @param function memberfunction poitner
- * @param argument the first argument
- * @param argument1 the second argument
- * @tparam TClass1 the type of the Class to be called
- * @tparam Targ the type of the argument to be called
- * @tparam Targ1 the type of the first argument to be called
- */
- template<class TClass1, class Targ, class Targ1>
- void asyncCall(TClass1* instance, void (TClass1::*function)(Targ argument, Targ1& argument1), Targ argument, Targ1& argument1)
- {
- auto t = std::make_tuple(argument, argument1);
- doAsyncCall(instance, function, t);
- }
+ typedef CAmDelegate *CAmDelegagePtr; //!< pointer to a delegate
- /**
- * calls a function with two arguments asynchronously threadsafe, both arguments are references. for more see asyncCall with one argument
- * @param instance pointer to the instance of the class
- * @param function memberfunction poitner
- * @param argument the first argument
- * @param argument1 the second argument
- * @tparam TClass1 the type of the Class to be called
- * @tparam Targ the type of the argument to be called
- * @tparam Targ1 the type of the first argument to be called
- */
- template<class TClass1, class Targ, class Targ1>
- void asyncCall(TClass1* instance, void (TClass1::*function)(Targ& argument, Targ1& argument1), Targ& argument, Targ1& argument1)
- {
- auto t = std::make_tuple(argument, argument1);
- doAsyncCall(instance, function, t);
- }
+public:
+ /**
+ * instantiates a async delegate with given arguments and sends the delegate pointer over the pipe
+ */
+ template<typename Class, typename Method, typename Tuple>
+ void doAsyncCall(Class intsance, Method method, Tuple &arguments)
+ {
+ typedef typename std::decay<Tuple>::type ttype;
+ typedef CAmDelegateAsyncImpl<Class, Method, Tuple, 0 == std::tuple_size<ttype>::value, std::tuple_size<ttype>::value> AsyncDelegate;
+ AsyncDelegate *pImp = new AsyncDelegate(intsance, method, std::forward<Tuple>(arguments));
+ send(pImp);
+ // Do not delete the pointer. It will be deleted automatically later.
+ }
- /**
- * calls a function with three arguments asynchronously threadsafe. for more see other asycCall
- */
- template<class TClass1, class Targ, class Targ1, class Targ2>
- void asyncCall(TClass1* instance, void (TClass1::*function)(Targ argument, Targ1 argument1, Targ2 argument2), Targ argument, Targ1 argument1, Targ2 argument2)
- {
- auto t = std::make_tuple(argument, argument1, argument2);
- doAsyncCall(instance, function, t);
- }
+ /**
+ * instantiates a sync delegate with given arguments and sends the delegate pointer over the pipe
+ */
+ template<typename Class, typename Method, typename Return, typename Tuple>
+ void doSyncCall(Class intsance, Method method, Return &result, Tuple &arguments)
+ {
+ typedef typename std::decay<Tuple>::type ttype;
+ typedef CAmDelegateSyncImpl<Class, Method, Return, Tuple, 0 == std::tuple_size<ttype>::value, std::tuple_size<ttype>::value> SyncDelegate;
+ SyncDelegate *pImp = new SyncDelegate(intsance, method, std::forward<Tuple>(arguments));
+ send(pImp);
+ int numReads;
+ SyncDelegate *p = NULL;
+ if ((numReads = read(mReturnPipe[0], &p, sizeof(p))) == -1)
+ {
+ logError("CAmSerializer::doSyncCall could not read pipe!");
+ throw std::runtime_error("CAmSerializer Could not read pipe!");
+ }
- /**
- * calls a function with three arguments asynchronously threadsafe. for more see other asycCall
- */
- template<class TClass1, class Targ, class Targ1, class Targ2>
- void asyncCall(TClass1* instance, void (TClass1::*function)(Targ& argument, Targ1 argument1, Targ2 argument2), Targ& argument, Targ1 argument1, Targ2 argument2)
- {
- auto t = std::make_tuple(argument, argument1, argument2);
- doAsyncCall(instance, function, t);
- }
+ result = std::move(pImp->mReturn);
+ arguments = std::move(pImp->mArguments);
+ // Delete the pointer.
+ delete pImp;
+ }
- /**
- * calls a function with three arguments asynchronously threadsafe. for more see other asycCall
- */
- template<class TClass1, class Targ, class Targ1, class Targ2>
- void asyncCall(TClass1* instance, void (TClass1::*function)(Targ argument, Targ1& argument1, Targ2 argument2), Targ argument, Targ1& argument1, Targ2 argument2)
- {
- auto t = std::make_tuple(argument, argument1, argument2);
- doAsyncCall(instance, function, t);
- }
+private:
- /**
- * calls a function with three arguments asynchronously threadsafe. for more see other asycCall
- */
- template<class TClass1, class Targ, class Targ1, class Targ2>
- void asyncCall(TClass1* instance, void (TClass1::*function)(Targ argument, Targ1 argument1, Targ2& argument2), Targ argument, Targ1 argument1, Targ2& argument2)
- {
- auto t = std::make_tuple(argument, argument1, argument2);
- doAsyncCall(instance, function, t);
- }
+ /**
+ * rings the line of the pipe and adds the delegate pointer to the queue
+ * @param p delegate pointer
+ */
+ inline void send(CAmDelegagePtr p)
+ {
+ if (write(mPipe[1], &p, sizeof(p)) == -1)
+ {
+ throw std::runtime_error("could not write to pipe !");
+ }
+ }
- /**
- * calls a function with three arguments asynchronously threadsafe. for more see other asycCall
- */
- template<class TClass1, class Targ, class Targ1, class Targ2>
- void asyncCall(TClass1* instance, void (TClass1::*function)(Targ argument, Targ1& argument1, Targ2& argument2), Targ argument, Targ1& argument1, Targ2& argument2)
- {
- auto t = std::make_tuple(argument, argument1, argument2);
- doAsyncCall(instance, function, t);
- }
+ int mPipe[2]; //!< the pipe
+ int mReturnPipe[2]; //!< pipe handling returns
+ sh_pollHandle_t mHandle;
+ CAmSocketHandler *mpSocketHandler;
+ std::deque<CAmDelegagePtr> mListDelegatePoiters; //!< intermediate queue to store the pipe results
- /**
- * calls a function with three arguments asynchronously threadsafe. for more see other asycCall
- */
- template<class TClass1, class Targ, class Targ1, class Targ2>
- void asyncCall(TClass1* instance, void (TClass1::*function)(Targ& argument, Targ1& argument1, Targ2& argument2), Targ& argument, Targ1& argument1, Targ2& argument2)
- {
- auto t = std::make_tuple(argument, argument1, argument2);
- doAsyncCall(instance, function, t);
- }
+public:
- /**
- * calls a function with three arguments asynchronously threadsafe. for more see other asycCall
- */
- template<class TClass1, class Targ, class Targ1, class Targ2>
- void asyncCall(TClass1* instance, void (TClass1::*function)(Targ& argument, Targ1& argument1, Targ2 argument2), Targ& argument, Targ1& argument1, Targ2 argument2)
- {
- auto t = std::make_tuple(argument, argument1, argument2);
- doAsyncCall(instance, function, t);
- }
+ /**
+ * get the size of delegate pointers
+ */
+ int getListDelegatePoiters()
+ {
+ return mListDelegatePoiters.size();
+ }
- /**
- * calls a function with three arguments asynchronously threadsafe. for more see other asycCall
- */
- template<class TClass1, class Targ, class Targ1, class Targ2>
- void asyncCall(TClass1* instance, void (TClass1::*function)(Targ& argument, Targ1 argument1, Targ2& argument2), Targ& argument, Targ1 argument1, Targ2& argument2)
- {
- auto t = std::make_tuple(argument, argument1, argument2);
- doAsyncCall(instance, function, t);
- }
+ /**
+ * calls a function with variadic arguments threadsafe
+ * @param instance the instance of the class that shall be called
+ * @param function the function that shall be called as member function pointer.
+ * @param output variable.
+ * @tparam TClass the type of the Class to be called
+ * @tparam TRet the type of the result
+ * @tparam TArgs argument list
+ * \section ex Example:
+ * @code
+ * class MyGreatClass
+ * {
+ * public:
+ * int AGreatMethod(int x);
+ * }
+ * CAmSerializer serial(&Sockethandler);
+ * MyGreatClass anInstance;
+ * int result;
+ * serial.syncCall<MyGreatClass, int, int>(&anInstance,&MyGreatClass::AGreatMethod, result, 100);
+ * @endcode
+ */
+ template<class TClass, class TRet, class... TArgs>
+ void syncCall(TClass *instance, TRet (TClass::*method)(TArgs...), TRet &result, TArgs & ... arguments)
+ {
+ auto t = std::make_tuple(arguments...);
+ doSyncCall(instance, method, result, t);
+ std::tie(arguments...) = t;
+ }
- /**
- * calls a function with four arguments asynchronously threadsafe. for more see other asycCall
- */
- template<class TClass1, class Targ, class Targ1, class Targ2, class Targ3>
- void asyncCall(TClass1* instance, void (TClass1::*function)(Targ argument, Targ1 argument1, Targ2 argument2, Targ3 argument3), Targ argument, Targ1 argument1, Targ2 argument2, Targ3 argument3)
- {
- auto t = std::make_tuple(argument, argument1, argument2, argument3);
- doAsyncCall(instance, function, t);
- }
+ /**
+ * calls a function with variadic arguments threadsafe
+ * @param instance the instance of the class that shall be called
+ * @param function the function that shall be called as member function pointer.
+ * @tparam TClass the type of the Class to be called
+ * @tparam TRet the type of the result
+ * @tparam TArgs argument list
+ * \section ex Example:
+ * @code
+ * class MyGreatClass
+ * {
+ * public:
+ * int AGreatMethod(int x);
+ * }
+ * CAmSerializer serial(&Sockethandler);
+ * MyGreatClass anInstance;
+ * serial.asyncCall<MyGreatClass, void, int>(&anInstance,&MyGreatClass::AGreatMethod, 100);
+ * @endcode
+ */
+ template<class TClass, class TRet, class... TArgs>
+ void asyncCall(TClass *instance, TRet (TClass::*method)(TArgs...), TArgs & ... arguments)
+ {
+ auto t = std::make_tuple(arguments...);
+ doAsyncCall(instance, method, t);
+ }
- /**
- * calls a synchronous function with no arguments threadsafe
- * @param instance the instance of the class that shall be called
- * @param function the function that shall be called as memberfunction pointer.
- * @param retVal the return parameter, no const allowed !
- * @tparam TClass1 the type of the class to be called
- * @tparam TretVal the type of the return parameter
- * \section ex Example:
- * @code
- * class myClass
- * {
- * public:
- * am_Error_e myfunction();
- * }
- * CAmSerializer serial(&Sockethandler);
- * myClass instanceMyClass;
- * am_Error_e error;
- * serial<CommandSender,am_Error_e>(&instanceMyClass,&myClass::myfunction, error);
- * @endcode
- * All arguments given to synchronous functions must be non-const since the results of the operations will be written back to the arguments.
- *
- */
- template<class TClass1, class TretVal>
- void syncCall(TClass1* instance, TretVal (TClass1::*function)(), TretVal& retVal)
- {
- auto t = std::make_tuple();
- doSyncCall(instance, function, retVal, t);
- }
+ /**
+ * calls a function with no arguments threadsafe
+ * @param instance the instance of the class that shall be called
+ * @param function the function that shall be called as memberfunction pointer.
+ * @tparam TClass1 the type of the Class to be called
+ * \section ex Example:
+ * @code
+ * class myClass
+ * {
+ * public:
+ * void myfunction();
+ * }
+ * CAmSerializer serial(&Sockethandler);
+ * myClass instanceMyClass;
+ * serial<CommandSender>(&instanceMyClass,&myClass::myfunction);
+ * @endcode
+ */
+ template<class TClass>
+ void asyncCall(TClass *instance, void (TClass::*function)())
+ {
+ auto t = std::make_tuple();
+ doAsyncCall(instance, function, t);
+ }
- /**
- * calls a function with one argument synchronous threadsafe
- * @param instance the instance of the class that shall be called
- * @param function the function that shall be called as memberfunction pointer.
- * @param retVal the return parameter, no const allowed !
- * @param argument the argument, no const allowed !
- * @tparam TClass1 the type of the class to be called
- * @tparam TretVal the type of the return parameter
- * @tparam TargCall the type of the argument like in the function to be called. here all references and const must be
- * respected!
- * @tparam Targ the type of the argument, here no const and no references allowed !
- * \section ex Example:
- * @code
- * class myClass
- * {
- * public:
- * am_Error_e myfunction(int k);
- * }
- * CAmSerializer serial(&Sockethandler);
- * myClass instanceMyClass;
- * am_Error_e error;
- * int l;
- * serial<CommandSender,am_Error_e,int>(&instanceMyClass,&myClass::myfunction,error,l);
- * @endcode
- * All arguments given to synchronous functions must be non-const since the results of the operations will be written back to the arguments.
- */
- template<class TClass1, class TretVal, class TargCall, class Targ>
- void syncCall(TClass1* instance, TretVal (TClass1::*function)(TargCall), TretVal& retVal, Targ& argument)
- {
- auto t = std::make_tuple(argument);
- doSyncCall(instance, function, retVal, t);
- std::tie(argument) = t;
- }
+ /**
+ * calls a function with one arguments asynchronously threadsafe
+ * @param instance the instance of the class that shall be called
+ * @param function the function that shall be called as memberfunction pointer.
+ * @param argument the argument
+ * @tparam TClass1 the type of the Class to be called
+ * @tparam Targ the type of the argument to be called
+ * \section ex Example:
+ * @code
+ * class myClass
+ * {
+ * public:
+ * void myfunction(int k);
+ * }
+ * CAmSerializer serial(&Sockethandler);
+ * myClass instanceMyClass;
+ * serial<CommandSender,int>(&instanceMyClass,&myClass::myfunction,k);
+ * @endcode
+ *
+ */
+ template<class TClass1, class Targ>
+ void asyncCall(TClass1 *instance, void (TClass1::*function)(Targ), Targ argument)
+ {
+ auto t = std::make_tuple(argument);
+ doAsyncCall(instance, function, t);
+ }
- /**
- * calls a function with one argument synchronous threadsafe for const functions. For more see syncCall with one argument
- */
- template<class TClass1, class TretVal, class TargCall, class Targ>
- void syncCall(TClass1* instance, TretVal (TClass1::*function)(TargCall) const, TretVal& retVal, Targ& argument)
- {
- auto t = std::make_tuple(argument);
- doSyncCall(instance, function, retVal, t);
- std::tie(argument) = t;
- }
+ /**
+ * calls a function with one argument called by reference asynchronously threadsafe
+ * @param instance the instance of the class that shall be called
+ * @param function the function that shall be called as memberfunction pointer.
+ * @param argument the argument
+ * @tparam TClass1 the type of the Class to be called
+ * @tparam Targ the type of the argument to be called
+ * \section ex Example:
+ * @code
+ * class myClass
+ * {
+ * public:
+ * void myfunction(int k);
+ * }
+ * CAmSerializer serial(&Sockethandler);
+ * myClass instanceMyClass;
+ * serial<CommandSender,int>(&instanceMyClass,&myClass::myfunction,k);
+ * @endcode
+ *
+ */
+ template<class TClass1, class Targ>
+ void asyncCall(TClass1 *instance, void (TClass1::*function)(Targ &), Targ &argument)
+ {
+ auto t = std::make_tuple(argument);
+ doAsyncCall(instance, function, t);
+ }
- /**
- * calls a function with two arguments synchronously threadsafe. For more see syncCall with one argument
- */
- template<class TClass1, class TretVal, class TargCall, class Targ1Call, class Targ, class Targ1>
- void syncCall(TClass1* instance, TretVal (TClass1::*function)(TargCall, Targ1Call), TretVal& retVal, Targ& argument, Targ1& argument1)
- {
- auto t = std::make_tuple(argument, argument1);
- doSyncCall(instance, function, retVal, t);
- std::tie(argument, argument1) = t;
- }
- /**
- * calls a function with two arguments synchronously threadsafe const. For more see syncCall with one argument
- */
- template<class TClass1, class TretVal, class TargCall, class Targ1Call, class Targ, class Targ1>
- void syncCall(TClass1* instance, TretVal (TClass1::*function)(TargCall, Targ1Call) const, TretVal& retVal, Targ& argument, Targ1& argument1)
- {
- auto t = std::make_tuple(argument, argument1);
- doSyncCall(instance, function, retVal, t);
- std::tie(argument, argument1) = t;
- }
+ /**
+ * calls a function with two arguments asynchronously threadsafe. for more see asyncCall with one argument
+ * @param instance pointer to the instance of the class
+ * @param function memberfunction poitner
+ * @param argument the first argument
+ * @param argument1 the second argument
+ * @tparam TClass1 the type of the Class to be called
+ * @tparam Targ the type of the argument to be called
+ * @tparam Targ1 the type of the first argument to be called
+ */
+ template<class TClass1, class Targ, class Targ1>
+ void asyncCall(TClass1 *instance, void (TClass1::*function)(Targ argument, Targ1 argument1), Targ argument, Targ1 argument1)
+ {
+ auto t = std::make_tuple(argument, argument1);
+ doAsyncCall(instance, function, t);
+ }
- /**
- * calls a function with three arguments synchronously threadsafe. for more see syncCall with one argument
- */
- template<class TClass1, class TretVal, class TargCall, class TargCall1, class TargCall2, class Targ, class Targ1, class Targ2>
- void syncCall(TClass1* instance, TretVal (TClass1::*function)(TargCall, TargCall1, TargCall2), TretVal& retVal, Targ& argument, Targ1& argument1, Targ2& argument2)
- {
- auto t = std::make_tuple(argument, argument1, argument2);
- doSyncCall(instance, function, retVal, t);
- std::tie(argument, argument1, argument2) = t;
- }
+ /**
+ * calls a function with two arguments asynchronously threadsafe, first argument is a reference. for more see asyncCall with one argument
+ * @param instance pointer to the instance of the class
+ * @param function memberfunction poitner
+ * @param argument the first argument
+ * @param argument1 the second argument
+ * @tparam TClass1 the type of the Class to be called
+ * @tparam Targ the type of the argument to be called
+ * @tparam Targ1 the type of the first argument to be called
+ */
+ template<class TClass1, class Targ, class Targ1>
+ void asyncCall(TClass1 *instance, void (TClass1::*function)(Targ & argument, Targ1 argument1), Targ &argument, Targ1 argument1)
+ {
+ auto t = std::make_tuple(argument, argument1);
+ doAsyncCall(instance, function, t);
+ }
- /**
- * calls a const function with three arguments synchronously threadsafe. for more see syncCall with one argument
- */
- template<class TClass1, class TretVal, class TargCall, class TargCall1, class TargCall2, class Targ, class Targ1, class Targ2>
- void syncCall(TClass1* instance, TretVal (TClass1::*function)(TargCall, TargCall1, TargCall2) const, TretVal& retVal, Targ& argument, Targ1& argument1, Targ2& argument2)
- {
- auto t = std::make_tuple(argument, argument1, argument2);
- doSyncCall(instance, function, retVal, t);
- std::tie(argument, argument1, argument2) = t;
- }
+ /**
+ * calls a function with two arguments asynchronously threadsafe, second argument is a reference. for more see asyncCall with one argument
+ * @param instance pointer to the instance of the class
+ * @param function memberfunction poitner
+ * @param argument the first argument
+ * @param argument1 the second argument
+ * @tparam TClass1 the type of the Class to be called
+ * @tparam Targ the type of the argument to be called
+ * @tparam Targ1 the type of the first argument to be called
+ */
+ template<class TClass1, class Targ, class Targ1>
+ void asyncCall(TClass1 *instance, void (TClass1::*function)(Targ argument, Targ1 & argument1), Targ argument, Targ1 &argument1)
+ {
+ auto t = std::make_tuple(argument, argument1);
+ doAsyncCall(instance, function, t);
+ }
- /**
- * calls a function with four arguments synchronously threadsafe. for more see syncCall with one argument
- */
- template<class TClass1, class TretVal, class TargCall, class TargCall1, class TargCall2, class TargCall3, class Targ, class Targ1, class Targ2, class Targ3>
- void syncCall(TClass1* instance, TretVal (TClass1::*function)(TargCall, TargCall1, TargCall2, TargCall3), TretVal& retVal, Targ& argument, Targ1& argument1, Targ2& argument2, Targ3& argument3)
- {
- auto t = std::make_tuple(argument, argument1, argument2, argument3);
- doSyncCall(instance, function, retVal, t);
- std::tie(argument, argument1, argument2, argument3) = t;
- }
+ /**
+ * calls a function with two arguments asynchronously threadsafe, both arguments are references. for more see asyncCall with one argument
+ * @param instance pointer to the instance of the class
+ * @param function memberfunction poitner
+ * @param argument the first argument
+ * @param argument1 the second argument
+ * @tparam TClass1 the type of the Class to be called
+ * @tparam Targ the type of the argument to be called
+ * @tparam Targ1 the type of the first argument to be called
+ */
+ template<class TClass1, class Targ, class Targ1>
+ void asyncCall(TClass1 *instance, void (TClass1::*function)(Targ & argument, Targ1 & argument1), Targ &argument, Targ1 &argument1)
+ {
+ auto t = std::make_tuple(argument, argument1);
+ doAsyncCall(instance, function, t);
+ }
- /**
- * calls a function with five arguments synchronously threadsafe. for more see syncCall with one argument
- */
- template<class TClass1, class TretVal, class TargCall, class TargCall1, class TargCall2, class TargCall3, class TargCall4, class Targ, class Targ1, class Targ2, class Targ3, class Targ4>
- void syncCall(TClass1* instance, TretVal (TClass1::*function)(TargCall, TargCall1, TargCall2, TargCall3, TargCall4), TretVal& retVal, Targ& argument, Targ1& argument1, Targ2& argument2, Targ3& argument3, Targ4& argument4)
- {
- auto t = std::make_tuple(argument, argument1, argument2, argument3, argument4);
- doSyncCall(instance, function, retVal, t);
- std::tie(argument, argument1, argument2, argument3, argument4) = t;
- }
+ /**
+ * calls a function with three arguments asynchronously threadsafe. for more see other asycCall
+ */
+ template<class TClass1, class Targ, class Targ1, class Targ2>
+ void asyncCall(TClass1 *instance, void (TClass1::*function)(Targ argument, Targ1 argument1, Targ2 argument2), Targ argument, Targ1 argument1, Targ2 argument2)
+ {
+ auto t = std::make_tuple(argument, argument1, argument2);
+ doAsyncCall(instance, function, t);
+ }
- /**
- * calls a function with six arguments synchronously threadsafe. for more see syncCall with one argument
- */
- template<class TClass1, class TretVal, class TargCall, class TargCall1, class TargCall2, class TargCall3, class TargCall4, class TargCall5, class Targ, class Targ1, class Targ2, class Targ3, class Targ4, class Targ5>
- void syncCall(TClass1* instance, TretVal (TClass1::*function)(TargCall, TargCall1, TargCall2, TargCall3, TargCall4, TargCall5), TretVal& retVal, Targ& argument, Targ1& argument1, Targ2& argument2, Targ3& argument3,
- Targ4& argument4, Targ5& argument5)
- {
- auto t = std::make_tuple(argument, argument1, argument2, argument3, argument4, argument5);
- doSyncCall(instance, function, retVal, t);
- std::tie(argument, argument1, argument2, argument3, argument4, argument5) = t;
- }
+ /**
+ * calls a function with three arguments asynchronously threadsafe. for more see other asycCall
+ */
+ template<class TClass1, class Targ, class Targ1, class Targ2>
+ void asyncCall(TClass1 *instance, void (TClass1::*function)(Targ & argument, Targ1 argument1, Targ2 argument2), Targ &argument, Targ1 argument1, Targ2 argument2)
+ {
+ auto t = std::make_tuple(argument, argument1, argument2);
+ doAsyncCall(instance, function, t);
+ }
- /**
- * receiver callback for sockethandling, for more, see CAmSocketHandler
- */
- void receiverCallback(const pollfd pollfd, const sh_pollHandle_t handle, void* userData)
- {
- (void) handle;
- (void) userData;
- int numReads;
- CAmDelegagePtr listPointers[3];
- if ((numReads = read(pollfd.fd, &listPointers, sizeof(listPointers))) == -1)
- {
- logError("CAmSerializer::receiverCallback could not read pipe!");
- throw std::runtime_error("CAmSerializer Could not read pipe!");
- }
- mListDelegatePoiters.assign(listPointers, listPointers + (numReads / sizeof(CAmDelegagePtr)));
- }
+ /**
+ * calls a function with three arguments asynchronously threadsafe. for more see other asycCall
+ */
+ template<class TClass1, class Targ, class Targ1, class Targ2>
+ void asyncCall(TClass1 *instance, void (TClass1::*function)(Targ argument, Targ1 & argument1, Targ2 argument2), Targ argument, Targ1 &argument1, Targ2 argument2)
+ {
+ auto t = std::make_tuple(argument, argument1, argument2);
+ doAsyncCall(instance, function, t);
+ }
- /**
- * checker callback for sockethandling, for more, see CAmSocketHandler
- */
- bool checkerCallback(const sh_pollHandle_t handle, void* userData)
- {
- (void) handle;
- (void) userData;
- if (mListDelegatePoiters.empty())
- return (false);
- return (true);
- }
+ /**
+ * calls a function with three arguments asynchronously threadsafe. for more see other asycCall
+ */
+ template<class TClass1, class Targ, class Targ1, class Targ2>
+ void asyncCall(TClass1 *instance, void (TClass1::*function)(Targ argument, Targ1 argument1, Targ2 & argument2), Targ argument, Targ1 argument1, Targ2 &argument2)
+ {
+ auto t = std::make_tuple(argument, argument1, argument2);
+ doAsyncCall(instance, function, t);
+ }
- /**
- * dispatcher callback for sockethandling, for more, see CAmSocketHandler
- */
- bool dispatcherCallback(const sh_pollHandle_t handle, void* userData)
- {
- (void) handle;
- (void) userData;
- CAmDelegagePtr delegatePoiter = mListDelegatePoiters.front();
- mListDelegatePoiters.pop_front();
- if (delegatePoiter->call(mReturnPipe))
- delete delegatePoiter;
- if (mListDelegatePoiters.empty())
- return (false);
- return (true);
- }
+ /**
+ * calls a function with three arguments asynchronously threadsafe. for more see other asycCall
+ */
+ template<class TClass1, class Targ, class Targ1, class Targ2>
+ void asyncCall(TClass1 *instance, void (TClass1::*function)(Targ argument, Targ1 & argument1, Targ2 & argument2), Targ argument, Targ1 &argument1, Targ2 &argument2)
+ {
+ auto t = std::make_tuple(argument, argument1, argument2);
+ doAsyncCall(instance, function, t);
+ }
- TAmShPollFired<CAmSerializer> receiverCallbackT;
- TAmShPollDispatch<CAmSerializer> dispatcherCallbackT;
- TAmShPollCheck<CAmSerializer> checkerCallbackT;
-
- /**
- * The constructor must be called in the mainthread context !
- * @param iSocketHandler pointer to the CAmSocketHandler
- */
- CAmSerializer(CAmSocketHandler *iSocketHandler) :
- mPipe(),
- mReturnPipe(),
- mHandle(),
- mpSocketHandler(iSocketHandler),
- mListDelegatePoiters(),
- receiverCallbackT(this, &CAmSerializer::receiverCallback),
- dispatcherCallbackT(this, &CAmSerializer::dispatcherCallback),
- checkerCallbackT(this, &CAmSerializer::checkerCallback)
- {
- assert(NULL!=iSocketHandler);
-
- if (pipe(mPipe) == -1)
- {
- logError("CAmSerializer could not create pipe!");
- throw std::runtime_error("CAmSerializer Could not open pipe!");
- }
-
- if (pipe(mReturnPipe) == -1)
- {
- logError("CAmSerializer could not create mReturnPipe!");
- throw std::runtime_error("CAmSerializer Could not open mReturnPipe!");
- }
-
- short event = 0;
- event |= POLLIN;
- mpSocketHandler->addFDPoll(mPipe[0], event, NULL, &receiverCallbackT, &checkerCallbackT, &dispatcherCallbackT, NULL, mHandle);
- }
+ /**
+ * calls a function with three arguments asynchronously threadsafe. for more see other asycCall
+ */
+ template<class TClass1, class Targ, class Targ1, class Targ2>
+ void asyncCall(TClass1 *instance, void (TClass1::*function)(Targ & argument, Targ1 & argument1, Targ2 & argument2), Targ &argument, Targ1 &argument1, Targ2 &argument2)
+ {
+ auto t = std::make_tuple(argument, argument1, argument2);
+ doAsyncCall(instance, function, t);
+ }
- ~CAmSerializer()
- {
- mpSocketHandler->removeFDPoll(mHandle);
- close(mPipe[0]);
- close(mPipe[1]);
- close(mReturnPipe[0]);
- close(mReturnPipe[1]);
- }
- };
+ /**
+ * calls a function with three arguments asynchronously threadsafe. for more see other asycCall
+ */
+ template<class TClass1, class Targ, class Targ1, class Targ2>
+ void asyncCall(TClass1 *instance, void (TClass1::*function)(Targ & argument, Targ1 & argument1, Targ2 argument2), Targ &argument, Targ1 &argument1, Targ2 argument2)
+ {
+ auto t = std::make_tuple(argument, argument1, argument2);
+ doAsyncCall(instance, function, t);
+ }
+
+ /**
+ * calls a function with three arguments asynchronously threadsafe. for more see other asycCall
+ */
+ template<class TClass1, class Targ, class Targ1, class Targ2>
+ void asyncCall(TClass1 *instance, void (TClass1::*function)(Targ & argument, Targ1 argument1, Targ2 & argument2), Targ &argument, Targ1 argument1, Targ2 &argument2)
+ {
+ auto t = std::make_tuple(argument, argument1, argument2);
+ doAsyncCall(instance, function, t);
+ }
+
+ /**
+ * calls a function with four arguments asynchronously threadsafe. for more see other asycCall
+ */
+ template<class TClass1, class Targ, class Targ1, class Targ2, class Targ3>
+ void asyncCall(TClass1 *instance, void (TClass1::*function)(Targ argument, Targ1 argument1, Targ2 argument2, Targ3 argument3), Targ argument, Targ1 argument1, Targ2 argument2, Targ3 argument3)
+ {
+ auto t = std::make_tuple(argument, argument1, argument2, argument3);
+ doAsyncCall(instance, function, t);
+ }
- } /* namespace V1 */
+ /**
+ * calls a synchronous function with no arguments threadsafe
+ * @param instance the instance of the class that shall be called
+ * @param function the function that shall be called as memberfunction pointer.
+ * @param retVal the return parameter, no const allowed !
+ * @tparam TClass1 the type of the class to be called
+ * @tparam TretVal the type of the return parameter
+ * \section ex Example:
+ * @code
+ * class myClass
+ * {
+ * public:
+ * am_Error_e myfunction();
+ * }
+ * CAmSerializer serial(&Sockethandler);
+ * myClass instanceMyClass;
+ * am_Error_e error;
+ * serial<CommandSender,am_Error_e>(&instanceMyClass,&myClass::myfunction, error);
+ * @endcode
+ * All arguments given to synchronous functions must be non-const since the results of the operations will be written back to the arguments.
+ *
+ */
+ template<class TClass1, class TretVal>
+ void syncCall(TClass1 *instance, TretVal (TClass1::*function)(), TretVal &retVal)
+ {
+ auto t = std::make_tuple();
+ doSyncCall(instance, function, retVal, t);
+ }
+
+ /**
+ * calls a function with one argument synchronous threadsafe
+ * @param instance the instance of the class that shall be called
+ * @param function the function that shall be called as memberfunction pointer.
+ * @param retVal the return parameter, no const allowed !
+ * @param argument the argument, no const allowed !
+ * @tparam TClass1 the type of the class to be called
+ * @tparam TretVal the type of the return parameter
+ * @tparam TargCall the type of the argument like in the function to be called. here all references and const must be
+ * respected!
+ * @tparam Targ the type of the argument, here no const and no references allowed !
+ * \section ex Example:
+ * @code
+ * class myClass
+ * {
+ * public:
+ * am_Error_e myfunction(int k);
+ * }
+ * CAmSerializer serial(&Sockethandler);
+ * myClass instanceMyClass;
+ * am_Error_e error;
+ * int l;
+ * serial<CommandSender,am_Error_e,int>(&instanceMyClass,&myClass::myfunction,error,l);
+ * @endcode
+ * All arguments given to synchronous functions must be non-const since the results of the operations will be written back to the arguments.
+ */
+ template<class TClass1, class TretVal, class TargCall, class Targ>
+ void syncCall(TClass1 *instance, TretVal (TClass1::*function)(TargCall), TretVal &retVal, Targ &argument)
+ {
+ auto t = std::make_tuple(argument);
+ doSyncCall(instance, function, retVal, t);
+ std::tie(argument) = t;
+ }
+
+ /**
+ * calls a function with one argument synchronous threadsafe for const functions. For more see syncCall with one argument
+ */
+ template<class TClass1, class TretVal, class TargCall, class Targ>
+ void syncCall(TClass1 *instance, TretVal (TClass1::*function)(TargCall) const, TretVal &retVal, Targ &argument)
+ {
+ auto t = std::make_tuple(argument);
+ doSyncCall(instance, function, retVal, t);
+ std::tie(argument) = t;
+ }
+
+ /**
+ * calls a function with two arguments synchronously threadsafe. For more see syncCall with one argument
+ */
+ template<class TClass1, class TretVal, class TargCall, class Targ1Call, class Targ, class Targ1>
+ void syncCall(TClass1 *instance, TretVal (TClass1::*function)(TargCall, Targ1Call), TretVal &retVal, Targ &argument, Targ1 &argument1)
+ {
+ auto t = std::make_tuple(argument, argument1);
+ doSyncCall(instance, function, retVal, t);
+ std::tie(argument, argument1) = t;
+ }
+
+ /**
+ * calls a function with two arguments synchronously threadsafe const. For more see syncCall with one argument
+ */
+ template<class TClass1, class TretVal, class TargCall, class Targ1Call, class Targ, class Targ1>
+ void syncCall(TClass1 *instance, TretVal (TClass1::*function)(TargCall, Targ1Call) const, TretVal &retVal, Targ &argument, Targ1 &argument1)
+ {
+ auto t = std::make_tuple(argument, argument1);
+ doSyncCall(instance, function, retVal, t);
+ std::tie(argument, argument1) = t;
+ }
+
+ /**
+ * calls a function with three arguments synchronously threadsafe. for more see syncCall with one argument
+ */
+ template<class TClass1, class TretVal, class TargCall, class TargCall1, class TargCall2, class Targ, class Targ1, class Targ2>
+ void syncCall(TClass1 *instance, TretVal (TClass1::*function)(TargCall, TargCall1, TargCall2), TretVal &retVal, Targ &argument, Targ1 &argument1, Targ2 &argument2)
+ {
+ auto t = std::make_tuple(argument, argument1, argument2);
+ doSyncCall(instance, function, retVal, t);
+ std::tie(argument, argument1, argument2) = t;
+ }
+
+ /**
+ * calls a const function with three arguments synchronously threadsafe. for more see syncCall with one argument
+ */
+ template<class TClass1, class TretVal, class TargCall, class TargCall1, class TargCall2, class Targ, class Targ1, class Targ2>
+ void syncCall(TClass1 *instance, TretVal (TClass1::*function)(TargCall, TargCall1, TargCall2) const, TretVal &retVal, Targ &argument, Targ1 &argument1, Targ2 &argument2)
+ {
+ auto t = std::make_tuple(argument, argument1, argument2);
+ doSyncCall(instance, function, retVal, t);
+ std::tie(argument, argument1, argument2) = t;
+ }
- /**@}*/
+ /**
+ * calls a function with four arguments synchronously threadsafe. for more see syncCall with one argument
+ */
+ template<class TClass1, class TretVal, class TargCall, class TargCall1, class TargCall2, class TargCall3, class Targ, class Targ1, class Targ2, class Targ3>
+ void syncCall(TClass1 *instance, TretVal (TClass1::*function)(TargCall, TargCall1, TargCall2, TargCall3), TretVal &retVal, Targ &argument, Targ1 &argument1, Targ2 &argument2, Targ3 &argument3)
+ {
+ auto t = std::make_tuple(argument, argument1, argument2, argument3);
+ doSyncCall(instance, function, retVal, t);
+ std::tie(argument, argument1, argument2, argument3) = t;
+ }
- namespace V2
+ /**
+ * calls a function with five arguments synchronously threadsafe. for more see syncCall with one argument
+ */
+ template<class TClass1, class TretVal, class TargCall, class TargCall1, class TargCall2, class TargCall3, class TargCall4, class Targ, class Targ1, class Targ2, class Targ3, class Targ4>
+ void syncCall(TClass1 *instance, TretVal (TClass1::*function)(TargCall, TargCall1, TargCall2, TargCall3, TargCall4), TretVal &retVal, Targ &argument, Targ1 &argument1, Targ2 &argument2, Targ3 &argument3, Targ4 &argument4)
+ {
+ auto t = std::make_tuple(argument, argument1, argument2, argument3, argument4);
+ doSyncCall(instance, function, retVal, t);
+ std::tie(argument, argument1, argument2, argument3, argument4) = t;
+ }
+
+ /**
+ * calls a function with six arguments synchronously threadsafe. for more see syncCall with one argument
+ */
+ template<class TClass1, class TretVal, class TargCall, class TargCall1, class TargCall2, class TargCall3, class TargCall4, class TargCall5, class Targ, class Targ1, class Targ2, class Targ3, class Targ4, class Targ5>
+ void syncCall(TClass1 *instance, TretVal (TClass1::*function)(TargCall, TargCall1, TargCall2, TargCall3, TargCall4, TargCall5), TretVal &retVal, Targ &argument, Targ1 &argument1, Targ2 &argument2, Targ3 &argument3,
+ Targ4 &argument4, Targ5 &argument5)
{
- class CAmSerializer
+ auto t = std::make_tuple(argument, argument1, argument2, argument3, argument4, argument5);
+ doSyncCall(instance, function, retVal, t);
+ std::tie(argument, argument1, argument2, argument3, argument4, argument5) = t;
+ }
+
+ /**
+ * receiver callback for sockethandling, for more, see CAmSocketHandler
+ */
+ void receiverCallback(const pollfd pollfd, const sh_pollHandle_t handle, void *userData)
+ {
+ (void)handle;
+ (void)userData;
+ int numReads;
+ CAmDelegagePtr listPointers[3];
+ if ((numReads = read(pollfd.fd, &listPointers, sizeof(listPointers))) == -1)
{
- /**
- * Prototype for a delegate
- */
- class CAmDelegate
- {
- public:
- typedef enum
- :bool
- {
- SyncCallType = false, AsyncCallType = true
- } CallType;
-
- virtual ~CAmDelegate()
- {
- }
- ;
- virtual CallType call(int* pipe)=0;
- };
-
- /**
- * Prototype for a delegate with variadic template arguments.
- */
- template<class TInvocation>
- class CAmDelegateAsyncImpl: public CAmDelegate
- {
- TInvocation mInvocation;
- public:
- friend class CAmSerializer;
- CAmDelegateAsyncImpl(TInvocation && invocation) :
- mInvocation(std::move(invocation))
- {
- }
-
- CallType call(int* pipe)
- {
- (void) pipe;
- mInvocation();
- return (AsyncCallType);
- }
- ;
- };
-
- template<class TInvocation, class TRet>
- class CAmDelegateSyncImpl: public CAmDelegate
- {
- TInvocation mInvocation;
- TRet & mReturn;
- public:
- friend class CAmSerializer;
- CAmDelegateSyncImpl(TInvocation && invocation, TRet && ret) :
- mInvocation(std::move(invocation)), mReturn(ret)
- {
- }
-
- CallType call(int* pipe)
- {
- mReturn = mInvocation();
- ssize_t result(-1);
- result = write(pipe[1], this, sizeof(this));
- if (result == -1)
- logError("CAmSerializer: Problem writing into pipe! Error No:", errno);
- return (SyncCallType);
- }
- ;
- };
-
- template<class TInvocation>
- class CAmDelegateSyncVoidImpl: public CAmDelegate
- {
- TInvocation mInvocation;
- public:
- friend class CAmSerializer;
- CAmDelegateSyncVoidImpl(TInvocation && invocation) :
- mInvocation(std::move(invocation))
- {
- }
-
- CallType call(int* pipe)
- {
- mInvocation();
- ssize_t result(-1);
- result = write(pipe[1], this, sizeof(this));
- if (result == -1)
- logError("CAmSerializer: Problem writing into pipe! Error No:", errno);
- return (SyncCallType);
- }
- ;
- };
-
- typedef CAmDelegate* CAmDelegagePtr; //!< pointer to a delegate
-
- void sendSync(CAmDelegagePtr pDelegate)
- {
- send(pDelegate);
- int numReads;
- CAmDelegagePtr *p = NULL;
- if ((numReads = read(mReturnPipe[0], &p, sizeof(p))) == -1)
- {
- logError("CAmSerializer::doSyncCall could not read pipe!");
- throw std::runtime_error("CAmSerializer Could not read pipe!");
- }
- }
+ logError("CAmSerializer::receiverCallback could not read pipe!");
+ throw std::runtime_error("CAmSerializer Could not read pipe!");
+ }
- /**
- * rings the line of the pipe and adds the delegate pointer to the queue
- * @param p delegate pointer
- */
- inline void send(CAmDelegagePtr p)
- {
- if (write(mPipe[1], &p, sizeof(p)) == -1)
- {
- throw std::runtime_error("could not write to pipe !");
- }
- }
+ mListDelegatePoiters.assign(listPointers, listPointers + (numReads / sizeof(CAmDelegagePtr)));
+ }
- int mPipe[2]; //!< the pipe
- int mReturnPipe[2]; //!< pipe handling returns
- sh_pollHandle_t mHandle;
- CAmSocketHandler* mpSocketHandler;
- std::deque<CAmDelegagePtr> mListDelegatePointers; //!< intermediate queue to store the pipe results
+ /**
+ * checker callback for sockethandling, for more, see CAmSocketHandler
+ */
+ bool checkerCallback(const sh_pollHandle_t handle, void *userData)
+ {
+ (void)handle;
+ (void)userData;
+ if (mListDelegatePoiters.empty())
+ {
+ return (false);
+ }
- public:
+ return (true);
+ }
- /**
- * get the size of delegate pointers
- */
- size_t getListDelegatePointers()
- {
- return mListDelegatePointers.size();
- }
+ /**
+ * dispatcher callback for sockethandling, for more, see CAmSocketHandler
+ */
+ bool dispatcherCallback(const sh_pollHandle_t handle, void *userData)
+ {
+ (void)handle;
+ (void)userData;
+ CAmDelegagePtr delegatePoiter = mListDelegatePoiters.front();
+ mListDelegatePoiters.pop_front();
+ if (delegatePoiter->call(mReturnPipe))
+ {
+ delete delegatePoiter;
+ }
- /**
- * calls a function with variadic arguments threadsafe
- * @param invocation is a type is produced by std::bind
- * \section ex Example:
- * @code
- * CAmSerializer serial(&Sockethandler);
- * serial.asyncInvocation(std::bind([]()->bool{return true;}));
- * @endcode
- */
- template<class TFunc>
- void asyncInvocation(TFunc invocation)
- {
- static_assert(std::is_bind_expression<TFunc>::value,"The type is not produced by std::bind");
- typedef CAmDelegateAsyncImpl<TFunc> AsyncDelegate;
- AsyncDelegate *pImp = new AsyncDelegate(std::forward<TFunc>(invocation));
- send(pImp);
- //Do not delete the pointer. It will be deleted automatically later.
- }
+ if (mListDelegatePoiters.empty())
+ {
+ return (false);
+ }
- /**
- * calls a function with variadic arguments threadsafe
- * @param instance the instance of the class that shall be called
- * @param function the function that shall be called as member function pointer.
- * @tparam TClass the type of the Class to be called
- * @tparam TRet the type of the result
- * @tparam TArgs argument list
- * \section ex Example:
- * @code
- * class AClass
- * {
- * public:
- * void instanceMethod(int x);
- * }
- * CAmSerializer serial(&Sockethandler);
- * AClass anInstance;
- * serial.asyncCall(&anInstance,&AClass::instanceMethod, 100);
- * @endcode
- */
- template<class TClass, class TMeth, class TRet, class ... TArgs>
- void asyncCall(TClass* instance, TMeth method, TArgs && ... arguments)
- {
- auto invocation = std::bind(method, instance, std::forward<TArgs>(arguments)...);
- asyncInvocation(invocation);
- }
+ return (true);
+ }
- template<class TClass, class TMeth, class ... TArgs>
- void asyncCall(TClass* instance, TMeth method, TArgs && ... arguments)
- {
- auto invocation = std::bind(method, instance, std::forward<TArgs>(arguments)...);
- asyncInvocation(invocation);
- }
+ TAmShPollFired<CAmSerializer> receiverCallbackT;
+ TAmShPollDispatch<CAmSerializer> dispatcherCallbackT;
+ TAmShPollCheck<CAmSerializer> checkerCallbackT;
- /**
- * calls a function with variadic arguments threadsafe
- * @param invocation is a type is produced by std::bind
- * @param result from type TRet
- * \section ex Example:
- * @code
- * CAmSerializer serial(&Sockethandler);
- * bool result;
- * serial.syncCall(std::bind([]()->bool{return true;}), result);
- * @endcode
- */
- template<class TFunc, class TRet>
- void syncInvocation(TFunc invocation, TRet && result)
- {
- static_assert(std::is_bind_expression<TFunc>::value,"The type is not produced by std::bind");
+ /**
+ * The constructor must be called in the mainthread context !
+ * @param iSocketHandler pointer to the CAmSocketHandler
+ */
+ CAmSerializer(CAmSocketHandler *iSocketHandler)
+ : mPipe()
+ , mReturnPipe()
+ , mHandle()
+ , mpSocketHandler(iSocketHandler)
+ , mListDelegatePoiters()
+ , receiverCallbackT(this, &CAmSerializer::receiverCallback)
+ , dispatcherCallbackT(this, &CAmSerializer::dispatcherCallback)
+ , checkerCallbackT(this, &CAmSerializer::checkerCallback)
+ {
+ assert(NULL != iSocketHandler);
- typedef CAmDelegateSyncImpl<TFunc, TRet> SyncDelegate;
+ if (pipe(mPipe) == -1)
+ {
+ logError("CAmSerializer could not create pipe!");
+ throw std::runtime_error("CAmSerializer Could not open pipe!");
+ }
- SyncDelegate *pImp = new SyncDelegate(std::forward<TFunc>(invocation), std::forward<TRet>(result));
- sendSync(pImp);
- //Delete the pointer.
- delete pImp;
- }
+ if (pipe(mReturnPipe) == -1)
+ {
+ logError("CAmSerializer could not create mReturnPipe!");
+ throw std::runtime_error("CAmSerializer Could not open mReturnPipe!");
+ }
- /**
- * calls a function with variadic arguments threadsafe
- * @param invocation is a type produced by std::bind
- * \section ex Example:
- * @code
- * CAmSerializer serial(&Sockethandler);
- * serial.syncCall(std::bind([]()->bool{return true;}));
- * @endcode
- */
- template<class TFunc>
- void syncInvocation(TFunc invocation)
- {
- static_assert(std::is_bind_expression<TFunc>::value,"The type is not produced by std::bind");
+ short event = 0;
+ event |= POLLIN;
+ mpSocketHandler->addFDPoll(mPipe[0], event, NULL, &receiverCallbackT, &checkerCallbackT, &dispatcherCallbackT, NULL, mHandle);
+ }
- typedef CAmDelegateSyncVoidImpl<TFunc> SyncDelegate;
+ ~CAmSerializer()
+ {
+ mpSocketHandler->removeFDPoll(mHandle);
+ close(mPipe[0]);
+ close(mPipe[1]);
+ close(mReturnPipe[0]);
+ close(mReturnPipe[1]);
+ }
- SyncDelegate *pImp = new SyncDelegate(std::forward<TFunc>(invocation));
- sendSync(pImp);
- //Delete the pointer.
- delete pImp;
- }
- /**
- * calls a function with variadic arguments threadsafe
- * @param instance the instance of the class that shall be called
- * @param function the function that shall be called as member function pointer.
- * @param output variable.
- * @tparam TClass the type of the Class to be called
- * @tparam TRet the type of the result
- * @tparam TArgs argument list
- * \section ex Example:
- * @code
- * class AClass
- * {
- * public:
- * int instanceMethod(int x);
- * }
- * CAmSerializer serial(&Sockethandler);
- * AClass anInstance;
- * int result;
- * serial.syncCall(&anInstance,&AClass::instanceMethod, result, 100);
- * @endcode
- */
- template<class TClass, class TMeth, class TRet, class ... TArgs>
- void syncCall(TClass* instance, TMeth method, TRet & result, TArgs && ... arguments)
- {
- auto invocation = std::bind(method, instance, std::ref(arguments)...);
- syncInvocation(invocation, result);
- }
+};
- template<class TClass, class TMeth, class ... TArgs>
- void syncCall(TClass* instance, TMeth method, TArgs && ... arguments)
- {
- auto invocation = std::bind(method, instance, std::ref(arguments)...);
- syncInvocation(invocation);
- }
+} /* namespace V1 */
- /**
- * receiver callback for sockethandling, for more, see CAmSocketHandler
- */
- void receiverCallback(const pollfd pollfd, const sh_pollHandle_t handle, void* userData)
- {
- (void) handle;
- (void) userData;
- int numReads;
- CAmDelegagePtr listPointers[3];
- if ((numReads = read(pollfd.fd, &listPointers, sizeof(listPointers))) == -1)
- {
- logError("CAmSerializer::receiverCallback could not read pipe!");
- throw std::runtime_error("CAmSerializer Could not read pipe!");
- }
- mListDelegatePointers.assign(listPointers, listPointers + (numReads / sizeof(CAmDelegagePtr)));
- }
+/**@}*/
- /**
- * checker callback for sockethandling, for more, see CAmSocketHandler
- */
- bool checkerCallback(const sh_pollHandle_t handle, void* userData)
- {
- (void) handle;
- (void) userData;
- if (mListDelegatePointers.empty())
- return (false);
- return (true);
- }
+namespace V2
+{
+class CAmSerializer
+{
+ /**
+ * Prototype for a delegate
+ */
+ class CAmDelegate
+ {
+ public:
+ typedef enum
+ : bool
+ {
+ SyncCallType = false, AsyncCallType = true
+ } CallType;
- /**
- * dispatcher callback for sockethandling, for more, see CAmSocketHandler
- */
- bool dispatcherCallback(const sh_pollHandle_t handle, void* userData)
- {
- (void) handle;
- (void) userData;
- CAmDelegagePtr delegatePoiter = mListDelegatePointers.front();
- mListDelegatePointers.pop_front();
- if (delegatePoiter->call(mReturnPipe))
- delete delegatePoiter;
- if (mListDelegatePointers.empty())
- return (false);
- return (true);
- }
+ virtual ~CAmDelegate()
+ {
+ }
+
+ virtual CallType call(int *pipe) = 0;
+
+ };
+
+ /**
+ * Prototype for a delegate with variadic template arguments.
+ */
+ template<class TInvocation>
+ class CAmDelegateAsyncImpl : public CAmDelegate
+ {
+ TInvocation mInvocation;
+ public:
+ friend class CAmSerializer;
+ CAmDelegateAsyncImpl(TInvocation &&invocation)
+ : mInvocation(std::move(invocation))
+ {
+ }
+
+ CallType call(int *pipe)
+ {
+ (void)pipe;
+ mInvocation();
+ return (AsyncCallType);
+ }
+
+ };
- TAmShPollFired<CAmSerializer> receiverCallbackT;
- TAmShPollDispatch<CAmSerializer> dispatcherCallbackT;
- TAmShPollCheck<CAmSerializer> checkerCallbackT;
-
- /**
- * The constructor must be called in the mainthread context !
- * @param iSocketHandler pointer to the CAmSocketHandler
- */
- CAmSerializer(CAmSocketHandler *iSocketHandler) :
- mPipe(),
- mReturnPipe(),
- mHandle(),
- mpSocketHandler(iSocketHandler),
- mListDelegatePointers(),
- receiverCallbackT(this, &CAmSerializer::receiverCallback),
- dispatcherCallbackT(this, &CAmSerializer::dispatcherCallback),
- checkerCallbackT(this, &CAmSerializer::checkerCallback)
+ template<class TInvocation, class TRet>
+ class CAmDelegateSyncImpl : public CAmDelegate
+ {
+ TInvocation mInvocation;
+ TRet &mReturn;
+ public:
+ friend class CAmSerializer;
+ CAmDelegateSyncImpl(TInvocation &&invocation, TRet &&ret)
+ : mInvocation(std::move(invocation))
+ , mReturn(ret)
+ {
+ }
+
+ CallType call(int *pipe)
+ {
+ mReturn = mInvocation();
+ ssize_t result(-1);
+ result = write(pipe[1], this, sizeof(this));
+ if (result == -1)
{
- assert(NULL!=iSocketHandler);
-
- if (pipe(mPipe) == -1)
- {
- logError("CAmSerializer could not create pipe!");
- throw std::runtime_error("CAmSerializer Could not open pipe!");
- }
-
- if (pipe(mReturnPipe) == -1)
- {
- logError("CAmSerializer could not create mReturnPipe!");
- throw std::runtime_error("CAmSerializer Could not open mReturnPipe!");
- }
-
- short event = 0;
- event |= POLLIN;
- mpSocketHandler->addFDPoll(mPipe[0], event, NULL, &receiverCallbackT, &checkerCallbackT, &dispatcherCallbackT, NULL, mHandle);
+ logError("CAmSerializer: Problem writing into pipe! Error No:", errno);
}
- ~CAmSerializer()
+ return (SyncCallType);
+ }
+
+ };
+
+ template<class TInvocation>
+ class CAmDelegateSyncVoidImpl : public CAmDelegate
+ {
+ TInvocation mInvocation;
+ public:
+ friend class CAmSerializer;
+ CAmDelegateSyncVoidImpl(TInvocation &&invocation)
+ : mInvocation(std::move(invocation))
+ {
+ }
+
+ CallType call(int *pipe)
+ {
+ mInvocation();
+ ssize_t result(-1);
+ result = write(pipe[1], this, sizeof(this));
+ if (result == -1)
{
- mpSocketHandler->removeFDPoll(mHandle);
- close(mPipe[0]);
- close(mPipe[1]);
- close(mReturnPipe[0]);
- close(mReturnPipe[1]);
+ logError("CAmSerializer: Problem writing into pipe! Error No:", errno);
}
- };
- } /* namespace V2 */
- typedef V1::CAmSerializer CAmSerializer DEPRECATED("You should use V2::CAmSerializer instead!");
+ return (SyncCallType);
+ }
+
+ };
+
+ typedef CAmDelegate *CAmDelegagePtr; //!< pointer to a delegate
+
+ void sendSync(CAmDelegagePtr pDelegate)
+ {
+ send(pDelegate);
+ int numReads;
+ CAmDelegagePtr *p = NULL;
+ if ((numReads = read(mReturnPipe[0], &p, sizeof(p))) == -1)
+ {
+ logError("CAmSerializer::doSyncCall could not read pipe!");
+ throw std::runtime_error("CAmSerializer Could not read pipe!");
+ }
+ }
+
+ /**
+ * rings the line of the pipe and adds the delegate pointer to the queue
+ * @param p delegate pointer
+ */
+ inline void send(CAmDelegagePtr p)
+ {
+ if (write(mPipe[1], &p, sizeof(p)) == -1)
+ {
+ throw std::runtime_error("could not write to pipe !");
+ }
+ }
+
+ int mPipe[2]; //!< the pipe
+ int mReturnPipe[2]; //!< pipe handling returns
+ sh_pollHandle_t mHandle;
+ CAmSocketHandler *mpSocketHandler;
+ std::deque<CAmDelegagePtr> mListDelegatePointers; //!< intermediate queue to store the pipe results
+
+public:
+
+ /**
+ * get the size of delegate pointers
+ */
+ size_t getListDelegatePointers()
+ {
+ return mListDelegatePointers.size();
+ }
+
+ /**
+ * calls a function with variadic arguments threadsafe
+ * @param invocation is a type is produced by std::bind
+ * \section ex Example:
+ * @code
+ * CAmSerializer serial(&Sockethandler);
+ * serial.asyncInvocation(std::bind([]()->bool{return true;}));
+ * @endcode
+ */
+ template<class TFunc>
+ void asyncInvocation(TFunc invocation)
+ {
+ static_assert(std::is_bind_expression<TFunc>::value, "The type is not produced by std::bind");
+ typedef CAmDelegateAsyncImpl<TFunc> AsyncDelegate;
+ AsyncDelegate *pImp = new AsyncDelegate(std::forward<TFunc>(invocation));
+ send(pImp);
+ // Do not delete the pointer. It will be deleted automatically later.
+ }
+
+ /**
+ * calls a function with variadic arguments threadsafe
+ * @param instance the instance of the class that shall be called
+ * @param function the function that shall be called as member function pointer.
+ * @tparam TClass the type of the Class to be called
+ * @tparam TRet the type of the result
+ * @tparam TArgs argument list
+ * \section ex Example:
+ * @code
+ * class AClass
+ * {
+ * public:
+ * void instanceMethod(int x);
+ * }
+ * CAmSerializer serial(&Sockethandler);
+ * AClass anInstance;
+ * serial.asyncCall(&anInstance,&AClass::instanceMethod, 100);
+ * @endcode
+ */
+ template<class TClass, class TMeth, class TRet, class... TArgs>
+ void asyncCall(TClass *instance, TMeth method, TArgs && ... arguments)
+ {
+ auto invocation = std::bind(method, instance, std::forward<TArgs>(arguments) ...);
+ asyncInvocation(invocation);
+ }
+
+ template<class TClass, class TMeth, class... TArgs>
+ void asyncCall(TClass *instance, TMeth method, TArgs && ... arguments)
+ {
+ auto invocation = std::bind(method, instance, std::forward<TArgs>(arguments) ...);
+ asyncInvocation(invocation);
+ }
+
+ /**
+ * calls a function with variadic arguments threadsafe
+ * @param invocation is a type is produced by std::bind
+ * @param result from type TRet
+ * \section ex Example:
+ * @code
+ * CAmSerializer serial(&Sockethandler);
+ * bool result;
+ * serial.syncCall(std::bind([]()->bool{return true;}), result);
+ * @endcode
+ */
+ template<class TFunc, class TRet>
+ void syncInvocation(TFunc invocation, TRet &&result)
+ {
+ static_assert(std::is_bind_expression<TFunc>::value, "The type is not produced by std::bind");
+
+ typedef CAmDelegateSyncImpl<TFunc, TRet> SyncDelegate;
+
+ SyncDelegate *pImp = new SyncDelegate(std::forward<TFunc>(invocation), std::forward<TRet>(result));
+ sendSync(pImp);
+ // Delete the pointer.
+ delete pImp;
+ }
+
+ /**
+ * calls a function with variadic arguments threadsafe
+ * @param invocation is a type produced by std::bind
+ * \section ex Example:
+ * @code
+ * CAmSerializer serial(&Sockethandler);
+ * serial.syncCall(std::bind([]()->bool{return true;}));
+ * @endcode
+ */
+ template<class TFunc>
+ void syncInvocation(TFunc invocation)
+ {
+ static_assert(std::is_bind_expression<TFunc>::value, "The type is not produced by std::bind");
+
+ typedef CAmDelegateSyncVoidImpl<TFunc> SyncDelegate;
+
+ SyncDelegate *pImp = new SyncDelegate(std::forward<TFunc>(invocation));
+ sendSync(pImp);
+ // Delete the pointer.
+ delete pImp;
+ }
+
+ /**
+ * calls a function with variadic arguments threadsafe
+ * @param instance the instance of the class that shall be called
+ * @param function the function that shall be called as member function pointer.
+ * @param output variable.
+ * @tparam TClass the type of the Class to be called
+ * @tparam TRet the type of the result
+ * @tparam TArgs argument list
+ * \section ex Example:
+ * @code
+ * class AClass
+ * {
+ * public:
+ * int instanceMethod(int x);
+ * }
+ * CAmSerializer serial(&Sockethandler);
+ * AClass anInstance;
+ * int result;
+ * serial.syncCall(&anInstance,&AClass::instanceMethod, result, 100);
+ * @endcode
+ */
+ template<class TClass, class TMeth, class TRet, class... TArgs>
+ void syncCall(TClass *instance, TMeth method, TRet &result, TArgs && ... arguments)
+ {
+ auto invocation = std::bind(method, instance, std::ref(arguments) ...);
+ syncInvocation(invocation, result);
+ }
+
+ template<class TClass, class TMeth, class... TArgs>
+ void syncCall(TClass *instance, TMeth method, TArgs && ... arguments)
+ {
+ auto invocation = std::bind(method, instance, std::ref(arguments) ...);
+ syncInvocation(invocation);
+ }
+
+ /**
+ * receiver callback for sockethandling, for more, see CAmSocketHandler
+ */
+ void receiverCallback(const pollfd pollfd, const sh_pollHandle_t handle, void *userData)
+ {
+ (void)handle;
+ (void)userData;
+ int numReads;
+ CAmDelegagePtr listPointers[3];
+ if ((numReads = read(pollfd.fd, &listPointers, sizeof(listPointers))) == -1)
+ {
+ logError("CAmSerializer::receiverCallback could not read pipe!");
+ throw std::runtime_error("CAmSerializer Could not read pipe!");
+ }
+
+ mListDelegatePointers.assign(listPointers, listPointers + (numReads / sizeof(CAmDelegagePtr)));
+ }
+
+ /**
+ * checker callback for sockethandling, for more, see CAmSocketHandler
+ */
+ bool checkerCallback(const sh_pollHandle_t handle, void *userData)
+ {
+ (void)handle;
+ (void)userData;
+ if (mListDelegatePointers.empty())
+ {
+ return (false);
+ }
+
+ return (true);
+ }
+
+ /**
+ * dispatcher callback for sockethandling, for more, see CAmSocketHandler
+ */
+ bool dispatcherCallback(const sh_pollHandle_t handle, void *userData)
+ {
+ (void)handle;
+ (void)userData;
+ CAmDelegagePtr delegatePoiter = mListDelegatePointers.front();
+ mListDelegatePointers.pop_front();
+ if (delegatePoiter->call(mReturnPipe))
+ {
+ delete delegatePoiter;
+ }
+
+ if (mListDelegatePointers.empty())
+ {
+ return (false);
+ }
+
+ return (true);
+ }
+
+ TAmShPollFired<CAmSerializer> receiverCallbackT;
+ TAmShPollDispatch<CAmSerializer> dispatcherCallbackT;
+ TAmShPollCheck<CAmSerializer> checkerCallbackT;
+
+ /**
+ * The constructor must be called in the mainthread context !
+ * @param iSocketHandler pointer to the CAmSocketHandler
+ */
+ CAmSerializer(CAmSocketHandler *iSocketHandler)
+ : mPipe()
+ , mReturnPipe()
+ , mHandle()
+ , mpSocketHandler(iSocketHandler)
+ , mListDelegatePointers()
+ , receiverCallbackT(this, &CAmSerializer::receiverCallback)
+ , dispatcherCallbackT(this, &CAmSerializer::dispatcherCallback)
+ , checkerCallbackT(this, &CAmSerializer::checkerCallback)
+ {
+ assert(NULL != iSocketHandler);
+
+ if (pipe(mPipe) == -1)
+ {
+ logError("CAmSerializer could not create pipe!");
+ throw std::runtime_error("CAmSerializer Could not open pipe!");
+ }
+
+ if (pipe(mReturnPipe) == -1)
+ {
+ logError("CAmSerializer could not create mReturnPipe!");
+ throw std::runtime_error("CAmSerializer Could not open mReturnPipe!");
+ }
+
+ short event = 0;
+ event |= POLLIN;
+ mpSocketHandler->addFDPoll(mPipe[0], event, NULL, &receiverCallbackT, &checkerCallbackT, &dispatcherCallbackT, NULL, mHandle);
+ }
+
+ ~CAmSerializer()
+ {
+ mpSocketHandler->removeFDPoll(mHandle);
+ close(mPipe[0]);
+ close(mPipe[1]);
+ close(mReturnPipe[0]);
+ close(mReturnPipe[1]);
+ }
+
+};
+
+} /* namespace V2 */
+
+typedef V1::CAmSerializer CAmSerializer DEPRECATED ("You should use V2::CAmSerializer instead!");
} /* namespace am */
#endif /* CAMSERIALIZER_H_ */
diff --git a/AudioManagerUtilities/include/CAmSocketHandler.h b/AudioManagerUtilities/include/CAmSocketHandler.h
index 04d19c3..ffd9e71 100644
--- a/AudioManagerUtilities/include/CAmSocketHandler.h
+++ b/AudioManagerUtilities/include/CAmSocketHandler.h
@@ -33,189 +33,205 @@
#ifdef WITH_TIMERFD
-#include <stdio.h>
-#include <string>
-#include <stdexcept>
-#include <unistd.h>
-#include <fcntl.h>
+# include <stdio.h>
+# include <string>
+# include <stdexcept>
+# include <unistd.h>
+# include <fcntl.h>
-#endif
+#endif // ifdef WITH_TIMERFD
namespace am
{
-#define MAX_NS 1000000000L
+#define MAX_NS 1000000000L
#define MAX_TIMERHANDLE UINT16_MAX
-#define MAX_POLLHANDLE UINT16_MAX
+#define MAX_POLLHANDLE UINT16_MAX
-typedef uint16_t sh_pollHandle_t; //!<this is a handle for a filedescriptor to be used with the SocketHandler
-typedef sh_pollHandle_t sh_timerHandle_t; //!<this is a handle for a timer to be used with the SocketHandler
+typedef uint16_t sh_pollHandle_t; //!< this is a handle for a filedescriptor to be used with the SocketHandler
+typedef sh_pollHandle_t sh_timerHandle_t; //!< this is a handle for a timer to be used with the SocketHandler
/**
- * prototype for poll prepared callback
- */
+ * prototype for poll prepared callback
+ */
class IAmShPollPrepare
{
public:
- virtual void Call(const sh_pollHandle_t handle, void* userData) = 0;
+ virtual void Call(const sh_pollHandle_t handle, void *userData) = 0;
+
virtual ~IAmShPollPrepare() {}
};
/**
- * prototype for poll fired callback
- */
+ * prototype for poll fired callback
+ */
class IAmShPollFired
{
public:
- virtual void Call(const pollfd pollfd, const sh_pollHandle_t handle, void* userData) = 0;
- virtual ~ IAmShPollFired() {}
+ virtual void Call(const pollfd pollfd, const sh_pollHandle_t handle, void *userData) = 0;
+
+ virtual ~IAmShPollFired() {}
};
/**
- * prototype for poll check callback
- */
+ * prototype for poll check callback
+ */
class IAmShPollCheck
{
public:
- virtual bool Call(const sh_pollHandle_t handle, void* userData) = 0;
- virtual ~ IAmShPollCheck() {}
+ virtual bool Call(const sh_pollHandle_t handle, void *userData) = 0;
+
+ virtual ~IAmShPollCheck() {}
};
/**
- * prototype for dispatch callback
- */
+ * prototype for dispatch callback
+ */
class IAmShPollDispatch
{
public:
- virtual bool Call(const sh_pollHandle_t handle, void* userData) = 0;
- virtual ~ IAmShPollDispatch() {}
+ virtual bool Call(const sh_pollHandle_t handle, void *userData) = 0;
+
+ virtual ~IAmShPollDispatch() {}
};
/**
- * prototype for the timer callback
- */
+ * prototype for the timer callback
+ */
class IAmShTimerCallBack
{
public:
- IAmShTimerCallBack(){};
- virtual void Call(const sh_timerHandle_t handle, void* userData) = 0;
+ IAmShTimerCallBack(){}
+ virtual void Call(const sh_timerHandle_t handle, void *userData) = 0;
+
virtual ~IAmShTimerCallBack(){}
};
/**make private, not public
- * template for a callback
- */
-template<class TClass> class TAmShPollFired: public IAmShPollFired
+ * template for a callback
+ */
+template<class TClass>
+class TAmShPollFired : public IAmShPollFired
{
private:
- TClass* mInstance;
- void (TClass::*mFunction)(const pollfd pollfd, const sh_pollHandle_t handle, void* userData);
+ TClass *mInstance;
+ void (TClass::*mFunction)(const pollfd pollfd, const sh_pollHandle_t handle, void *userData);
public:
- TAmShPollFired(TClass* instance, void (TClass::*function)(const pollfd pollfd, const sh_pollHandle_t handle, void* userData)) :
- mInstance(instance),
- mFunction(function)
+ TAmShPollFired(TClass *instance, void (TClass::*function)(const pollfd pollfd, const sh_pollHandle_t handle, void *userData))
+ : mInstance(instance)
+ , mFunction(function)
{}
- virtual void Call(const pollfd pollfd, const sh_pollHandle_t handle, void* userData)
+ virtual void Call(const pollfd pollfd, const sh_pollHandle_t handle, void *userData)
{
(*mInstance.*mFunction)(pollfd, handle, userData);
}
+
};
/**
- * template for a callback
- */
-template<class TClass> class TAmShPollCheck: public IAmShPollCheck
+ * template for a callback
+ */
+template<class TClass>
+class TAmShPollCheck : public IAmShPollCheck
{
private:
- TClass* mInstance;
- bool (TClass::*mFunction)(const sh_pollHandle_t handle, void* userData);
+ TClass *mInstance;
+ bool (TClass::*mFunction)(const sh_pollHandle_t handle, void *userData);
public:
- TAmShPollCheck(TClass* instance, bool (TClass::*function)(const sh_pollHandle_t handle, void* userData)) :
- mInstance(instance),
- mFunction(function)
+ TAmShPollCheck(TClass *instance, bool (TClass::*function)(const sh_pollHandle_t handle, void *userData))
+ : mInstance(instance)
+ , mFunction(function)
{}
- virtual bool Call(const sh_pollHandle_t handle, void* userData)
+ virtual bool Call(const sh_pollHandle_t handle, void *userData)
{
return ((*mInstance.*mFunction)(handle, userData));
}
+
};
/**
- * template for a callback
- */
-template<class TClass> class TAmShPollDispatch: public IAmShPollDispatch
+ * template for a callback
+ */
+template<class TClass>
+class TAmShPollDispatch : public IAmShPollDispatch
{
private:
- TClass* mInstance;
- bool (TClass::*mFunction)(const sh_pollHandle_t handle, void* userData);
+ TClass *mInstance;
+ bool (TClass::*mFunction)(const sh_pollHandle_t handle, void *userData);
public:
- TAmShPollDispatch(TClass* instance, bool (TClass::*function)(const sh_pollHandle_t handle, void* userData)) :
- mInstance(instance),
- mFunction(function)
+ TAmShPollDispatch(TClass *instance, bool (TClass::*function)(const sh_pollHandle_t handle, void *userData))
+ : mInstance(instance)
+ , mFunction(function)
{}
- virtual bool Call(const sh_pollHandle_t handle, void* userData)
+ virtual bool Call(const sh_pollHandle_t handle, void *userData)
{
return ((*mInstance.*mFunction)(handle, userData));
}
+
};
/**
- * template to create the functor for a class
- */
-template<class TClass> class TAmShTimerCallBack: public IAmShTimerCallBack
+ * template to create the functor for a class
+ */
+template<class TClass>
+class TAmShTimerCallBack : public IAmShTimerCallBack
{
private:
- TClass* mInstance;
- void (TClass::*mFunction)(sh_timerHandle_t handle, void* userData);
+ TClass *mInstance;
+ void (TClass::*mFunction)(sh_timerHandle_t handle, void *userData);
public:
- TAmShTimerCallBack(TClass* instance, void (TClass::*function)(sh_timerHandle_t handle, void* userData)) :
- IAmShTimerCallBack(), mInstance(instance),
- mFunction(function)
+ TAmShTimerCallBack(TClass *instance, void (TClass::*function)(sh_timerHandle_t handle, void *userData))
+ : IAmShTimerCallBack()
+ , mInstance(instance)
+ , mFunction(function)
{}
- virtual void Call(sh_timerHandle_t handle, void* userData)
+ virtual void Call(sh_timerHandle_t handle, void *userData)
{
(*mInstance.*mFunction)(handle, userData);
}
+
};
/**
- * template for a callback
- */
+ * template for a callback
+ */
-template<class TClass> class TAmShPollPrepare: public IAmShPollPrepare
+template<class TClass>
+class TAmShPollPrepare : public IAmShPollPrepare
{
private:
- TClass* mInstance;
- void (TClass::*mFunction)(const sh_pollHandle_t handle, void* userData);
+ TClass *mInstance;
+ void (TClass::*mFunction)(const sh_pollHandle_t handle, void *userData);
public:
- TAmShPollPrepare(TClass* instance, void (TClass::*function)(const sh_pollHandle_t handle, void* userData)) :
- mInstance(instance),
- mFunction(function)
+ TAmShPollPrepare(TClass *instance, void (TClass::*function)(const sh_pollHandle_t handle, void *userData))
+ : mInstance(instance)
+ , mFunction(function)
{}
- virtual void Call(const sh_pollHandle_t handle, void* userData)
+ virtual void Call(const sh_pollHandle_t handle, void *userData)
{
(*mInstance.*mFunction)(handle, userData);
}
+
};
/**
- * The am::CAmSocketHandler implements a mainloop for the AudioManager. Plugins and different parts of the AudioManager add their filedescriptors to the handler
- * to get called on communication of the filedescriptors.\n
- * More information can be found here : \ref mainl
- */
+ * The am::CAmSocketHandler implements a mainloop for the AudioManager. Plugins and different parts of the AudioManager add their filedescriptors to the handler
+ * to get called on communication of the filedescriptors.\n
+ * More information can be found here : \ref mainl
+ */
class CAmSocketHandler
{
- typedef enum:uint8_t
+ typedef enum : uint8_t
{
ADD = 0u, // new, uninitialized element which needs to be added to ppoll array
UPDATE = 1u, // update of event information therefore update ppoll array
@@ -224,49 +240,60 @@ class CAmSocketHandler
INVALID = 4u // uninit element requested to be removed from internal map only
} poll_states_e;
- struct sh_poll_s //!<struct that holds information about polls
+ struct sh_poll_s //!< struct that holds information about polls
{
- sh_pollHandle_t handle; //!<handle to uniquely adress a filedesriptor
- pollfd pollfdValue; //!<the array for polling the filedescriptors
- std::function<void(const sh_pollHandle_t handle, void* userData)> prepareCB; //preperation callback
- std::function<void(const pollfd pollfd, const sh_pollHandle_t handle, void* userData)> firedCB; //fired callback
- std::function<bool(const sh_pollHandle_t handle, void* userData)> checkCB; //check callback
- std::function<bool(const sh_pollHandle_t handle, void* userData)> dispatchCB; //dispatch callback
- void* userData;
+ sh_pollHandle_t handle; //!< handle to uniquely adress a filedesriptor
+ pollfd pollfdValue; //!< the array for polling the filedescriptors
+ std::function<void(const sh_pollHandle_t handle, void *userData)> prepareCB; // preperation callback
+ std::function<void(const pollfd pollfd, const sh_pollHandle_t handle, void *userData)> firedCB; // fired callback
+ std::function<bool(const sh_pollHandle_t handle, void *userData)> checkCB; // check callback
+ std::function<bool(const sh_pollHandle_t handle, void *userData)> dispatchCB; // dispatch callback
+ void *userData;
poll_states_e state;
- sh_poll_s() :
- handle(0), pollfdValue(), prepareCB(), firedCB(), checkCB(), dispatchCB(), userData(0), state(ADD)
+ sh_poll_s()
+ : handle(0)
+ , pollfdValue()
+ , prepareCB()
+ , firedCB()
+ , checkCB()
+ , dispatchCB()
+ , userData(0)
+ , state(ADD)
{}
};
- struct sh_timer_s //!<struct that holds information of timers
+ struct sh_timer_s //!< struct that holds information of timers
{
- sh_timerHandle_t handle; //!<the handle of the timer
-#ifdef WITH_TIMERFD
+ sh_timerHandle_t handle; //!< the handle of the timer
+#ifdef WITH_TIMERFD
int fd;
- itimerspec countdown; //!<the countdown, this value is decreased every time the timer is up
+ itimerspec countdown; //!< the countdown, this value is decreased every time the timer is up
#else
- timespec countdown; //!<the countdown, this value is decreased every time the timer is up
-#endif
- std::function<void(const sh_timerHandle_t handle, void* userData)> callback; //timer callback
- void* userData;
- sh_timer_s() :
- handle(0)
+ timespec countdown; //!< the countdown, this value is decreased every time the timer is up
+#endif
+ std::function<void(const sh_timerHandle_t handle, void *userData)> callback; // timer callback
+ void *userData;
+ sh_timer_s()
+ : handle(0)
#ifdef WITH_TIMERFD
- , fd(-1)
+ , fd(-1)
#endif
- , countdown(), callback(), userData(0)
+ , countdown()
+ , callback()
+ , userData(0)
{}
};
struct sh_signal_s
{
- sh_pollHandle_t handle; //!<handle to uniquely adress a filedesriptor
- std::function<void(const sh_pollHandle_t handle, const signalfd_siginfo & info, void* userData)> callback;
- void* userData;
- sh_signal_s() :
- handle(0), callback(), userData(0)
+ sh_pollHandle_t handle; //!< handle to uniquely adress a filedesriptor
+ std::function<void(const sh_pollHandle_t handle, const signalfd_siginfo &info, void *userData)> callback;
+ void *userData;
+ sh_signal_s()
+ : handle(0)
+ , callback()
+ , userData(0)
{}
};
@@ -275,17 +302,19 @@ class CAmSocketHandler
std::set<sh_pollHandle_t> pollHandles;
uint16_t limit;
uint16_t lastUsedID;
- sh_identifier_s(const uint16_t pollLimit = UINT16_MAX) :
- pollHandles(), limit(pollLimit), lastUsedID(0)
+ sh_identifier_s(const uint16_t pollLimit = UINT16_MAX)
+ : pollHandles()
+ , limit(pollLimit)
+ , lastUsedID(0)
{}
};
- typedef std::reverse_iterator<sh_timer_s> rListTimerIter; //!<typedef for reverseiterator on timer lists
- typedef std::vector<pollfd> VectorPollfd_t; //!<vector of filedescriptors
- typedef std::map<int, sh_poll_s> MapShPoll_t; //!<list for the callbacks
- typedef std::vector<sh_signal_s> VectorSignalHandlers_t; //!<list for the callbacks
+ typedef std::reverse_iterator<sh_timer_s> rListTimerIter; //!< typedef for reverseiterator on timer lists
+ typedef std::vector<pollfd> VectorPollfd_t; //!< vector of filedescriptors
+ typedef std::map<int, sh_poll_s> MapShPoll_t; //!< list for the callbacks
+ typedef std::vector<sh_signal_s> VectorSignalHandlers_t; //!< list for the callbacks
- typedef enum:uint8_t
+ typedef enum : uint8_t
{
NO_ERROR = 0u, // OK
FD_ERROR = 1u, // Invalid file descriptor
@@ -293,53 +322,55 @@ class CAmSocketHandler
} internal_codes_e;
typedef uint8_t internal_codes_t;
- int mEventFd;
- int mSignalFd;
- bool mDispatchDone; //this starts / stops the mainloop
- MapShPoll_t mMapShPoll; //!<list that holds all information for the ppoll
+ int mEventFd;
+ int mSignalFd;
+ bool mDispatchDone; // this starts / stops the mainloop
+ MapShPoll_t mMapShPoll; //!< list that holds all information for the ppoll
- sh_identifier_s mSetPollKeys; //!A set of all used ppoll keys
- sh_identifier_s mSetTimerKeys; //!A set of all used timer keys
- std::list<sh_timer_s> mListTimer; //!<list of all timers
+ sh_identifier_s mSetPollKeys; //! A set of all used ppoll keys
+ sh_identifier_s mSetTimerKeys; //! A set of all used timer keys
+ std::list<sh_timer_s> mListTimer; //!< list of all timers
#ifndef WITH_TIMERFD
- std::list<sh_timer_s> mListActiveTimer; //!<list of all currently active timers
+ std::list<sh_timer_s> mListActiveTimer; //!< list of all currently active timers
#endif
- sh_identifier_s mSetSignalhandlerKeys; //!A set of all used signal handler keys
+ sh_identifier_s mSetSignalhandlerKeys; //! A set of all used signal handler keys
VectorSignalHandlers_t mSignalHandlers;
- internal_codes_t mInternalCodes;
+ internal_codes_t mInternalCodes;
#ifndef WITH_TIMERFD
- timespec mStartTime; //!<here the actual time is saved for timecorrection
+ timespec mStartTime; //!< here the actual time is saved for timecorrection
#endif
private:
bool fdIsValid(const int fd) const;
- void wakeupWorker(const std::string & func, const uint64_t value = 1u);
+ void wakeupWorker(const std::string &func, const uint64_t value = 1u);
+
+ timespec *insertTime(timespec &buffertime);
- timespec* insertTime(timespec& buffertime);
-#ifdef WITH_TIMERFD
- am_Error_e createTimeFD(const itimerspec & timeouts, int & fd);
-#else
+#ifdef WITH_TIMERFD
+ am_Error_e createTimeFD(const itimerspec &timeouts, int &fd);
+
+#else
void timerUp();
void timerCorrection();
/**
- * compares countdown values
- * @param a
- * @param b
- * @return true if b greater a
- */
- inline static bool compareCountdown(const sh_timer_s& a, const sh_timer_s& b)
+ * compares countdown values
+ * @param a
+ * @param b
+ * @return true if b greater a
+ */
+ inline static bool compareCountdown(const sh_timer_s &a, const sh_timer_s &b)
{
return ((a.countdown.tv_sec == b.countdown.tv_sec) ? (a.countdown.tv_nsec < b.countdown.tv_nsec) : (a.countdown.tv_sec < b.countdown.tv_sec));
}
/**
- * Subtracts b from a
- * @param a
- * @param b
- * @return subtracted value
- */
- inline static timespec timespecSub(const timespec& a, const timespec& b)
+ * Subtracts b from a
+ * @param a
+ * @param b
+ * @return subtracted value
+ */
+ inline static timespec timespecSub(const timespec &a, const timespec &b)
{
timespec result;
@@ -360,136 +391,149 @@ private:
result.tv_nsec = a.tv_nsec - b.tv_nsec;
}
}
+
return (result);
}
/**
- * adds timespec values
- * @param a
- * @param b
- * @return the added values
- */
- inline timespec timespecAdd(const timespec& a, const timespec& b)
+ * adds timespec values
+ * @param a
+ * @param b
+ * @return the added values
+ */
+ inline timespec timespecAdd(const timespec &a, const timespec &b)
{
timespec result;
- result.tv_sec = a.tv_sec + b.tv_sec;
+ result.tv_sec = a.tv_sec + b.tv_sec;
result.tv_nsec = a.tv_nsec + b.tv_nsec;
if (result.tv_nsec >= MAX_NS)
{
result.tv_sec++;
result.tv_nsec = result.tv_nsec - MAX_NS;
}
+
return (result);
}
/**
- * comapares timespec values
- * @param a
- * @param b
- * @return
- */
- inline int timespecCompare(const timespec& a, const timespec& b)
+ * comapares timespec values
+ * @param a
+ * @param b
+ * @return
+ */
+ inline int timespecCompare(const timespec &a, const timespec &b)
{
- //less
+ // less
if (a.tv_sec < b.tv_sec)
- return (-1);
- //greater
+ {
+ return (-1);
+ }
+ // greater
else if (a.tv_sec > b.tv_sec)
- return (1);
- //less
+ {
+ return (1);
+ }
+ // less
else if (a.tv_nsec < b.tv_nsec)
- return (-1);
- //greater
+ {
+ return (-1);
+ }
+ // greater
else if (a.tv_nsec > b.tv_nsec)
- return (1);
- //equal
+ {
+ return (1);
+ }
+
+ // equal
return (0);
}
-#endif
+#endif // ifdef WITH_TIMERFD
/**
- * functor to prepare all fire events
- * @param a
- * @return
- */
- inline static void prepare(sh_poll_s& row);
+ * functor to prepare all fire events
+ * @param a
+ * @return
+ */
+ inline static void prepare(sh_poll_s &row);
/**
- * functor to return all fired events
- * @param a
- * @return
- */
- inline static void fire(const sh_poll_s& a);
+ * functor to return all fired events
+ * @param a
+ * @return
+ */
+ inline static void fire(const sh_poll_s &a);
/**
- * functor to help find the items that do not need dispatching
- * @param a
- * @return
- */
- inline static bool noDispatching(const sh_poll_s* a);
+ * functor to help find the items that do not need dispatching
+ * @param a
+ * @return
+ */
+ inline static bool noDispatching(const sh_poll_s *a);
/**
- * checks if dispatching is already finished
- * @param a
- * @return
- */
- inline static bool dispatchingFinished(const sh_poll_s* a);
+ * checks if dispatching is already finished
+ * @param a
+ * @return
+ */
+ inline static bool dispatchingFinished(const sh_poll_s *a);
/**
- * timer fire callback
- * @param a
- * @return
- */
- inline static void callTimer(sh_timer_s& a);
+ * timer fire callback
+ * @param a
+ * @return
+ */
+ inline static void callTimer(sh_timer_s &a);
/**
- * next handle id
- * @param std::set handles
- * @return handle
- */
- bool nextHandle(sh_identifier_s & handle);
+ * next handle id
+ * @param std::set handles
+ * @return handle
+ */
+ bool nextHandle(sh_identifier_s &handle);
public:
CAmSocketHandler();
~CAmSocketHandler();
-
- /**
+
+ /**
* install the signal fd
*/
- am_Error_e listenToSignals(const std::vector<uint8_t> & listSignals);
-
- am_Error_e addFDPoll(const int fd, const short event, std::function<void(const sh_pollHandle_t handle, void* userData)> prepare, std::function<void(const pollfd pollfd, const sh_pollHandle_t handle, void* userData)> fired,
- std::function<bool(const sh_pollHandle_t handle, void* userData)> check, std::function<bool(const sh_pollHandle_t handle, void* userData)> dispatch, void* userData, sh_pollHandle_t& handle);
+ am_Error_e listenToSignals(const std::vector<uint8_t> &listSignals);
+
+ am_Error_e addFDPoll(const int fd, const short event, std::function<void(const sh_pollHandle_t handle, void *userData)> prepare, std::function<void(const pollfd pollfd, const sh_pollHandle_t handle, void *userData)> fired,
+ std::function<bool(const sh_pollHandle_t handle, void *userData)> check, std::function<bool(const sh_pollHandle_t handle, void *userData)> dispatch, void *userData, sh_pollHandle_t &handle);
- am_Error_e addFDPoll(const int fd, const short event, IAmShPollPrepare *prepare, IAmShPollFired *fired, IAmShPollCheck *check, IAmShPollDispatch *dispatch, void* userData, sh_pollHandle_t& handle);
+ am_Error_e addFDPoll(const int fd, const short event, IAmShPollPrepare *prepare, IAmShPollFired *fired, IAmShPollCheck *check, IAmShPollDispatch *dispatch, void *userData, sh_pollHandle_t &handle);
am_Error_e removeFDPoll(const sh_pollHandle_t handle);
am_Error_e updateEventFlags(const sh_pollHandle_t handle, const short events);
- am_Error_e addSignalHandler(std::function<void(const sh_pollHandle_t handle, const signalfd_siginfo & info, void* userData)> callback, sh_pollHandle_t& handle, void * userData);
+ am_Error_e addSignalHandler(std::function<void(const sh_pollHandle_t handle, const signalfd_siginfo &info, void *userData)> callback, sh_pollHandle_t &handle, void *userData);
am_Error_e removeSignalHandler(const sh_pollHandle_t handle);
- am_Error_e addTimer(const timespec & timeouts, IAmShTimerCallBack* callback, sh_timerHandle_t& handle, void * userData,
+
+ am_Error_e addTimer(const timespec &timeouts, IAmShTimerCallBack *callback, sh_timerHandle_t & handle, void *userData,
#ifndef WITH_TIMERFD
- const bool __attribute__((__unused__)) repeats = false
+ const bool __attribute__((__unused__)) repeats = false
#else
- const bool repeats = false
+ const bool repeats = false
#endif
- );
- am_Error_e addTimer(const timespec & timeouts, std::function<void(const sh_timerHandle_t handle, void* userData)> callback, sh_timerHandle_t& handle, void* userData,
+ );
+ am_Error_e addTimer(const timespec &timeouts, std::function<void(const sh_timerHandle_t handle, void *userData)> callback, sh_timerHandle_t & handle, void *userData,
#ifndef WITH_TIMERFD
- const bool __attribute__((__unused__)) repeats = false
+ const bool __attribute__((__unused__)) repeats = false
#else
- const bool repeats = false
+ const bool repeats = false
#endif
- );
+ );
am_Error_e removeTimer(const sh_timerHandle_t handle);
am_Error_e restartTimer(const sh_timerHandle_t handle);
- am_Error_e updateTimer(const sh_timerHandle_t handle, const timespec & timeouts);
+ am_Error_e updateTimer(const sh_timerHandle_t handle, const timespec &timeouts);
am_Error_e stopTimer(const sh_timerHandle_t handle);
void start_listenting();
void stop_listening();
void exit_mainloop();
-
+
bool fatalErrorOccurred();
+
};
} /* namespace am */
diff --git a/AudioManagerUtilities/include/CAmWatchdog.h b/AudioManagerUtilities/include/CAmWatchdog.h
index 4449c75..bbd2c00 100755..100644
--- a/AudioManagerUtilities/include/CAmWatchdog.h
+++ b/AudioManagerUtilities/include/CAmWatchdog.h
@@ -35,15 +35,16 @@ namespace am
class CAmWatchdog
{
public:
- CAmWatchdog(CAmSocketHandler* CAmSocketHandler);
+ CAmWatchdog(CAmSocketHandler *CAmSocketHandler);
virtual ~CAmWatchdog();
- void startWatchdog(); //!< starts the watchdog by sending ready to systemD
- void timerCallback(sh_timerHandle_t handle, void * userData); //!< the watchdog timer callback
+ void startWatchdog(); //!< starts the watchdog by sending ready to systemD
+ void timerCallback(sh_timerHandle_t handle, void *userData); //!< the watchdog timer callback
+
TAmShTimerCallBack<CAmWatchdog> TimerCallback;
private:
- CAmSocketHandler* mpCAmSocketHandler; //!< pointer to the sockethandler
- sh_timerHandle_t mHandle; //!< handle of the timer
+ CAmSocketHandler *mpCAmSocketHandler; //!< pointer to the sockethandler
+ sh_timerHandle_t mHandle; //!< handle of the timer
};
} /* namespace am */
diff --git a/AudioManagerUtilities/include/TAmPluginTemplate.h b/AudioManagerUtilities/include/TAmPluginTemplate.h
index 95523f1..b030123 100644
--- a/AudioManagerUtilities/include/TAmPluginTemplate.h
+++ b/AudioManagerUtilities/include/TAmPluginTemplate.h
@@ -37,24 +37,25 @@ namespace am
* @param libraryHandle the handle to the library that gets returned
* @return returns the pointer to the class to be loaded
*/
-template<class T> T* getCreateFunction(const std::string& libname, void*& libraryHandle)
+template<class T>
+T *getCreateFunction(const std::string &libname, void * &libraryHandle)
{
- logInfo("getCreateFunction : Trying to load library with name: ",libname);
+ logInfo("getCreateFunction : Trying to load library with name: ", libname);
// cut off directories
- char* fileWithPath = const_cast<char*>(libname.c_str());
- std::string libFileName = basename(fileWithPath);
+ char *fileWithPath = const_cast<char *>(libname.c_str());
+ std::string libFileName = basename(fileWithPath);
// cut off "lib" in front and cut off .so end"
std::string createFunctionName = libFileName.substr(3, libFileName.length() - 6) + "Factory";
// open library
dlerror(); // Clear any existing error
- libraryHandle = dlopen(libname.c_str(), RTLD_LAZY );
- const char* dlopen_error = dlerror();
+ libraryHandle = dlopen(libname.c_str(), RTLD_LAZY);
+ const char *dlopen_error = dlerror();
if (!libraryHandle || dlopen_error)
{
- logError("getCreateFunction : dlopen failed",dlopen_error);
+ logError("getCreateFunction : dlopen failed", dlopen_error);
return (0);
}
@@ -63,8 +64,8 @@ template<class T> T* getCreateFunction(const std::string& libname, void*& librar
union
{
- void* voidPointer;
- T* typedPointer;
+ void *voidPointer;
+ T *typedPointer;
} functionPointer;
// Note: direct cast is not allowed by ISO C++. e.g.
@@ -72,17 +73,18 @@ template<class T> T* getCreateFunction(const std::string& libname, void*& librar
// compiler warning: "forbids casting between pointer-to-function and pointer-to-object"
functionPointer.voidPointer = dlsym(libraryHandle, createFunctionName.c_str());
- T* createFunction = functionPointer.typedPointer;
+ T *createFunction = functionPointer.typedPointer;
- const char* dlsym_error = dlerror();
+ const char *dlsym_error = dlerror();
if (!createFunction || dlsym_error)
{
- logError("getCreateFunction: Failed to load shared lib entry point",dlsym_error);
+ logError("getCreateFunction: Failed to load shared lib entry point", dlsym_error);
}
else
{
logInfo("getCreateFunction : loaded successfully plugin", createFunctionName);
}
+
return (createFunction);
}
@@ -91,13 +93,14 @@ template<class T> T* getCreateFunction(const std::string& libname, void*& librar
* @param libname the full path to the library to be loaded
*
*/
-template<class T> T* getDestroyFunction(const std::string& libname,void* libraryHandle)
+template<class T>
+T *getDestroyFunction(const std::string &libname, void *libraryHandle)
{
- logInfo("destroy : Trying to destroy : ",libname);
+ logInfo("destroy : Trying to destroy : ", libname);
// cut off directories
- char* fileWithPath = const_cast<char*>(libname.c_str());
- std::string libFileName = basename(fileWithPath);
+ char *fileWithPath = const_cast<char *>(libname.c_str());
+ std::string libFileName = basename(fileWithPath);
// cut off "lib" in front and cut off .so end"
std::string destroyFunctionName = "destroy" + libFileName.substr(3, libFileName.length() - 6);
@@ -106,23 +109,24 @@ template<class T> T* getDestroyFunction(const std::string& libname,void* library
dlerror(); // Clear any existing error
union
{
- void* voidPointer;
- T* typedPointer;
+ void *voidPointer;
+ T *typedPointer;
} functionPointer;
functionPointer.voidPointer = dlsym(libraryHandle, destroyFunctionName.c_str());
- T* destroyFunction = functionPointer.typedPointer;
+ T *destroyFunction = functionPointer.typedPointer;
- const char* dlsym_error = dlerror();
+ const char *dlsym_error = dlerror();
if (!destroyFunction || dlsym_error)
{
logError("getDestroyFunction: Failed to load shared lib entry point function name=",
- destroyFunctionName, "error=",dlsym_error);
+ destroyFunctionName, "error=", dlsym_error);
}
else
{
logInfo("getDestroyFunction: loaded successfully plugin", destroyFunctionName);
}
+
return (destroyFunction);
}
diff --git a/AudioManagerUtilities/src/CAmCommandLineSingleton.cpp b/AudioManagerUtilities/src/CAmCommandLineSingleton.cpp
index 1170c31..493b842 100644
--- a/AudioManagerUtilities/src/CAmCommandLineSingleton.cpp
+++ b/AudioManagerUtilities/src/CAmCommandLineSingleton.cpp
@@ -19,41 +19,46 @@
namespace am {
-static TCLAP::CmdLine* pSingleCmdLine = NULL;
+static TCLAP::CmdLine *pSingleCmdLine = NULL;
-CAmCommandLineSingleton::CAmCommandLineSingleton() {
- // TODO Auto-generated constructor stub
+CAmCommandLineSingleton::CAmCommandLineSingleton()
+{
+ // TODO Auto-generated constructor stub
}
-TCLAP::CmdLine* CAmCommandLineSingleton::instanciateOnce(const std::string& message,
- const char delimiter,
- const std::string& version,
- bool helpAndVersion)
+TCLAP::CmdLine *CAmCommandLineSingleton::instanciateOnce(const std::string &message,
+ const char delimiter,
+ const std::string &version,
+ bool helpAndVersion)
{
- if(NULL==pSingleCmdLine)
- {
- pSingleCmdLine = new TCLAP::CmdLine(message,delimiter,version,helpAndVersion);
- }
- return pSingleCmdLine;
+ if (NULL == pSingleCmdLine)
+ {
+ pSingleCmdLine = new TCLAP::CmdLine(message, delimiter, version, helpAndVersion);
+ }
+
+ return pSingleCmdLine;
}
-TCLAP::CmdLine* CAmCommandLineSingleton::instance()
+TCLAP::CmdLine *CAmCommandLineSingleton::instance()
{
- assert(NULL!=pSingleCmdLine);
- return pSingleCmdLine;
+ assert(NULL != pSingleCmdLine);
+ return pSingleCmdLine;
}
void CAmCommandLineSingleton::deleteInstance()
{
- if (pSingleCmdLine)
- delete pSingleCmdLine;
-
- pSingleCmdLine=NULL;
+ if (pSingleCmdLine)
+ {
+ delete pSingleCmdLine;
+ }
+
+ pSingleCmdLine = NULL;
}
-CAmCommandLineSingleton::~CAmCommandLineSingleton() {
- // TODO Auto-generated destructor stub
+CAmCommandLineSingleton::~CAmCommandLineSingleton()
+{
+ // TODO Auto-generated destructor stub
}
} /* namespace am */
diff --git a/AudioManagerUtilities/src/CAmCommonAPIWrapper.cpp b/AudioManagerUtilities/src/CAmCommonAPIWrapper.cpp
index f9cefa6..e22dcd6 100644
--- a/AudioManagerUtilities/src/CAmCommonAPIWrapper.cpp
+++ b/AudioManagerUtilities/src/CAmCommonAPIWrapper.cpp
@@ -30,115 +30,133 @@
#include "CAmDltWrapper.h"
#include "CAmCommonAPIWrapper.h"
-
namespace am
{
-static CAmCommonAPIWrapper* pSingleCommonAPIInstance = NULL;
+static CAmCommonAPIWrapper *pSingleCommonAPIInstance = NULL;
+
+CAmCommonAPIWrapper::CAmCommonAPIWrapper(CAmSocketHandler *socketHandler, const std::string &applicationName)
+ : pCommonPrepareCallback(this, &CAmCommonAPIWrapper::commonPrepareCallback)
+ , pCommonDispatchCallback(this, &CAmCommonAPIWrapper::commonDispatchCallback)
+ , pCommonFireCallback(this, &CAmCommonAPIWrapper::commonFireCallback)
+ , pCommonCheckCallback(this, &CAmCommonAPIWrapper::commonCheckCallback)
+ , pCommonTimerCallback(this, &CAmCommonAPIWrapper::commonTimerCallback)
+ , mpSocketHandler(socketHandler)
+ , mWatchToCheck(NULL)
+{
+ assert(NULL != socketHandler);
+// Get the runtime
+ mRuntime = CommonAPI::Runtime::get();
+ assert(NULL != mRuntime);
+ // Create the context
+ if (applicationName.size())
+ {
+ mContext = std::make_shared<CommonAPI::MainLoopContext>(applicationName);
+ }
+ else
+ {
+ mContext = std::make_shared<CommonAPI::MainLoopContext>();
+ }
-CAmCommonAPIWrapper::CAmCommonAPIWrapper(CAmSocketHandler* socketHandler, const std::string & applicationName):
- pCommonPrepareCallback(this,&CAmCommonAPIWrapper::commonPrepareCallback),
- pCommonDispatchCallback(this, &CAmCommonAPIWrapper::commonDispatchCallback),
- pCommonFireCallback(this, &CAmCommonAPIWrapper::commonFireCallback),
- pCommonCheckCallback(this, &CAmCommonAPIWrapper::commonCheckCallback),
- pCommonTimerCallback(this, &CAmCommonAPIWrapper::commonTimerCallback),
- mpSocketHandler(socketHandler),
- mWatchToCheck(NULL)
-{
- assert(NULL!=socketHandler);
-//Get the runtime
- mRuntime = CommonAPI::Runtime::get();
- assert(NULL!=mRuntime);
-
- //Create the context
- if(applicationName.size())
- mContext = std::make_shared<CommonAPI::MainLoopContext>(applicationName);
- else
- mContext = std::make_shared<CommonAPI::MainLoopContext>();
- assert(NULL!=mContext);
- logInfo(__func__,"CommonAPI main loop context with name '", mContext->getName(), "' has been created!");
-
-//Make subscriptions
- mDispatchSourceListenerSubscription = mContext->subscribeForDispatchSources(
- std::bind(&CAmCommonAPIWrapper::registerDispatchSource, this, std::placeholders::_1, std::placeholders::_2),
- std::bind(&CAmCommonAPIWrapper::deregisterDispatchSource, this, std::placeholders::_1));
- mWatchListenerSubscription = mContext->subscribeForWatches(
- std::bind(&CAmCommonAPIWrapper::registerWatch, this, std::placeholders::_1, std::placeholders::_2),
- std::bind(&CAmCommonAPIWrapper::deregisterWatch, this, std::placeholders::_1));
- mTimeoutSourceListenerSubscription = mContext->subscribeForTimeouts(
- std::bind(&CAmCommonAPIWrapper::registerTimeout, this, std::placeholders::_1, std::placeholders::_2),
- std::bind(&CAmCommonAPIWrapper::deregisterTimeout, this, std::placeholders::_1));
+ assert(NULL != mContext);
+ logInfo(__func__, "CommonAPI main loop context with name '", mContext->getName(), "' has been created!");
+
+// Make subscriptions
+ mDispatchSourceListenerSubscription = mContext->subscribeForDispatchSources(
+ std::bind(&CAmCommonAPIWrapper::registerDispatchSource, this, std::placeholders::_1, std::placeholders::_2),
+ std::bind(&CAmCommonAPIWrapper::deregisterDispatchSource, this, std::placeholders::_1));
+ mWatchListenerSubscription = mContext->subscribeForWatches(
+ std::bind(&CAmCommonAPIWrapper::registerWatch, this, std::placeholders::_1, std::placeholders::_2),
+ std::bind(&CAmCommonAPIWrapper::deregisterWatch, this, std::placeholders::_1));
+ mTimeoutSourceListenerSubscription = mContext->subscribeForTimeouts(
+ std::bind(&CAmCommonAPIWrapper::registerTimeout, this, std::placeholders::_1, std::placeholders::_2),
+ std::bind(&CAmCommonAPIWrapper::deregisterTimeout, this, std::placeholders::_1));
}
CAmCommonAPIWrapper::~CAmCommonAPIWrapper()
{
- mContext->unsubscribeForDispatchSources(mDispatchSourceListenerSubscription);
- mContext->unsubscribeForWatches(mWatchListenerSubscription);
- mContext->unsubscribeForTimeouts(mTimeoutSourceListenerSubscription);
- mContext.reset();
- mpSocketHandler = NULL;
- mWatchToCheck = NULL;
+ mContext->unsubscribeForDispatchSources(mDispatchSourceListenerSubscription);
+ mContext->unsubscribeForWatches(mWatchListenerSubscription);
+ mContext->unsubscribeForTimeouts(mTimeoutSourceListenerSubscription);
+ mContext.reset();
+ mpSocketHandler = NULL;
+ mWatchToCheck = NULL;
}
-CAmCommonAPIWrapper* CAmCommonAPIWrapper::instantiateOnce(CAmSocketHandler* socketHandler, const std::string & applicationName)
+CAmCommonAPIWrapper *CAmCommonAPIWrapper::instantiateOnce(CAmSocketHandler *socketHandler, const std::string &applicationName)
{
- if(NULL==pSingleCommonAPIInstance)
- {
- if(NULL==socketHandler)
- throw std::runtime_error(std::string("Expected a valid socket handler. The socket handler pointer must not be NULL."));
- else
- pSingleCommonAPIInstance = new CAmCommonAPIWrapper(socketHandler, applicationName);
- }
- else
- throw std::logic_error(std::string("The singleton instance has been already instantiated. This method should be called only once."));
- return pSingleCommonAPIInstance;
+ if (NULL == pSingleCommonAPIInstance)
+ {
+ if (NULL == socketHandler)
+ {
+ throw std::runtime_error(std::string("Expected a valid socket handler. The socket handler pointer must not be NULL."));
+ }
+ else
+ {
+ pSingleCommonAPIInstance = new CAmCommonAPIWrapper(socketHandler, applicationName);
+ }
+ }
+ else
+ {
+ throw std::logic_error(std::string("The singleton instance has been already instantiated. This method should be called only once."));
+ }
+
+ return pSingleCommonAPIInstance;
}
void CAmCommonAPIWrapper::deleteInstance()
{
- try
- {
- if (pSingleCommonAPIInstance!=NULL)
- delete pSingleCommonAPIInstance;
-
- pSingleCommonAPIInstance=NULL;
- }
- catch(...)
- {
- logError(__func__,"error while deleting CAPIWrapper instance");
- }
+ try
+ {
+ if (pSingleCommonAPIInstance != NULL)
+ {
+ delete pSingleCommonAPIInstance;
+ }
+
+ pSingleCommonAPIInstance = NULL;
+ }
+ catch (...)
+ {
+ logError(__func__, "error while deleting CAPIWrapper instance");
+ }
}
-CAmCommonAPIWrapper* CAmCommonAPIWrapper::getInstance()
+CAmCommonAPIWrapper *CAmCommonAPIWrapper::getInstance()
{
- assert(NULL!=pSingleCommonAPIInstance);
- return pSingleCommonAPIInstance;
+ assert(NULL != pSingleCommonAPIInstance);
+ return pSingleCommonAPIInstance;
}
bool CAmCommonAPIWrapper::commonDispatchCallback(const sh_pollHandle_t handle, void *userData)
{
- (void) handle;
- (void) userData;
+ (void)handle;
+ (void)userData;
- std::list<CommonAPI::DispatchSource*>::iterator iterator(mSourcesToDispatch.begin());
- for(;iterator!=mSourcesToDispatch.end();)
+ std::list<CommonAPI::DispatchSource *>::iterator iterator(mSourcesToDispatch.begin());
+ for (; iterator != mSourcesToDispatch.end();)
{
- CommonAPI::DispatchSource* source = *iterator;
- if (!source->dispatch()) {
- iterator=mSourcesToDispatch.erase(iterator);
+ CommonAPI::DispatchSource *source = *iterator;
+ if (!source->dispatch())
+ {
+ iterator = mSourcesToDispatch.erase(iterator);
}
else
+ {
iterator++;
+ }
}
+
if (!mSourcesToDispatch.empty())
+ {
return (true);
+ }
return false;
}
bool CAmCommonAPIWrapper::commonCheckCallback(const sh_pollHandle_t, void *)
{
- std::vector<CommonAPI::DispatchSource*> vecDispatch=mWatchToCheck->getDependentDispatchSources();
+ std::vector<CommonAPI::DispatchSource *> vecDispatch = mWatchToCheck->getDependentDispatchSources();
mSourcesToDispatch.insert(mSourcesToDispatch.end(), vecDispatch.begin(), vecDispatch.end());
return (mWatchToCheck || !mSourcesToDispatch.empty());
@@ -146,54 +164,59 @@ bool CAmCommonAPIWrapper::commonCheckCallback(const sh_pollHandle_t, void *)
void CAmCommonAPIWrapper::commonFireCallback(const pollfd pollfd, const sh_pollHandle_t, void *)
{
- mWatchToCheck=NULL;
+ mWatchToCheck = NULL;
try
{
- mWatchToCheck=mMapWatches.at(pollfd.fd);
+ mWatchToCheck = mMapWatches.at(pollfd.fd);
}
- catch (const std::out_of_range& error) {
- logInfo(__PRETTY_FUNCTION__,error.what());
- return;
+ catch (const std::out_of_range &error)
+ {
+ logInfo(__PRETTY_FUNCTION__, error.what());
+ return;
}
mWatchToCheck->dispatch(pollfd.revents);
}
-void CAmCommonAPIWrapper::commonPrepareCallback(const sh_pollHandle_t, void*)
+void CAmCommonAPIWrapper::commonPrepareCallback(const sh_pollHandle_t, void *)
{
for (auto dispatchSourceIterator = mRegisteredDispatchSources.begin();
- dispatchSourceIterator != mRegisteredDispatchSources.end();
- dispatchSourceIterator++)
+ dispatchSourceIterator != mRegisteredDispatchSources.end();
+ dispatchSourceIterator++)
{
int64_t dispatchTimeout(CommonAPI::TIMEOUT_INFINITE);
- if(dispatchSourceIterator->second->prepare(dispatchTimeout))
+ if (dispatchSourceIterator->second->prepare(dispatchTimeout))
{
- while (dispatchSourceIterator->second->dispatch());
+ while (dispatchSourceIterator->second->dispatch())
+ {
+ }
}
}
}
-void CAmCommonAPIWrapper::registerDispatchSource(CommonAPI::DispatchSource* dispatchSource, const CommonAPI::DispatchPriority dispatchPriority)
+void CAmCommonAPIWrapper::registerDispatchSource(CommonAPI::DispatchSource *dispatchSource, const CommonAPI::DispatchPriority dispatchPriority)
{
mRegisteredDispatchSources.insert({dispatchPriority, dispatchSource});
}
-void CAmCommonAPIWrapper::deregisterDispatchSource(CommonAPI::DispatchSource* dispatchSource)
+void CAmCommonAPIWrapper::deregisterDispatchSource(CommonAPI::DispatchSource *dispatchSource)
{
- for(auto dispatchSourceIterator = mRegisteredDispatchSources.begin();
- dispatchSourceIterator != mRegisteredDispatchSources.end();
- dispatchSourceIterator++) {
+ for (auto dispatchSourceIterator = mRegisteredDispatchSources.begin();
+ dispatchSourceIterator != mRegisteredDispatchSources.end();
+ dispatchSourceIterator++)
+ {
- if(dispatchSourceIterator->second == dispatchSource) {
+ if (dispatchSourceIterator->second == dispatchSource)
+ {
mRegisteredDispatchSources.erase(dispatchSourceIterator);
break;
}
}
}
-void CAmCommonAPIWrapper::deregisterWatch(CommonAPI::Watch* watch)
+void CAmCommonAPIWrapper::deregisterWatch(CommonAPI::Watch *watch)
{
- for(std::map<int,CommonAPI::Watch*>::iterator iter(mMapWatches.begin());iter!=mMapWatches.end();iter++)
+ for (std::map<int, CommonAPI::Watch *>::iterator iter(mMapWatches.begin()); iter != mMapWatches.end(); iter++)
{
if (iter->second == watch)
{
@@ -203,82 +226,84 @@ void CAmCommonAPIWrapper::deregisterWatch(CommonAPI::Watch* watch)
}
}
-void CAmCommonAPIWrapper::registerTimeout(CommonAPI::Timeout* timeout, const CommonAPI::DispatchPriority)
+void CAmCommonAPIWrapper::registerTimeout(CommonAPI::Timeout *timeout, const CommonAPI::DispatchPriority)
{
timespec pollTimeout;
- int64_t localTimeout = timeout->getTimeoutInterval();
-
- if(CommonAPI::TIMEOUT_INFINITE==localTimeout)//dispatch never
+ int64_t localTimeout = timeout->getTimeoutInterval();
+
+ if (CommonAPI::TIMEOUT_INFINITE == localTimeout)// dispatch never
{
- pollTimeout.tv_sec = localTimeout;
+ pollTimeout.tv_sec = localTimeout;
pollTimeout.tv_nsec = 0;
}
- else if(CommonAPI::TIMEOUT_NONE==localTimeout)//dispatch immediately
+ else if (CommonAPI::TIMEOUT_NONE == localTimeout)// dispatch immediately
{
- pollTimeout.tv_sec = 0;
- pollTimeout.tv_nsec = 1000000;
+ pollTimeout.tv_sec = 0;
+ pollTimeout.tv_nsec = 1000000;
}
- else
+ else
{
- pollTimeout.tv_sec = localTimeout / 1000;
- pollTimeout.tv_nsec = (localTimeout % 1000) * 1000000;
+ pollTimeout.tv_sec = localTimeout / 1000;
+ pollTimeout.tv_nsec = (localTimeout % 1000) * 1000000;
}
- //prepare handle and callback. new is eval, but there is no other choice because we need the pointer!
+ // prepare handle and callback. new is eval, but there is no other choice because we need the pointer!
sh_timerHandle_t handle;
- //add the timer to the pollLoop
+ // add the timer to the pollLoop
am_Error_e error = mpSocketHandler->addTimer(pollTimeout, &pCommonTimerCallback, handle, timeout);
if (error != am_Error_e::E_OK || handle == 0)
{
- logError(__func__,"adding timer failed");
+ logError(__func__, "adding timer failed");
}
else
{
- timerHandles myHandle({handle,timeout});
- mpListTimerhandles.push_back(myHandle);
+ timerHandles myHandle({handle, timeout});
+ mpListTimerhandles.push_back(myHandle);
}
}
-void CAmCommonAPIWrapper::deregisterTimeout(CommonAPI::Timeout* timeout)
+void CAmCommonAPIWrapper::deregisterTimeout(CommonAPI::Timeout *timeout)
{
- for( std::vector<timerHandles>::iterator iter(mpListTimerhandles.begin());iter!=mpListTimerhandles.end();iter++)
+ for ( std::vector<timerHandles>::iterator iter(mpListTimerhandles.begin()); iter != mpListTimerhandles.end(); iter++)
{
- if(iter->timeout==timeout)
+ if (iter->timeout == timeout)
{
mpSocketHandler->removeTimer(iter->handle);
}
}
}
-void CAmCommonAPIWrapper::registerWatch(CommonAPI::Watch* watch, const CommonAPI::DispatchPriority)
+void CAmCommonAPIWrapper::registerWatch(CommonAPI::Watch *watch, const CommonAPI::DispatchPriority)
{
logInfo(__PRETTY_FUNCTION__);
- pollfd pollfd_ (watch->getAssociatedFileDescriptor());
- sh_pollHandle_t handle (0);
+ pollfd pollfd_(watch->getAssociatedFileDescriptor());
+ sh_pollHandle_t handle(0);
am_Error_e error = mpSocketHandler->addFDPoll(pollfd_.fd, pollfd_.events, &pCommonPrepareCallback, &pCommonFireCallback, &pCommonCheckCallback, &pCommonDispatchCallback, watch, handle);
- //if everything is alright, add the watch and the handle to our map so we know this relationship
+ // if everything is alright, add the watch and the handle to our map so we know this relationship
if (error != am_Error_e::E_OK || handle == 0)
{
- logError(__func__,"entering watch failed");
+ logError(__func__, "entering watch failed");
}
else
- mMapWatches.insert(std::make_pair(pollfd_.fd,watch));
+ {
+ mMapWatches.insert(std::make_pair(pollfd_.fd, watch));
+ }
}
void CAmCommonAPIWrapper::commonTimerCallback(sh_timerHandle_t handle, void *)
{
- for( std::vector<timerHandles>::iterator iter(mpListTimerhandles.begin());iter!=mpListTimerhandles.end();iter++)
+ for ( std::vector<timerHandles>::iterator iter(mpListTimerhandles.begin()); iter != mpListTimerhandles.end(); iter++)
{
- if(iter->handle==handle)
+ if (iter->handle == handle)
{
iter->timeout->dispatch();
}
}
}
-CAmCommonAPIWrapper* (*getCAPI)() = CAmCommonAPIWrapper::getInstance;
+CAmCommonAPIWrapper *(*getCAPI)() = CAmCommonAPIWrapper::getInstance;
}
diff --git a/AudioManagerUtilities/src/CAmDbusWrapper.cpp b/AudioManagerUtilities/src/CAmDbusWrapper.cpp
index 1881526..504bf38 100644
--- a/AudioManagerUtilities/src/CAmDbusWrapper.cpp
+++ b/AudioManagerUtilities/src/CAmDbusWrapper.cpp
@@ -38,36 +38,38 @@ namespace am
/**
* introspectio header
*/
-#define ROOT_INTROSPECT_XML \
-DBUS_INTROSPECT_1_0_XML_DOCTYPE_DECL_NODE \
-"<node>" \
-"<interface name='org.AudioManager.freedesktop.DBus.Introspectable'>" \
-"<method name='Introspect'>" \
-" <arg name='xml_data' type='s' direction='out'/>" \
-"</method>" \
-"</interface>" \
-
-CAmDbusWrapper* CAmDbusWrapper::mpReference = NULL;
-
-CAmDbusWrapper::CAmDbusWrapper(CAmSocketHandler* socketHandler, DBusBusType type, const std::string& prefix, const std::string& objectPath) :
- pDbusPrepareCallback(this,&CAmDbusWrapper::dbusPrepareCallback),
- pDbusDispatchCallback(this, &CAmDbusWrapper::dbusDispatchCallback),
- pDbusFireCallback(this, &CAmDbusWrapper::dbusFireCallback),
- pDbusCheckCallback(this, &CAmDbusWrapper::dbusCheckCallback),
- pDbusTimerCallback(this, &CAmDbusWrapper::dbusTimerCallback),
- mpDbusConnection(0),
- mDBusError(),
- mListNodes(),
- mpListTimerhandles(),
- mpSocketHandler(socketHandler),
- mDbusType(type)
+#define ROOT_INTROSPECT_XML \
+ DBUS_INTROSPECT_1_0_XML_DOCTYPE_DECL_NODE \
+ "<node>" \
+ "<interface name='org.AudioManager.freedesktop.DBus.Introspectable'>" \
+ "<method name='Introspect'>" \
+ " <arg name='xml_data' type='s' direction='out'/>" \
+ "</method>" \
+ "</interface>" \
+
+CAmDbusWrapper *CAmDbusWrapper::mpReference = NULL;
+
+CAmDbusWrapper::CAmDbusWrapper(CAmSocketHandler *socketHandler, DBusBusType type, const std::string &prefix, const std::string &objectPath)
+ : pDbusPrepareCallback(this, &CAmDbusWrapper::dbusPrepareCallback)
+ , pDbusDispatchCallback(this, &CAmDbusWrapper::dbusDispatchCallback)
+ , pDbusFireCallback(this, &CAmDbusWrapper::dbusFireCallback)
+ , pDbusCheckCallback(this, &CAmDbusWrapper::dbusCheckCallback)
+ , pDbusTimerCallback(this, &CAmDbusWrapper::dbusTimerCallback)
+ , mpDbusConnection(0)
+ , mDBusError()
+ , mListNodes()
+ , mpListTimerhandles()
+ , mpSocketHandler(socketHandler)
+ , mDbusType(type)
{
- assert(mpSocketHandler!=0);
+ assert(mpSocketHandler != 0);
dbus_error_init(&mDBusError);
if (!dbus_threads_init_default())
+ {
logError("CAmDbusWrapper::CAmDbusWrapper threads init call failed");
+ }
logInfo("DBusWrapper::DBusWrapper Opening DBus connection of:", prefix, objectPath);
mpDbusConnection = dbus_bus_get(mDbusType, &mDBusError);
@@ -76,6 +78,7 @@ CAmDbusWrapper::CAmDbusWrapper(CAmSocketHandler* socketHandler, DBusBusType type
logError("DBusWrapper::DBusWrapper Error while getting the DBus");
dbus_error_free(&mDBusError);
}
+
if (NULL == mpDbusConnection)
{
logError("DBusWrapper::DBusWrapper DBus Connection is null");
@@ -85,21 +88,21 @@ CAmDbusWrapper::CAmDbusWrapper(CAmSocketHandler* socketHandler, DBusBusType type
logInfo("DBusWrapper::DBusWrapper DBus Connection is", mpDbusConnection);
}
- //then we need to adopt the dbus to our mainloop:
- //first, we are old enought to live longer then the connection:
+ // then we need to adopt the dbus to our mainloop:
+ // first, we are old enought to live longer then the connection:
dbus_connection_set_exit_on_disconnect(mpDbusConnection, FALSE);
- //we do not need the manual dispatching, since it is not allowed to call from a different thread. So leave it uncommented:
- //dbus_connection_set_dispatch_status_function
+ // we do not need the manual dispatching, since it is not allowed to call from a different thread. So leave it uncommented:
+ // dbus_connection_set_dispatch_status_function
- //add watch functions:
+ // add watch functions:
dbus_bool_t watch = dbus_connection_set_watch_functions(mpDbusConnection, addWatch, removeWatch, toogleWatch, this, NULL);
if (!watch)
{
logError("DBusWrapper::DBusWrapper Registering of watch functions failed");
}
- //add timer functions:
+ // add timer functions:
dbus_bool_t timer = dbus_connection_set_timeout_functions(mpDbusConnection, addTimeout, removeTimeout, toggleTimeout, this, NULL);
if (!timer)
{
@@ -112,35 +115,35 @@ CAmDbusWrapper::CAmDbusWrapper(CAmSocketHandler* socketHandler, DBusBusType type
return;
}
- //register callback for Introspectio
+ // register callback for Introspectio
mObjectPathVTable.message_function = CAmDbusWrapper::cbRootIntrospection;
dbus_connection_register_object_path(mpDbusConnection, objectPath.c_str(), &mObjectPathVTable, this);
int ret = dbus_bus_request_name(mpDbusConnection, prefix.c_str(), DBUS_NAME_FLAG_DO_NOT_QUEUE, &mDBusError);
if (DBUS_REQUEST_NAME_REPLY_PRIMARY_OWNER == ret)
{
- logInfo("DBusWrapper::DBusWrapper We own", prefix);
+ logInfo("DBusWrapper::DBusWrapper We own", prefix);
}
else
{
std::ostringstream sserror("DBusWrapper::DBusWrapper ");
switch (ret)
{
- case -1:
- sserror << "Couldn't acquire name " << prefix << ". DBus message: " << mDBusError.message;
- dbus_error_free(&mDBusError);
- break;
- case DBUS_REQUEST_NAME_REPLY_IN_QUEUE:
- sserror << "We are queued for " << prefix;
- break;
- case DBUS_REQUEST_NAME_REPLY_EXISTS:
- sserror << ":-( " << prefix << " already exists!";
- break;
- case DBUS_REQUEST_NAME_REPLY_ALREADY_OWNER:
- sserror << "Eh? We already own " << prefix;
- break;
- default:
- sserror << "Unknown result = " << ret;
- break;
+ case -1:
+ sserror << "Couldn't acquire name " << prefix << ". DBus message: " << mDBusError.message;
+ dbus_error_free(&mDBusError);
+ break;
+ case DBUS_REQUEST_NAME_REPLY_IN_QUEUE:
+ sserror << "We are queued for " << prefix;
+ break;
+ case DBUS_REQUEST_NAME_REPLY_EXISTS:
+ sserror << ":-( " << prefix << " already exists!";
+ break;
+ case DBUS_REQUEST_NAME_REPLY_ALREADY_OWNER:
+ sserror << "Eh? We already own " << prefix;
+ break;
+ default:
+ sserror << "Unknown result = " << ret;
+ break;
}
logError(sserror.str());
@@ -150,12 +153,12 @@ CAmDbusWrapper::CAmDbusWrapper(CAmSocketHandler* socketHandler, DBusBusType type
CAmDbusWrapper::~CAmDbusWrapper()
{
- //close the connection again
+ // close the connection again
logInfo("DBusWrapper::~DBusWrapper Closing DBus connection");
dbus_connection_unref(mpDbusConnection);
- //clean up all timerhandles we created but did not delete before
- std::vector<sh_timerHandle_t*>::iterator it = mpListTimerhandles.begin();
+ // clean up all timerhandles we created but did not delete before
+ std::vector<sh_timerHandle_t *>::iterator it = mpListTimerhandles.begin();
for (; it != mpListTimerhandles.end(); ++it)
{
delete *it;
@@ -170,7 +173,7 @@ CAmDbusWrapper::~CAmDbusWrapper()
* @param userdata pointer to the class that will handle the callback
* @param prefix before the path which is optional
*/
-void CAmDbusWrapper::registerCallback(const DBusObjectPathVTable* vtable, const std::string& path, void* userdata, const std::string& prefix)
+void CAmDbusWrapper::registerCallback(const DBusObjectPathVTable *vtable, const std::string &path, void *userdata, const std::string &prefix)
{
logInfo("DBusWrapper::registerCallback register callback:", path);
@@ -182,16 +185,17 @@ void CAmDbusWrapper::registerCallback(const DBusObjectPathVTable* vtable, const
logError("DBusWrapper::registerCallack error: ", mDBusError.message);
dbus_error_free(&mDBusError);
}
+
mListNodes.push_back(path);
}
/**
-* register signal watch callback to matching rule
-* @param handler pointer to the callback function
-* @param rule signal watch rule like "type='signal',interface='org.genivi.audiomanager.something'"
-* @param userdata userdata
-*/
-void CAmDbusWrapper::registerSignalWatch(DBusHandleMessageFunction handler, const std::string& rule, void* userdata)
+ * register signal watch callback to matching rule
+ * @param handler pointer to the callback function
+ * @param rule signal watch rule like "type='signal',interface='org.genivi.audiomanager.something'"
+ * @param userdata userdata
+ */
+void CAmDbusWrapper::registerSignalWatch(DBusHandleMessageFunction handler, const std::string &rule, void *userdata)
{
logInfo("DBusWrapper::registerSignalWatch register callback:", rule);
dbus_error_init(&mDBusError);
@@ -205,6 +209,7 @@ void CAmDbusWrapper::registerSignalWatch(DBusHandleMessageFunction handler, cons
dbus_error_free(&mDBusError);
}
}
+
/**
* internal callback for the root introspection
* @param conn
@@ -214,28 +219,29 @@ void CAmDbusWrapper::registerSignalWatch(DBusHandleMessageFunction handler, cons
*/
DBusHandlerResult CAmDbusWrapper::cbRootIntrospection(DBusConnection *conn, DBusMessage *msg, void *reference)
{
- //logInfo("DBusWrapper::~cbRootIntrospection called:");
+ // logInfo("DBusWrapper::~cbRootIntrospection called:");
- mpReference = (CAmDbusWrapper*) reference;
+ mpReference = (CAmDbusWrapper *)reference;
std::vector<std::string> nodesList = mpReference->mListNodes;
- DBusMessage * reply;
- DBusMessageIter args;
- dbus_uint32_t serial = 0;
+ DBusMessage *reply;
+ DBusMessageIter args;
+ dbus_uint32_t serial = 0;
if (dbus_message_is_method_call(msg, DBUS_INTERFACE_INTROSPECTABLE, "Introspect"))
{
std::vector<std::string>::iterator nodeIter = nodesList.begin();
- const char *xml = ROOT_INTROSPECT_XML;
- std::stringstream introspect;
+ const char *xml = ROOT_INTROSPECT_XML;
+ std::stringstream introspect;
introspect << std::string(xml);
for (; nodeIter != nodesList.end(); ++nodeIter)
{
introspect << "<node name='" << nodeIter->c_str() << "'/>";
}
+
introspect << "</node>";
reply = dbus_message_new_method_return(msg);
- std::string s = introspect.str();
- const char* string = s.c_str();
+ std::string s = introspect.str();
+ const char *string = s.c_str();
// add the arguments to the reply
dbus_message_iter_init_append(reply, &args);
@@ -249,6 +255,7 @@ DBusHandlerResult CAmDbusWrapper::cbRootIntrospection(DBusConnection *conn, DBus
{
logError("DBusWrapper::~cbRootIntrospection DBUS Out Of Memory!");
}
+
dbus_connection_flush(conn);
// free the reply
dbus_message_unref(reply);
@@ -265,58 +272,65 @@ DBusHandlerResult CAmDbusWrapper::cbRootIntrospection(DBusConnection *conn, DBus
* returns the dbus connection
* @param connection pointer to the connection
*/
-void CAmDbusWrapper::getDBusConnection(DBusConnection *& connection) const
+void CAmDbusWrapper::getDBusConnection(DBusConnection * &connection) const
{
connection = mpDbusConnection;
}
dbus_bool_t CAmDbusWrapper::addWatch(DBusWatch *watch, void *userData)
{
- mpReference = (CAmDbusWrapper*) userData;
- assert(mpReference!=0);
+ mpReference = (CAmDbusWrapper *)userData;
+ assert(mpReference != 0);
return (mpReference->addWatchDelegate(watch, userData));
}
-dbus_bool_t CAmDbusWrapper::addWatchDelegate(DBusWatch * watch, void* userData)
+dbus_bool_t CAmDbusWrapper::addWatchDelegate(DBusWatch *watch, void *userData)
{
- (void) userData;
- int16_t event = 0;
+ (void)userData;
+ int16_t event = 0;
sh_pollHandle_t handle = 0;
- uint flags = dbus_watch_get_flags(watch);
+ uint flags = dbus_watch_get_flags(watch);
/* no watch flags for disabled watches */
if (dbus_watch_get_enabled(watch))
{
if (flags & DBUS_WATCH_READABLE)
+ {
event |= POLLIN;
+ }
+
if (flags & DBUS_WATCH_WRITABLE)
+ {
event |= POLLOUT;
+ }
logInfo("DBusWrapper::addWatchDelegate entered new watch, fd=", dbus_watch_get_unix_fd(watch), "event flag=", event);
am_Error_e error = mpSocketHandler->addFDPoll(dbus_watch_get_unix_fd(watch), event, &pDbusPrepareCallback, &pDbusFireCallback, &pDbusCheckCallback, &pDbusDispatchCallback, watch, handle);
- //if everything is alright, add the watch and the handle to our map so we know this relationship
+ // if everything is alright, add the watch and the handle to our map so we know this relationship
if (error == E_OK && handle != 0)
{
mMapHandleWatch.insert(std::make_pair(watch, handle));
return (true);
}
+
logError("DBusWrapper::addWatchDelegate entering watch failed");
}
+
return (true);
}
void CAmDbusWrapper::removeWatch(DBusWatch *watch, void *userData)
{
- mpReference = (CAmDbusWrapper*) userData;
- assert(mpReference!=0);
+ mpReference = (CAmDbusWrapper *)userData;
+ assert(mpReference != 0);
mpReference->removeWatchDelegate(watch, userData);
}
void CAmDbusWrapper::removeWatchDelegate(DBusWatch *watch, void *userData)
{
- (void) userData;
- std::map<DBusWatch*, sh_pollHandle_t>::iterator iterator = mMapHandleWatch.begin();
+ (void)userData;
+ std::map<DBusWatch *, sh_pollHandle_t>::iterator iterator = mMapHandleWatch.begin();
iterator = mMapHandleWatch.find(watch);
if (iterator != mMapHandleWatch.end())
{
@@ -332,14 +346,14 @@ void CAmDbusWrapper::removeWatchDelegate(DBusWatch *watch, void *userData)
void CAmDbusWrapper::toogleWatch(DBusWatch *watch, void *userData)
{
- mpReference = (CAmDbusWrapper*) userData;
- assert(mpReference!=0);
+ mpReference = (CAmDbusWrapper *)userData;
+ assert(mpReference != 0);
mpReference->toogleWatchDelegate(watch, userData);
}
void CAmDbusWrapper::toogleWatchDelegate(DBusWatch *watch, void *userData)
{
- (void) userData;
+ (void)userData;
int16_t event = 0;
dbus_watch_get_unix_fd(watch);
uint flags = dbus_watch_get_flags(watch);
@@ -347,65 +361,75 @@ void CAmDbusWrapper::toogleWatchDelegate(DBusWatch *watch, void *userData)
if (dbus_watch_get_enabled(watch))
{
if (flags & DBUS_WATCH_READABLE)
+ {
event |= POLLIN;
+ }
+
if (flags & DBUS_WATCH_WRITABLE)
+ {
event |= POLLOUT;
+ }
}
- std::map<DBusWatch*, sh_pollHandle_t>::iterator iterator = mMapHandleWatch.begin();
+
+ std::map<DBusWatch *, sh_pollHandle_t>::iterator iterator = mMapHandleWatch.begin();
iterator = mMapHandleWatch.find(watch);
if (iterator != mMapHandleWatch.end())
+ {
mpSocketHandler->updateEventFlags(iterator->second, event);
+ }
}
-dbus_bool_t CAmDbusWrapper::addTimeout(DBusTimeout *timeout, void* userData)
+dbus_bool_t CAmDbusWrapper::addTimeout(DBusTimeout *timeout, void *userData)
{
- mpReference = (CAmDbusWrapper*) userData;
- assert(mpReference!=0);
+ mpReference = (CAmDbusWrapper *)userData;
+ assert(mpReference != 0);
return (mpReference->addTimeoutDelegate(timeout, userData));
}
-dbus_bool_t CAmDbusWrapper::addTimeoutDelegate(DBusTimeout *timeout, void* userData)
+dbus_bool_t CAmDbusWrapper::addTimeoutDelegate(DBusTimeout *timeout, void *userData)
{
(void)userData;
if (!dbus_timeout_get_enabled(timeout))
+ {
return (false);
+ }
- //calculate the timeout in timeval
+ // calculate the timeout in timeval
timespec pollTimeout;
- int localTimeout = dbus_timeout_get_interval(timeout);
- pollTimeout.tv_sec = localTimeout / 1000;
+ int localTimeout = dbus_timeout_get_interval(timeout);
+ pollTimeout.tv_sec = localTimeout / 1000;
pollTimeout.tv_nsec = (localTimeout % 1000) * 1000000;
- //prepare handle and callback. new is eval, but there is no other choice because we need the pointer!
- sh_timerHandle_t* handle = new sh_timerHandle_t;
+ // prepare handle and callback. new is eval, but there is no other choice because we need the pointer!
+ sh_timerHandle_t *handle = new sh_timerHandle_t;
mpListTimerhandles.push_back(handle);
- //add the timer to the pollLoop
+ // add the timer to the pollLoop
mpSocketHandler->addTimer(pollTimeout, &pDbusTimerCallback, *handle, timeout);
- //save the handle with dbus context
+ // save the handle with dbus context
dbus_timeout_set_data(timeout, handle, NULL);
return (true);
}
-void CAmDbusWrapper::removeTimeout(DBusTimeout *timeout, void* userData)
+void CAmDbusWrapper::removeTimeout(DBusTimeout *timeout, void *userData)
{
- mpReference = (CAmDbusWrapper*) userData;
- assert(mpReference!=0);
+ mpReference = (CAmDbusWrapper *)userData;
+ assert(mpReference != 0);
mpReference->removeTimeoutDelegate(timeout, userData);
}
-void CAmDbusWrapper::removeTimeoutDelegate(DBusTimeout *timeout, void* userData)
+void CAmDbusWrapper::removeTimeoutDelegate(DBusTimeout *timeout, void *userData)
{
- (void) userData;
- //get the pointer to the handle and remove the timer
- sh_timerHandle_t* handle = (sh_timerHandle_t*) dbus_timeout_get_data(timeout);
+ (void)userData;
+ // get the pointer to the handle and remove the timer
+ sh_timerHandle_t *handle = (sh_timerHandle_t *)dbus_timeout_get_data(timeout);
mpSocketHandler->removeTimer(*handle);
- //now go throught the timerlist and remove the pointer, free memory
- std::vector<sh_timerHandle_t*>::iterator it = mpListTimerhandles.begin();
+ // now go throught the timerlist and remove the pointer, free memory
+ std::vector<sh_timerHandle_t *>::iterator it = mpListTimerhandles.begin();
for (; it != mpListTimerhandles.end(); ++it)
{
if (*it == handle)
@@ -414,92 +438,111 @@ void CAmDbusWrapper::removeTimeoutDelegate(DBusTimeout *timeout, void* userData)
break;
}
}
+
delete handle;
- }
+}
-void CAmDbusWrapper::toggleTimeout(DBusTimeout *timeout, void* userData)
+void CAmDbusWrapper::toggleTimeout(DBusTimeout *timeout, void *userData)
{
- mpReference = (CAmDbusWrapper*) userData;
- assert(mpReference!=0);
+ mpReference = (CAmDbusWrapper *)userData;
+ assert(mpReference != 0);
mpReference->toggleTimeoutDelegate(timeout, userData);
}
bool am::CAmDbusWrapper::dbusDispatchCallback(const sh_pollHandle_t handle, void *userData)
{
- (void) handle;
- (void) userData;
+ (void)handle;
+ (void)userData;
bool returnVal = true;
dbus_connection_ref(mpDbusConnection);
if (dbus_connection_dispatch(mpDbusConnection) == DBUS_DISPATCH_COMPLETE)
+ {
returnVal = false;
+ }
+
dbus_connection_unref(mpDbusConnection);
- //logInfo("DBusWrapper::dbusDispatchCallback was called");
+ // logInfo("DBusWrapper::dbusDispatchCallback was called");
return (returnVal);
}
bool am::CAmDbusWrapper::dbusCheckCallback(const sh_pollHandle_t handle, void *userData)
{
- (void) handle;
- (void) userData;
+ (void)handle;
+ (void)userData;
bool returnVal = false;
dbus_connection_ref(mpDbusConnection);
if (dbus_connection_get_dispatch_status(mpDbusConnection) == DBUS_DISPATCH_DATA_REMAINS)
+ {
returnVal = true;
+ }
+
dbus_connection_unref(mpDbusConnection);
- //logInfo("DBusWrapper::dbusCheckCallback was called");
+ // logInfo("DBusWrapper::dbusCheckCallback was called");
return (returnVal);
}
void am::CAmDbusWrapper::dbusFireCallback(const pollfd pollfd, const sh_pollHandle_t handle, void *userData)
{
- (void) handle;
- (void) userData;
- assert(userData!=NULL);
+ (void)handle;
+ (void)userData;
+ assert(userData != NULL);
uint flags = 0;
if (pollfd.revents & POLLIN)
+ {
flags |= DBUS_WATCH_READABLE;
+ }
+
if (pollfd.revents & POLLOUT)
+ {
flags |= DBUS_WATCH_WRITABLE;
+ }
+
if (pollfd.revents & POLLHUP)
+ {
flags |= DBUS_WATCH_HANGUP;
+ }
+
if (pollfd.revents & POLLERR)
+ {
flags |= DBUS_WATCH_ERROR;
+ }
- DBusWatch *watch = (DBusWatch*) userData;
+ DBusWatch *watch = (DBusWatch *)userData;
dbus_connection_ref(mpDbusConnection);
dbus_watch_handle(watch, flags);
dbus_connection_unref(mpDbusConnection);
- //logInfo("DBusWrapper::dbusFireCallback was called");
+ // logInfo("DBusWrapper::dbusFireCallback was called");
}
-void CAmDbusWrapper::dbusPrepareCallback(const sh_pollHandle_t handle, void* userData)
+void CAmDbusWrapper::dbusPrepareCallback(const sh_pollHandle_t handle, void *userData)
{
- (void) handle;
- (void) userData;
+ (void)handle;
+ (void)userData;
dbus_connection_ref(mpDbusConnection);
while (dbus_connection_get_dispatch_status(mpDbusConnection) == DBUS_DISPATCH_DATA_REMAINS)
{
- dbus_connection_dispatch(mpDbusConnection);
- //logInfo("prepare was neccessary!");
+ dbus_connection_dispatch(mpDbusConnection);
+ // logInfo("prepare was neccessary!");
}
+
dbus_connection_unref(mpDbusConnection);
}
-void CAmDbusWrapper::toggleTimeoutDelegate(DBusTimeout *timeout, void* userData)
+void CAmDbusWrapper::toggleTimeoutDelegate(DBusTimeout *timeout, void *userData)
{
- (void) userData;
- //get the pointer to the handle and remove the timer
- sh_timerHandle_t* handle = (sh_timerHandle_t*) dbus_timeout_get_data(timeout);
+ (void)userData;
+ // get the pointer to the handle and remove the timer
+ sh_timerHandle_t *handle = (sh_timerHandle_t *)dbus_timeout_get_data(timeout);
- //stop or restart?
+ // stop or restart?
if (dbus_timeout_get_enabled(timeout))
{
- //calculate the timeout in timeval
+ // calculate the timeout in timeval
timespec pollTimeout;
- int localTimeout = dbus_timeout_get_interval(timeout);
- pollTimeout.tv_sec = localTimeout / 1000;
+ int localTimeout = dbus_timeout_get_interval(timeout);
+ pollTimeout.tv_sec = localTimeout / 1000;
pollTimeout.tv_nsec = (localTimeout % 1000) * 1000000;
mpSocketHandler->updateTimer(*handle, pollTimeout);
}
@@ -511,20 +554,22 @@ void CAmDbusWrapper::toggleTimeoutDelegate(DBusTimeout *timeout, void* userData)
void CAmDbusWrapper::dbusTimerCallback(sh_timerHandle_t handle, void *userData)
{
- assert(userData!=NULL);
- for (auto && timerHandle : mpListTimerhandles)
+ assert(userData != NULL);
+ for (auto &&timerHandle : mpListTimerhandles)
{
if (*timerHandle == handle)
{
- if (dbus_timeout_get_enabled((DBusTimeout*) userData))
+ if (dbus_timeout_get_enabled((DBusTimeout *)userData))
{
mpSocketHandler->restartTimer(handle);
}
- dbus_timeout_handle((DBusTimeout*) userData);
+
+ dbus_timeout_handle((DBusTimeout *)userData);
return;
}
}
+
logWarning("CAmDbusWrapper::dbusTimerCallback Unknown timer handle");
}
-}
+}
diff --git a/AudioManagerUtilities/src/CAmDltWrapper.cpp b/AudioManagerUtilities/src/CAmDltWrapper.cpp
index 44ec614..fff4a57 100644
--- a/AudioManagerUtilities/src/CAmDltWrapper.cpp
+++ b/AudioManagerUtilities/src/CAmDltWrapper.cpp
@@ -22,7 +22,6 @@
*
*/
-
#include <string>
#include <iostream>
#include <string.h>
@@ -34,668 +33,781 @@
namespace am
{
-CAmDltWrapper* CAmDltWrapper::mpDLTWrapper = NULL;
-pthread_mutex_t CAmDltWrapper::mMutex = PTHREAD_MUTEX_INITIALIZER;
-
-const std::vector<const char*> CAmDltWrapper::mStr_error =
-{
- "E_OK",
- "E_UNKNOWN",
- "E_OUT_OF_RANGE",
- "E_NOT_USED",
- "E_DATABASE_ERROR",
- "E_ALREADY_EXISTS",
- "E_NO_CHANGE",
- "E_NOT_POSSIBLE",
- "E_NON_EXISTENT",
- "E_ABORTED",
- "E_WRONG_FORMAT",
- "E_COMMUNICATION",
- "E_MAX"
-};
+CAmDltWrapper *CAmDltWrapper::mpDLTWrapper = NULL;
+pthread_mutex_t CAmDltWrapper::mMutex = PTHREAD_MUTEX_INITIALIZER;
-const std::vector<const char*> CAmDltWrapper::mStr_sourceState =
+const std::vector<const char *> CAmDltWrapper::mStr_error =
{
- "SS_UNKNNOWN",
- "SS_ON",
- "SS_OFF",
- "SS_PAUSED",
- "SS_MAX"
+ "E_OK",
+ "E_UNKNOWN",
+ "E_OUT_OF_RANGE",
+ "E_NOT_USED",
+ "E_DATABASE_ERROR",
+ "E_ALREADY_EXISTS",
+ "E_NO_CHANGE",
+ "E_NOT_POSSIBLE",
+ "E_NON_EXISTENT",
+ "E_ABORTED",
+ "E_WRONG_FORMAT",
+ "E_COMMUNICATION",
+ "E_MAX"
};
-const std::vector<const char*> CAmDltWrapper::mStr_MuteState =
+const std::vector<const char *> CAmDltWrapper::mStr_sourceState =
{
- "MS_UNKNOWN" ,
- "MS_MUTED" ,
- "MS_UNMUTED" ,
- "MS_MAX"
+ "SS_UNKNNOWN",
+ "SS_ON",
+ "SS_OFF",
+ "SS_PAUSED",
+ "SS_MAX"
};
-const std::vector<const char*> CAmDltWrapper::mStr_DomainState =
+const std::vector<const char *> CAmDltWrapper::mStr_MuteState =
{
- "DS_UNKNOWN",
- "DS_CONTROLLED",
- "DS_INDEPENDENT_STARTUP",
- "DS_INDEPENDENT_RUNDOWN",
- "DS_MAX"
+ "MS_UNKNOWN",
+ "MS_MUTED",
+ "MS_UNMUTED",
+ "MS_MAX"
};
-const std::vector<const char*> CAmDltWrapper::mStr_ConnectionState =
+const std::vector<const char *> CAmDltWrapper::mStr_DomainState =
{
- "CS_UNKNOWN",
- "CS_CONNECTING",
- "CS_CONNECTED",
- "CS_DISCONNECTING",
- "CS_DISCONNECTED",
- "CS_SUSPENDED",
- "CS_MAX"
+ "DS_UNKNOWN",
+ "DS_CONTROLLED",
+ "DS_INDEPENDENT_STARTUP",
+ "DS_INDEPENDENT_RUNDOWN",
+ "DS_MAX"
};
-const std::vector<const char*> CAmDltWrapper::mStr_Availability =
+const std::vector<const char *> CAmDltWrapper::mStr_ConnectionState =
{
- "A_UNKNOWN",
- "A_AVAILABLE",
- "A_UNAVAILABLE",
- "A_MAX"
+ "CS_UNKNOWN",
+ "CS_CONNECTING",
+ "CS_CONNECTED",
+ "CS_DISCONNECTING",
+ "CS_DISCONNECTED",
+ "CS_SUSPENDED",
+ "CS_MAX"
};
-const std::vector<const char*> CAmDltWrapper::mStr_Interrupt =
+const std::vector<const char *> CAmDltWrapper::mStr_Availability =
{
- "IS_UNKNOWN",
- "IS_OFF",
- "IS_INTERRUPTED",
- "IS_MAX"
+ "A_UNKNOWN",
+ "A_AVAILABLE",
+ "A_UNAVAILABLE",
+ "A_MAX"
};
-const std::vector<const char*> CAmDltWrapper::mStr_Handle =
-{
- "H_UNKNOWN",
- "H_CONNECT",
- "H_DISCONNECT",
- "H_SETSOURCESTATE",
- "H_SETSINKVOLUME",
- "H_SETSOURCEVOLUME",
- "H_SETSINKSOUNDPROPERTY",
- "H_SETSOURCESOUNDPROPERTY",
- "H_SETSINKSOUNDPROPERTIES",
- "H_SETSOURCESOUNDPROPERTIES",
- "H_CROSSFADE",
- "H_SETVOLUMES",
- "H_SETSINKNOTIFICATION",
- "H_SETSOURCENOTIFICATION",
- "H_MAX"
+const std::vector<const char *> CAmDltWrapper::mStr_Interrupt =
+{
+ "IS_UNKNOWN",
+ "IS_OFF",
+ "IS_INTERRUPTED",
+ "IS_MAX"
};
-const std::vector<const char*> CAmDltWrapper::mStr_NotificationStatus =
+const std::vector<const char *> CAmDltWrapper::mStr_Handle =
{
- "NS_UNKNOWN",
- "NS_OFF",
- "NS_PERIODIC",
- "NS_MINIMUM",
- "NS_MAXIMUM",
- "NS_CHANGE",
- "NS_MAX"
+ "H_UNKNOWN",
+ "H_CONNECT",
+ "H_DISCONNECT",
+ "H_SETSOURCESTATE",
+ "H_SETSINKVOLUME",
+ "H_SETSOURCEVOLUME",
+ "H_SETSINKSOUNDPROPERTY",
+ "H_SETSOURCESOUNDPROPERTY",
+ "H_SETSINKSOUNDPROPERTIES",
+ "H_SETSOURCESOUNDPROPERTIES",
+ "H_CROSSFADE",
+ "H_SETVOLUMES",
+ "H_SETSINKNOTIFICATION",
+ "H_SETSOURCENOTIFICATION",
+ "H_MAX"
};
-
+const std::vector<const char *> CAmDltWrapper::mStr_NotificationStatus =
+{
+ "NS_UNKNOWN",
+ "NS_OFF",
+ "NS_PERIODIC",
+ "NS_MINIMUM",
+ "NS_MAXIMUM",
+ "NS_CHANGE",
+ "NS_MAX"
+};
std::string CAmDltWrapper::now()
{
- std::time_t t(std::chrono::system_clock::to_time_t(std::chrono::system_clock::now()));
- struct tm * timeinfo(localtime(&t));
- char buffer[80];
- std::strftime(buffer,80,"%D %T ",timeinfo);
- return (std::string(buffer));
+ std::time_t t(std::chrono::system_clock::to_time_t(std::chrono::system_clock::now()));
+ struct tm *timeinfo(localtime(&t));
+ char buffer[80];
+ std::strftime(buffer, 80, "%D %T ", timeinfo);
+ return (std::string(buffer));
}
-CAmDltWrapper* CAmDltWrapper::instanctiateOnce(const char *appid, const char * description, const bool debugEnabled, const logDestination logDest, const std::string Filename,bool onlyError)
+CAmDltWrapper *CAmDltWrapper::instanctiateOnce(const char *appid, const char *description, const bool debugEnabled, const logDestination logDest, const std::string Filename, bool onlyError)
{
- if (!mpDLTWrapper)
- {
- mpDLTWrapper = new CAmDltWrapper(appid,description,debugEnabled,logDest,Filename,onlyError);
- }
- return (mpDLTWrapper);
+ if (!mpDLTWrapper)
+ {
+ mpDLTWrapper = new CAmDltWrapper(appid, description, debugEnabled, logDest, Filename, onlyError);
+ }
+
+ return (mpDLTWrapper);
}
-CAmDltWrapper* CAmDltWrapper::instance()
+CAmDltWrapper *CAmDltWrapper::instance()
{
- if (!mpDLTWrapper)
- {
- // an application seems not to use our CAmDltWrapper class therefore create default
- std::ostringstream description;
- description << "PID=" << getpid() << " _=" << getenv("_");
- mpDLTWrapper = new CAmDltWrapper("AMDL", description.str().c_str());
- std::cerr << "Application doesn't call CAmDltWrapper::instanciateOnce!!!" << std::endl;
- std::cerr << "-> CAmDltWrapper::instance registers DLT application [ AMDL | " << description.str() << " ]" << std::endl;
- }
- return mpDLTWrapper;
+ if (!mpDLTWrapper)
+ {
+ // an application seems not to use our CAmDltWrapper class therefore create default
+ std::ostringstream description;
+ description << "PID=" << getpid() << " _=" << getenv("_");
+ mpDLTWrapper = new CAmDltWrapper("AMDL", description.str().c_str());
+ std::cerr << "Application doesn't call CAmDltWrapper::instanciateOnce!!!" << std::endl;
+ std::cerr << "-> CAmDltWrapper::instance registers DLT application [ AMDL | " << description.str() << " ]" << std::endl;
+ }
+
+ return mpDLTWrapper;
}
bool CAmDltWrapper::getEnabled()
{
- return (mDebugEnabled);
-}
-
-bool CAmDltWrapper::initNoDlt(DltLogLevelType loglevel, DltContext* context)
-{
- if (mlogDestination==logDestination::COMMAND_LINE)
- {
- if (!context)
- {
- switch (loglevel)
- {
- case DLT_LOG_OFF :
- case DLT_LOG_FATAL :
- case DLT_LOG_ERROR :
- mNoDltContextData.buffer << "\033[0;31m"<<"[DEF] [Erro] \033[0m";
- mLogOn=true;
- break;
- case DLT_LOG_WARN :
- if (!mOnlyError)
- {
- mNoDltContextData.buffer << "\033[0;33m"<<"[DEF] [Warn] \033[0m";
- }
- else
- mLogOn=false;
- break;
- case DLT_LOG_INFO :
- if (!mOnlyError)
- {
- mNoDltContextData.buffer << "\033[0;36m"<<"[DEF] [Info] \033[0m";
- }
- else
- mLogOn=false;
- break;
- default:
- if (!mOnlyError)
- {
- mNoDltContextData.buffer << "\033[0;32m"<<"[DEF] [Defa] \033[0m";
- }
- else
- mLogOn=false;
- }
- }
- else
- {
- std::string con(mMapContext.at(context));
- switch (loglevel)
- {
- case DLT_LOG_OFF :
- case DLT_LOG_FATAL :
- case DLT_LOG_ERROR :
- mNoDltContextData.buffer << "\033[0;31m["<<con<<"] [Erro] \033[0m";
- mLogOn=true;
- break;
- case DLT_LOG_WARN :
- if (!mOnlyError)
- {
- mNoDltContextData.buffer << "\033[0;33m["<<con<<"] [Warn] \033[0m";
- }
- else
- mLogOn=false;
- break;
- case DLT_LOG_INFO :
- if (!mOnlyError)
- {
- mNoDltContextData.buffer << "\033[0;36m["<<con<<"] [Info] \033[0m";
- }
- else
- mLogOn=false;
-
- break;
- default:
- if (!mOnlyError)
- {
- mNoDltContextData.buffer << "\033[0;32m["<<con<<"] [Defa] \033[0m";
- }
- else
- mLogOn=false;
- }
- }
- return true;
- }
- else
- {
- if (!context)
- {
- switch (loglevel)
- {
- case DLT_LOG_OFF :
- case DLT_LOG_FATAL :
- case DLT_LOG_ERROR :
- mNoDltContextData.buffer <<"[DEF] [Erro] ";
- mLogOn=true;
- break;
- case DLT_LOG_WARN :
- if (!mOnlyError)
- {
- mNoDltContextData.buffer <<"[DEF] [Warn] ";
- }
- else
- mLogOn=false;
- break;
- case DLT_LOG_INFO :
- if (!mOnlyError)
- {
- mNoDltContextData.buffer <<"[DEF] [Info] ";
- }
- else
- mLogOn=false;
- break;
- default:
- if (!mOnlyError)
- {
- mNoDltContextData.buffer <<"[DEF] [Defa] ";
- }
- else
- mLogOn=false;
-
- }
- }
- else
- {
- std::string con(mMapContext.at(context));
- switch (loglevel)
- {
- case DLT_LOG_OFF :
- case DLT_LOG_FATAL :
- case DLT_LOG_ERROR :
- mNoDltContextData.buffer << "["<<con<<"] [Erro] ";
- mLogOn=true;
- break;
- case DLT_LOG_WARN :
- if (!mOnlyError)
- {
- mNoDltContextData.buffer << "["<<con<<"] [Warn] ";
- }
- else
- mLogOn=false;
- break;
- case DLT_LOG_INFO :
- if (!mOnlyError)
- {
- mNoDltContextData.buffer << "["<<con<<"] [Info] ";
- }
- else
- mLogOn=false;
-
- break;
- default:
- if (!mOnlyError)
- {
- mNoDltContextData.buffer << "["<<con<<"] [Defa] ";
- }
- else
- mLogOn=false;
- }
- }
- return true;
- }
-}
-
-#ifdef WITH_DLT
-
- CAmDltWrapper::CAmDltWrapper(const char *appid, const char * description, const bool debugEnabled, const logDestination logDest, const std::string Filename,bool onlyError) :
- mDebugEnabled(debugEnabled), //
- mlogDestination(logDest), //
- mFilename(NULL), //
- mOnlyError(onlyError), //
- mLogOn(true)
- {
- if (mDebugEnabled && mlogDestination==logDestination::DAEMON)
- {
- dlt_register_app(appid, description);
- //register a default context
- dlt_register_context(&mDltContext, "DEF", "Default Context registered by DLTWrapper Class");
- }
- else if (mDebugEnabled)
- {
- if (mlogDestination==logDestination::COMMAND_LINE)
- std::cout << "\033[0;36m[DLT] Registering AppID " << appid << " , " << description << "\033[0m"<< std::endl;
- else
- {
- mFilename.open(Filename, std::ofstream::out | std::ofstream::trunc);
- if (!mFilename.is_open())
- {
- throw std::runtime_error("Cannot open file for logging");
- }
- mFilename << now() << "[DLT] Registering AppID " << appid << " , " << description << std::endl;
- }
- }
- }
-
- CAmDltWrapper::~CAmDltWrapper()
- {
- if (mpDLTWrapper && mDebugEnabled && mlogDestination==logDestination::DAEMON)
- {
- mpDLTWrapper->unregisterContext(mDltContext);
- delete mpDLTWrapper;
- }
- else if (mpDLTWrapper && mDebugEnabled && mlogDestination==logDestination::COMMAND_LINE)
- {
- mFilename.close();
- }
- }
-
- void CAmDltWrapper::unregisterContext(DltContext & handle)
- {
- if (mDebugEnabled && mlogDestination==logDestination::DAEMON)
- {
- dlt_unregister_context(&handle);
- }
- }
-
- void CAmDltWrapper::deinit()
- {
- if (mDebugEnabled)
- {
- unregisterContext(mDltContext);
- }
- }
-
- void CAmDltWrapper::registerContext(DltContext& handle, const char *contextid, const char *description)
- {
- if (mDebugEnabled && mlogDestination==logDestination::DAEMON)
- {
- dlt_register_context(&handle, contextid, description);
- }
- else if (mDebugEnabled)
- {
- mMapContext.emplace(&handle,std::string(contextid));
-
- if (mlogDestination==logDestination::COMMAND_LINE)
- std::cout << "\033[0;36m[DLT] Registering Context " << contextid << " , " << description << "\033[0m"<< std::endl;
- else
- mFilename << now() << "[DLT] Registering Context " << contextid << " , " << description << std::endl;
- }
- }
-
- void CAmDltWrapper::registerContext(DltContext& handle, const char *contextid, const char * description,const DltLogLevelType level, const DltTraceStatusType status)
- {
- if (mDebugEnabled && mlogDestination==logDestination::DAEMON)
- {
- dlt_register_context_ll_ts(&handle, contextid, description, level, status);
- }
- else if (mDebugEnabled)
- {
- mMapContext.emplace(&handle,std::string(contextid));
-
- if (mlogDestination==logDestination::COMMAND_LINE)
- std::cout << "\033[0;36m[DLT] Registering Context " << contextid << " , " << description << "\033[0m"<< std::endl;
- else
- mFilename << now() << " [DLT] Registering Context " << contextid << " , " << description << std::endl;
- }
- }
-
- bool CAmDltWrapper::init(DltLogLevelType loglevel, DltContext* context)
- {
- pthread_mutex_lock(&mMutex);
- if (mlogDestination==logDestination::DAEMON)
- {
- if (!context)
- context = &mDltContext;
-
- if(dlt_user_log_write_start(context, &mDltContextData, loglevel) <= 0)
- {
- pthread_mutex_unlock(&mMutex);
- return false;
- }
- }
- else
- {
- initNoDlt(loglevel,context);
- }
- return true;
- }
-
- void CAmDltWrapper::send()
- {
- if (mlogDestination==logDestination::DAEMON)
- {
- dlt_user_log_write_finish(&mDltContextData);
- }
- else
- {
- if (mlogDestination==logDestination::COMMAND_LINE && mLogOn)
- std::cout << mNoDltContextData.buffer.str().c_str() << std::endl;
- else if (mLogOn)
- mFilename << now() << mNoDltContextData.buffer.str().c_str() << std::endl;
-
- mNoDltContextData.buffer.str("");
- mNoDltContextData.buffer.clear();
- }
- pthread_mutex_unlock(&mMutex);
- }
-
- void CAmDltWrapper::append(const int8_t value)
- {
- if (mlogDestination==logDestination::DAEMON)
- dlt_user_log_write_int8(&mDltContextData, value);
- else
- appendNoDLT(value);
- }
-
- void CAmDltWrapper::append(const uint8_t value)
- {
- if (mlogDestination==logDestination::DAEMON)
- dlt_user_log_write_uint8(&mDltContextData, value);
- else
- appendNoDLT(value);
- }
-
- void CAmDltWrapper::append(const int16_t value)
- {
- if (mlogDestination==logDestination::DAEMON)
- dlt_user_log_write_int16(&mDltContextData, value);
- else
- appendNoDLT(value);
- }
-
- void CAmDltWrapper::append(const uint16_t value)
- {
- if (mlogDestination==logDestination::DAEMON)
- dlt_user_log_write_uint16(&mDltContextData, value);
- else
- appendNoDLT(value);
- }
-
- void CAmDltWrapper::append(const int32_t value)
- {
- if (mlogDestination==logDestination::DAEMON)
- dlt_user_log_write_int32(&mDltContextData, value);
- else
- appendNoDLT(value);
- }
-
- void CAmDltWrapper::append(const uint32_t value)
- {
- if (mlogDestination==logDestination::DAEMON)
- dlt_user_log_write_uint32(&mDltContextData, value);
- else
- appendNoDLT(value);
- }
-
- void CAmDltWrapper::append(const std::string& value)
- {
- append(value.c_str());
- }
-
- void CAmDltWrapper::append(const bool value)
- {
- if (mlogDestination==logDestination::DAEMON)
- dlt_user_log_write_bool(&mDltContextData, static_cast<uint8_t>(value));
- else
- appendNoDLT(value);
- }
-
- void CAmDltWrapper::append(const int64_t value)
- {
- if (mlogDestination==logDestination::DAEMON)
- dlt_user_log_write_int64(&mDltContextData, value);
- else
- appendNoDLT(value);
- }
-
- void CAmDltWrapper::append(const uint64_t value)
- {
- if (mlogDestination==logDestination::DAEMON)
- dlt_user_log_write_uint64(&mDltContextData, value);
- else
- appendNoDLT(value);
- }
-
- void CAmDltWrapper::append(const std::vector<uint8_t> & data)
- {
- if (mlogDestination==logDestination::DAEMON)
- dlt_user_log_write_raw(&mDltContextData,(void*)data.data(),data.size());
- else
- mNoDltContextData.buffer << data.data();
- }
-}
-
-#else //------------------------------------------------------------------------------------------------- no DLT !
-
- CAmDltWrapper::CAmDltWrapper(const char *appid, const char * description, const bool debugEnabled, const logDestination logDest, const std::string Filename,bool onlyError) :
- mDebugEnabled(debugEnabled), //
- mlogDestination(logDest), //
- mFilename(NULL), //
- mOnlyError(onlyError), //
- mLogOn(true)
- {
- if (logDest==logDestination::DAEMON)
- {
- std::cout << "\033[0;31m[DLT] Cannot Use Daemon Logging, active in CMAKE! Using CommandLine\033[0m"<< std::endl;
- mlogDestination=logDestination::COMMAND_LINE;
- }
- if (mDebugEnabled)
- {
- if (mlogDestination==logDestination::COMMAND_LINE)
- std::cout << "\033[0;36m[DLT] Registering AppID " << appid << " , " << description << "\033[0m"<< std::endl;
- else
- {
- mFilename.open(Filename, std::ofstream::out | std::ofstream::trunc);
- if (!mFilename.is_open())
- {
- throw std::runtime_error("Cannot open file for logging");
- }
- mFilename << now() << "[DLT] Registering AppID " << appid << " , " << description << std::endl;
- }
- }
- }
-
- CAmDltWrapper::~CAmDltWrapper()
- {
- if (mpDLTWrapper && mDebugEnabled && mlogDestination==logDestination::COMMAND_LINE)
- {
- mFilename.close();
- }
- }
-
- void CAmDltWrapper::unregisterContext(DltContext & handle)
- {}
-
- void CAmDltWrapper::deinit()
- {}
-
- void CAmDltWrapper::registerContext(DltContext& handle, const char *contextid, const char *description)
- {
- if (mDebugEnabled)
- {
- mMapContext.emplace(&handle,std::string(contextid));
-
- if (mlogDestination==logDestination::COMMAND_LINE)
- std::cout << "\033[0;36m[DLT] Registering Context " << contextid << " , " << description << "\033[0m"<< std::endl;
- else
- mFilename << now() << "[DLT] Registering Context " << contextid << " , " << description << std::endl;
- }
- }
-
- void CAmDltWrapper::registerContext(DltContext& handle, const char *contextid, const char * description,const DltLogLevelType level, const DltTraceStatusType status)
- {
- if (mDebugEnabled)
- {
- mMapContext.emplace(&handle,std::string(contextid));
-
- if (mlogDestination==logDestination::COMMAND_LINE)
- std::cout << "\033[0;36m[DLT] Registering Context " << contextid << " , " << description << "\033[0m"<< std::endl;
- else
- mFilename << now() << " [DLT] Registering Context " << contextid << " , " << description << std::endl;
- }
- }
-
- bool CAmDltWrapper::init(DltLogLevelType loglevel, DltContext* context)
- {
- pthread_mutex_lock(&mMutex);
- return initNoDlt(loglevel,context);
- }
-
- void CAmDltWrapper::send()
- {
- if (mlogDestination==logDestination::COMMAND_LINE && mLogOn)
- std::cout << mNoDltContextData.buffer.str().c_str() << std::endl;
- else if (mLogOn)
- mFilename << now() << mNoDltContextData.buffer.str().c_str() << std::endl;
-
- mNoDltContextData.buffer.str("");
- mNoDltContextData.buffer.clear();
- pthread_mutex_unlock(&mMutex);
- }
-
- void CAmDltWrapper::append(const int8_t value)
- {
- appendNoDLT(value);
- }
-
- void CAmDltWrapper::append(const uint8_t value)
- {
- appendNoDLT(value);
- }
-
- void CAmDltWrapper::append(const int16_t value)
- {
- appendNoDLT(value);
- }
-
- void CAmDltWrapper::append(const uint16_t value)
- {
- appendNoDLT(value);
- }
-
- void CAmDltWrapper::append(const int32_t value)
- {
- appendNoDLT(value);
- }
-
- void CAmDltWrapper::append(const uint32_t value)
- {
- appendNoDLT(value);
- }
-
- void CAmDltWrapper::append(const std::string& value)
- {
- append(value.c_str());
- }
-
- void CAmDltWrapper::append(const bool value)
- {
- appendNoDLT(value);
- }
-
- void CAmDltWrapper::append(const int64_t value)
- {
- appendNoDLT(value);
- }
-
- void CAmDltWrapper::append(const uint64_t value)
- {
- appendNoDLT(value);
- }
-
- void CAmDltWrapper::append(const std::vector<uint8_t> & data)
- {
- mNoDltContextData.buffer << data.data();
- }
-}
-#endif //WITH_DLT
+ return (mDebugEnabled);
+}
+
+bool CAmDltWrapper::initNoDlt(DltLogLevelType loglevel, DltContext *context)
+{
+ if (mlogDestination == logDestination::COMMAND_LINE)
+ {
+ if (!context)
+ {
+ switch (loglevel)
+ {
+ case DLT_LOG_OFF:
+ case DLT_LOG_FATAL:
+ case DLT_LOG_ERROR:
+ mNoDltContextData.buffer << "\033[0;31m" << "[DEF] [Erro] \033[0m";
+ mLogOn = true;
+ break;
+ case DLT_LOG_WARN:
+ if (!mOnlyError)
+ {
+ mNoDltContextData.buffer << "\033[0;33m" << "[DEF] [Warn] \033[0m";
+ }
+ else
+ {
+ mLogOn = false;
+ }
+
+ break;
+ case DLT_LOG_INFO:
+ if (!mOnlyError)
+ {
+ mNoDltContextData.buffer << "\033[0;36m" << "[DEF] [Info] \033[0m";
+ }
+ else
+ {
+ mLogOn = false;
+ }
+
+ break;
+ default:
+ if (!mOnlyError)
+ {
+ mNoDltContextData.buffer << "\033[0;32m" << "[DEF] [Defa] \033[0m";
+ }
+ else
+ {
+ mLogOn = false;
+ }
+ }
+ }
+ else
+ {
+ std::string con(mMapContext.at(context));
+ switch (loglevel)
+ {
+ case DLT_LOG_OFF:
+ case DLT_LOG_FATAL:
+ case DLT_LOG_ERROR:
+ mNoDltContextData.buffer << "\033[0;31m[" << con << "] [Erro] \033[0m";
+ mLogOn = true;
+ break;
+ case DLT_LOG_WARN:
+ if (!mOnlyError)
+ {
+ mNoDltContextData.buffer << "\033[0;33m[" << con << "] [Warn] \033[0m";
+ }
+ else
+ {
+ mLogOn = false;
+ }
+
+ break;
+ case DLT_LOG_INFO:
+ if (!mOnlyError)
+ {
+ mNoDltContextData.buffer << "\033[0;36m[" << con << "] [Info] \033[0m";
+ }
+ else
+ {
+ mLogOn = false;
+ }
+
+ break;
+ default:
+ if (!mOnlyError)
+ {
+ mNoDltContextData.buffer << "\033[0;32m[" << con << "] [Defa] \033[0m";
+ }
+ else
+ {
+ mLogOn = false;
+ }
+ }
+ }
+
+ return true;
+ }
+ else
+ {
+ if (!context)
+ {
+ switch (loglevel)
+ {
+ case DLT_LOG_OFF:
+ case DLT_LOG_FATAL:
+ case DLT_LOG_ERROR:
+ mNoDltContextData.buffer << "[DEF] [Erro] ";
+ mLogOn = true;
+ break;
+ case DLT_LOG_WARN:
+ if (!mOnlyError)
+ {
+ mNoDltContextData.buffer << "[DEF] [Warn] ";
+ }
+ else
+ {
+ mLogOn = false;
+ }
+
+ break;
+ case DLT_LOG_INFO:
+ if (!mOnlyError)
+ {
+ mNoDltContextData.buffer << "[DEF] [Info] ";
+ }
+ else
+ {
+ mLogOn = false;
+ }
+
+ break;
+ default:
+ if (!mOnlyError)
+ {
+ mNoDltContextData.buffer << "[DEF] [Defa] ";
+ }
+ else
+ {
+ mLogOn = false;
+ }
+ }
+ }
+ else
+ {
+ std::string con(mMapContext.at(context));
+ switch (loglevel)
+ {
+ case DLT_LOG_OFF:
+ case DLT_LOG_FATAL:
+ case DLT_LOG_ERROR:
+ mNoDltContextData.buffer << "[" << con << "] [Erro] ";
+ mLogOn = true;
+ break;
+ case DLT_LOG_WARN:
+ if (!mOnlyError)
+ {
+ mNoDltContextData.buffer << "[" << con << "] [Warn] ";
+ }
+ else
+ {
+ mLogOn = false;
+ }
+
+ break;
+ case DLT_LOG_INFO:
+ if (!mOnlyError)
+ {
+ mNoDltContextData.buffer << "[" << con << "] [Info] ";
+ }
+ else
+ {
+ mLogOn = false;
+ }
+
+ break;
+ default:
+ if (!mOnlyError)
+ {
+ mNoDltContextData.buffer << "[" << con << "] [Defa] ";
+ }
+ else
+ {
+ mLogOn = false;
+ }
+ }
+ }
+
+ return true;
+ }
+}
+
+#ifdef WITH_DLT
+CAmDltWrapper::CAmDltWrapper(const char *appid, const char *description, const bool debugEnabled, const logDestination logDest, const std::string Filename, bool onlyError)
+ : mDebugEnabled(debugEnabled)
+ , //
+ mlogDestination(logDest)
+ , //
+ mFilename(NULL)
+ , //
+ mOnlyError(onlyError)
+ , //
+ mLogOn(true)
+{
+ if (mDebugEnabled && mlogDestination == logDestination::DAEMON)
+ {
+ dlt_register_app(appid, description);
+ // register a default context
+ dlt_register_context(&mDltContext, "DEF", "Default Context registered by DLTWrapper Class");
+ }
+ else if (mDebugEnabled)
+ {
+ if (mlogDestination == logDestination::COMMAND_LINE)
+ {
+ std::cout << "\033[0;36m[DLT] Registering AppID " << appid << " , " << description << "\033[0m" << std::endl;
+ }
+ else
+ {
+ mFilename.open(Filename, std::ofstream::out | std::ofstream::trunc);
+ if (!mFilename.is_open())
+ {
+ throw std::runtime_error("Cannot open file for logging");
+ }
+
+ mFilename << now() << "[DLT] Registering AppID " << appid << " , " << description << std::endl;
+ }
+ }
+}
+
+CAmDltWrapper::~CAmDltWrapper()
+{
+ if (mpDLTWrapper && mDebugEnabled && mlogDestination == logDestination::DAEMON)
+ {
+ mpDLTWrapper->unregisterContext(mDltContext);
+ delete mpDLTWrapper;
+ }
+ else if (mpDLTWrapper && mDebugEnabled && mlogDestination == logDestination::COMMAND_LINE)
+ {
+ mFilename.close();
+ }
+}
+
+void CAmDltWrapper::unregisterContext(DltContext &handle)
+{
+ if (mDebugEnabled && mlogDestination == logDestination::DAEMON)
+ {
+ dlt_unregister_context(&handle);
+ }
+}
+
+void CAmDltWrapper::deinit()
+{
+ if (mDebugEnabled)
+ {
+ unregisterContext(mDltContext);
+ }
+}
+
+void CAmDltWrapper::registerContext(DltContext &handle, const char *contextid, const char *description)
+{
+ if (mDebugEnabled && mlogDestination == logDestination::DAEMON)
+ {
+ dlt_register_context(&handle, contextid, description);
+ }
+ else if (mDebugEnabled)
+ {
+ mMapContext.emplace(&handle, std::string(contextid));
+
+ if (mlogDestination == logDestination::COMMAND_LINE)
+ {
+ std::cout << "\033[0;36m[DLT] Registering Context " << contextid << " , " << description << "\033[0m" << std::endl;
+ }
+ else
+ {
+ mFilename << now() << "[DLT] Registering Context " << contextid << " , " << description << std::endl;
+ }
+ }
+}
+
+void CAmDltWrapper::registerContext(DltContext &handle, const char *contextid, const char *description, const DltLogLevelType level, const DltTraceStatusType status)
+{
+ if (mDebugEnabled && mlogDestination == logDestination::DAEMON)
+ {
+ dlt_register_context_ll_ts(&handle, contextid, description, level, status);
+ }
+ else if (mDebugEnabled)
+ {
+ mMapContext.emplace(&handle, std::string(contextid));
+
+ if (mlogDestination == logDestination::COMMAND_LINE)
+ {
+ std::cout << "\033[0;36m[DLT] Registering Context " << contextid << " , " << description << "\033[0m" << std::endl;
+ }
+ else
+ {
+ mFilename << now() << " [DLT] Registering Context " << contextid << " , " << description << std::endl;
+ }
+ }
+}
+
+bool CAmDltWrapper::init(DltLogLevelType loglevel, DltContext *context)
+{
+ pthread_mutex_lock(&mMutex);
+ if (mlogDestination == logDestination::DAEMON)
+ {
+ if (!context)
+ {
+ context = &mDltContext;
+ }
+
+ if (dlt_user_log_write_start(context, &mDltContextData, loglevel) <= 0)
+ {
+ pthread_mutex_unlock(&mMutex);
+ return false;
+ }
+ }
+ else
+ {
+ initNoDlt(loglevel, context);
+ }
+
+ return true;
+}
+
+void CAmDltWrapper::send()
+{
+ if (mlogDestination == logDestination::DAEMON)
+ {
+ dlt_user_log_write_finish(&mDltContextData);
+ }
+ else
+ {
+ if (mlogDestination == logDestination::COMMAND_LINE && mLogOn)
+ {
+ std::cout << mNoDltContextData.buffer.str().c_str() << std::endl;
+ }
+ else if (mLogOn)
+ {
+ mFilename << now() << mNoDltContextData.buffer.str().c_str() << std::endl;
+ }
+
+ mNoDltContextData.buffer.str("");
+ mNoDltContextData.buffer.clear();
+ }
+
+ pthread_mutex_unlock(&mMutex);
+}
+
+void CAmDltWrapper::append(const int8_t value)
+{
+ if (mlogDestination == logDestination::DAEMON)
+ {
+ dlt_user_log_write_int8(&mDltContextData, value);
+ }
+ else
+ {
+ appendNoDLT(value);
+ }
+}
+
+void CAmDltWrapper::append(const uint8_t value)
+{
+ if (mlogDestination == logDestination::DAEMON)
+ {
+ dlt_user_log_write_uint8(&mDltContextData, value);
+ }
+ else
+ {
+ appendNoDLT(value);
+ }
+}
+
+void CAmDltWrapper::append(const int16_t value)
+{
+ if (mlogDestination == logDestination::DAEMON)
+ {
+ dlt_user_log_write_int16(&mDltContextData, value);
+ }
+ else
+ {
+ appendNoDLT(value);
+ }
+}
+
+void CAmDltWrapper::append(const uint16_t value)
+{
+ if (mlogDestination == logDestination::DAEMON)
+ {
+ dlt_user_log_write_uint16(&mDltContextData, value);
+ }
+ else
+ {
+ appendNoDLT(value);
+ }
+}
+
+void CAmDltWrapper::append(const int32_t value)
+{
+ if (mlogDestination == logDestination::DAEMON)
+ {
+ dlt_user_log_write_int32(&mDltContextData, value);
+ }
+ else
+ {
+ appendNoDLT(value);
+ }
+}
+
+void CAmDltWrapper::append(const uint32_t value)
+{
+ if (mlogDestination == logDestination::DAEMON)
+ {
+ dlt_user_log_write_uint32(&mDltContextData, value);
+ }
+ else
+ {
+ appendNoDLT(value);
+ }
+}
+
+void CAmDltWrapper::append(const std::string &value)
+{
+ append(value.c_str());
+}
+
+void CAmDltWrapper::append(const bool value)
+{
+ if (mlogDestination == logDestination::DAEMON)
+ {
+ dlt_user_log_write_bool(&mDltContextData, static_cast<uint8_t>(value));
+ }
+ else
+ {
+ appendNoDLT(value);
+ }
+}
+
+void CAmDltWrapper::append(const int64_t value)
+{
+ if (mlogDestination == logDestination::DAEMON)
+ {
+ dlt_user_log_write_int64(&mDltContextData, value);
+ }
+ else
+ {
+ appendNoDLT(value);
+ }
+}
+
+void CAmDltWrapper::append(const uint64_t value)
+{
+ if (mlogDestination == logDestination::DAEMON)
+ {
+ dlt_user_log_write_uint64(&mDltContextData, value);
+ }
+ else
+ {
+ appendNoDLT(value);
+ }
+}
+
+void CAmDltWrapper::append(const std::vector<uint8_t> &data)
+{
+ if (mlogDestination == logDestination::DAEMON)
+ {
+ dlt_user_log_write_raw(&mDltContextData, (void *)data.data(), data.size());
+ }
+ else
+ {
+ mNoDltContextData.buffer << data.data();
+ }
+}
+
+}
+#else // ------------------------------------------------------------------------------------------------- no DLT !
+CAmDltWrapper::CAmDltWrapper(const char *appid, const char *description, const bool debugEnabled, const logDestination logDest, const std::string Filename, bool onlyError)
+ : mDebugEnabled(debugEnabled)
+ , //
+ mlogDestination(logDest)
+ , //
+ mFilename(NULL)
+ , //
+ mOnlyError(onlyError)
+ , //
+ mLogOn(true)
+{
+ if (logDest == logDestination::DAEMON)
+ {
+ std::cout << "\033[0;31m[DLT] Cannot Use Daemon Logging, active in CMAKE! Using CommandLine\033[0m" << std::endl;
+ mlogDestination = logDestination::COMMAND_LINE;
+ }
+
+ if (mDebugEnabled)
+ {
+ if (mlogDestination == logDestination::COMMAND_LINE)
+ {
+ std::cout << "\033[0;36m[DLT] Registering AppID " << appid << " , " << description << "\033[0m" << std::endl;
+ }
+ else
+ {
+ mFilename.open(Filename, std::ofstream::out | std::ofstream::trunc);
+ if (!mFilename.is_open())
+ {
+ throw std::runtime_error("Cannot open file for logging");
+ }
+
+ mFilename << now() << "[DLT] Registering AppID " << appid << " , " << description << std::endl;
+ }
+ }
+}
+
+CAmDltWrapper::~CAmDltWrapper()
+{
+ if (mpDLTWrapper && mDebugEnabled && mlogDestination == logDestination::COMMAND_LINE)
+ {
+ mFilename.close();
+ }
+}
+
+void CAmDltWrapper::unregisterContext(DltContext &handle)
+{
+}
+
+void CAmDltWrapper::deinit()
+{
+}
+
+void CAmDltWrapper::registerContext(DltContext &handle, const char *contextid, const char *description)
+{
+ if (mDebugEnabled)
+ {
+ mMapContext.emplace(&handle, std::string(contextid));
+
+ if (mlogDestination == logDestination::COMMAND_LINE)
+ {
+ std::cout << "\033[0;36m[DLT] Registering Context " << contextid << " , " << description << "\033[0m" << std::endl;
+ }
+ else
+ {
+ mFilename << now() << "[DLT] Registering Context " << contextid << " , " << description << std::endl;
+ }
+ }
+}
+
+void CAmDltWrapper::registerContext(DltContext &handle, const char *contextid, const char *description, const DltLogLevelType level, const DltTraceStatusType status)
+{
+ if (mDebugEnabled)
+ {
+ mMapContext.emplace(&handle, std::string(contextid));
+
+ if (mlogDestination == logDestination::COMMAND_LINE)
+ {
+ std::cout << "\033[0;36m[DLT] Registering Context " << contextid << " , " << description << "\033[0m" << std::endl;
+ }
+ else
+ {
+ mFilename << now() << " [DLT] Registering Context " << contextid << " , " << description << std::endl;
+ }
+ }
+}
+
+bool CAmDltWrapper::init(DltLogLevelType loglevel, DltContext *context)
+{
+ pthread_mutex_lock(&mMutex);
+ return initNoDlt(loglevel, context);
+}
+
+void CAmDltWrapper::send()
+{
+ if (mlogDestination == logDestination::COMMAND_LINE && mLogOn)
+ {
+ std::cout << mNoDltContextData.buffer.str().c_str() << std::endl;
+ }
+ else if (mLogOn)
+ {
+ mFilename << now() << mNoDltContextData.buffer.str().c_str() << std::endl;
+ }
+
+ mNoDltContextData.buffer.str("");
+ mNoDltContextData.buffer.clear();
+ pthread_mutex_unlock(&mMutex);
+}
+void CAmDltWrapper::append(const int8_t value)
+{
+ appendNoDLT(value);
+}
+void CAmDltWrapper::append(const uint8_t value)
+{
+ appendNoDLT(value);
+}
+
+void CAmDltWrapper::append(const int16_t value)
+{
+ appendNoDLT(value);
+}
+
+void CAmDltWrapper::append(const uint16_t value)
+{
+ appendNoDLT(value);
+}
+
+void CAmDltWrapper::append(const int32_t value)
+{
+ appendNoDLT(value);
+}
+
+void CAmDltWrapper::append(const uint32_t value)
+{
+ appendNoDLT(value);
+}
+
+void CAmDltWrapper::append(const std::string &value)
+{
+ append(value.c_str());
+}
+
+void CAmDltWrapper::append(const bool value)
+{
+ appendNoDLT(value);
+}
+
+void CAmDltWrapper::append(const int64_t value)
+{
+ appendNoDLT(value);
+}
+
+void CAmDltWrapper::append(const uint64_t value)
+{
+ appendNoDLT(value);
+}
+
+void CAmDltWrapper::append(const std::vector<uint8_t> &data)
+{
+ mNoDltContextData.buffer << data.data();
+}
+
+}
+#endif // WITH_DLT
diff --git a/AudioManagerUtilities/src/CAmSocketHandler.cpp b/AudioManagerUtilities/src/CAmSocketHandler.cpp
index 9d9196a..8f0cdb0 100644
--- a/AudioManagerUtilities/src/CAmSocketHandler.cpp
+++ b/AudioManagerUtilities/src/CAmSocketHandler.cpp
@@ -37,66 +37,71 @@
#include "CAmSocketHandler.h"
#ifdef WITH_TIMERFD
-#include <sys/timerfd.h>
+# include <sys/timerfd.h>
#endif
-#define END_EVENT (UINT64_MAX >> 1)
+#define END_EVENT (UINT64_MAX >> 1)
namespace am
{
-CAmSocketHandler::CAmSocketHandler() :
- mEventFd(-1),
- mSignalFd(-1),
- mDispatchDone(true),
- mSetPollKeys(MAX_POLLHANDLE),
- mMapShPoll(),
- mSetTimerKeys(MAX_TIMERHANDLE),
- mListTimer(),
+CAmSocketHandler::CAmSocketHandler()
+ : mEventFd(-1)
+ , mSignalFd(-1)
+ , mDispatchDone(true)
+ , mSetPollKeys(MAX_POLLHANDLE)
+ , mMapShPoll()
+ , mSetTimerKeys(MAX_TIMERHANDLE)
+ , mListTimer()
+ ,
#ifndef WITH_TIMERFD
- mListActiveTimer(),
+ mListActiveTimer()
+ ,
#endif
- mSetSignalhandlerKeys(MAX_POLLHANDLE),
- mSignalHandlers(),
- mInternalCodes(internal_codes_e::NO_ERROR)
+ mSetSignalhandlerKeys(MAX_POLLHANDLE)
+ , mSignalHandlers()
+ , mInternalCodes(internal_codes_e::NO_ERROR)
#ifndef WITH_TIMERFD
- ,mStartTime()
+ , mStartTime()
#endif
{
- auto actionPoll = [this](const pollfd pollfd, const sh_pollHandle_t, void*)
- {
- /* We have a valid signal, read the info from the fd */
- uint64_t events;
- ssize_t bytes = read(pollfd.fd, &events, sizeof(events));
- if (bytes == sizeof(events))
- {
- if (events >= END_EVENT)
- {
- for (auto & elem : mMapShPoll)
- {
- if (elem.second.state == poll_states_e::UPDATE ||
- elem.second.state == poll_states_e::VALID)
- {
- elem.second.state = poll_states_e::ADD;
- }
- }
- mDispatchDone = true;
- }
- return;
- }
-
- // ppoll on EAGAIN
- if ((bytes == -1) && (errno == EAGAIN))
- return;
-
- //Failed to read from event fd...
- std::ostringstream msg;
- msg << "Failed to read from event fd: " << pollfd.fd << " errno: " << std::strerror(errno);
- throw std::runtime_error(msg.str());
- };
-
- //add the pipe to the poll - nothing needs to be processed here we just need the pipe to trigger the ppoll
+ auto actionPoll = [this](const pollfd pollfd, const sh_pollHandle_t, void *){
+ /* We have a valid signal, read the info from the fd */
+ uint64_t events;
+ ssize_t bytes = read(pollfd.fd, &events, sizeof(events));
+ if (bytes == sizeof(events))
+ {
+ if (events >= END_EVENT)
+ {
+ for (auto &elem : mMapShPoll)
+ {
+ if (elem.second.state == poll_states_e::UPDATE ||
+ elem.second.state == poll_states_e::VALID)
+ {
+ elem.second.state = poll_states_e::ADD;
+ }
+ }
+
+ mDispatchDone = true;
+ }
+
+ return;
+ }
+
+ // ppoll on EAGAIN
+ if ((bytes == -1) && (errno == EAGAIN))
+ {
+ return;
+ }
+
+ // Failed to read from event fd...
+ std::ostringstream msg;
+ msg << "Failed to read from event fd: " << pollfd.fd << " errno: " << std::strerror(errno);
+ throw std::runtime_error(msg.str());
+ };
+
+ // add the pipe to the poll - nothing needs to be processed here we just need the pipe to trigger the ppoll
sh_pollHandle_t handle;
mEventFd = eventfd(1, EFD_NONBLOCK | EFD_CLOEXEC);
if (addFDPoll(mEventFd, POLLIN, NULL, actionPoll, NULL, NULL, NULL, handle) != E_OK)
@@ -107,26 +112,26 @@ CAmSocketHandler::CAmSocketHandler() :
CAmSocketHandler::~CAmSocketHandler()
{
- for (const auto& it : mMapShPoll)
+ for (const auto &it : mMapShPoll)
{
close(it.second.pollfdValue.fd);
}
}
-//todo: maybe have some: give me more time returned?
+// todo: maybe have some: give me more time returned?
/**
- * start the block listening for filedescriptors. This is the mainloop.
- */
+ * start the block listening for filedescriptors. This is the mainloop.
+ */
void CAmSocketHandler::start_listenting()
{
mDispatchDone = false;
-#ifndef WITH_TIMERFD
+#ifndef WITH_TIMERFD
clock_gettime(CLOCK_MONOTONIC, &mStartTime);
-#endif
+#endif
timespec buffertime;
- VectorPollfd_t fdPollingArray; //!<the polling array for ppoll
+ VectorPollfd_t fdPollingArray; //!< the polling array for ppoll
while (!mDispatchDone)
{
@@ -138,35 +143,35 @@ void CAmSocketHandler::start_listenting()
for (auto it = mMapShPoll.begin(); it != mMapShPoll.end(); )
{
// NOTE: The order of the switch/case statement reflects the state flow
- auto& elem = it->second;
+ auto &elem = it->second;
switch (elem.state)
{
- case poll_states_e::ADD:
- elem.state = poll_states_e::UPDATE;
- fdPollIt = fdPollingArray.emplace(fdPollIt);
- break;
-
- case poll_states_e::UPDATE:
- elem.state = poll_states_e::VALID;
- CAmSocketHandler::prepare(elem);
- *fdPollIt = elem.pollfdValue;
- break;
-
- case poll_states_e::VALID:
- // check for multi-thread access
- assert(fdPollIt != fdPollingArray.end());
- ++fdPollIt;
- ++it;
- break;
-
- case poll_states_e::REMOVE:
- elem.state = poll_states_e::INVALID;
- fdPollIt = fdPollingArray.erase(fdPollIt);
- break;
-
- case poll_states_e::INVALID:
- it = mMapShPoll.erase(it);
- break;
+ case poll_states_e::ADD:
+ elem.state = poll_states_e::UPDATE;
+ fdPollIt = fdPollingArray.emplace(fdPollIt);
+ break;
+
+ case poll_states_e::UPDATE:
+ elem.state = poll_states_e::VALID;
+ CAmSocketHandler::prepare(elem);
+ *fdPollIt = elem.pollfdValue;
+ break;
+
+ case poll_states_e::VALID:
+ // check for multi-thread access
+ assert(fdPollIt != fdPollingArray.end());
+ ++fdPollIt;
+ ++it;
+ break;
+
+ case poll_states_e::REMOVE:
+ elem.state = poll_states_e::INVALID;
+ fdPollIt = fdPollingArray.erase(fdPollIt);
+ break;
+
+ case poll_states_e::INVALID:
+ it = mMapShPoll.erase(it);
+ break;
}
}
@@ -186,16 +191,20 @@ void CAmSocketHandler::start_listenting()
if (pollStatus > 0)
{
// stage 0+1, call firedCB
- std::list<sh_poll_s*> listPoll;
- for (auto& it : fdPollingArray)
+ std::list<sh_poll_s *> listPoll;
+ for (auto &it : fdPollingArray)
{
it.revents &= it.events;
if (it.revents == 0)
+ {
continue;
+ }
- sh_poll_s& pollObj = mMapShPoll.at(it.fd);
+ sh_poll_s &pollObj = mMapShPoll.at(it.fd);
if (pollObj.state != poll_states_e::VALID)
+ {
continue;
+ }
// ensure to copy the revents fired in fdPollingArray
pollObj.pollfdValue.revents = it.revents;
@@ -203,11 +212,11 @@ void CAmSocketHandler::start_listenting()
CAmSocketHandler::fire(pollObj);
it.revents = 0;
}
-
- //stage 2, lets ask around if some dispatching is necessary, the ones who need stay on the list
+
+ // stage 2, lets ask around if some dispatching is necessary, the ones who need stay on the list
listPoll.remove_if(CAmSocketHandler::noDispatching);
- //stage 3, the ones left need to dispatch, we do this as long as there is something to dispatch..
+ // stage 3, the ones left need to dispatch, we do this as long as there is something to dispatch..
do
{
listPoll.remove_if(CAmSocketHandler::dispatchingFinished);
@@ -218,11 +227,11 @@ void CAmSocketHandler::start_listenting()
logError("SocketHandler::start_listenting ppoll returned with error", errno);
throw std::runtime_error(std::string("SocketHandler::start_listenting ppoll returned with error."));
}
- else //Timerevent
+ else // Timerevent
{
#ifndef WITH_TIMERFD
- //this was a timer event, we need to take care about the timers
- //find out the timedifference to starttime
+ // this was a timer event, we need to take care about the timers
+ // find out the timedifference to starttime
timerUp();
#endif
}
@@ -230,36 +239,39 @@ void CAmSocketHandler::start_listenting()
}
/**
- * exits the loop
- */
+ * exits the loop
+ */
void CAmSocketHandler::stop_listening()
{
- //fire the ending event
+ // fire the ending event
if (mDispatchDone)
+ {
return;
+ }
wakeupWorker("stop_listening", END_EVENT);
#ifndef WITH_TIMERFD
- //this is for all running timers only - we need to handle the additional offset here
+ // this is for all running timers only - we need to handle the additional offset here
if (!mListActiveTimer.empty())
{
timespec currentTime, correctionTime;
clock_gettime(CLOCK_MONOTONIC, &currentTime);
correctionTime = timespecSub(currentTime, mStartTime);
- std::for_each(mListActiveTimer.begin(), mListActiveTimer.end(), [&correctionTime](sh_timer_s& t)
- { t.countdown = timespecSub(t.countdown, correctionTime);});
+ std::for_each(mListActiveTimer.begin(), mListActiveTimer.end(), [&correctionTime](sh_timer_s &t){
+ t.countdown = timespecSub(t.countdown, correctionTime);
+ });
}
-#endif
+#endif // ifndef WITH_TIMERFD
}
void CAmSocketHandler::exit_mainloop()
{
- //end the while loop
+ // end the while loop
stop_listening();
}
-void CAmSocketHandler::wakeupWorker(const std::string & func, const uint64_t value)
+void CAmSocketHandler::wakeupWorker(const std::string &func, const uint64_t value)
{
if (write(mEventFd, &value, sizeof(value)) < 0)
{
@@ -270,27 +282,27 @@ void CAmSocketHandler::wakeupWorker(const std::string & func, const uint64_t val
}
}
-bool CAmSocketHandler::fatalErrorOccurred()
+bool CAmSocketHandler::fatalErrorOccurred()
{
return (mInternalCodes != internal_codes_e::NO_ERROR);
}
/**
- * Adds a signal handler filedescriptor to the polling loop
- *
- */
-am_Error_e CAmSocketHandler::listenToSignals(const std::vector<uint8_t> & listSignals)
+ * Adds a signal handler filedescriptor to the polling loop
+ *
+ */
+am_Error_e CAmSocketHandler::listenToSignals(const std::vector<uint8_t> &listSignals)
{
- int fdErr;
- uint8_t addedSignals = 0;
+ int fdErr;
+ uint8_t addedSignals = 0;
sigset_t sigset;
-
- if(0==listSignals.size())
+
+ if (0 == listSignals.size())
{
logWarning("Empty signal list!");
return (E_NOT_POSSIBLE);
}
-
+
/* Create a sigset of all the signals that we're interested in */
fdErr = sigemptyset(&sigset);
if (fdErr != 0)
@@ -298,17 +310,21 @@ am_Error_e CAmSocketHandler::listenToSignals(const std::vector<uint8_t> & listSi
logError("Could not create sigset!");
return (E_NOT_POSSIBLE);
}
-
- for(uint8_t itSignal : listSignals)
+
+ for (uint8_t itSignal : listSignals)
{
fdErr = sigaddset(&sigset, itSignal);
if (fdErr != 0)
+ {
logWarning("Could not add", itSignal);
+ }
else
- addedSignals++;
+ {
+ addedSignals++;
+ }
}
-
- if(0==addedSignals)
+
+ if (0 == addedSignals)
{
logWarning("None of the signals were added!");
return (E_NOT_POSSIBLE);
@@ -332,32 +348,36 @@ am_Error_e CAmSocketHandler::listenToSignals(const std::vector<uint8_t> & listSi
return (E_NOT_POSSIBLE);
}
- auto actionPoll = [this](const pollfd pollfd, const sh_pollHandle_t, void*)
- {
- /* We have a valid signal, read the info from the fd */
- struct signalfd_siginfo info;
- ssize_t bytes = read(pollfd.fd, &info, sizeof(info));
- if (bytes == sizeof(info))
- {
- /* Notify all listeners */
- for(const auto& it: mSignalHandlers)
- it.callback(it.handle, info, it.userData);
- return;
- }
-
- // ppoll on EAGAIN
- if ((bytes == -1) && (errno == EAGAIN))
- return;
-
- //Failed to read from fd...
- std::ostringstream msg;
- msg << "Failed to read from signal fd: " << pollfd.fd << " errno: " << std::strerror(errno);
- throw std::runtime_error(msg.str());
- };
+ auto actionPoll = [this](const pollfd pollfd, const sh_pollHandle_t, void *){
+ /* We have a valid signal, read the info from the fd */
+ struct signalfd_siginfo info;
+ ssize_t bytes = read(pollfd.fd, &info, sizeof(info));
+ if (bytes == sizeof(info))
+ {
+ /* Notify all listeners */
+ for (const auto &it: mSignalHandlers)
+ {
+ it.callback(it.handle, info, it.userData);
+ }
+
+ return;
+ }
+
+ // ppoll on EAGAIN
+ if ((bytes == -1) && (errno == EAGAIN))
+ {
+ return;
+ }
+
+ // Failed to read from fd...
+ std::ostringstream msg;
+ msg << "Failed to read from signal fd: " << pollfd.fd << " errno: " << std::strerror(errno);
+ throw std::runtime_error(msg.str());
+ };
/* We're going to add the signal fd through addFDPoll. At this point we don't have any signal listeners. */
sh_pollHandle_t handle;
return addFDPoll(mSignalFd, POLLIN | POLLERR | POLLHUP, NULL, actionPoll, NULL, NULL, NULL, handle);
- }
+ }
else
{
if (signalfd(mSignalFd, &sigset, 0) == -1)
@@ -365,39 +385,41 @@ am_Error_e CAmSocketHandler::listenToSignals(const std::vector<uint8_t> & listSi
logError("Could not update signal fd!", std::strerror(errno));
return (E_NOT_POSSIBLE);
}
+
return E_OK;
}
}
/**
- * Adds a filedescriptor to the polling loop
- * @param fd the filedescriptor
- * @param event the event flags
- * @param prepare a std::function that is called before the loop is entered
- * @param fired a std::function that is called when the filedescriptor needs to be read
- * @param check a std::function that is called to check if further actions are neccessary
- * @param dispatch a std::function that is called to dispatch the received data
- * @param userData a pointer to userdata that is always passed around
- * @param handle the handle of this poll
- * @return E_OK if the descriptor was added
- * E_NON_EXISTENT if the fd is not valid
- * E_ALREADY_EXISTS if the fd is already known
- * E_NOT_POSSIBLE if the maximum handle threshold is reached
- */
-
+ * Adds a filedescriptor to the polling loop
+ * @param fd the filedescriptor
+ * @param event the event flags
+ * @param prepare a std::function that is called before the loop is entered
+ * @param fired a std::function that is called when the filedescriptor needs to be read
+ * @param check a std::function that is called to check if further actions are neccessary
+ * @param dispatch a std::function that is called to dispatch the received data
+ * @param userData a pointer to userdata that is always passed around
+ * @param handle the handle of this poll
+ * @return E_OK if the descriptor was added
+ * E_NON_EXISTENT if the fd is not valid
+ * E_ALREADY_EXISTS if the fd is already known
+ * E_NOT_POSSIBLE if the maximum handle threshold is reached
+ */
am_Error_e CAmSocketHandler::addFDPoll(const int fd,
- const short event,
- std::function<void(const sh_pollHandle_t handle, void* userData)> prepare,
- std::function<void(const pollfd pollfd, const sh_pollHandle_t handle, void* userData)> fired,
- std::function<bool(const sh_pollHandle_t handle, void* userData)> check,
- std::function<bool(const sh_pollHandle_t handle, void* userData)> dispatch,
- void* userData,
- sh_pollHandle_t& handle)
+ const short event,
+ std::function<void(const sh_pollHandle_t handle, void *userData)> prepare,
+ std::function<void(const pollfd pollfd, const sh_pollHandle_t handle, void *userData)> fired,
+ std::function<bool(const sh_pollHandle_t handle, void *userData)> check,
+ std::function<bool(const sh_pollHandle_t handle, void *userData)> dispatch,
+ void *userData,
+ sh_pollHandle_t &handle)
{
sh_poll_s pollData;
if (!fdIsValid(fd))
+ {
return E_NON_EXISTENT;
+ }
const auto elem = mMapShPoll.find(fd);
if (elem != mMapShPoll.end())
@@ -405,38 +427,38 @@ am_Error_e CAmSocketHandler::addFDPoll(const int fd,
// The fd was already in map therefore we need to trigger an update instead
switch (elem->second.state)
{
- case poll_states_e::REMOVE:
- pollData.state = poll_states_e::UPDATE;
- break;
+ case poll_states_e::REMOVE:
+ pollData.state = poll_states_e::UPDATE;
+ break;
- case poll_states_e::INVALID:
- pollData.state = poll_states_e::ADD;
- break;
+ case poll_states_e::INVALID:
+ pollData.state = poll_states_e::ADD;
+ break;
- default:
- logError("CAmSocketHandler::addFDPoll fd", fd, "already registered!");
- return E_ALREADY_EXISTS;
+ default:
+ logError("CAmSocketHandler::addFDPoll fd", fd, "already registered!");
+ return E_ALREADY_EXISTS;
}
}
- //create a new handle for the poll
+ // create a new handle for the poll
if (!nextHandle(mSetPollKeys))
{
logError("CAmSocketHandler::addFDPoll Max handle count reached!");
return (E_NOT_POSSIBLE);
}
- pollData.pollfdValue.fd = fd;
- pollData.handle = mSetPollKeys.lastUsedID;
- pollData.pollfdValue.events = event;
+ pollData.pollfdValue.fd = fd;
+ pollData.handle = mSetPollKeys.lastUsedID;
+ pollData.pollfdValue.events = event;
pollData.pollfdValue.revents = 0;
- pollData.prepareCB = prepare;
- pollData.firedCB = fired;
- pollData.checkCB = check;
- pollData.dispatchCB = dispatch;
- pollData.userData = userData;
+ pollData.prepareCB = prepare;
+ pollData.firedCB = fired;
+ pollData.checkCB = check;
+ pollData.dispatchCB = dispatch;
+ pollData.userData = userData;
- //add new data to the list
+ // add new data to the list
mMapShPoll[fd] = pollData;
wakeupWorker("addFDPoll");
@@ -446,49 +468,60 @@ am_Error_e CAmSocketHandler::addFDPoll(const int fd,
}
/**
- * Adds a filedescriptor to the polling loop
- * @param fd the filedescriptor
- * @param event the event flags
- * @param prepare a callback that is called before the loop is entered
- * @param fired a callback that is called when the filedescriptor needs to be read
- * @param check a callback that is called to check if further actions are neccessary
- * @param dispatch a callback that is called to dispatch the received data
- * @param userData a pointer to userdata that is always passed around
- * @param handle the handle of this poll
- * @return E_OK if the descriptor was added
- * E_NON_EXISTENT if the fd is not valid
- * E_ALREADY_EXISTS if the fd is already known
- * E_NOT_POSSIBLE if the maximum handle threshold is reached
- */
-am::am_Error_e CAmSocketHandler::addFDPoll(const int fd, const short event, IAmShPollPrepare *prepare, IAmShPollFired *fired, IAmShPollCheck *check, IAmShPollDispatch *dispatch, void *userData, sh_pollHandle_t & handle)
+ * Adds a filedescriptor to the polling loop
+ * @param fd the filedescriptor
+ * @param event the event flags
+ * @param prepare a callback that is called before the loop is entered
+ * @param fired a callback that is called when the filedescriptor needs to be read
+ * @param check a callback that is called to check if further actions are neccessary
+ * @param dispatch a callback that is called to dispatch the received data
+ * @param userData a pointer to userdata that is always passed around
+ * @param handle the handle of this poll
+ * @return E_OK if the descriptor was added
+ * E_NON_EXISTENT if the fd is not valid
+ * E_ALREADY_EXISTS if the fd is already known
+ * E_NOT_POSSIBLE if the maximum handle threshold is reached
+ */
+am::am_Error_e CAmSocketHandler::addFDPoll(const int fd, const short event, IAmShPollPrepare *prepare, IAmShPollFired *fired, IAmShPollCheck *check, IAmShPollDispatch *dispatch, void *userData, sh_pollHandle_t &handle)
{
- std::function<void(const sh_pollHandle_t, void*)> prepareCB; //preperation callback
- std::function<void(const pollfd, const sh_pollHandle_t, void*)> firedCB; //fired callback
- std::function<bool(const sh_pollHandle_t, void*)> checkCB; //check callback
- std::function<bool(const sh_pollHandle_t, void*)> dispatchCB; //check callback
+ std::function<void(const sh_pollHandle_t, void *)> prepareCB; // preperation callback
+ std::function<void(const pollfd, const sh_pollHandle_t, void *)> firedCB; // fired callback
+ std::function<bool(const sh_pollHandle_t, void *)> checkCB; // check callback
+ std::function<bool(const sh_pollHandle_t, void *)> dispatchCB; // check callback
if (prepare)
+ {
prepareCB = std::bind(&IAmShPollPrepare::Call, prepare, std::placeholders::_1, std::placeholders::_2);
+ }
+
if (fired)
+ {
firedCB = std::bind(&IAmShPollFired::Call, fired, std::placeholders::_1, std::placeholders::_2, std::placeholders::_3);
+ }
+
if (check)
+ {
checkCB = std::bind(&IAmShPollCheck::Call, check, std::placeholders::_1, std::placeholders::_2);
+ }
+
if (dispatch)
+ {
dispatchCB = std::bind(&IAmShPollDispatch::Call, dispatch, std::placeholders::_1, std::placeholders::_2);
+ }
return addFDPoll(fd, event, prepareCB, firedCB, checkCB, dispatchCB, userData, handle);
}
/**
- * removes a filedescriptor from the poll loop
- * @param handle
- * @param [rmv] default RMV_ONLY_FDPOLL
- * @return
- */
+ * removes a filedescriptor from the poll loop
+ * @param handle
+ * @param [rmv] default RMV_ONLY_FDPOLL
+ * @return
+ */
am_Error_e CAmSocketHandler::removeFDPoll(const sh_pollHandle_t handle)
{
- for (auto& it : mMapShPoll)
+ for (auto &it : mMapShPoll)
{
if (it.second.handle == handle)
{
@@ -498,18 +531,19 @@ am_Error_e CAmSocketHandler::removeFDPoll(const sh_pollHandle_t handle)
return E_OK;
}
}
+
logWarning("CAmSocketHandler::removeFDPoll handle unknown", handle);
return E_UNKNOWN;
}
/**
- * Adds a callback for any signals
- * @param callback
- * @param handle the handle of this poll
- * @param userData a pointer to userdata that is always passed around
- * @return E_OK if the descriptor was added, E_NON_EXISTENT if the fd is not valid
- */
-am_Error_e CAmSocketHandler::addSignalHandler(std::function<void(const sh_pollHandle_t handle, const signalfd_siginfo & info, void* userData)> callback, sh_pollHandle_t& handle, void * userData)
+ * Adds a callback for any signals
+ * @param callback
+ * @param handle the handle of this poll
+ * @param userData a pointer to userdata that is always passed around
+ * @return E_OK if the descriptor was added, E_NON_EXISTENT if the fd is not valid
+ */
+am_Error_e CAmSocketHandler::addSignalHandler(std::function<void(const sh_pollHandle_t handle, const signalfd_siginfo &info, void *userData)> callback, sh_pollHandle_t &handle, void *userData)
{
if (!nextHandle(mSetSignalhandlerKeys))
{
@@ -519,7 +553,7 @@ am_Error_e CAmSocketHandler::addSignalHandler(std::function<void(const sh_pollHa
mSignalHandlers.emplace_back();
mSignalHandlers.back().callback = callback;
- mSignalHandlers.back().handle = mSetSignalhandlerKeys.lastUsedID;
+ mSignalHandlers.back().handle = mSetSignalhandlerKeys.lastUsedID;
mSignalHandlers.back().userData = userData;
handle = mSetSignalhandlerKeys.lastUsedID;
@@ -527,10 +561,10 @@ am_Error_e CAmSocketHandler::addSignalHandler(std::function<void(const sh_pollHa
}
/**
- * removes a signal handler from the list
- * @param handle is signal handler id
- * @return E_OK in case of success, E_UNKNOWN if the handler was not found.
- */
+ * removes a signal handler from the list
+ * @param handle is signal handler id
+ * @return E_OK in case of success, E_UNKNOWN if the handler was not found.
+ */
am_Error_e CAmSocketHandler::removeSignalHandler(const sh_pollHandle_t handle)
{
VectorSignalHandlers_t::iterator it(mSignalHandlers.begin());
@@ -543,37 +577,37 @@ am_Error_e CAmSocketHandler::removeSignalHandler(const sh_pollHandle_t handle)
return (E_OK);
}
}
+
return (E_UNKNOWN);
}
/**
- * adds a timer to the list of timers. The callback will be fired when the timer is up.
- * This is not a high precise timer, it is very coarse. It is meant to be used for timeouts when waiting
- * for an answer via a filedescriptor.
- * One time timer. If you need again a timer, you need to add a new timer in the callback of the old one.
- * @param timeouts timeouts time until the callback is fired
- * @param callback callback the callback
- * @param handle handle the handle that is created for the timer is returned. Can be used to remove the timer
- * @param userData pointer always passed with the call
- * @return E_OK in case of success
- */
-
-am_Error_e CAmSocketHandler::addTimer(const timespec & timeouts, IAmShTimerCallBack* callback, sh_timerHandle_t& handle, void * userData, const bool repeats)
+ * adds a timer to the list of timers. The callback will be fired when the timer is up.
+ * This is not a high precise timer, it is very coarse. It is meant to be used for timeouts when waiting
+ * for an answer via a filedescriptor.
+ * One time timer. If you need again a timer, you need to add a new timer in the callback of the old one.
+ * @param timeouts timeouts time until the callback is fired
+ * @param callback callback the callback
+ * @param handle handle the handle that is created for the timer is returned. Can be used to remove the timer
+ * @param userData pointer always passed with the call
+ * @return E_OK in case of success
+ */
+am_Error_e CAmSocketHandler::addTimer(const timespec &timeouts, IAmShTimerCallBack *callback, sh_timerHandle_t &handle, void *userData, const bool repeats)
{
- assert(callback!=NULL);
+ assert(callback != NULL);
- std::function<void(const sh_timerHandle_t handle, void* userData)> callbackFunc;
+ std::function<void(const sh_timerHandle_t handle, void *userData)> callbackFunc;
callbackFunc = std::bind(&IAmShTimerCallBack::Call, callback, std::placeholders::_1, std::placeholders::_2);
return addTimer(timeouts, callbackFunc, handle, userData, repeats);
}
-am_Error_e CAmSocketHandler::addTimer(const timespec & timeouts, std::function<void(const sh_timerHandle_t handle, void* userData)> callback, sh_timerHandle_t& handle, void * userData, const bool repeats)
+am_Error_e CAmSocketHandler::addTimer(const timespec &timeouts, std::function<void(const sh_timerHandle_t handle, void *userData)> callback, sh_timerHandle_t &handle, void *userData, const bool repeats)
{
assert(!((timeouts.tv_sec == 0) && (timeouts.tv_nsec == 0)));
-#ifndef WITH_TIMERFD
- //create a new handle for the timer
+#ifndef WITH_TIMERFD
+ // create a new handle for the timer
if (!nextHandle(mSetTimerKeys))
{
logError("CAmSocketHandler::addTimer Could not create new timers, too many open!");
@@ -581,69 +615,78 @@ am_Error_e CAmSocketHandler::addTimer(const timespec & timeouts, std::function<v
}
mListTimer.emplace_back();
- sh_timer_s & timerItem = mListTimer.back();
+ sh_timer_s &timerItem = mListTimer.back();
- //create a new handle for the timer
+ // create a new handle for the timer
handle = mSetTimerKeys.lastUsedID;
timerItem.countdown = timeouts;
- timerItem.callback = callback;
- timerItem.userData = userData;
+ timerItem.callback = callback;
+ timerItem.userData = userData;
timerItem.handle = handle;
- //we add here the time difference between startTime and currenttime, because this time will be substracted later on in timecorrection
+ // we add here the time difference between startTime and currenttime, because this time will be substracted later on in timecorrection
timespec currentTime;
clock_gettime(CLOCK_MONOTONIC, &currentTime);
- if (!mDispatchDone)//the mainloop is started
- timerItem.countdown = timespecAdd(timeouts, timespecSub(currentTime, mStartTime));
+ if (!mDispatchDone)// the mainloop is started
+ {
+ timerItem.countdown = timespecAdd(timeouts, timespecSub(currentTime, mStartTime));
+ }
+
mListActiveTimer.push_back(timerItem);
mListActiveTimer.sort(compareCountdown);
return (E_OK);
-
-#else
+#else // ifndef WITH_TIMERFD
sh_timer_s timerItem;
timerItem.countdown.it_value = timeouts;
if (repeats)
+ {
timerItem.countdown.it_interval = timeouts;
+ }
else
{
timespec zero;
- zero.tv_sec = 0;
- zero.tv_nsec = 0;
+ zero.tv_sec = 0;
+ zero.tv_nsec = 0;
timerItem.countdown.it_interval = zero;
}
- timerItem.fd = -1;
+ timerItem.fd = -1;
timerItem.userData = userData;
am_Error_e err = createTimeFD(timerItem.countdown, timerItem.fd);
if (err != E_OK)
+ {
return err;
+ }
- auto actionPoll = [this](const pollfd pollfd, const sh_pollHandle_t handle, void* userData)
- {
- uint64_t expCnt;
- ssize_t bytes = read(pollfd.fd, &expCnt, sizeof(expCnt));
- if (bytes == sizeof(expCnt))
- return;
+ auto actionPoll = [this](const pollfd pollfd, const sh_pollHandle_t handle, void *userData){
+ uint64_t expCnt;
+ ssize_t bytes = read(pollfd.fd, &expCnt, sizeof(expCnt));
+ if (bytes == sizeof(expCnt))
+ {
+ return;
+ }
- // ppoll has to be called again in following case
- if ((bytes == -1) && (errno == EAGAIN))
- return;
+ // ppoll has to be called again in following case
+ if ((bytes == -1) && (errno == EAGAIN))
+ {
+ return;
+ }
- // failed to read data from timer_fd...
- std::ostringstream msg;
- msg << "Failed to read from timer fd: " << pollfd.fd << " errno: " << std::strerror(errno);
- throw std::runtime_error(msg.str());
- };
+ // failed to read data from timer_fd...
+ std::ostringstream msg;
+ msg << "Failed to read from timer fd: " << pollfd.fd << " errno: " << std::strerror(errno);
+ throw std::runtime_error(msg.str());
+ };
err = addFDPoll(timerItem.fd, POLLIN | POLLERR, NULL, actionPoll,
- [callback](const sh_pollHandle_t handle, void* userData)->bool {
- callback(handle, userData);
- return false;
- },
- NULL, userData, handle);
+ [callback](const sh_pollHandle_t handle, void *userData) -> bool {
+ callback(handle, userData);
+ return false;
+ },
+ NULL, userData, handle);
if (err == E_OK)
{
@@ -654,24 +697,25 @@ am_Error_e CAmSocketHandler::addTimer(const timespec & timeouts, std::function<v
// E_NOT_POSSIBLE is the only case were we need to close the timer
if (err == E_NOT_POSSIBLE)
+ {
close(timerItem.fd);
-
+ }
return err;
-#endif
+#endif // ifndef WITH_TIMERFD
}
/**
- * removes a timer from the list of timers
- * @param handle the handle to the timer
- * @return E_OK in case of success, E_UNKNOWN if timer was not found.
- */
+ * removes a timer from the list of timers
+ * @param handle the handle to the timer
+ * @return E_OK in case of success, E_UNKNOWN if timer was not found.
+ */
am_Error_e CAmSocketHandler::removeTimer(const sh_timerHandle_t handle)
{
assert(handle != 0);
- //stop the current timer
-#ifdef WITH_TIMERFD
+ // stop the current timer
+#ifdef WITH_TIMERFD
std::list<sh_timer_s>::iterator it(mListTimer.begin());
while (it != mListTimer.end())
{
@@ -682,11 +726,12 @@ am_Error_e CAmSocketHandler::removeTimer(const sh_timerHandle_t handle)
mListTimer.erase(it);
return err;
}
+
++it;
}
- return (E_NON_EXISTENT);
-#else
+ return (E_NON_EXISTENT);
+#else // ifdef WITH_TIMERFD
stopTimer(handle);
std::list<sh_timer_s>::iterator it(mListTimer.begin());
while (it != mListTimer.end())
@@ -697,39 +742,50 @@ am_Error_e CAmSocketHandler::removeTimer(const sh_timerHandle_t handle)
mSetTimerKeys.pollHandles.erase(handle);
return (E_OK);
}
+
++it;
}
return (E_UNKNOWN);
-#endif
+#endif // ifdef WITH_TIMERFD
}
/**
- * restarts a timer and updates with a new interva
- * @param handle handle to the timer
- * @param timeouts new timout time
- * @return E_OK on success, E_NON_EXISTENT if the handle was not found
- */
-am_Error_e CAmSocketHandler::updateTimer(const sh_timerHandle_t handle, const timespec & timeouts)
+ * restarts a timer and updates with a new interva
+ * @param handle handle to the timer
+ * @param timeouts new timout time
+ * @return E_OK on success, E_NON_EXISTENT if the handle was not found
+ */
+am_Error_e CAmSocketHandler::updateTimer(const sh_timerHandle_t handle, const timespec &timeouts)
{
#ifdef WITH_TIMERFD
std::list<sh_timer_s>::iterator it = mListTimer.begin();
for (; it != mListTimer.end(); ++it)
{
if (it->handle == handle)
+ {
break;
+ }
}
+
if (it == mListTimer.end())
+ {
return (E_NON_EXISTENT);
+ }
if (it->countdown.it_interval.tv_nsec != 0 || it->countdown.it_interval.tv_sec != 0)
+ {
it->countdown.it_interval = timeouts;
+ }
+
it->countdown.it_value = timeouts;
if (!fdIsValid(it->fd))
{
am_Error_e err = createTimeFD(it->countdown, it->fd);
if (err != E_OK)
+ {
return err;
+ }
}
else
{
@@ -739,60 +795,66 @@ am_Error_e CAmSocketHandler::updateTimer(const sh_timerHandle_t handle, const ti
return E_NOT_POSSIBLE;
}
}
-#else
-
- //update the mList ....
- sh_timer_s timerItem;
+#else // ifdef WITH_TIMERFD
+ // update the mList ....
+ sh_timer_s timerItem;
std::list<sh_timer_s>::iterator it(mListTimer.begin()), activeIt(mListActiveTimer.begin());
- bool found(false);
+ bool found(false);
for (; it != mListTimer.end(); ++it)
{
if (it->handle == handle)
{
it->countdown = timeouts;
- timerItem = *it;
- found = true;
+ timerItem = *it;
+ found = true;
break;
}
}
+
if (!found)
- return (E_NON_EXISTENT);
+ {
+ return (E_NON_EXISTENT);
+ }
found = false;
- //we add here the time difference between startTime and currenttime, because this time will be substracted later on in timecorrection
+ // we add here the time difference between startTime and currenttime, because this time will be substracted later on in timecorrection
timespec currentTime, timeoutsCorrected;
- currentTime.tv_nsec=timeoutsCorrected.tv_nsec=0;
- currentTime.tv_sec=timeoutsCorrected.tv_sec=0;
+ currentTime.tv_nsec = timeoutsCorrected.tv_nsec = 0;
+ currentTime.tv_sec = timeoutsCorrected.tv_sec = 0;
clock_gettime(CLOCK_MONOTONIC, &currentTime);
- if (!mDispatchDone)//the mainloop is started
- timeoutsCorrected = timespecAdd(timeouts, timespecSub(currentTime, mStartTime));
+ if (!mDispatchDone)// the mainloop is started
+ {
+ timeoutsCorrected = timespecAdd(timeouts, timespecSub(currentTime, mStartTime));
+ }
for (; activeIt != mListActiveTimer.end(); ++activeIt)
{
if (activeIt->handle == handle)
{
activeIt->countdown = timeoutsCorrected;
- found = true;
+ found = true;
break;
}
}
if (!found)
- timerItem.countdown = timeoutsCorrected;
+ {
+ timerItem.countdown = timeoutsCorrected;
+ }
+
mListActiveTimer.push_back(timerItem);
mListActiveTimer.sort(compareCountdown);
-
-#endif
+#endif // ifdef WITH_TIMERFD
return (E_OK);
}
/**
- * restarts a timer with the original value
- * @param handle
- * @return E_OK on success, E_NON_EXISTENT if the handle was not found
- */
+ * restarts a timer with the original value
+ * @param handle
+ * @return E_OK on success, E_NON_EXISTENT if the handle was not found
+ */
am_Error_e CAmSocketHandler::restartTimer(const sh_timerHandle_t handle)
{
#ifdef WITH_TIMERFD
@@ -800,16 +862,23 @@ am_Error_e CAmSocketHandler::restartTimer(const sh_timerHandle_t handle)
for (; it != mListTimer.end(); ++it)
{
if (it->handle == handle)
+ {
break;
+ }
}
+
if (it == mListTimer.end())
+ {
return (E_NON_EXISTENT);
+ }
if (!fdIsValid(it->fd))
{
am_Error_e err = createTimeFD(it->countdown, it->fd);
if (err != E_OK)
+ {
return err;
+ }
}
else
{
@@ -819,32 +888,34 @@ am_Error_e CAmSocketHandler::restartTimer(const sh_timerHandle_t handle)
return E_NOT_POSSIBLE;
}
}
-#else
-
- sh_timer_s timerItem; //!<the original timer value
- //find the original value
+#else // ifdef WITH_TIMERFD
+ sh_timer_s timerItem; //!< the original timer value
+ // find the original value
std::list<sh_timer_s>::iterator it(mListTimer.begin()), activeIt(mListActiveTimer.begin());
- bool found(false);
+ bool found(false);
for (; it != mListTimer.end(); ++it)
{
if (it->handle == handle)
{
timerItem = *it;
- found = true;
+ found = true;
break;
}
}
+
if (!found)
- return (E_NON_EXISTENT);
+ {
+ return (E_NON_EXISTENT);
+ }
found = false;
- //we add here the time difference between startTime and currenttime, because this time will be substracted later on in timecorrection
+ // we add here the time difference between startTime and currenttime, because this time will be substracted later on in timecorrection
timespec currentTime, timeoutsCorrected;
clock_gettime(CLOCK_MONOTONIC, &currentTime);
- if (!mDispatchDone)//the mainloop is started
+ if (!mDispatchDone)// the mainloop is started
{
- timeoutsCorrected = timespecAdd(timerItem.countdown, timespecSub(currentTime, mStartTime));
+ timeoutsCorrected = timespecAdd(timerItem.countdown, timespecSub(currentTime, mStartTime));
timerItem.countdown = timeoutsCorrected;
}
@@ -853,35 +924,38 @@ am_Error_e CAmSocketHandler::restartTimer(const sh_timerHandle_t handle)
if (activeIt->handle == handle)
{
activeIt->countdown = timerItem.countdown;
- found = true;
+ found = true;
break;
}
}
if (!found)
- mListActiveTimer.push_back(timerItem);
-
+ {
+ mListActiveTimer.push_back(timerItem);
+ }
mListActiveTimer.sort(compareCountdown);
-#endif
+#endif // ifdef WITH_TIMERFD
return (E_OK);
}
/**
- * stops a timer
- * @param handle
- * @return E_OK on success, E_NON_EXISTENT if the handle was not found
- */
+ * stops a timer
+ * @param handle
+ * @return E_OK on success, E_NON_EXISTENT if the handle was not found
+ */
am_Error_e CAmSocketHandler::stopTimer(const sh_timerHandle_t handle)
{
#ifdef WITH_TIMERFD
for (auto elem : mListTimer)
{
if (elem.handle != handle)
+ {
continue;
+ }
itimerspec countdown = elem.countdown;
countdown.it_value.tv_nsec = 0;
- countdown.it_value.tv_sec = 0;
+ countdown.it_value.tv_sec = 0;
if (timerfd_settime(elem.fd, 0, &countdown, NULL) < 0)
{
@@ -891,8 +965,8 @@ am_Error_e CAmSocketHandler::stopTimer(const sh_timerHandle_t handle)
return E_OK;
}
-#else
- //go through the list and remove the timer with the handle
+#else // ifdef WITH_TIMERFD
+ // go through the list and remove the timer with the handle
std::list<sh_timer_s>::iterator it(mListActiveTimer.begin());
while (it != mListActiveTimer.end())
{
@@ -901,53 +975,57 @@ am_Error_e CAmSocketHandler::stopTimer(const sh_timerHandle_t handle)
mListActiveTimer.erase(it);
return E_OK;
}
+
++it;
}
-#endif
+#endif // ifdef WITH_TIMERFD
return E_NON_EXISTENT;
}
/**
- * updates the eventFlags of a poll
- * @param handle
- * @param events
- * @return @return E_OK on succsess, E_NON_EXISTENT if fd was not found
- */
+ * updates the eventFlags of a poll
+ * @param handle
+ * @param events
+ * @return @return E_OK on succsess, E_NON_EXISTENT if fd was not found
+ */
am_Error_e CAmSocketHandler::updateEventFlags(const sh_pollHandle_t handle, const short events)
{
- for (auto& it : mMapShPoll)
+ for (auto &it : mMapShPoll)
{
- auto& elem = it.second;
+ auto &elem = it.second;
if (elem.handle != handle)
+ {
continue;
+ }
switch (elem.state)
{
- case poll_states_e::ADD:
- elem.pollfdValue.events = events;
- return (E_OK);
+ case poll_states_e::ADD:
+ elem.pollfdValue.events = events;
+ return (E_OK);
- case poll_states_e::UPDATE:
- case poll_states_e::VALID:
- elem.state = poll_states_e::UPDATE;
- elem.pollfdValue.revents = 0;
- elem.pollfdValue.events = events;
- return (E_OK);
+ case poll_states_e::UPDATE:
+ case poll_states_e::VALID:
+ elem.state = poll_states_e::UPDATE;
+ elem.pollfdValue.revents = 0;
+ elem.pollfdValue.events = events;
+ return (E_OK);
- default:
- // This issue should never happen!
- return (E_DATABASE_ERROR);
+ default:
+ // This issue should never happen!
+ return (E_DATABASE_ERROR);
}
}
+
return (E_UNKNOWN);
}
/**
- * checks if a filedescriptor is validCAmShSubstractTime
- * @param fd the filedescriptor
- * @return true if the fd is valid
- */
+ * checks if a filedescriptor is validCAmShSubstractTime
+ * @param fd the filedescriptor
+ * @return true if the fd is valid
+ */
bool CAmSocketHandler::fdIsValid(const int fd) const
{
return (fcntl(fd, F_GETFL) != -1 || errno != EBADF);
@@ -955,148 +1033,158 @@ bool CAmSocketHandler::fdIsValid(const int fd) const
#ifndef WITH_TIMERFD
/**
- * timer is up.
- */
+ * timer is up.
+ */
void CAmSocketHandler::timerUp()
{
- //find out the timedifference to starttime
+ // find out the timedifference to starttime
static timespec currentTime, diffTime;
clock_gettime(CLOCK_MONOTONIC, &currentTime);
diffTime = timespecSub(currentTime, mStartTime);
- static auto countdownUp = [&](const sh_timer_s& row)->bool
- {
- timespec sub = timespecSub(row.countdown, diffTime);
- if (sub.tv_nsec == 0 && sub.tv_sec == 0)
- return (true);
- return (false);
- };
+ static auto countdownUp = [&](const sh_timer_s &row) -> bool {
+ timespec sub = timespecSub(row.countdown, diffTime);
+ if (sub.tv_nsec == 0 && sub.tv_sec == 0)
+ {
+ return (true);
+ }
+
+ return (false);
+ };
- //now we need to substract the diffTime from all timers and see if they are up
+ // now we need to substract the diffTime from all timers and see if they are up
std::list<sh_timer_s>::reverse_iterator overflowIter = std::find_if(mListActiveTimer.rbegin(), mListActiveTimer.rend(), countdownUp);
- //copy all fired timers into a list
+ // copy all fired timers into a list
std::vector<sh_timer_s> tempList(overflowIter, mListActiveTimer.rend());
- //erase all fired timers
+ // erase all fired timers
std::list<sh_timer_s>::iterator it(overflowIter.base());
mListActiveTimer.erase(mListActiveTimer.begin(), it);
- //call the callbacks for the timers
+ // call the callbacks for the timers
std::for_each(tempList.begin(), tempList.end(), CAmSocketHandler::callTimer);
}
/**
- * correct timers and fire the ones who are up
- */
+ * correct timers and fire the ones who are up
+ */
void CAmSocketHandler::timerCorrection()
{
- //get the current time and calculate the correction value
+ // get the current time and calculate the correction value
static timespec currentTime, correctionTime;
clock_gettime(CLOCK_MONOTONIC, &currentTime);
correctionTime = timespecSub(currentTime, mStartTime);
- mStartTime = currentTime;
+ mStartTime = currentTime;
- static auto countdownZero = [](const sh_timer_s& row)->bool
- {
- if (row.countdown.tv_nsec == 0 && row.countdown.tv_sec == 0)
- return (true);
- return (false);
- };
+ static auto countdownZero = [](const sh_timer_s &row) -> bool {
+ if (row.countdown.tv_nsec == 0 && row.countdown.tv_sec == 0)
+ {
+ return (true);
+ }
- static auto substractTime = [&](sh_timer_s& t)
- {
- t.countdown = timespecSub(t.countdown, correctionTime);
- };
+ return (false);
+ };
+
+ static auto substractTime = [&](sh_timer_s &t){
+ t.countdown = timespecSub(t.countdown, correctionTime);
+ };
if (!mListActiveTimer.empty())
{
- //subtract the correction value from all items in the list
+ // subtract the correction value from all items in the list
std::for_each(mListActiveTimer.begin(), mListActiveTimer.end(), substractTime);
- //find the last occurrence of zero -> timer overflowed
+ // find the last occurrence of zero -> timer overflowed
std::list<sh_timer_s>::reverse_iterator overflowIter = std::find_if(mListActiveTimer.rbegin(), mListActiveTimer.rend(), countdownZero);
- //only if a timer overflowed
+ // only if a timer overflowed
if (overflowIter != mListActiveTimer.rend())
{
- //copy all timers that need to be called to a new list
+ // copy all timers that need to be called to a new list
std::vector<sh_timer_s> tempList(overflowIter, mListActiveTimer.rend());
- //erase all fired timers
+ // erase all fired timers
std::list<sh_timer_s>::iterator it(overflowIter.base());
mListActiveTimer.erase(mListActiveTimer.begin(), it);
- //call the callbacks for the timers
+ // call the callbacks for the timers
std::for_each(tempList.begin(), tempList.end(), CAmSocketHandler::callTimer);
}
}
}
-#endif
+#endif // ifndef WITH_TIMERFD
/**
- * prepare for poll
- */
-void CAmSocketHandler::prepare(am::CAmSocketHandler::sh_poll_s& row)
+ * prepare for poll
+ */
+void CAmSocketHandler::prepare(am::CAmSocketHandler::sh_poll_s &row)
{
if (!row.prepareCB)
+ {
return;
+ }
try
{
row.prepareCB(row.handle, row.userData);
}
- catch (std::exception& e)
+ catch (std::exception &e)
{
logError("CAmSocketHandler::prepare Exception caught", e.what());
}
}
/**
- * fire callback
- */
-void CAmSocketHandler::fire(const sh_poll_s& a)
+ * fire callback
+ */
+void CAmSocketHandler::fire(const sh_poll_s &a)
{
try
{
a.firedCB(a.pollfdValue, a.handle, a.userData);
}
- catch (std::exception& e)
+ catch (std::exception &e)
{
logError("CAmSocketHandler::fire Exception caught", e.what());
}
}
/**
- * should disptach
- */
-bool CAmSocketHandler::noDispatching(const sh_poll_s* a)
+ * should disptach
+ */
+bool CAmSocketHandler::noDispatching(const sh_poll_s *a)
{
- //remove from list of there is no checkCB
+ // remove from list of there is no checkCB
if (nullptr == a->checkCB || a->state != poll_states_e::VALID)
+ {
return (true);
+ }
+
return (!a->checkCB(a->handle, a->userData));
}
/**
- * disptach
- */
-bool CAmSocketHandler::dispatchingFinished(const sh_poll_s* a)
+ * disptach
+ */
+bool CAmSocketHandler::dispatchingFinished(const sh_poll_s *a)
{
- //remove from list of there is no dispatchCB
+ // remove from list of there is no dispatchCB
if (nullptr == a->dispatchCB || a->state != poll_states_e::VALID)
+ {
return (true);
+ }
return (!a->dispatchCB(a->handle, a->userData));
}
/**
- * is used to set the pointer for the ppoll command
- * @param buffertime
- * @return
- */
-inline timespec* CAmSocketHandler::insertTime(timespec& buffertime)
+ * is used to set the pointer for the ppoll command
+ * @param buffertime
+ * @return
+ */
+inline timespec *CAmSocketHandler::insertTime(timespec &buffertime)
{
#ifndef WITH_TIMERFD
if (!mListActiveTimer.empty())
@@ -1105,19 +1193,19 @@ inline timespec* CAmSocketHandler::insertTime(timespec& buffertime)
return (&buffertime);
}
else
-#endif
+#endif // ifndef WITH_TIMERFD
{
return (NULL);
}
}
-#ifdef WITH_TIMERFD
-am_Error_e CAmSocketHandler::createTimeFD(const itimerspec & timeouts, int & fd)
+#ifdef WITH_TIMERFD
+am_Error_e CAmSocketHandler::createTimeFD(const itimerspec &timeouts, int &fd)
{
fd = timerfd_create(CLOCK_MONOTONIC, TFD_NONBLOCK | TFD_CLOEXEC);
if (fd < 0)
{
- logError("CAmSocketHandler::createTimeFD Failed with", static_cast<const char*>(std::strerror(errno)));
+ logError("CAmSocketHandler::createTimeFD Failed with", static_cast<const char *>(std::strerror(errno)));
return E_NOT_POSSIBLE;
}
@@ -1128,25 +1216,26 @@ am_Error_e CAmSocketHandler::createTimeFD(const itimerspec & timeouts, int & fd)
fd = -1;
return E_NOT_POSSIBLE;
}
+
return E_OK;
}
-#endif
+#endif // ifdef WITH_TIMERFD
-void CAmSocketHandler::callTimer(sh_timer_s& a)
+void CAmSocketHandler::callTimer(sh_timer_s &a)
{
try
{
a.callback(a.handle, a.userData);
}
- catch (std::exception& e)
+ catch (std::exception &e)
{
logError("CAmSocketHandler::callTimer() Exception caught", e.what());
}
}
-bool CAmSocketHandler::nextHandle(sh_identifier_s & handle)
+bool CAmSocketHandler::nextHandle(sh_identifier_s &handle)
{
- //create a new handle for the poll
+ // create a new handle for the poll
const sh_pollHandle_t lastHandle(handle.lastUsedID);
do
{
@@ -1155,11 +1244,11 @@ bool CAmSocketHandler::nextHandle(sh_identifier_s & handle)
{
handle.lastUsedID = 1;
}
+
if (handle.lastUsedID == lastHandle)
{
return (false);
}
-
} while (handle.pollHandles.find(handle.lastUsedID) != handle.pollHandles.end());
handle.pollHandles.insert(handle.lastUsedID);
@@ -1168,4 +1257,3 @@ bool CAmSocketHandler::nextHandle(sh_identifier_s & handle)
}
}
-
diff --git a/AudioManagerUtilities/src/CAmWatchdog.cpp b/AudioManagerUtilities/src/CAmWatchdog.cpp
index 2161630..3bac79c 100755..100644
--- a/AudioManagerUtilities/src/CAmWatchdog.cpp
+++ b/AudioManagerUtilities/src/CAmWatchdog.cpp
@@ -32,40 +32,40 @@
namespace am
{
-CAmWatchdog::CAmWatchdog(CAmSocketHandler* CAmSocketHandler) :
- TimerCallback(this, &CAmWatchdog::timerCallback),
- mpCAmSocketHandler(CAmSocketHandler),
- mHandle(0)
+CAmWatchdog::CAmWatchdog(CAmSocketHandler *CAmSocketHandler)
+ : TimerCallback(this, &CAmWatchdog::timerCallback)
+ , mpCAmSocketHandler(CAmSocketHandler)
+ , mHandle(0)
{
assert(mpCAmSocketHandler);
-
- //first retrieve the timeout interval
+ // first retrieve the timeout interval
int watchdogTimeout = 0;
- char* wusec=getenv("WATCHDOG_USEC");
+ char *wusec = getenv("WATCHDOG_USEC");
if (wusec)
- watchdogTimeout=atoi(wusec);
+ {
+ watchdogTimeout = atoi(wusec);
+ }
if (watchdogTimeout > 0)
{
timespec timeout;
- //calculate the half cycle as the right interval to trigger the watchdog.
- timeout.tv_sec = (watchdogTimeout / 2) / 1000000;
+ // calculate the half cycle as the right interval to trigger the watchdog.
+ timeout.tv_sec = (watchdogTimeout / 2) / 1000000;
timeout.tv_nsec = ((watchdogTimeout / 2) % 1000000) * 1000;
logInfo("CAmWatchdog::CAmWatchdog setting watchdog timeout:", watchdogTimeout, "us. Notification set to:",
- (int)timeout.tv_sec, "sec and", (int)timeout.tv_nsec, "ns");
+ (int)timeout.tv_sec, "sec and", (int)timeout.tv_nsec, "ns");
- //add the timer here
+ // add the timer here
if (mpCAmSocketHandler->addTimer(timeout, &TimerCallback, mHandle, NULL))
{
logError("CAmWatchdog::CAmWatchdog failed to add timer");
throw std::runtime_error("CAmWatchdog::CAmWatchdog failed to add timer");
}
}
-
else
{
logInfo("CAmWatchdog::CAmWatchdog watchdog timeout was ", watchdogTimeout, " museconds, no watchdog active");
@@ -74,14 +74,16 @@ CAmWatchdog::CAmWatchdog(CAmSocketHandler* CAmSocketHandler) :
CAmWatchdog::~CAmWatchdog()
{
- //remove the timer again.
- if (mHandle!=0)
- mpCAmSocketHandler->removeTimer(mHandle);
+ // remove the timer again.
+ if (mHandle != 0)
+ {
+ mpCAmSocketHandler->removeTimer(mHandle);
+ }
}
-void CAmWatchdog::timerCallback(sh_timerHandle_t handle, void* userData)
+void CAmWatchdog::timerCallback(sh_timerHandle_t handle, void *userData)
{
- (void) userData;
+ (void)userData;
int error(sd_notify(0, "WATCHDOG=1"));
if (error < 0)
{
@@ -100,6 +102,7 @@ void CAmWatchdog::startWatchdog()
logError("CAmWatchdog::startWatchdog could not start watchdog, error ", error);
throw std::runtime_error("CAmWatchdog::startWatchdog could not start watchdog");
}
+
logInfo("READY=1 was sent to systemd");
}