diff options
Diffstat (limited to 'AudioManagerUtilities/src')
-rw-r--r-- | AudioManagerUtilities/src/CAmCommandLineSingleton.cpp | 47 | ||||
-rw-r--r-- | AudioManagerUtilities/src/CAmCommonAPIWrapper.cpp | 263 | ||||
-rw-r--r-- | AudioManagerUtilities/src/CAmDbusWrapper.cpp | 317 | ||||
-rw-r--r-- | AudioManagerUtilities/src/CAmDltWrapper.cpp | 1366 | ||||
-rw-r--r-- | AudioManagerUtilities/src/CAmSocketHandler.cpp | 916 | ||||
-rw-r--r--[-rwxr-xr-x] | AudioManagerUtilities/src/CAmWatchdog.cpp | 39 |
6 files changed, 1613 insertions, 1335 deletions
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, ¤tTime); 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, ¤tTime); - 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, ¤tTime); - 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, ¤tTime); - 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, ¤tTime); 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, ¤tTime); 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"); } |