From a01d68a61fe8eec202407d82c10f88d93cf06aac Mon Sep 17 00:00:00 2001 From: Erik Frojdh Date: Tue, 12 Mar 2019 08:22:07 +0100 Subject: [PATCH 1/7] initial changes --- .../multiSlsDetector/multiSlsDetector.cpp | 35 +++++++----- .../multiSlsDetector/multiSlsDetector.h | 17 +++--- .../sharedMemory/SharedMemory.cpp | 57 ++++++++++++------- .../sharedMemory/SharedMemory.h | 25 ++++++-- .../slsDetector/slsDetector.cpp | 8 +-- slsDetectorSoftware/slsDetector/slsDetector.h | 28 ++++----- 6 files changed, 100 insertions(+), 70 deletions(-) diff --git a/slsDetectorSoftware/multiSlsDetector/multiSlsDetector.cpp b/slsDetectorSoftware/multiSlsDetector/multiSlsDetector.cpp index 925d78ae6..9ee47eca2 100644 --- a/slsDetectorSoftware/multiSlsDetector/multiSlsDetector.cpp +++ b/slsDetectorSoftware/multiSlsDetector/multiSlsDetector.cpp @@ -33,7 +33,7 @@ multiSlsDetector::multiSlsDetector(int id, bool verify, bool update) multiSlsDetector::~multiSlsDetector() { if (sharedMemory) { - sharedMemory->UnmapSharedMemory(thisMultiDetector); + sharedMemory->UnmapSharedMemory(); delete sharedMemory; } } @@ -252,20 +252,21 @@ void multiSlsDetector::freeSharedMemory(int multiId, int detPos) { // multi // get number of detectors int numDetectors = 0; - auto shm = SharedMemory(multiId, -1); + auto shm = SharedMemory(multiId, -1); // get number of detectors from multi shm if (shm.IsExisting()) { - sharedMultiSlsDetector *mdet = - (sharedMultiSlsDetector *)shm.OpenSharedMemory( - sizeof(sharedMultiSlsDetector)); - numDetectors = mdet->numberOfDetectors; - shm.UnmapSharedMemory(mdet); + // sharedMultiSlsDetector *mdet = + // (sharedMultiSlsDetector *)shm.OpenSharedMemory( + // sizeof(sharedMultiSlsDetector)); + shm.OpenSharedMemory(sizeof(sharedMultiSlsDetector)); + numDetectors = shm()->numberOfDetectors; + shm.UnmapSharedMemory(); shm.RemoveSharedMemory(); } for (int i = 0; i < numDetectors; ++i) { - auto shm = SharedMemory(multiId, i); + auto shm = SharedMemory(multiId, i); shm.RemoveSharedMemory(); } } @@ -288,7 +289,7 @@ void multiSlsDetector::freeSharedMemory(int detPos) { // clear multi detector shm if (sharedMemory) { if (thisMultiDetector) { - sharedMemory->UnmapSharedMemory(thisMultiDetector); + sharedMemory->UnmapSharedMemory(); thisMultiDetector = nullptr; } sharedMemory->RemoveSharedMemory(); @@ -326,19 +327,23 @@ std::string multiSlsDetector::getUserDetails() { void multiSlsDetector::initSharedMemory(bool verify) { try { // shared memory object with name - sharedMemory = new SharedMemory(detId, -1); + sharedMemory = new SharedMemory(detId, -1); size_t sz = sizeof(sharedMultiSlsDetector); // create if (!sharedMemory->IsExisting()) { - thisMultiDetector = - (sharedMultiSlsDetector *)sharedMemory->CreateSharedMemory(sz); + // thisMultiDetector = + // (sharedMultiSlsDetector *)sharedMemory->CreateSharedMemory(sz); + sharedMemory->CreateSharedMemory(sz); + thisMultiDetector= (*sharedMemory)(); //TODO remove line initializeDetectorStructure(); } // open and verify version else { - thisMultiDetector = - (sharedMultiSlsDetector *)sharedMemory->OpenSharedMemory(sz); + // thisMultiDetector = + // (sharedMultiSlsDetector *)sharedMemory->OpenSharedMemory(sz); + sharedMemory->OpenSharedMemory(sz); + thisMultiDetector = (*sharedMemory)(); if (verify && thisMultiDetector->shmversion != MULTI_SHMVERSION) { FILE_LOG(logERROR) << "Multi shared memory (" << detId << ") version mismatch " "(expected 0x" @@ -350,7 +355,7 @@ void multiSlsDetector::initSharedMemory(bool verify) { if (sharedMemory) { // unmap if (thisMultiDetector) { - sharedMemory->UnmapSharedMemory(thisMultiDetector); + sharedMemory->UnmapSharedMemory(); thisMultiDetector = nullptr; } // delete diff --git a/slsDetectorSoftware/multiSlsDetector/multiSlsDetector.h b/slsDetectorSoftware/multiSlsDetector/multiSlsDetector.h index 6b52bddab..3a80bc2f2 100644 --- a/slsDetectorSoftware/multiSlsDetector/multiSlsDetector.h +++ b/slsDetectorSoftware/multiSlsDetector/multiSlsDetector.h @@ -10,9 +10,9 @@ #include "error_defs.h" #include "logger.h" #include "sls_detector_defs.h" - +#include "SharedMemory.h" class slsDetector; -class SharedMemory; +// class SharedMemory; class ZmqSocket; class detectorData; @@ -27,10 +27,7 @@ class detectorData; #define SHORT_STRING_LENGTH 50 #define DATE_LENGTH 30 -class multiSlsDetector : public virtual slsDetectorDefs, - public virtual errorDefs { - private: /** * @short structure allocated in shared memory to store detector settings * for IPC and cache @@ -99,7 +96,7 @@ class multiSlsDetector : public virtual slsDetectorDefs, int maxNumberOfChannelsPerDetector[2]; /** timer values */ - int64_t timerValue[MAX_TIMERS]; + int64_t timerValue[slsDetectorDefs::timerIndex::MAX_TIMERS]; /** flag for acquiring */ bool acquiringFlag; @@ -113,6 +110,12 @@ class multiSlsDetector : public virtual slsDetectorDefs, } sharedMultiSlsDetector; +class multiSlsDetector : public virtual slsDetectorDefs, + public virtual errorDefs { + + // private: + + public: /** * Constructor @@ -1963,7 +1966,7 @@ class multiSlsDetector : public virtual slsDetectorDefs, int detId; /** Shared Memory object */ - SharedMemory *sharedMemory {nullptr}; + SharedMemory *sharedMemory {nullptr}; /** Shared memory structure */ sharedMultiSlsDetector *thisMultiDetector {nullptr}; diff --git a/slsDetectorSoftware/sharedMemory/SharedMemory.cpp b/slsDetectorSoftware/sharedMemory/SharedMemory.cpp index 10a47d37c..97b76f903 100644 --- a/slsDetectorSoftware/sharedMemory/SharedMemory.cpp +++ b/slsDetectorSoftware/sharedMemory/SharedMemory.cpp @@ -3,6 +3,9 @@ #include "ansi.h" #include "logger.h" +#include "slsDetector.h" +#include "multiSlsDetector.h" + #include #include // printf #include // errno @@ -18,7 +21,8 @@ #define SHM_SLS_PREFIX "_sls_" #define SHM_ENV_NAME "SLSDETNAME" -SharedMemory::SharedMemory(int multiId, int slsId): +template +SharedMemory::SharedMemory(int multiId, int slsId): fd(-1), shmSize(0) { @@ -26,14 +30,14 @@ SharedMemory::SharedMemory(int multiId, int slsId): } - -SharedMemory::~SharedMemory(){ +template +SharedMemory::~SharedMemory(){ if (fd >= 0) close(fd); } - -bool SharedMemory::IsExisting() { +template +bool SharedMemory::IsExisting() { bool ret = true; int tempfd = shm_open(name.c_str(), O_RDWR, 0); if ((tempfd < 0) && (errno == ENOENT)) { @@ -43,12 +47,13 @@ bool SharedMemory::IsExisting() { return ret; } -std::string SharedMemory::GetName() { +template +std::string SharedMemory::GetName() { return name; } - -void* SharedMemory::CreateSharedMemory(size_t sz){ +template +void SharedMemory::CreateSharedMemory(size_t sz){ // create fd = shm_open(name.c_str(), O_CREAT | O_TRUNC | O_EXCL | O_RDWR, S_IRUSR | S_IWUSR); if (fd < 0) { @@ -65,12 +70,15 @@ void* SharedMemory::CreateSharedMemory(size_t sz){ } // map - void* addr = MapSharedMemory(sz); + // void* addr = MapSharedMemory(sz); + shared_struct = MapSharedMemory(sz); FILE_LOG(logINFO) << "Shared memory created " << name; - return addr; + + // return addr; } -void* SharedMemory::OpenSharedMemory(size_t sz){ +template +void SharedMemory::OpenSharedMemory(size_t sz){ // open fd = shm_open(name.c_str(), O_RDWR, 0); if (fd < 0) { @@ -78,19 +86,21 @@ void* SharedMemory::OpenSharedMemory(size_t sz){ throw SharedMemoryException(); } - return MapSharedMemory(sz); + shared_struct = MapSharedMemory(sz); + // return MapSharedMemory(sz); } - -void SharedMemory::UnmapSharedMemory(void* addr) { - if (munmap(addr, shmSize) < 0) { +template +void SharedMemory::UnmapSharedMemory() { + if (munmap(shared_struct, shmSize) < 0) { FILE_LOG(logERROR) << "Unmapping shared memory " << name << " failed: " << strerror(errno); close(fd); throw SharedMemoryException(); } } -void SharedMemory::RemoveSharedMemory() { +template +void SharedMemory::RemoveSharedMemory() { if (shm_unlink(name.c_str()) < 0) { // silent exit if shm did not exist anyway if (errno == ENOENT) @@ -102,7 +112,8 @@ void SharedMemory::RemoveSharedMemory() { } -void* SharedMemory::MapSharedMemory(size_t sz) { +template +T* SharedMemory::MapSharedMemory(size_t sz) { void* addr = mmap(nullptr, sz, PROT_READ | PROT_WRITE, MAP_SHARED, fd, 0); if (addr == MAP_FAILED) { FILE_LOG(logERROR) << "Mapping shared memory " << name << " failed: " << strerror(errno); @@ -111,11 +122,11 @@ void* SharedMemory::MapSharedMemory(size_t sz) { } shmSize = sz; close(fd); - return addr; + return (T*)addr; } - -std::string SharedMemory::ConstructSharedMemoryName(int multiId, int slsId) { +template +std::string SharedMemory::ConstructSharedMemoryName(int multiId, int slsId) { // using environment path std::string sEnvPath = ""; @@ -141,8 +152,8 @@ std::string SharedMemory::ConstructSharedMemoryName(int multiId, int slsId) { return temp; } - -int SharedMemory::VerifySizeMatch(size_t expectedSize) { +template +int SharedMemory::VerifySizeMatch(size_t expectedSize) { struct stat sb; // could not fstat if (fstat(fd, &sb) < 0) { @@ -163,3 +174,5 @@ int SharedMemory::VerifySizeMatch(size_t expectedSize) { return 0; } +template class SharedMemory; +template class SharedMemory; \ No newline at end of file diff --git a/slsDetectorSoftware/sharedMemory/SharedMemory.h b/slsDetectorSoftware/sharedMemory/SharedMemory.h index ebec18606..6b15e61d4 100644 --- a/slsDetectorSoftware/sharedMemory/SharedMemory.h +++ b/slsDetectorSoftware/sharedMemory/SharedMemory.h @@ -11,6 +11,7 @@ #include #include +template class SharedMemory{ public: /** @@ -43,21 +44,20 @@ public: * throws a SharedMemoryException exception on failure to create, ftruncate or map * @param sz of shared memory */ - void* CreateSharedMemory(size_t sz); + void CreateSharedMemory(size_t sz); /** * Open existing Shared memory and call MapSharedMemory to map it to an address * throws a SharedMemoryException exception on failure to open or map * @param sz of shared memory */ - void* OpenSharedMemory(size_t sz); + void OpenSharedMemory(size_t sz); /** * Unmap shared memory from an address * throws a SharedMemoryException exception on failure - * @param addr double pointer to address to be mapped */ - void UnmapSharedMemory(void* addr); + void UnmapSharedMemory(); /** * Remove existing Shared memory @@ -69,6 +69,19 @@ public: */ static const int NAME_MAX = 255; + + /* + Using the call operator to access the pointer + + */ + T* operator()(){ + return shared_struct; + } + + const T* operator()() const{ + return shared_struct; + } + private: /** * Create Shared memory name @@ -84,7 +97,7 @@ private: * throws a SharedMemoryException exception on failure * @param sz of shared memory */ - void* MapSharedMemory(size_t sz); + T* MapSharedMemory(size_t sz); /** * Verify if existing shared memory size matches expected size @@ -102,4 +115,6 @@ private: /** shm size */ size_t shmSize; + T* shared_struct; + }; diff --git a/slsDetectorSoftware/slsDetector/slsDetector.cpp b/slsDetectorSoftware/slsDetector/slsDetector.cpp index cfbef4cdd..502c391e2 100644 --- a/slsDetectorSoftware/slsDetector/slsDetector.cpp +++ b/slsDetectorSoftware/slsDetector/slsDetector.cpp @@ -31,7 +31,7 @@ slsDetector::slsDetector(detectorType type, int multiId, int id, bool verify) * so sls shared memory will be created */ // ensure shared memory was not created before - auto shm = SharedMemory(multiId, id); + auto shm = SharedMemory(multiId, id); if (shm.IsExisting()) { FILE_LOG(logWARNING) << "This shared memory should have been " "deleted before! " @@ -202,7 +202,7 @@ int64_t slsDetector::getId(idMode mode) { } void slsDetector::freeSharedMemory(int multiId, int slsId) { - auto shm = SharedMemory(multiId, slsId); + auto shm = SharedMemory(multiId, slsId); shm.RemoveSharedMemory(); } @@ -236,7 +236,7 @@ void slsDetector::initSharedMemory(bool created, detectorType type, int multiId, int sz = calculateSharedMemorySize(type); // shared memory object with name - sharedMemory = new SharedMemory(multiId, detId); + sharedMemory = new SharedMemory(multiId, detId); // create if (created) { @@ -636,7 +636,7 @@ int slsDetector::receiveModule(sls_detector_module *myMod) { } slsDetectorDefs::detectorType slsDetector::getDetectorTypeFromShm(int multiId, bool verify) { - auto shm = SharedMemory(multiId, detId); + auto shm = SharedMemory(multiId, detId); if (!shm.IsExisting()) { FILE_LOG(logERROR) << "Shared memory " << shm.GetName() << " does not exist.\n" "Corrupted Multi Shared memory. Please free shared memory."; diff --git a/slsDetectorSoftware/slsDetector/slsDetector.h b/slsDetectorSoftware/slsDetector/slsDetector.h index 74239311e..dabc95bd7 100644 --- a/slsDetectorSoftware/slsDetector/slsDetector.h +++ b/slsDetectorSoftware/slsDetector/slsDetector.h @@ -13,13 +13,13 @@ #include "error_defs.h" #include "logger.h" #include "ClientSocket.h" - +#include "SharedMemory.h" class ClientInterface; #include class multiSlsDetector; -class SharedMemory; +// class SharedMemory; class ServerInterface; class MySocketTCP; @@ -42,9 +42,6 @@ typedef struct detParameterList { } detParameterList; -class slsDetector : public virtual slsDetectorDefs, public virtual errorDefs { - -private: /** * @short structure allocated in shared memory to store detector settings for IPC and cache */ @@ -68,7 +65,7 @@ private: char hostname[MAX_STR_LENGTH]; /** detector type \ see :: detectorType*/ - detectorType myDetectorType; + slsDetectorDefs::detectorType myDetectorType; /** END OF FIXED PATTERN -----------------------------------------------*/ @@ -125,22 +122,22 @@ private: int nROI; /** list of rois */ - ROI roiLimits[MAX_ROIS]; + slsDetectorDefs::ROI roiLimits[MAX_ROIS]; /** readout flags */ - readOutFlags roFlags; + slsDetectorDefs::readOutFlags roFlags; /** name root of the output files */ char settingsFile[MAX_STR_LENGTH]; /** detector settings (standard, fast, etc.) */ - detectorSettings currentSettings; + slsDetectorDefs::detectorSettings currentSettings; /** detector threshold (eV) */ int currentThresholdEV; /** timer values */ - int64_t timerValue[MAX_TIMERS]; + int64_t timerValue[slsDetectorDefs::timerIndex::MAX_TIMERS]; /** memory offsets for the module structures */ int modoff; @@ -226,7 +223,7 @@ private: int64_t receiverAPIVersion; /** receiver frames discard policy */ - frameDiscardPolicy receiver_frameDiscardMode; + slsDetectorDefs::frameDiscardPolicy receiver_frameDiscardMode; /** receiver partial frames padding enable */ bool receiver_framePadding; @@ -250,7 +247,7 @@ private: int receiver_fileIndex; /** file format */ - fileFormat receiver_fileFormatType; + slsDetectorDefs::fileFormat receiver_fileFormatType; /** frames per file */ int receiver_framesPerFile; @@ -263,10 +260,7 @@ private: } sharedSlsDetector; - - - - +class slsDetector : public virtual slsDetectorDefs, public virtual errorDefs { public: /** @@ -1794,7 +1788,7 @@ private: int detId; /** Shared Memory object */ - SharedMemory* sharedMemory {nullptr}; + SharedMemory* sharedMemory {nullptr}; /** Shared memory structure */ sharedSlsDetector *thisDetector {nullptr}; From 507a22ac05b385aa170092229f8f808599263237 Mon Sep 17 00:00:00 2001 From: Erik Frojdh Date: Tue, 12 Mar 2019 10:14:24 +0100 Subject: [PATCH 2/7] default args --- slsDetectorSoftware/CMakeLists.txt | 6 +- .../multiSlsDetector/multiSlsDetector.cpp | 8 +- .../sharedMemory/SharedMemory.cpp | 306 +++++++++--------- .../sharedMemory/SharedMemory.h | 197 +++++++++-- .../slsDetector/slsDetector.cpp | 24 +- slsDetectorSoftware/tests/CMakeLists.txt | 23 ++ .../tests/test-SharedMemory.cpp | 30 ++ slsDetectorSoftware/tests/test.cpp | 3 + 8 files changed, 401 insertions(+), 196 deletions(-) create mode 100644 slsDetectorSoftware/tests/CMakeLists.txt create mode 100644 slsDetectorSoftware/tests/test-SharedMemory.cpp create mode 100644 slsDetectorSoftware/tests/test.cpp diff --git a/slsDetectorSoftware/CMakeLists.txt b/slsDetectorSoftware/CMakeLists.txt index aaf0d2bf9..120b3644e 100644 --- a/slsDetectorSoftware/CMakeLists.txt +++ b/slsDetectorSoftware/CMakeLists.txt @@ -1,6 +1,6 @@ set(SOURCES multiSlsDetector/multiSlsDetector.cpp - sharedMemory/SharedMemory.cpp + # sharedMemory/SharedMemory.cpp slsDetector/slsDetectorUsers.cpp slsDetector/slsDetectorCommand.cpp slsDetector/slsDetector.cpp @@ -49,6 +49,10 @@ if(DOXYGEN_FOUND) ) endif() +if (SLS_USE_TESTS) + add_subdirectory(tests) +endif(SLS_USE_TESTS) + install(TARGETS slsDetectorShared EXPORT "${TARGETS_EXPORT_NAME}" diff --git a/slsDetectorSoftware/multiSlsDetector/multiSlsDetector.cpp b/slsDetectorSoftware/multiSlsDetector/multiSlsDetector.cpp index 9ee47eca2..0c551799e 100644 --- a/slsDetectorSoftware/multiSlsDetector/multiSlsDetector.cpp +++ b/slsDetectorSoftware/multiSlsDetector/multiSlsDetector.cpp @@ -259,7 +259,7 @@ void multiSlsDetector::freeSharedMemory(int multiId, int detPos) { // sharedMultiSlsDetector *mdet = // (sharedMultiSlsDetector *)shm.OpenSharedMemory( // sizeof(sharedMultiSlsDetector)); - shm.OpenSharedMemory(sizeof(sharedMultiSlsDetector)); + shm.OpenSharedMemory(); numDetectors = shm()->numberOfDetectors; shm.UnmapSharedMemory(); shm.RemoveSharedMemory(); @@ -328,13 +328,13 @@ void multiSlsDetector::initSharedMemory(bool verify) { try { // shared memory object with name sharedMemory = new SharedMemory(detId, -1); - size_t sz = sizeof(sharedMultiSlsDetector); + // size_t sz = sizeof(sharedMultiSlsDetector); // create if (!sharedMemory->IsExisting()) { // thisMultiDetector = // (sharedMultiSlsDetector *)sharedMemory->CreateSharedMemory(sz); - sharedMemory->CreateSharedMemory(sz); + sharedMemory->CreateSharedMemory(); thisMultiDetector= (*sharedMemory)(); //TODO remove line initializeDetectorStructure(); } @@ -342,7 +342,7 @@ void multiSlsDetector::initSharedMemory(bool verify) { else { // thisMultiDetector = // (sharedMultiSlsDetector *)sharedMemory->OpenSharedMemory(sz); - sharedMemory->OpenSharedMemory(sz); + sharedMemory->OpenSharedMemory(); thisMultiDetector = (*sharedMemory)(); if (verify && thisMultiDetector->shmversion != MULTI_SHMVERSION) { FILE_LOG(logERROR) << "Multi shared memory (" << detId << ") version mismatch " diff --git a/slsDetectorSoftware/sharedMemory/SharedMemory.cpp b/slsDetectorSoftware/sharedMemory/SharedMemory.cpp index 97b76f903..f752e5e36 100644 --- a/slsDetectorSoftware/sharedMemory/SharedMemory.cpp +++ b/slsDetectorSoftware/sharedMemory/SharedMemory.cpp @@ -1,178 +1,178 @@ -#include "SharedMemory.h" -#include "sls_detector_exceptions.h" -#include "ansi.h" -#include "logger.h" +// #include "SharedMemory.h" +// #include "sls_detector_exceptions.h" +// #include "ansi.h" +// #include "logger.h" -#include "slsDetector.h" -#include "multiSlsDetector.h" +// #include "slsDetector.h" +// #include "multiSlsDetector.h" -#include -#include // printf -#include // errno -#include // strerror -#include -#include // O_CREAT, O_TRUNC.. -#include // fstat -#include // shared memory -#include -#include "stdlib.h" +// #include +// #include // printf +// #include // errno +// #include // strerror +// #include +// #include // O_CREAT, O_TRUNC.. +// #include // fstat +// #include // shared memory +// #include +// #include "stdlib.h" -#define SHM_MULTI_PREFIX "/slsDetectorPackage_multi_" -#define SHM_SLS_PREFIX "_sls_" -#define SHM_ENV_NAME "SLSDETNAME" +// #define SHM_MULTI_PREFIX "/slsDetectorPackage_multi_" +// #define SHM_SLS_PREFIX "_sls_" +// #define SHM_ENV_NAME "SLSDETNAME" -template -SharedMemory::SharedMemory(int multiId, int slsId): - fd(-1), - shmSize(0) -{ - name = ConstructSharedMemoryName(multiId, slsId); -} +// template +// SharedMemory::SharedMemory(int multiId, int slsId): +// fd(-1), +// shmSize(0) +// { +// name = ConstructSharedMemoryName(multiId, slsId); +// } -template -SharedMemory::~SharedMemory(){ - if (fd >= 0) - close(fd); -} +// template +// SharedMemory::~SharedMemory(){ +// if (fd >= 0) +// close(fd); +// } -template -bool SharedMemory::IsExisting() { - bool ret = true; - int tempfd = shm_open(name.c_str(), O_RDWR, 0); - if ((tempfd < 0) && (errno == ENOENT)) { - ret = false; - } - close(tempfd); - return ret; -} +// template +// bool SharedMemory::IsExisting() { +// bool ret = true; +// int tempfd = shm_open(name.c_str(), O_RDWR, 0); +// if ((tempfd < 0) && (errno == ENOENT)) { +// ret = false; +// } +// close(tempfd); +// return ret; +// } -template -std::string SharedMemory::GetName() { - return name; -} +// template +// std::string SharedMemory::GetName() { +// return name; +// } -template -void SharedMemory::CreateSharedMemory(size_t sz){ - // create - fd = shm_open(name.c_str(), O_CREAT | O_TRUNC | O_EXCL | O_RDWR, S_IRUSR | S_IWUSR); - if (fd < 0) { - FILE_LOG(logERROR) << "Create shared memory " << name << " failed: " << strerror(errno); - throw SharedMemoryException(); - } +// template +// void SharedMemory::CreateSharedMemory(size_t sz){ +// // create +// fd = shm_open(name.c_str(), O_CREAT | O_TRUNC | O_EXCL | O_RDWR, S_IRUSR | S_IWUSR); +// if (fd < 0) { +// FILE_LOG(logERROR) << "Create shared memory " << name << " failed: " << strerror(errno); +// throw SharedMemoryException(); +// } - // resize - if (ftruncate(fd, sz) < 0) { - FILE_LOG(logERROR) << "Create shared memory " << name << " failed at ftruncate: " << strerror(errno); - close(fd); - RemoveSharedMemory(); - throw SharedMemoryException(); - } +// // resize +// if (ftruncate(fd, sz) < 0) { +// FILE_LOG(logERROR) << "Create shared memory " << name << " failed at ftruncate: " << strerror(errno); +// close(fd); +// RemoveSharedMemory(); +// throw SharedMemoryException(); +// } - // map - // void* addr = MapSharedMemory(sz); - shared_struct = MapSharedMemory(sz); - FILE_LOG(logINFO) << "Shared memory created " << name; +// // map +// // void* addr = MapSharedMemory(sz); +// shared_struct = MapSharedMemory(sz); +// FILE_LOG(logINFO) << "Shared memory created " << name; - // return addr; -} +// // return addr; +// } -template -void SharedMemory::OpenSharedMemory(size_t sz){ - // open - fd = shm_open(name.c_str(), O_RDWR, 0); - if (fd < 0) { - FILE_LOG(logERROR) << "Open existing shared memory " << name << " failed: " << strerror(errno); - throw SharedMemoryException(); - } +// template +// void SharedMemory::OpenSharedMemory(size_t sz){ +// // open +// fd = shm_open(name.c_str(), O_RDWR, 0); +// if (fd < 0) { +// FILE_LOG(logERROR) << "Open existing shared memory " << name << " failed: " << strerror(errno); +// throw SharedMemoryException(); +// } - shared_struct = MapSharedMemory(sz); - // return MapSharedMemory(sz); -} +// shared_struct = MapSharedMemory(sz); +// // return MapSharedMemory(sz); +// } -template -void SharedMemory::UnmapSharedMemory() { - if (munmap(shared_struct, shmSize) < 0) { - FILE_LOG(logERROR) << "Unmapping shared memory " << name << " failed: " << strerror(errno); - close(fd); - throw SharedMemoryException(); - } -} +// template +// void SharedMemory::UnmapSharedMemory() { +// if (munmap(shared_struct, shmSize) < 0) { +// FILE_LOG(logERROR) << "Unmapping shared memory " << name << " failed: " << strerror(errno); +// close(fd); +// throw SharedMemoryException(); +// } +// } -template -void SharedMemory::RemoveSharedMemory() { - if (shm_unlink(name.c_str()) < 0) { - // silent exit if shm did not exist anyway - if (errno == ENOENT) - return; - FILE_LOG(logERROR) << "Free Shared Memory " << name << " Failed: " << strerror(errno); - throw SharedMemoryException(); - } - FILE_LOG(logINFO) << "Shared memory deleted " << name; -} +// template +// void SharedMemory::RemoveSharedMemory() { +// if (shm_unlink(name.c_str()) < 0) { +// // silent exit if shm did not exist anyway +// if (errno == ENOENT) +// return; +// FILE_LOG(logERROR) << "Free Shared Memory " << name << " Failed: " << strerror(errno); +// throw SharedMemoryException(); +// } +// FILE_LOG(logINFO) << "Shared memory deleted " << name; +// } -template -T* SharedMemory::MapSharedMemory(size_t sz) { - void* addr = mmap(nullptr, sz, PROT_READ | PROT_WRITE, MAP_SHARED, fd, 0); - if (addr == MAP_FAILED) { - FILE_LOG(logERROR) << "Mapping shared memory " << name << " failed: " << strerror(errno); - close(fd); - throw SharedMemoryException(); - } - shmSize = sz; - close(fd); - return (T*)addr; -} +// template +// T* SharedMemory::MapSharedMemory(size_t sz) { +// void* addr = mmap(nullptr, sz, PROT_READ | PROT_WRITE, MAP_SHARED, fd, 0); +// if (addr == MAP_FAILED) { +// FILE_LOG(logERROR) << "Mapping shared memory " << name << " failed: " << strerror(errno); +// close(fd); +// throw SharedMemoryException(); +// } +// shmSize = sz; +// close(fd); +// return (T*)addr; +// } -template -std::string SharedMemory::ConstructSharedMemoryName(int multiId, int slsId) { +// template +// std::string SharedMemory::ConstructSharedMemoryName(int multiId, int slsId) { - // using environment path - std::string sEnvPath = ""; - char* envpath = getenv(SHM_ENV_NAME); - if (envpath != nullptr) { - sEnvPath.assign(envpath); - sEnvPath.insert(0,"_"); - } +// // using environment path +// std::string sEnvPath = ""; +// char* envpath = getenv(SHM_ENV_NAME); +// if (envpath != nullptr) { +// sEnvPath.assign(envpath); +// sEnvPath.insert(0,"_"); +// } - std::stringstream ss; - if (slsId < 0) - ss << SHM_MULTI_PREFIX << multiId << sEnvPath; - else - ss << SHM_MULTI_PREFIX << multiId << SHM_SLS_PREFIX << slsId << sEnvPath; +// std::stringstream ss; +// if (slsId < 0) +// ss << SHM_MULTI_PREFIX << multiId << sEnvPath; +// else +// ss << SHM_MULTI_PREFIX << multiId << SHM_SLS_PREFIX << slsId << sEnvPath; - std::string temp = ss.str(); - if (temp.length() > NAME_MAX) { - FILE_LOG(logERROR) << "Shared memory initialization failed. " << - temp << " has " << temp.length() << " characters. \n" - "Maximum is " << NAME_MAX << ". Change the environment variable " << SHM_ENV_NAME; - throw SharedMemoryException(); - } - return temp; -} +// std::string temp = ss.str(); +// if (temp.length() > NAME_MAX) { +// FILE_LOG(logERROR) << "Shared memory initialization failed. " << +// temp << " has " << temp.length() << " characters. \n" +// "Maximum is " << NAME_MAX << ". Change the environment variable " << SHM_ENV_NAME; +// throw SharedMemoryException(); +// } +// return temp; +// // } -template -int SharedMemory::VerifySizeMatch(size_t expectedSize) { - struct stat sb; - // could not fstat - if (fstat(fd, &sb) < 0) { - FILE_LOG(logERROR) << "Could not verify existing shared memory " << name << " size match " - "(could not fstat): " << strerror(errno); - close(fd); - throw SharedMemoryException(); - } +// template +// int SharedMemory::VerifySizeMatch(size_t expectedSize) { +// struct stat sb; +// // could not fstat +// if (fstat(fd, &sb) < 0) { +// FILE_LOG(logERROR) << "Could not verify existing shared memory " << name << " size match " +// "(could not fstat): " << strerror(errno); +// close(fd); +// throw SharedMemoryException(); +// } - //size does not match - long unsigned int sz = (long unsigned int)sb.st_size; - if (sz != expectedSize) { - FILE_LOG(logERROR) << "Existing shared memory " << name << " size does not match"; - FILE_LOG(logDEBUG1) << "Expected " << expectedSize << ", found " << sz; - throw SharedMemoryException(); - return 1; - } - return 0; -} +// //size does not match +// long unsigned int sz = (long unsigned int)sb.st_size; +// if (sz != expectedSize) { +// FILE_LOG(logERROR) << "Existing shared memory " << name << " size does not match"; +// FILE_LOG(logDEBUG1) << "Expected " << expectedSize << ", found " << sz; +// throw SharedMemoryException(); +// return 1; +// } +// return 0; +// } -template class SharedMemory; -template class SharedMemory; \ No newline at end of file +// template class SharedMemory; +// template class SharedMemory; \ No newline at end of file diff --git a/slsDetectorSoftware/sharedMemory/SharedMemory.h b/slsDetectorSoftware/sharedMemory/SharedMemory.h index 6b15e61d4..19782263e 100644 --- a/slsDetectorSoftware/sharedMemory/SharedMemory.h +++ b/slsDetectorSoftware/sharedMemory/SharedMemory.h @@ -8,81 +8,168 @@ *@short functions basic implemenation of shared memory */ +#include "ansi.h" +#include "logger.h" +#include "sls_detector_exceptions.h" + +#include "stdlib.h" +#include // errno +#include // strerror +#include // O_CREAT, O_TRUNC.. +#include +#include +#include // printf +#include // shared memory +#include // fstat +#include + +#define SHM_MULTI_PREFIX "/slsDetectorPackage_multi_" +#define SHM_SLS_PREFIX "_sls_" +#define SHM_ENV_NAME "SLSDETNAME" + #include #include template -class SharedMemory{ -public: - /** +class SharedMemory { + public: + /** * Constructor * creates the single/multi detector shared memory name * @param multiId multi detector id * @param slsId sls detector id, -1 if a multi detector shared memory */ - SharedMemory(int multiId, int slsId); + SharedMemory(int multiId, int slsId) : fd(-1), + shmSize(0) { + name = ConstructSharedMemoryName(multiId, slsId); + } - /** + /** * Destructor */ - ~SharedMemory(); + ~SharedMemory() { + if (fd >= 0) + close(fd); + } /** * Verify if it exists * @param name of shared memory * @return true if exists, else false */ - bool IsExisting(); + bool IsExisting() { + bool ret = true; + int tempfd = shm_open(name.c_str(), O_RDWR, 0); + if ((tempfd < 0) && (errno == ENOENT)) { + ret = false; + } + close(tempfd); + return ret; + } - /** + /** * Get shared memory name */ - std::string GetName(); + std::string GetName() { + return name; + } /** * Create Shared memory and call MapSharedMemory to map it to an address * throws a SharedMemoryException exception on failure to create, ftruncate or map * @param sz of shared memory */ - void CreateSharedMemory(size_t sz); + void CreateSharedMemory(size_t sz = 0) { + // create + if (sz == 0){ + sz = sizeof(T); + } + + fd = shm_open(name.c_str(), O_CREAT | O_TRUNC | O_EXCL | O_RDWR, S_IRUSR | S_IWUSR); + if (fd < 0) { + FILE_LOG(logERROR) << "Create shared memory " << name << " failed: " << strerror(errno); + throw SharedMemoryException(); + } + + // resize + if (ftruncate(fd, sz) < 0) { + FILE_LOG(logERROR) << "Create shared memory " << name << " failed at ftruncate: " << strerror(errno); + close(fd); + RemoveSharedMemory(); + throw SharedMemoryException(); + } + + // map + // void* addr = MapSharedMemory(sz); + shared_struct = MapSharedMemory(sz); + FILE_LOG(logINFO) << "Shared memory created " << name; + + // return addr; + } /** * Open existing Shared memory and call MapSharedMemory to map it to an address * throws a SharedMemoryException exception on failure to open or map * @param sz of shared memory */ - void OpenSharedMemory(size_t sz); + void OpenSharedMemory() { + // open + size_t sz = sizeof(T); + fd = shm_open(name.c_str(), O_RDWR, 0); + if (fd < 0) { + FILE_LOG(logERROR) << "Open existing shared memory " << name << " failed: " << strerror(errno); + throw SharedMemoryException(); + } + + shared_struct = MapSharedMemory(sz); + // return MapSharedMemory(sz); + } /** * Unmap shared memory from an address * throws a SharedMemoryException exception on failure */ - void UnmapSharedMemory(); + void UnmapSharedMemory() { + if (munmap(shared_struct, shmSize) < 0) { + FILE_LOG(logERROR) << "Unmapping shared memory " << name << " failed: " << strerror(errno); + close(fd); + throw SharedMemoryException(); + } + } - /** + /** * Remove existing Shared memory */ - void RemoveSharedMemory(); + void RemoveSharedMemory() { + if (shm_unlink(name.c_str()) < 0) { + // silent exit if shm did not exist anyway + if (errno == ENOENT) + return; + FILE_LOG(logERROR) << "Free Shared Memory " << name << " Failed: " << strerror(errno); + throw SharedMemoryException(); + } + FILE_LOG(logINFO) << "Shared memory deleted " << name; + } /** * Maximum length of name as from man pages */ static const int NAME_MAX = 255; - /* Using the call operator to access the pointer */ - T* operator()(){ + + T *operator()() { return shared_struct; } - const T* operator()() const{ + const T *operator()() const { return shared_struct; } -private: + private: /** * Create Shared memory name * throws exception if name created is longer than required 255(manpages) @@ -90,31 +177,85 @@ private: * @param slsId sls detector id, -1 if a multi detector shared memory * @returns shared memory name */ - std::string ConstructSharedMemoryName(int multiId, int slsId); + std::string ConstructSharedMemoryName(int multiId, int slsId) { + + // using environment path + std::string sEnvPath = ""; + char *envpath = getenv(SHM_ENV_NAME); + if (envpath != nullptr) { + sEnvPath.assign(envpath); + sEnvPath.insert(0, "_"); + } + + std::stringstream ss; + if (slsId < 0) + ss << SHM_MULTI_PREFIX << multiId << sEnvPath; + else + ss << SHM_MULTI_PREFIX << multiId << SHM_SLS_PREFIX << slsId << sEnvPath; + + std::string temp = ss.str(); + if (temp.length() > NAME_MAX) { + FILE_LOG(logERROR) << "Shared memory initialization failed. " << temp << " has " << temp.length() << " characters. \n" + "Maximum is " + << NAME_MAX << ". Change the environment variable " << SHM_ENV_NAME; + throw SharedMemoryException(); + } + return temp; + } /** * Map shared memory to an address * throws a SharedMemoryException exception on failure * @param sz of shared memory */ - T* MapSharedMemory(size_t sz); + + T *MapSharedMemory(size_t sz) { + void *addr = mmap(nullptr, sz, PROT_READ | PROT_WRITE, MAP_SHARED, fd, 0); + if (addr == MAP_FAILED) { + FILE_LOG(logERROR) << "Mapping shared memory " << name << " failed: " << strerror(errno); + close(fd); + throw SharedMemoryException(); + } + shmSize = sz; + close(fd); + return (T *)addr; + } /** * Verify if existing shared memory size matches expected size * @param expectedSize expected size of shared memory, replaced with smaller size if size does not match * @return 0 for success, 1 for fail */ - int VerifySizeMatch(size_t expectedSize); + int VerifySizeMatch(size_t expectedSize) { + struct stat sb; + // could not fstat + if (fstat(fd, &sb) < 0) { + FILE_LOG(logERROR) << "Could not verify existing shared memory " << name << " size match " + "(could not fstat): " + << strerror(errno); + close(fd); + throw SharedMemoryException(); + } - /** Shared memory name */ - std::string name; + //size does not match + long unsigned int sz = (long unsigned int)sb.st_size; + if (sz != expectedSize) { + FILE_LOG(logERROR) << "Existing shared memory " << name << " size does not match"; + FILE_LOG(logDEBUG1) << "Expected " << expectedSize << ", found " << sz; + throw SharedMemoryException(); + return 1; + } + return 0; + } - /** File descriptor */ - int fd; + /** Shared memory name */ + std::string name; - /** shm size */ - size_t shmSize; + /** File descriptor */ + int fd; - T* shared_struct; + /** shm size */ + size_t shmSize; + T *shared_struct; }; diff --git a/slsDetectorSoftware/slsDetector/slsDetector.cpp b/slsDetectorSoftware/slsDetector/slsDetector.cpp index 502c391e2..d0c039c87 100644 --- a/slsDetectorSoftware/slsDetector/slsDetector.cpp +++ b/slsDetectorSoftware/slsDetector/slsDetector.cpp @@ -59,7 +59,7 @@ slsDetector::slsDetector(int multiId, int id, bool verify) slsDetector::~slsDetector() { if (sharedMemory) { - sharedMemory->UnmapSharedMemory(thisDetector); + sharedMemory->UnmapSharedMemory(); delete sharedMemory; } } @@ -208,7 +208,7 @@ void slsDetector::freeSharedMemory(int multiId, int slsId) { void slsDetector::freeSharedMemory() { if (sharedMemory) { - sharedMemory->UnmapSharedMemory(thisDetector); + sharedMemory->UnmapSharedMemory(); sharedMemory->RemoveSharedMemory(); delete sharedMemory; sharedMemory = nullptr; @@ -240,11 +240,15 @@ void slsDetector::initSharedMemory(bool created, detectorType type, int multiId, // create if (created) { - thisDetector = (sharedSlsDetector *)sharedMemory->CreateSharedMemory(sz); + // thisDetector = (sharedSlsDetector *)sharedMemory->CreateSharedMemory(sz); + sharedMemory->CreateSharedMemory(sz); + thisDetector = (*sharedMemory)(); } // open and verify version else { - thisDetector = (sharedSlsDetector *)sharedMemory->OpenSharedMemory(sz); + // thisDetector = (sharedSlsDetector *)sharedMemory->OpenSharedMemory(sz); + sharedMemory->OpenSharedMemory(); + thisDetector = (*sharedMemory)(); if (verify && thisDetector->shmversion != SLS_SHMVERSION) { FILE_LOG(logERROR) << "Single shared memory " "(" @@ -259,7 +263,7 @@ void slsDetector::initSharedMemory(bool created, detectorType type, int multiId, if (sharedMemory) { // unmap if (thisDetector) { - sharedMemory->UnmapSharedMemory(thisDetector); + sharedMemory->UnmapSharedMemory(); thisDetector = nullptr; } // delete @@ -643,10 +647,10 @@ slsDetectorDefs::detectorType slsDetector::getDetectorTypeFromShm(int multiId, b throw SharedMemoryException(); } - size_t sz = sizeof(sharedSlsDetector); - // open, map, verify version - auto sdet = (sharedSlsDetector *)shm.OpenSharedMemory(sz); + // auto sdet = (sharedSlsDetector *)shm.OpenSharedMemory(sz); + shm.OpenSharedMemory(); + auto sdet = shm(); if (verify && sdet->shmversion != SLS_SHMVERSION) { FILE_LOG(logERROR) << "Single shared memory " "(" @@ -654,13 +658,13 @@ slsDetectorDefs::detectorType slsDetector::getDetectorTypeFromShm(int multiId, b "(expected 0x" << std::hex << SLS_SHMVERSION << " but got 0x" << sdet->shmversion << ")" << std::dec; // unmap and throw - sharedMemory->UnmapSharedMemory(thisDetector); + sharedMemory->UnmapSharedMemory(); throw SharedMemoryException(); } // get type, unmap auto type = sdet->myDetectorType; - shm.UnmapSharedMemory(sdet); + shm.UnmapSharedMemory(); return type; } diff --git a/slsDetectorSoftware/tests/CMakeLists.txt b/slsDetectorSoftware/tests/CMakeLists.txt new file mode 100644 index 000000000..bbe9c32aa --- /dev/null +++ b/slsDetectorSoftware/tests/CMakeLists.txt @@ -0,0 +1,23 @@ + + +include_directories( + ${PROJECT_SOURCE_DIR}/catch +) + +set(SOURCES + test.cpp + test-SharedMemory.cpp +) + +add_executable(testSlsDetector ${SOURCES}) +target_link_libraries(testSlsDetector + slsSupportLib + slsDetectorShared + pthread + rt +) +set_target_properties(testSlsDetector PROPERTIES + RUNTIME_OUTPUT_DIRECTORY ${CMAKE_BINARY_DIR}/bin + ) +#TODO! Move to automatic test discovery +add_test(test-testSlsDetector ${CMAKE_BINARY_DIR}/bin/testSlsDetector) \ No newline at end of file diff --git a/slsDetectorSoftware/tests/test-SharedMemory.cpp b/slsDetectorSoftware/tests/test-SharedMemory.cpp new file mode 100644 index 000000000..e541ad3e2 --- /dev/null +++ b/slsDetectorSoftware/tests/test-SharedMemory.cpp @@ -0,0 +1,30 @@ + +#include "catch.hpp" +#include "SharedMemory.h" +#include "string_utils.h" + + +TEST_CASE("SharedMemory") { + struct Data{ + int x; + double y; + char mess[50]; + }; + + + SharedMemory shm(0,-1); + shm.CreateSharedMemory(); + CHECK(shm.GetName() == "/slsDetectorPackage_multi_0"); + + shm()->x = 3; + shm()->y = 5.7; + sls::strcpy_safe(shm()->mess, "Some string"); + + CHECK(shm()->x == 3); + CHECK(shm()->y == 5.7); + CHECK(std::string(shm()->mess) == "Some string"); + + shm.UnmapSharedMemory(); + shm.RemoveSharedMemory(); + +} \ No newline at end of file diff --git a/slsDetectorSoftware/tests/test.cpp b/slsDetectorSoftware/tests/test.cpp new file mode 100644 index 000000000..8daed99c4 --- /dev/null +++ b/slsDetectorSoftware/tests/test.cpp @@ -0,0 +1,3 @@ +// tests-main.cpp +#define CATCH_CONFIG_MAIN +#include "catch.hpp" \ No newline at end of file From 3b2c734efdd4bae880b579a3017ecdbfb3bf4941 Mon Sep 17 00:00:00 2001 From: Erik Frojdh Date: Tue, 12 Mar 2019 11:43:28 +0100 Subject: [PATCH 3/7] adding tests --- .../multiSlsDetector/multiSlsDetector.cpp | 334 ++++++++---------- .../multiSlsDetector/multiSlsDetector.h | 2 +- .../sharedMemory/SharedMemory.h | 36 +- .../slsDetector/slsDetector.cpp | 2 +- .../tests/test-SharedMemory.cpp | 66 +++- 5 files changed, 225 insertions(+), 215 deletions(-) diff --git a/slsDetectorSoftware/multiSlsDetector/multiSlsDetector.cpp b/slsDetectorSoftware/multiSlsDetector/multiSlsDetector.cpp index 0c551799e..e160c9700 100644 --- a/slsDetectorSoftware/multiSlsDetector/multiSlsDetector.cpp +++ b/slsDetectorSoftware/multiSlsDetector/multiSlsDetector.cpp @@ -31,12 +31,7 @@ multiSlsDetector::multiSlsDetector(int id, bool verify, bool update) setupMultiDetector(verify, update); } -multiSlsDetector::~multiSlsDetector() { - if (sharedMemory) { - sharedMemory->UnmapSharedMemory(); - delete sharedMemory; - } -} +multiSlsDetector::~multiSlsDetector() = default; void multiSlsDetector::setupMultiDetector(bool verify, bool update) { initSharedMemory(verify); @@ -197,21 +192,21 @@ void multiSlsDetector::setErrorMaskFromAllDetectors() { } void multiSlsDetector::setAcquiringFlag(bool b) { - thisMultiDetector->acquiringFlag = b; + sharedMemory()->acquiringFlag = b; } bool multiSlsDetector::getAcquiringFlag() const { - return thisMultiDetector->acquiringFlag; + return sharedMemory()->acquiringFlag; } bool multiSlsDetector::isAcquireReady() { - if (thisMultiDetector->acquiringFlag) { + if (sharedMemory()->acquiringFlag) { FILE_LOG(logWARNING) << "Acquire has already started. " "If previous acquisition terminated unexpectedly, " "reset busy flag to restart.(sls_detector_put busy 0)"; return FAIL; } - thisMultiDetector->acquiringFlag = true; + sharedMemory()->acquiringFlag = true; return OK; } @@ -250,23 +245,17 @@ void multiSlsDetector::freeSharedMemory(int multiId, int detPos) { } // multi - // get number of detectors + auto multiShm = SharedMemory(multiId, -1); int numDetectors = 0; - auto shm = SharedMemory(multiId, -1); - // get number of detectors from multi shm - if (shm.IsExisting()) { - // sharedMultiSlsDetector *mdet = - // (sharedMultiSlsDetector *)shm.OpenSharedMemory( - // sizeof(sharedMultiSlsDetector)); - shm.OpenSharedMemory(); - numDetectors = shm()->numberOfDetectors; - shm.UnmapSharedMemory(); - shm.RemoveSharedMemory(); + if (multiShm.IsExisting()) { + multiShm.OpenSharedMemory(); + numDetectors = multiShm()->numberOfDetectors; + multiShm.RemoveSharedMemory(); } for (int i = 0; i < numDetectors; ++i) { - auto shm = SharedMemory(multiId, i); + auto shm = SharedMemory(multiId, i); shm.RemoveSharedMemory(); } } @@ -287,17 +276,7 @@ void multiSlsDetector::freeSharedMemory(int detPos) { detectors.clear(); // clear multi detector shm - if (sharedMemory) { - if (thisMultiDetector) { - sharedMemory->UnmapSharedMemory(); - thisMultiDetector = nullptr; - } - sharedMemory->RemoveSharedMemory(); - delete sharedMemory; - sharedMemory = nullptr; - } - - // zmq + sharedMemory.RemoveSharedMemory(); //TODO verify use client_downstream = false; } @@ -313,82 +292,56 @@ std::string multiSlsDetector::getUserDetails() { sstream << d->getDetectorTypeAsString() << "+"; } - sstream << "\nPID: " << thisMultiDetector->lastPID - << "\nUser: " << thisMultiDetector->lastUser - << "\nDate: " << thisMultiDetector->lastDate << std::endl; + sstream << "\nPID: " << sharedMemory()->lastPID + << "\nUser: " << sharedMemory()->lastUser + << "\nDate: " << sharedMemory()->lastDate << std::endl; return sstream.str(); } /* - * pre: sharedMemory=0, thisMultiDetector = 0, detectors.size() = 0 - * exceptions are caught in calling function, shm unmapped and deleted + * pre: sharedMemory=0, sharedMemory() = 0, detectors.size() = 0 */ void multiSlsDetector::initSharedMemory(bool verify) { - try { - // shared memory object with name - sharedMemory = new SharedMemory(detId, -1); - // size_t sz = sizeof(sharedMultiSlsDetector); - - // create - if (!sharedMemory->IsExisting()) { - // thisMultiDetector = - // (sharedMultiSlsDetector *)sharedMemory->CreateSharedMemory(sz); - sharedMemory->CreateSharedMemory(); - thisMultiDetector= (*sharedMemory)(); //TODO remove line - initializeDetectorStructure(); + sharedMemory = SharedMemory(detId, -1); + if (!sharedMemory.IsExisting()) { + sharedMemory.CreateSharedMemory(); + initializeDetectorStructure(); + } + else { + sharedMemory.OpenSharedMemory(); + if (verify && sharedMemory()->shmversion != MULTI_SHMVERSION) { + FILE_LOG(logERROR) << "Multi shared memory (" << detId << ") version mismatch " + "(expected 0x" + << std::hex << MULTI_SHMVERSION << " but got 0x" << sharedMemory()->shmversion << std::dec; + throw SharedMemoryException(); } - // open and verify version - else { - // thisMultiDetector = - // (sharedMultiSlsDetector *)sharedMemory->OpenSharedMemory(sz); - sharedMemory->OpenSharedMemory(); - thisMultiDetector = (*sharedMemory)(); - if (verify && thisMultiDetector->shmversion != MULTI_SHMVERSION) { - FILE_LOG(logERROR) << "Multi shared memory (" << detId << ") version mismatch " - "(expected 0x" - << std::hex << MULTI_SHMVERSION << " but got 0x" << thisMultiDetector->shmversion << std::dec; - throw SharedMemoryException(); - } - } - } catch (...) { - if (sharedMemory) { - // unmap - if (thisMultiDetector) { - sharedMemory->UnmapSharedMemory(); - thisMultiDetector = nullptr; - } - // delete - delete sharedMemory; - sharedMemory = nullptr; - } - throw; } } void multiSlsDetector::initializeDetectorStructure() { - thisMultiDetector->shmversion = MULTI_SHMVERSION; - thisMultiDetector->numberOfDetectors = 0; - thisMultiDetector->numberOfDetector[X] = 0; - thisMultiDetector->numberOfDetector[Y] = 0; - thisMultiDetector->onlineFlag = 1; - thisMultiDetector->stoppedFlag = 0; - thisMultiDetector->dataBytes = 0; - thisMultiDetector->dataBytesInclGapPixels = 0; - thisMultiDetector->numberOfChannels = 0; - thisMultiDetector->numberOfChannel[X] = 0; - thisMultiDetector->numberOfChannel[Y] = 0; - thisMultiDetector->numberOfChannelInclGapPixels[X] = 0; - thisMultiDetector->numberOfChannelInclGapPixels[Y] = 0; - thisMultiDetector->maxNumberOfChannelsPerDetector[X] = 0; - thisMultiDetector->maxNumberOfChannelsPerDetector[Y] = 0; - for (int64_t &i : thisMultiDetector->timerValue) { + sharedMemory()->shmversion = MULTI_SHMVERSION; + sharedMemory()->numberOfDetectors = 0; + sharedMemory()->numberOfDetector[X] = 0; + sharedMemory()->numberOfDetector[Y] = 0; + sharedMemory()->onlineFlag = 1; + sharedMemory()->stoppedFlag = 0; + sharedMemory()->dataBytes = 0; + sharedMemory()->dataBytesInclGapPixels = 0; + sharedMemory()->numberOfChannels = 0; + sharedMemory()->numberOfChannel[X] = 0; + sharedMemory()->numberOfChannel[Y] = 0; + sharedMemory()->numberOfChannelInclGapPixels[X] = 0; + sharedMemory()->numberOfChannelInclGapPixels[Y] = 0; + sharedMemory()->maxNumberOfChannelsPerDetector[X] = 0; + sharedMemory()->maxNumberOfChannelsPerDetector[Y] = 0; + for (int64_t &i : sharedMemory()->timerValue) { i = 0; } - thisMultiDetector->acquiringFlag = false; - thisMultiDetector->receiverOnlineFlag = OFFLINE_FLAG; - thisMultiDetector->receiver_upstream = false; + sharedMemory()->acquiringFlag = false; + sharedMemory()->receiverOnlineFlag = OFFLINE_FLAG; + sharedMemory()->receiver_upstream = false; } void multiSlsDetector::initializeMembers(bool verify) { @@ -396,7 +349,7 @@ void multiSlsDetector::initializeMembers(bool verify) { zmqSocket.clear(); // get objects from single det shared memory (open) - for (int i = 0; i < thisMultiDetector->numberOfDetectors; i++) { + for (int i = 0; i < sharedMemory()->numberOfDetectors; i++) { try { detectors.push_back( sls::make_unique(detId, i, verify)); @@ -411,15 +364,15 @@ void multiSlsDetector::initializeMembers(bool verify) { } void multiSlsDetector::updateUserdetails() { - thisMultiDetector->lastPID = getpid(); - memset(thisMultiDetector->lastUser, 0, SHORT_STRING_LENGTH); - memset(thisMultiDetector->lastDate, 0, SHORT_STRING_LENGTH); + sharedMemory()->lastPID = getpid(); + memset(sharedMemory()->lastUser, 0, SHORT_STRING_LENGTH); + memset(sharedMemory()->lastDate, 0, SHORT_STRING_LENGTH); try { - sls::strcpy_safe(thisMultiDetector->lastUser, exec("whoami").c_str()); - sls::strcpy_safe(thisMultiDetector->lastDate, exec("date").c_str()); + sls::strcpy_safe(sharedMemory()->lastUser, exec("whoami").c_str()); + sls::strcpy_safe(sharedMemory()->lastDate, exec("date").c_str()); } catch (...) { - sls::strcpy_safe(thisMultiDetector->lastUser, "errorreading"); - sls::strcpy_safe(thisMultiDetector->lastDate, "errorreading"); + sls::strcpy_safe(sharedMemory()->lastUser, "errorreading"); + sls::strcpy_safe(sharedMemory()->lastDate, "errorreading"); } } @@ -455,7 +408,7 @@ void multiSlsDetector::setHostname(const char *name, int detPos) { // multi // this check is there only to allow the previous detsizechan command - if (thisMultiDetector->numberOfDetectors) { + if (sharedMemory()->numberOfDetectors) { FILE_LOG(logWARNING) << "There are already detector(s) in shared memory." "Freeing Shared memory now."; freeSharedMemory(); @@ -508,11 +461,11 @@ void multiSlsDetector::addSlsDetector(const std::string &hostname) { int pos = (int)detectors.size(); detectors.push_back(sls::make_unique(type, detId, pos, false)); - thisMultiDetector->numberOfDetectors = detectors.size(); - thisMultiDetector->dataBytes += detectors[pos]->getDataBytes(); - thisMultiDetector->dataBytesInclGapPixels += + sharedMemory()->numberOfDetectors = detectors.size(); + sharedMemory()->dataBytes += detectors[pos]->getDataBytes(); + sharedMemory()->dataBytesInclGapPixels += detectors[pos]->getDataBytesInclGapPixels(); - thisMultiDetector->numberOfChannels += + sharedMemory()->numberOfChannels += detectors[pos]->getTotalNumberOfChannels(); detectors[pos]->setHostname(hostname); @@ -546,12 +499,12 @@ int multiSlsDetector::getNumberOfDetectors() const { } int multiSlsDetector::getNumberOfDetectors(dimension d) const { - return thisMultiDetector->numberOfDetector[d]; + return sharedMemory()->numberOfDetector[d]; } void multiSlsDetector::getNumberOfDetectors(int &nx, int &ny) const { - nx = thisMultiDetector->numberOfDetector[X]; - ny = thisMultiDetector->numberOfDetector[Y]; + nx = sharedMemory()->numberOfDetector[X]; + ny = sharedMemory()->numberOfDetector[Y]; } int multiSlsDetector::getTotalNumberOfChannels(int detPos) { @@ -561,7 +514,7 @@ int multiSlsDetector::getTotalNumberOfChannels(int detPos) { } // multi - return thisMultiDetector->numberOfChannels; + return sharedMemory()->numberOfChannels; } int multiSlsDetector::getTotalNumberOfChannels(dimension d, int detPos) { @@ -571,7 +524,7 @@ int multiSlsDetector::getTotalNumberOfChannels(dimension d, int detPos) { } // multi - return thisMultiDetector->numberOfChannel[d]; + return sharedMemory()->numberOfChannel[d]; } int multiSlsDetector::getTotalNumberOfChannelsInclGapPixels(dimension d, @@ -582,16 +535,16 @@ int multiSlsDetector::getTotalNumberOfChannelsInclGapPixels(dimension d, } // multi - return thisMultiDetector->numberOfChannelInclGapPixels[d]; + return sharedMemory()->numberOfChannelInclGapPixels[d]; } int multiSlsDetector::getMaxNumberOfChannelsPerDetector(dimension d) { - return thisMultiDetector->maxNumberOfChannelsPerDetector[d]; + return sharedMemory()->maxNumberOfChannelsPerDetector[d]; } int multiSlsDetector::setMaxNumberOfChannelsPerDetector(dimension d, int i) { - thisMultiDetector->maxNumberOfChannelsPerDetector[d] = i; - return thisMultiDetector->maxNumberOfChannelsPerDetector[d]; + sharedMemory()->maxNumberOfChannelsPerDetector[d] = i; + return sharedMemory()->maxNumberOfChannelsPerDetector[d]; } int multiSlsDetector::getDetectorOffset(dimension d, int detPos) { @@ -606,22 +559,22 @@ void multiSlsDetector::updateOffsets() { FILE_LOG(logDEBUG1) << "Updating Multi-Detector Offsets"; int offsetX = 0, offsetY = 0, numX = 0, numY = 0; - int maxChanX = thisMultiDetector->maxNumberOfChannelsPerDetector[X]; - int maxChanY = thisMultiDetector->maxNumberOfChannelsPerDetector[Y]; + int maxChanX = sharedMemory()->maxNumberOfChannelsPerDetector[X]; + int maxChanY = sharedMemory()->maxNumberOfChannelsPerDetector[Y]; int prevChanX = 0; int prevChanY = 0; bool firstTime = true; - thisMultiDetector->numberOfChannel[X] = 0; - thisMultiDetector->numberOfChannel[Y] = 0; - thisMultiDetector->numberOfDetector[X] = 0; - thisMultiDetector->numberOfDetector[Y] = 0; + sharedMemory()->numberOfChannel[X] = 0; + sharedMemory()->numberOfChannel[Y] = 0; + sharedMemory()->numberOfDetector[X] = 0; + sharedMemory()->numberOfDetector[Y] = 0; // gap pixels int offsetX_gp = 0, offsetY_gp = 0, numX_gp = 0, numY_gp = 0; int prevChanX_gp = 0, prevChanY_gp = 0; - thisMultiDetector->numberOfChannelInclGapPixels[X] = 0; - thisMultiDetector->numberOfChannelInclGapPixels[Y] = 0; + sharedMemory()->numberOfChannelInclGapPixels[X] = 0; + sharedMemory()->numberOfChannelInclGapPixels[Y] = 0; for (size_t idet = 0; idet < detectors.size(); ++idet) { FILE_LOG(logDEBUG1) << "offsetX:" << offsetX << " prevChanX:" << prevChanX << " offsetY:" << offsetY << " prevChanY:" << prevChanY << " offsetX_gp:" << offsetX_gp << " prevChanX_gp:" << prevChanX_gp << " offsetY_gp:" << offsetY_gp << " prevChanY_gp:" << prevChanY_gp; @@ -654,8 +607,8 @@ void multiSlsDetector::updateOffsets() { detectors[idet]->getTotalNumberOfChannelsInclGapPixels(X); numY_gp += detectors[idet]->getTotalNumberOfChannelsInclGapPixels(Y); - ++thisMultiDetector->numberOfDetector[X]; - ++thisMultiDetector->numberOfDetector[Y]; + ++sharedMemory()->numberOfDetector[X]; + ++sharedMemory()->numberOfDetector[Y]; FILE_LOG(logDEBUG1) << "incrementing in both direction"; } @@ -673,8 +626,8 @@ void multiSlsDetector::updateOffsets() { numY_gp += detectors[idet]->getTotalNumberOfChannelsInclGapPixels(Y); // increment in y again only in the first column (else you double increment) - if (thisMultiDetector->numberOfDetector[X] == 1) - ++thisMultiDetector->numberOfDetector[Y]; + if (sharedMemory()->numberOfDetector[X] == 1) + ++sharedMemory()->numberOfDetector[Y]; FILE_LOG(logDEBUG1) << "incrementing in y direction"; } @@ -703,7 +656,7 @@ void multiSlsDetector::updateOffsets() { numX += detectors[idet]->getTotalNumberOfChannels(X); numX_gp += detectors[idet]->getTotalNumberOfChannelsInclGapPixels(X); - ++thisMultiDetector->numberOfDetector[X]; + ++sharedMemory()->numberOfDetector[X]; FILE_LOG(logDEBUG1) << "incrementing in x direction"; } @@ -721,28 +674,28 @@ void multiSlsDetector::updateOffsets() { << detectors[idet]->getDetectorOffset(Y) << ")"; // offsetY has been reset sometimes and offsetX the first time, // but remember the highest values - if (numX > thisMultiDetector->numberOfChannel[X]) { - thisMultiDetector->numberOfChannel[X] = numX; + if (numX > sharedMemory()->numberOfChannel[X]) { + sharedMemory()->numberOfChannel[X] = numX; } - if (numY > thisMultiDetector->numberOfChannel[Y]) { - thisMultiDetector->numberOfChannel[Y] = numY; + if (numY > sharedMemory()->numberOfChannel[Y]) { + sharedMemory()->numberOfChannel[Y] = numY; } - if (numX_gp > thisMultiDetector->numberOfChannelInclGapPixels[X]) { - thisMultiDetector->numberOfChannelInclGapPixels[X] = numX_gp; + if (numX_gp > sharedMemory()->numberOfChannelInclGapPixels[X]) { + sharedMemory()->numberOfChannelInclGapPixels[X] = numX_gp; } - if (numY_gp > thisMultiDetector->numberOfChannelInclGapPixels[Y]) { - thisMultiDetector->numberOfChannelInclGapPixels[Y] = numY_gp; + if (numY_gp > sharedMemory()->numberOfChannelInclGapPixels[Y]) { + sharedMemory()->numberOfChannelInclGapPixels[Y] = numY_gp; } } - FILE_LOG(logDEBUG1) << "\n\tNumber of Channels in X direction:" << thisMultiDetector->numberOfChannel[X] << "\n\tNumber of Channels in Y direction:" << thisMultiDetector->numberOfChannel[Y] << "\n\tNumber of Channels in X direction with Gap Pixels:" << thisMultiDetector->numberOfChannelInclGapPixels[X] << "\n\tNumber of Channels in Y direction with Gap Pixels:" << thisMultiDetector->numberOfChannelInclGapPixels[Y]; + FILE_LOG(logDEBUG1) << "\n\tNumber of Channels in X direction:" << sharedMemory()->numberOfChannel[X] << "\n\tNumber of Channels in Y direction:" << sharedMemory()->numberOfChannel[Y] << "\n\tNumber of Channels in X direction with Gap Pixels:" << sharedMemory()->numberOfChannelInclGapPixels[X] << "\n\tNumber of Channels in Y direction with Gap Pixels:" << sharedMemory()->numberOfChannelInclGapPixels[Y]; - thisMultiDetector->numberOfChannels = - thisMultiDetector->numberOfChannel[0] * - thisMultiDetector->numberOfChannel[1]; + sharedMemory()->numberOfChannels = + sharedMemory()->numberOfChannel[0] * + sharedMemory()->numberOfChannel[1]; for (auto &d : detectors) { - d->updateMultiSize(thisMultiDetector->numberOfDetector[0], - thisMultiDetector->numberOfDetector[1]); + d->updateMultiSize(sharedMemory()->numberOfDetector[0], + sharedMemory()->numberOfDetector[1]); } } @@ -755,9 +708,9 @@ int multiSlsDetector::setOnline(int value, int detPos) { // multi if (value != GET_ONLINE_FLAG) { auto r = parallelCall(&slsDetector::setOnline, value); - thisMultiDetector->onlineFlag = sls::minusOneIfDifferent(r); + sharedMemory()->onlineFlag = sls::minusOneIfDifferent(r); } - return thisMultiDetector->onlineFlag; + return sharedMemory()->onlineFlag; } std::string multiSlsDetector::checkOnline(int detPos) { @@ -1109,12 +1062,12 @@ int multiSlsDetector::stopAcquisition(int detPos) { if (detPos >= 0) { // if only 1 detector, set flag to stop current acquisition if (detectors.size() == 1) { - thisMultiDetector->stoppedFlag = 1; + sharedMemory()->stoppedFlag = 1; } return detectors[detPos]->stopAcquisition(); } else { - thisMultiDetector->stoppedFlag = 1; + sharedMemory()->stoppedFlag = 1; auto r = parallelCall(&slsDetector::stopAcquisition); return sls::allEqualTo(r, static_cast(OK)) ? OK : FAIL; } @@ -1201,7 +1154,7 @@ int64_t multiSlsDetector::setTimer(timerIndex index, int64_t t, int detPos) { << "Cannot set number of frames, cycles, " "storage cells or measurements individually."; setErrorMask(getErrorMask() | MUST_BE_MULTI_CMD); - return thisMultiDetector->timerValue[index]; + return sharedMemory()->timerValue[index]; default: break; } @@ -1232,7 +1185,7 @@ int64_t multiSlsDetector::setTimer(timerIndex index, int64_t t, int detPos) { } } - thisMultiDetector->timerValue[index] = ret; + sharedMemory()->timerValue[index] = ret; return ret; } @@ -1400,16 +1353,16 @@ int multiSlsDetector::setDynamicRange(int dr, int detPos) { int ret = sls::minusOneIfDifferent(r); // update shm - int prevValue = thisMultiDetector->dataBytes; - int prevGValue = thisMultiDetector->dataBytesInclGapPixels; - thisMultiDetector->dataBytes = 0; - thisMultiDetector->dataBytesInclGapPixels = 0; - thisMultiDetector->numberOfChannels = 0; + int prevValue = sharedMemory()->dataBytes; + int prevGValue = sharedMemory()->dataBytesInclGapPixels; + sharedMemory()->dataBytes = 0; + sharedMemory()->dataBytesInclGapPixels = 0; + sharedMemory()->numberOfChannels = 0; for (auto &d : detectors) { - thisMultiDetector->dataBytes += d->getDataBytes(); - thisMultiDetector->dataBytesInclGapPixels += + sharedMemory()->dataBytes += d->getDataBytes(); + sharedMemory()->dataBytesInclGapPixels += d->getDataBytesInclGapPixels(); - thisMultiDetector->numberOfChannels += d->getTotalNumberOfChannels(); + sharedMemory()->numberOfChannels += d->getTotalNumberOfChannels(); } // for usability @@ -1432,8 +1385,8 @@ int multiSlsDetector::setDynamicRange(int dr, int detPos) { // update offsets if there was a change FIXME:add dr to sls shm and check // that instead - if ((prevValue != thisMultiDetector->dataBytes) || - (prevGValue != thisMultiDetector->dataBytesInclGapPixels)) { + if ((prevValue != sharedMemory()->dataBytes) || + (prevGValue != sharedMemory()->dataBytesInclGapPixels)) { updateOffsets(); } @@ -1960,7 +1913,6 @@ std::string multiSlsDetector::getAdditionalJsonParameter(const std::string &key, return sls::concatenateIfDifferent(r); } - int multiSlsDetector::setDetectorMinMaxEnergyThreshold(const int index, int value, int detPos) { std::string parameter = (index ? "emax" : "emin"); @@ -1976,7 +1928,7 @@ int multiSlsDetector::setDetectorMinMaxEnergyThreshold(const int index, int valu return stoi(result); } // not found or cannot scan integer - catch(...) { + catch (...) { return -1; } } @@ -2069,7 +2021,7 @@ int multiSlsDetector::loadImageToDetector(imageType index, // multi // read image for all - int nch = thisMultiDetector->numberOfChannels; + int nch = sharedMemory()->numberOfChannels; short int imageVals[nch]; if (readDataFile(fname, imageVals, nch) < nch * (int)sizeof(short int)) { FILE_LOG(logERROR) << "Could not open file or not enough data in file " @@ -2098,7 +2050,7 @@ int multiSlsDetector::writeCounterBlockFile(const std::string &fname, // multi // get image from all - int nch = thisMultiDetector->numberOfChannels; + int nch = sharedMemory()->numberOfChannels; short int imageVals[nch]; std::vector r; for (size_t idet = 0; idet < detectors.size(); ++idet) { @@ -2542,7 +2494,7 @@ int multiSlsDetector::enableGapPixels(int val, int detPos) { // update data bytes incl gap pixels if (val != -1) { auto r = serialCall(&slsDetector::getDataBytesInclGapPixels); - thisMultiDetector->dataBytesInclGapPixels = sls::sum(r); + sharedMemory()->dataBytesInclGapPixels = sls::sum(r); // update updateOffsets(); @@ -2749,9 +2701,9 @@ int multiSlsDetector::setReceiverOnline(int value, int detPos) { // multi if (value != GET_ONLINE_FLAG) { auto r = parallelCall(&slsDetector::setReceiverOnline, value); - thisMultiDetector->receiverOnlineFlag = sls::minusOneIfDifferent(r); + sharedMemory()->receiverOnlineFlag = sls::minusOneIfDifferent(r); } - return thisMultiDetector->receiverOnlineFlag; + return sharedMemory()->receiverOnlineFlag; } std::string multiSlsDetector::checkReceiverOnline(int detPos) { @@ -3089,8 +3041,8 @@ int multiSlsDetector::createReceivingDataSockets(const bool destroy) { void multiSlsDetector::readFrameFromReceiver() { int nX = - thisMultiDetector->numberOfDetector[X]; // to copy data in multi module - int nY = thisMultiDetector + sharedMemory()->numberOfDetector[X]; // to copy data in multi module + int nY = sharedMemory() ->numberOfDetector[Y]; // for eiger, to reverse the data bool gappixelsenable = false; bool eiger = false; @@ -3238,8 +3190,8 @@ void multiSlsDetector::readFrameFromReceiver() { // 4bit gap pixels if (dynamicRange == 4 && gappixelsenable) { int n = processImageWithGapPixels(multiframe, multigappixels); - nPixelsX = thisMultiDetector->numberOfChannelInclGapPixels[X]; - nPixelsY = thisMultiDetector->numberOfChannelInclGapPixels[Y]; + nPixelsX = sharedMemory()->numberOfChannelInclGapPixels[X]; + nPixelsY = sharedMemory()->numberOfChannelInclGapPixels[Y]; thisData = new detectorData(getCurrentProgress(), currentFileName.c_str(), nPixelsX, nPixelsY, multigappixels, n, @@ -3295,12 +3247,12 @@ void multiSlsDetector::readFrameFromReceiver() { int multiSlsDetector::processImageWithGapPixels(char *image, char *&gpImage) { // eiger 4 bit mode - int nxb = thisMultiDetector->numberOfDetector[X] * (512 + 3); - int nyb = thisMultiDetector->numberOfDetector[Y] * (256 + 1); + int nxb = sharedMemory()->numberOfDetector[X] * (512 + 3); + int nyb = sharedMemory()->numberOfDetector[Y] * (256 + 1); int gapdatabytes = nxb * nyb; - int nxchip = thisMultiDetector->numberOfDetector[X] * 4; - int nychip = thisMultiDetector->numberOfDetector[Y] * 1; + int nxchip = sharedMemory()->numberOfDetector[X] * 4; + int nychip = sharedMemory()->numberOfDetector[Y] * 1; // allocate if (gpImage == nullptr) { @@ -3564,7 +3516,7 @@ uint64_t multiSlsDetector::setPatternWord(int addr, uint64_t word, int detPos) { } int multiSlsDetector::setPatternLoops(int level, int &start, int &stop, int &n, - int detPos) { + int detPos) { // single if (detPos >= 0) { return detectors[detPos]->setPatternLoops(level, start, stop, n); @@ -3907,20 +3859,20 @@ void multiSlsDetector::registerDataCallback( int multiSlsDetector::setTotalProgress() { int nf = 1, nc = 1, ns = 1, nm = 1; - if (thisMultiDetector->timerValue[FRAME_NUMBER]) { - nf = thisMultiDetector->timerValue[FRAME_NUMBER]; + if (sharedMemory()->timerValue[FRAME_NUMBER]) { + nf = sharedMemory()->timerValue[FRAME_NUMBER]; } - if (thisMultiDetector->timerValue[CYCLES_NUMBER] > 0) { - nc = thisMultiDetector->timerValue[CYCLES_NUMBER]; + if (sharedMemory()->timerValue[CYCLES_NUMBER] > 0) { + nc = sharedMemory()->timerValue[CYCLES_NUMBER]; } - if (thisMultiDetector->timerValue[STORAGE_CELL_NUMBER] > 0) { - ns = thisMultiDetector->timerValue[STORAGE_CELL_NUMBER] + 1; + if (sharedMemory()->timerValue[STORAGE_CELL_NUMBER] > 0) { + ns = sharedMemory()->timerValue[STORAGE_CELL_NUMBER] + 1; } - if (thisMultiDetector->timerValue[MEASUREMENTS_NUMBER] > 0) { - nm = thisMultiDetector->timerValue[MEASUREMENTS_NUMBER]; + if (sharedMemory()->timerValue[MEASUREMENTS_NUMBER] > 0) { + nm = sharedMemory()->timerValue[MEASUREMENTS_NUMBER]; } totalProgress = nm * nf * nc * ns; @@ -3972,10 +3924,10 @@ int multiSlsDetector::acquire() { bool receiver = (setReceiverOnline() == ONLINE_FLAG); progressIndex = 0; - thisMultiDetector->stoppedFlag = 0; + sharedMemory()->stoppedFlag = 0; setJoinThreadFlag(false); - int nm = thisMultiDetector->timerValue[MEASUREMENTS_NUMBER]; + int nm = sharedMemory()->timerValue[MEASUREMENTS_NUMBER]; if (nm < 1) { nm = 1; } @@ -3985,7 +3937,7 @@ int multiSlsDetector::acquire() { std::lock_guard lock(mg); if (getReceiverStatus() != IDLE) { if (stopReceiver() == FAIL) { - thisMultiDetector->stoppedFlag = 1; + sharedMemory()->stoppedFlag = 1; } } } @@ -3996,13 +3948,13 @@ int multiSlsDetector::acquire() { if (receiver) { std::lock_guard lock(mg); if (resetFramesCaught() == FAIL) { - thisMultiDetector->stoppedFlag = 1; + sharedMemory()->stoppedFlag = 1; } } // loop through measurements for (int im = 0; im < nm; ++im) { - if (thisMultiDetector->stoppedFlag) { + if (sharedMemory()->stoppedFlag) { break; } @@ -4012,7 +3964,7 @@ int multiSlsDetector::acquire() { if (startReceiver() == FAIL) { FILE_LOG(logERROR) << "Start receiver failed "; stopReceiver(); - thisMultiDetector->stoppedFlag = 1; + sharedMemory()->stoppedFlag = 1; break; } // let processing thread listen to these packets @@ -4025,7 +3977,7 @@ int multiSlsDetector::acquire() { std::lock_guard lock(mg); if (receiver) { if (stopReceiver() == FAIL) { - thisMultiDetector->stoppedFlag = 1; + sharedMemory()->stoppedFlag = 1; } else { if (dataReady) { sem_wait(&sem_endRTAcquisition); // waits for receiver's @@ -4040,7 +3992,7 @@ int multiSlsDetector::acquire() { if (measurement_finished) { measurement_finished(im, findex, measFinished_p); } - if (thisMultiDetector->stoppedFlag) { + if (sharedMemory()->stoppedFlag) { break; } diff --git a/slsDetectorSoftware/multiSlsDetector/multiSlsDetector.h b/slsDetectorSoftware/multiSlsDetector/multiSlsDetector.h index 3a80bc2f2..21d6b0dd9 100644 --- a/slsDetectorSoftware/multiSlsDetector/multiSlsDetector.h +++ b/slsDetectorSoftware/multiSlsDetector/multiSlsDetector.h @@ -1966,7 +1966,7 @@ class multiSlsDetector : public virtual slsDetectorDefs, int detId; /** Shared Memory object */ - SharedMemory *sharedMemory {nullptr}; + SharedMemory sharedMemory{0,-1}; /** Shared memory structure */ sharedMultiSlsDetector *thisMultiDetector {nullptr}; diff --git a/slsDetectorSoftware/sharedMemory/SharedMemory.h b/slsDetectorSoftware/sharedMemory/SharedMemory.h index 19782263e..a5c9d68f5 100644 --- a/slsDetectorSoftware/sharedMemory/SharedMemory.h +++ b/slsDetectorSoftware/sharedMemory/SharedMemory.h @@ -39,8 +39,7 @@ class SharedMemory { * @param multiId multi detector id * @param slsId sls detector id, -1 if a multi detector shared memory */ - SharedMemory(int multiId, int slsId) : fd(-1), - shmSize(0) { + SharedMemory(int multiId, int slsId){ name = ConstructSharedMemoryName(multiId, slsId); } @@ -50,6 +49,10 @@ class SharedMemory { ~SharedMemory() { if (fd >= 0) close(fd); + + if (shared_struct) { + UnmapSharedMemory(); + } } /** @@ -81,10 +84,10 @@ class SharedMemory { */ void CreateSharedMemory(size_t sz = 0) { // create - if (sz == 0){ + if (sz == 0) { sz = sizeof(T); } - + fd = shm_open(name.c_str(), O_CREAT | O_TRUNC | O_EXCL | O_RDWR, S_IRUSR | S_IWUSR); if (fd < 0) { FILE_LOG(logERROR) << "Create shared memory " << name << " failed: " << strerror(errno); @@ -112,9 +115,12 @@ class SharedMemory { * throws a SharedMemoryException exception on failure to open or map * @param sz of shared memory */ - void OpenSharedMemory() { + void OpenSharedMemory(size_t sz = 0) { // open - size_t sz = sizeof(T); + if (sz == 0) { + sz = sizeof(T); + } + fd = shm_open(name.c_str(), O_RDWR, 0); if (fd < 0) { FILE_LOG(logERROR) << "Open existing shared memory " << name << " failed: " << strerror(errno); @@ -130,10 +136,13 @@ class SharedMemory { * throws a SharedMemoryException exception on failure */ void UnmapSharedMemory() { - if (munmap(shared_struct, shmSize) < 0) { - FILE_LOG(logERROR) << "Unmapping shared memory " << name << " failed: " << strerror(errno); - close(fd); - throw SharedMemoryException(); + if (shared_struct != nullptr) { + if (munmap(shared_struct, shmSize) < 0) { + FILE_LOG(logERROR) << "Unmapping shared memory " << name << " failed: " << strerror(errno); + close(fd); + throw SharedMemoryException(); + } + shared_struct = nullptr; } } @@ -141,6 +150,7 @@ class SharedMemory { * Remove existing Shared memory */ void RemoveSharedMemory() { + UnmapSharedMemory(); if (shm_unlink(name.c_str()) < 0) { // silent exit if shm did not exist anyway if (errno == ENOENT) @@ -252,10 +262,10 @@ class SharedMemory { std::string name; /** File descriptor */ - int fd; + int fd{-1}; /** shm size */ - size_t shmSize; + size_t shmSize{0}; - T *shared_struct; + T *shared_struct{nullptr}; }; diff --git a/slsDetectorSoftware/slsDetector/slsDetector.cpp b/slsDetectorSoftware/slsDetector/slsDetector.cpp index d0c039c87..e3291fa52 100644 --- a/slsDetectorSoftware/slsDetector/slsDetector.cpp +++ b/slsDetectorSoftware/slsDetector/slsDetector.cpp @@ -247,7 +247,7 @@ void slsDetector::initSharedMemory(bool created, detectorType type, int multiId, // open and verify version else { // thisDetector = (sharedSlsDetector *)sharedMemory->OpenSharedMemory(sz); - sharedMemory->OpenSharedMemory(); + sharedMemory->OpenSharedMemory(sz); thisDetector = (*sharedMemory)(); if (verify && thisDetector->shmversion != SLS_SHMVERSION) { FILE_LOG(logERROR) << "Single shared memory " diff --git a/slsDetectorSoftware/tests/test-SharedMemory.cpp b/slsDetectorSoftware/tests/test-SharedMemory.cpp index e541ad3e2..8231070a9 100644 --- a/slsDetectorSoftware/tests/test-SharedMemory.cpp +++ b/slsDetectorSoftware/tests/test-SharedMemory.cpp @@ -1,18 +1,17 @@ -#include "catch.hpp" #include "SharedMemory.h" +#include "catch.hpp" #include "string_utils.h" +struct Data { + int x; + double y; + char mess[50]; +}; -TEST_CASE("SharedMemory") { - struct Data{ - int x; - double y; - char mess[50]; - }; +TEST_CASE("Create SharedMemory read and write") { - - SharedMemory shm(0,-1); + SharedMemory shm(0, -1); shm.CreateSharedMemory(); CHECK(shm.GetName() == "/slsDetectorPackage_multi_0"); @@ -26,5 +25,54 @@ TEST_CASE("SharedMemory") { shm.UnmapSharedMemory(); shm.RemoveSharedMemory(); +} +TEST_CASE("Open existing SharedMemory and read") { + + SharedMemory shm(0, -1); + shm.CreateSharedMemory(); + *shm() = 5.3; + shm.UnmapSharedMemory(); + + SharedMemory shm2(0, -1); + shm2.OpenSharedMemory(); + CHECK(*shm2() == 5.3); + + shm2.RemoveSharedMemory(); +} + +TEST_CASE("Two shared memories with the same name throws") { + + SharedMemory shm0(0, -1); + SharedMemory shm1(0, -1); + + shm0.CreateSharedMemory(); + CHECK_THROWS(shm1.CreateSharedMemory()); + shm0.RemoveSharedMemory(); +} + +TEST_CASE("Open two shared memories to the same place") { + + //Create the first shared memory + SharedMemory shm(0, -1); + shm.CreateSharedMemory(); + shm()->x = 5; + CHECK(shm()->x == 5); + + //Open the second shared memory with the same name + SharedMemory shm2(0, -1); + shm2.OpenSharedMemory(); + CHECK(shm2()->x == 5); + CHECK(shm.GetName() == shm2.GetName()); + + //Check that they still point to the same place + shm2()->x = 7; + CHECK(shm()->x == 7); + + + //Remove only needs to be done once since they refer + //to the same memory + shm2.RemoveSharedMemory(); + CHECK(shm.IsExisting() == false); + CHECK(shm2.IsExisting() == false); } \ No newline at end of file From 48e4cec56ff7772793f83927ef7cb677e9b08dab Mon Sep 17 00:00:00 2001 From: Erik Frojdh Date: Tue, 12 Mar 2019 11:52:13 +0100 Subject: [PATCH 4/7] minor --- .../multiSlsDetector/multiSlsDetector.h | 2 -- .../tests/test-SharedMemory.cpp | 18 ++++++++++-------- 2 files changed, 10 insertions(+), 10 deletions(-) diff --git a/slsDetectorSoftware/multiSlsDetector/multiSlsDetector.h b/slsDetectorSoftware/multiSlsDetector/multiSlsDetector.h index 21d6b0dd9..0894daa8a 100644 --- a/slsDetectorSoftware/multiSlsDetector/multiSlsDetector.h +++ b/slsDetectorSoftware/multiSlsDetector/multiSlsDetector.h @@ -1968,8 +1968,6 @@ class multiSlsDetector : public virtual slsDetectorDefs, /** Shared Memory object */ SharedMemory sharedMemory{0,-1}; - /** Shared memory structure */ - sharedMultiSlsDetector *thisMultiDetector {nullptr}; /** pointers to the slsDetector structures */ std::vector> detectors; diff --git a/slsDetectorSoftware/tests/test-SharedMemory.cpp b/slsDetectorSoftware/tests/test-SharedMemory.cpp index 8231070a9..28c943a81 100644 --- a/slsDetectorSoftware/tests/test-SharedMemory.cpp +++ b/slsDetectorSoftware/tests/test-SharedMemory.cpp @@ -25,14 +25,17 @@ TEST_CASE("Create SharedMemory read and write") { shm.UnmapSharedMemory(); shm.RemoveSharedMemory(); + + CHECK(shm.IsExisting() == false); } TEST_CASE("Open existing SharedMemory and read") { - - SharedMemory shm(0, -1); - shm.CreateSharedMemory(); - *shm() = 5.3; - shm.UnmapSharedMemory(); + + { + SharedMemory shm(0, -1); + shm.CreateSharedMemory(); + *shm() = 5.3; + } SharedMemory shm2(0, -1); shm2.OpenSharedMemory(); @@ -41,7 +44,7 @@ TEST_CASE("Open existing SharedMemory and read") { shm2.RemoveSharedMemory(); } -TEST_CASE("Two shared memories with the same name throws") { +TEST_CASE("Creating a second shared memory with the same name throws") { SharedMemory shm0(0, -1); SharedMemory shm1(0, -1); @@ -69,8 +72,7 @@ TEST_CASE("Open two shared memories to the same place") { shm2()->x = 7; CHECK(shm()->x == 7); - - //Remove only needs to be done once since they refer + //Remove only needs to be done once since they refer //to the same memory shm2.RemoveSharedMemory(); CHECK(shm.IsExisting() == false); From d4e4fb8ffefa73e9c9d7edabe7494acba5c3c259 Mon Sep 17 00:00:00 2001 From: Erik Frojdh Date: Tue, 12 Mar 2019 14:37:06 +0100 Subject: [PATCH 5/7] move constructor deleted copy constructor --- integrationTests/src/a.cpp | 32 +--- .../multiSlsDetector/multiSlsDetector.cpp | 4 +- .../sharedMemory/SharedMemory.cpp | 178 ------------------ .../sharedMemory/SharedMemory.h | 66 +++++-- .../slsDetector/slsDetector.cpp | 6 +- .../tests/test-SharedMemory.cpp | 50 ++++- 6 files changed, 104 insertions(+), 232 deletions(-) delete mode 100644 slsDetectorSoftware/sharedMemory/SharedMemory.cpp diff --git a/integrationTests/src/a.cpp b/integrationTests/src/a.cpp index 75f8f1957..18146edd7 100644 --- a/integrationTests/src/a.cpp +++ b/integrationTests/src/a.cpp @@ -10,42 +10,12 @@ #include "sls_detector_funcs.h" #include #include + #define VERBOSE int main() { - // const std::string hostname = "beb083"; - // auto d = slsDetector(hostname); - - // d.setOnline(1); - // std::cout << "type: " << d.getDetectorTypeAsString() << '\n'; - // std::cout << "hostname: " << d.getHostname() << '\n'; - // std::cout << "receiver: " << d.getReceiverOnline() << '\n'; - - // std::cout << "control: " << d.getControlPort() << '\n'; - // std::cout << "stop: " << d.getStopPort() << '\n'; - // std::cout << "receiver: " << d.getReceiverPort() << '\n'; - // std::cout << "exptime: " << d.setTimer(slsDetectorDefs::timerIndex::ACQUISITION_TIME) << '\n'; - // auto d2 = slsDetector(type, 0, 1); - // d2.setHostname("beb098");. - // auto d2 = slsDetector(); - // std::cout << "hn: " << d2.getHostname() << '\n'; - - // sls::Timer t; - // for (int i = 0; i != 100; ++i) { - // int fnum = 1; - // int ret = slsDetectorDefs::FAIL; - // slsDetectorDefs::detectorType retval = slsDetectorDefs::detectorType::GENERIC; - - // auto cs = sls::ClientSocket("beb083", 1952); - // cs.sendData(reinterpret_cast(&fnum), sizeof(fnum)); - // cs.receiveData(reinterpret_cast(&ret), sizeof(ret)); - // cs.receiveData(reinterpret_cast(&retval), sizeof(retval)); - // std::cout << "retval: " << retval << '\n'; - // } - // t.print_elapsed(); - return 0; } diff --git a/slsDetectorSoftware/multiSlsDetector/multiSlsDetector.cpp b/slsDetectorSoftware/multiSlsDetector/multiSlsDetector.cpp index e160c9700..a773ec868 100644 --- a/slsDetectorSoftware/multiSlsDetector/multiSlsDetector.cpp +++ b/slsDetectorSoftware/multiSlsDetector/multiSlsDetector.cpp @@ -245,7 +245,7 @@ void multiSlsDetector::freeSharedMemory(int multiId, int detPos) { } // multi - auto multiShm = SharedMemory(multiId, -1); + SharedMemory multiShm(multiId, -1); int numDetectors = 0; if (multiShm.IsExisting()) { @@ -255,7 +255,7 @@ void multiSlsDetector::freeSharedMemory(int multiId, int detPos) { } for (int i = 0; i < numDetectors; ++i) { - auto shm = SharedMemory(multiId, i); + SharedMemory shm(multiId, i); shm.RemoveSharedMemory(); } } diff --git a/slsDetectorSoftware/sharedMemory/SharedMemory.cpp b/slsDetectorSoftware/sharedMemory/SharedMemory.cpp deleted file mode 100644 index f752e5e36..000000000 --- a/slsDetectorSoftware/sharedMemory/SharedMemory.cpp +++ /dev/null @@ -1,178 +0,0 @@ -// #include "SharedMemory.h" -// #include "sls_detector_exceptions.h" -// #include "ansi.h" -// #include "logger.h" - -// #include "slsDetector.h" -// #include "multiSlsDetector.h" - -// #include -// #include // printf -// #include // errno -// #include // strerror -// #include -// #include // O_CREAT, O_TRUNC.. -// #include // fstat -// #include // shared memory -// #include -// #include "stdlib.h" - -// #define SHM_MULTI_PREFIX "/slsDetectorPackage_multi_" -// #define SHM_SLS_PREFIX "_sls_" -// #define SHM_ENV_NAME "SLSDETNAME" - -// template -// SharedMemory::SharedMemory(int multiId, int slsId): -// fd(-1), -// shmSize(0) -// { -// name = ConstructSharedMemoryName(multiId, slsId); -// } - - -// template -// SharedMemory::~SharedMemory(){ -// if (fd >= 0) -// close(fd); -// } - -// template -// bool SharedMemory::IsExisting() { -// bool ret = true; -// int tempfd = shm_open(name.c_str(), O_RDWR, 0); -// if ((tempfd < 0) && (errno == ENOENT)) { -// ret = false; -// } -// close(tempfd); -// return ret; -// } - -// template -// std::string SharedMemory::GetName() { -// return name; -// } - -// template -// void SharedMemory::CreateSharedMemory(size_t sz){ -// // create -// fd = shm_open(name.c_str(), O_CREAT | O_TRUNC | O_EXCL | O_RDWR, S_IRUSR | S_IWUSR); -// if (fd < 0) { -// FILE_LOG(logERROR) << "Create shared memory " << name << " failed: " << strerror(errno); -// throw SharedMemoryException(); -// } - -// // resize -// if (ftruncate(fd, sz) < 0) { -// FILE_LOG(logERROR) << "Create shared memory " << name << " failed at ftruncate: " << strerror(errno); -// close(fd); -// RemoveSharedMemory(); -// throw SharedMemoryException(); -// } - -// // map -// // void* addr = MapSharedMemory(sz); -// shared_struct = MapSharedMemory(sz); -// FILE_LOG(logINFO) << "Shared memory created " << name; - -// // return addr; -// } - -// template -// void SharedMemory::OpenSharedMemory(size_t sz){ -// // open -// fd = shm_open(name.c_str(), O_RDWR, 0); -// if (fd < 0) { -// FILE_LOG(logERROR) << "Open existing shared memory " << name << " failed: " << strerror(errno); -// throw SharedMemoryException(); -// } - -// shared_struct = MapSharedMemory(sz); -// // return MapSharedMemory(sz); -// } - -// template -// void SharedMemory::UnmapSharedMemory() { -// if (munmap(shared_struct, shmSize) < 0) { -// FILE_LOG(logERROR) << "Unmapping shared memory " << name << " failed: " << strerror(errno); -// close(fd); -// throw SharedMemoryException(); -// } -// } - -// template -// void SharedMemory::RemoveSharedMemory() { -// if (shm_unlink(name.c_str()) < 0) { -// // silent exit if shm did not exist anyway -// if (errno == ENOENT) -// return; -// FILE_LOG(logERROR) << "Free Shared Memory " << name << " Failed: " << strerror(errno); -// throw SharedMemoryException(); -// } -// FILE_LOG(logINFO) << "Shared memory deleted " << name; -// } - - -// template -// T* SharedMemory::MapSharedMemory(size_t sz) { -// void* addr = mmap(nullptr, sz, PROT_READ | PROT_WRITE, MAP_SHARED, fd, 0); -// if (addr == MAP_FAILED) { -// FILE_LOG(logERROR) << "Mapping shared memory " << name << " failed: " << strerror(errno); -// close(fd); -// throw SharedMemoryException(); -// } -// shmSize = sz; -// close(fd); -// return (T*)addr; -// } - -// template -// std::string SharedMemory::ConstructSharedMemoryName(int multiId, int slsId) { - -// // using environment path -// std::string sEnvPath = ""; -// char* envpath = getenv(SHM_ENV_NAME); -// if (envpath != nullptr) { -// sEnvPath.assign(envpath); -// sEnvPath.insert(0,"_"); -// } - -// std::stringstream ss; -// if (slsId < 0) -// ss << SHM_MULTI_PREFIX << multiId << sEnvPath; -// else -// ss << SHM_MULTI_PREFIX << multiId << SHM_SLS_PREFIX << slsId << sEnvPath; - -// std::string temp = ss.str(); -// if (temp.length() > NAME_MAX) { -// FILE_LOG(logERROR) << "Shared memory initialization failed. " << -// temp << " has " << temp.length() << " characters. \n" -// "Maximum is " << NAME_MAX << ". Change the environment variable " << SHM_ENV_NAME; -// throw SharedMemoryException(); -// } -// return temp; -// // } - -// template -// int SharedMemory::VerifySizeMatch(size_t expectedSize) { -// struct stat sb; -// // could not fstat -// if (fstat(fd, &sb) < 0) { -// FILE_LOG(logERROR) << "Could not verify existing shared memory " << name << " size match " -// "(could not fstat): " << strerror(errno); -// close(fd); -// throw SharedMemoryException(); -// } - -// //size does not match -// long unsigned int sz = (long unsigned int)sb.st_size; -// if (sz != expectedSize) { -// FILE_LOG(logERROR) << "Existing shared memory " << name << " size does not match"; -// FILE_LOG(logDEBUG1) << "Expected " << expectedSize << ", found " << sz; -// throw SharedMemoryException(); -// return 1; -// } -// return 0; -// } - -// template class SharedMemory; -// template class SharedMemory; \ No newline at end of file diff --git a/slsDetectorSoftware/sharedMemory/SharedMemory.h b/slsDetectorSoftware/sharedMemory/SharedMemory.h index a5c9d68f5..3cc1f4500 100644 --- a/slsDetectorSoftware/sharedMemory/SharedMemory.h +++ b/slsDetectorSoftware/sharedMemory/SharedMemory.h @@ -39,13 +39,48 @@ class SharedMemory { * @param multiId multi detector id * @param slsId sls detector id, -1 if a multi detector shared memory */ - SharedMemory(int multiId, int slsId){ + SharedMemory(int multiId, int slsId) { name = ConstructSharedMemoryName(multiId, slsId); } - /** - * Destructor - */ + /** + * Delete the copy constructor and copy assignment since we don't want two + * objects managing the same resource + */ + SharedMemory(const SharedMemory &) = delete; + SharedMemory &operator=(const SharedMemory &other) = delete; + + //Move constructor + SharedMemory(SharedMemory &&other) : name(other.name), + fd(other.fd), + shmSize(other.shmSize), + shared_struct(other.shared_struct) { + + other.fd = -1; + other.shared_struct = nullptr; + other.shmSize = 0; + } + + //Move assignment + SharedMemory &operator=(SharedMemory &&other) { + name = other.name; + if (fd) { + close(fd); + } + fd = other.fd; + other.fd = -1; + + if (shared_struct != nullptr) { + UnmapSharedMemory(); + } + shared_struct = other.shared_struct; + other.shared_struct = nullptr; + + shmSize = other.shmSize; + other.shmSize = 0; + return *this; + } + ~SharedMemory() { if (fd >= 0) close(fd); @@ -73,17 +108,20 @@ class SharedMemory { /** * Get shared memory name */ - std::string GetName() { + std::string GetName() const { return name; } + size_t size() const { + return shmSize; + } + /** * Create Shared memory and call MapSharedMemory to map it to an address * throws a SharedMemoryException exception on failure to create, ftruncate or map * @param sz of shared memory */ void CreateSharedMemory(size_t sz = 0) { - // create if (sz == 0) { sz = sizeof(T); } @@ -94,7 +132,6 @@ class SharedMemory { throw SharedMemoryException(); } - // resize if (ftruncate(fd, sz) < 0) { FILE_LOG(logERROR) << "Create shared memory " << name << " failed at ftruncate: " << strerror(errno); close(fd); @@ -102,12 +139,8 @@ class SharedMemory { throw SharedMemoryException(); } - // map - // void* addr = MapSharedMemory(sz); shared_struct = MapSharedMemory(sz); FILE_LOG(logINFO) << "Shared memory created " << name; - - // return addr; } /** @@ -116,7 +149,6 @@ class SharedMemory { * @param sz of shared memory */ void OpenSharedMemory(size_t sz = 0) { - // open if (sz == 0) { sz = sizeof(T); } @@ -128,7 +160,6 @@ class SharedMemory { } shared_struct = MapSharedMemory(sz); - // return MapSharedMemory(sz); } /** @@ -166,15 +197,16 @@ class SharedMemory { */ static const int NAME_MAX = 255; - /* - Using the call operator to access the pointer - + /** + *Using the call operator to access the pointer */ - T *operator()() { return shared_struct; } + /** + *Using the call operator to access the pointer, const overload + */ const T *operator()() const { return shared_struct; } diff --git a/slsDetectorSoftware/slsDetector/slsDetector.cpp b/slsDetectorSoftware/slsDetector/slsDetector.cpp index e3291fa52..179882e62 100644 --- a/slsDetectorSoftware/slsDetector/slsDetector.cpp +++ b/slsDetectorSoftware/slsDetector/slsDetector.cpp @@ -31,7 +31,7 @@ slsDetector::slsDetector(detectorType type, int multiId, int id, bool verify) * so sls shared memory will be created */ // ensure shared memory was not created before - auto shm = SharedMemory(multiId, id); + SharedMemory shm(multiId, id); if (shm.IsExisting()) { FILE_LOG(logWARNING) << "This shared memory should have been " "deleted before! " @@ -202,7 +202,7 @@ int64_t slsDetector::getId(idMode mode) { } void slsDetector::freeSharedMemory(int multiId, int slsId) { - auto shm = SharedMemory(multiId, slsId); + SharedMemory shm(multiId, slsId); shm.RemoveSharedMemory(); } @@ -640,7 +640,7 @@ int slsDetector::receiveModule(sls_detector_module *myMod) { } slsDetectorDefs::detectorType slsDetector::getDetectorTypeFromShm(int multiId, bool verify) { - auto shm = SharedMemory(multiId, detId); + SharedMemory shm(multiId, detId); if (!shm.IsExisting()) { FILE_LOG(logERROR) << "Shared memory " << shm.GetName() << " does not exist.\n" "Corrupted Multi Shared memory. Please free shared memory."; diff --git a/slsDetectorSoftware/tests/test-SharedMemory.cpp b/slsDetectorSoftware/tests/test-SharedMemory.cpp index 28c943a81..5746cebd9 100644 --- a/slsDetectorSoftware/tests/test-SharedMemory.cpp +++ b/slsDetectorSoftware/tests/test-SharedMemory.cpp @@ -3,6 +3,8 @@ #include "catch.hpp" #include "string_utils.h" +#include + struct Data { int x; double y; @@ -30,7 +32,7 @@ TEST_CASE("Create SharedMemory read and write") { } TEST_CASE("Open existing SharedMemory and read") { - + { SharedMemory shm(0, -1); shm.CreateSharedMemory(); @@ -77,4 +79,50 @@ TEST_CASE("Open two shared memories to the same place") { shm2.RemoveSharedMemory(); CHECK(shm.IsExisting() == false); CHECK(shm2.IsExisting() == false); +} + + +TEST_CASE("Move SharedMemory"){ + + SharedMemory shm(0,-1); + CHECK(shm.GetName() == "/slsDetectorPackage_multi_0"); + shm.CreateSharedMemory(); + shm()->x = 9; + + CHECK(shm.size()== sizeof(Data)); + + SharedMemory shm2(1,-1); + shm2 = std::move(shm); //shm is now a moved from object! + + CHECK(shm2()->x == 9); + CHECK(shm() == nullptr); + CHECK(shm.size() == 0); + + CHECK(shm2.GetName() == "/slsDetectorPackage_multi_0"); + shm2.RemoveSharedMemory(); + +} + + +TEST_CASE("Create several shared memories") { + constexpr int N = 5; + std::vector> v; + v.reserve(N); + for (int i = 0; i != N; ++i) { + v.emplace_back(i, -1); + CHECK(v[i].IsExisting() == false); + v[i].CreateSharedMemory(); + *v[i]() = i; + CHECK(*v[i]() == i); + } + + for (int i = 0; i != N; ++i) { + CHECK(*v[i]() == i); + CHECK(v[i].GetName() == std::string("/slsDetectorPackage_multi_")+std::to_string(i)); + } + + for (int i = 0; i != N; ++i) { + v[i].RemoveSharedMemory(); + CHECK(v[i].IsExisting() == false); + } } \ No newline at end of file From 7e793539ca80e5365b462e3d5d1cc297bf6c7d66 Mon Sep 17 00:00:00 2001 From: Erik Frojdh Date: Tue, 12 Mar 2019 14:42:27 +0100 Subject: [PATCH 6/7] removed typedef for shared struct --- .../multiSlsDetector/multiSlsDetector.h | 195 ++- slsDetectorSoftware/slsDetector/slsDetector.h | 1188 ++++++++--------- 2 files changed, 682 insertions(+), 701 deletions(-) diff --git a/slsDetectorSoftware/multiSlsDetector/multiSlsDetector.h b/slsDetectorSoftware/multiSlsDetector/multiSlsDetector.h index 0894daa8a..14e2b1d6f 100644 --- a/slsDetectorSoftware/multiSlsDetector/multiSlsDetector.h +++ b/slsDetectorSoftware/multiSlsDetector/multiSlsDetector.h @@ -7,10 +7,10 @@ * @short This is the base class for multi detector system functionalities * @author Anna Bergamaschi */ +#include "SharedMemory.h" #include "error_defs.h" #include "logger.h" #include "sls_detector_defs.h" -#include "SharedMemory.h" class slsDetector; // class SharedMemory; class ZmqSocket; @@ -27,94 +27,91 @@ class detectorData; #define SHORT_STRING_LENGTH 50 #define DATE_LENGTH 30 - - /** +/** * @short structure allocated in shared memory to store detector settings * for IPC and cache */ - typedef struct sharedMultiSlsDetector { +struct sharedMultiSlsDetector { - /* FIXED PATTERN FOR STATIC FUNCTIONS. DO NOT CHANGE, ONLY APPEND + /* FIXED PATTERN FOR STATIC FUNCTIONS. DO NOT CHANGE, ONLY APPEND * ------*/ - /** shared memory version */ - int shmversion; + /** shared memory version */ + int shmversion; - /** last process id accessing the shared memory */ - pid_t lastPID; + /** last process id accessing the shared memory */ + pid_t lastPID; - /** last user name accessing the shared memory */ - char lastUser[SHORT_STRING_LENGTH]; + /** last user name accessing the shared memory */ + char lastUser[SHORT_STRING_LENGTH]; - /** last time stamp when accessing the shared memory */ - char lastDate[SHORT_STRING_LENGTH]; + /** last time stamp when accessing the shared memory */ + char lastDate[SHORT_STRING_LENGTH]; - /** number of sls detectors in shared memory */ - int numberOfDetectors; + /** number of sls detectors in shared memory */ + int numberOfDetectors; - /** END OF FIXED PATTERN + /** END OF FIXED PATTERN * -----------------------------------------------*/ - /** Number of detectors operated at once */ - int numberOfDetector[2]; + /** Number of detectors operated at once */ + int numberOfDetector[2]; - /** online flag - is set if the detector is connected, unset if socket + /** online flag - is set if the detector is connected, unset if socket * connection is not possible */ - int onlineFlag; + int onlineFlag; - /** stopped flag - is set if an acquisition error occurs or the detector + /** stopped flag - is set if an acquisition error occurs or the detector * is stopped manually. Is reset to 0 at the start of the acquisition */ - int stoppedFlag; + int stoppedFlag; - /** size of the data that are transfered from all detectors */ - int dataBytes; + /** size of the data that are transfered from all detectors */ + int dataBytes; - /** data bytes including gap pixels transferred from all detectors */ - int dataBytesInclGapPixels; + /** data bytes including gap pixels transferred from all detectors */ + int dataBytesInclGapPixels; - /** total number of channels for all detectors */ - int numberOfChannels; + /** total number of channels for all detectors */ + int numberOfChannels; - /** total number of channels for all detectors in one dimension*/ - int numberOfChannel[2]; + /** total number of channels for all detectors in one dimension*/ + int numberOfChannel[2]; - /** total number of channels including gap pixels in one dimension */ - int numberOfChannelInclGapPixels[2]; + /** total number of channels including gap pixels in one dimension */ + int numberOfChannelInclGapPixels[2]; - /** total number of channels for all detectors */ - int maxNumberOfChannels; + /** total number of channels for all detectors */ + int maxNumberOfChannels; - /** max number of channels for all detectors in one dimension*/ - int maxNumberOfChannel[2]; + /** max number of channels for all detectors in one dimension*/ + int maxNumberOfChannel[2]; - /** max number of channels including gap pixels for all detectors in + /** max number of channels including gap pixels for all detectors in * one dimension*/ - int maxNumberOfChannelInclGapPixels[2]; + int maxNumberOfChannelInclGapPixels[2]; - /** max number of channels allowed for the complete set of detectors in + /** max number of channels allowed for the complete set of detectors in * one dimension */ - int maxNumberOfChannelsPerDetector[2]; + int maxNumberOfChannelsPerDetector[2]; - /** timer values */ - int64_t timerValue[slsDetectorDefs::timerIndex::MAX_TIMERS]; + /** timer values */ + int64_t timerValue[slsDetectorDefs::timerIndex::MAX_TIMERS]; - /** flag for acquiring */ - bool acquiringFlag; + /** flag for acquiring */ + bool acquiringFlag; - /** receiver online flag - is set if the receiver is connected, + /** receiver online flag - is set if the receiver is connected, * unset if socket connection is not possible */ - int receiverOnlineFlag; + int receiverOnlineFlag; - /** data streaming (up stream) enable in receiver */ - bool receiver_upstream; - - } sharedMultiSlsDetector; + /** data streaming (up stream) enable in receiver */ + bool receiver_upstream; +}; class multiSlsDetector : public virtual slsDetectorDefs, public virtual errorDefs { - // private: - + // private: public: /** @@ -234,7 +231,7 @@ class multiSlsDetector : public virtual slsDetectorDefs, * @returns FAIL for incompatibility, OK for compatibility */ int checkReceiverVersionCompatibility(int detPos = -1); - + /** * Get ID or version numbers * @param mode version type @@ -436,15 +433,13 @@ class multiSlsDetector : public virtual slsDetectorDefs, */ int setStopPort(int port_number = -1, int detPos = -1); - /** + /** * Set/Gets TCP Port of the receiver * @param port_number (-1 gets) * @param detPos -1 for all detectors in list or specific detector position * @returns port number */ int setReceiverPort(int port_number = -1, int detPos = -1); - - /** * Lock server for this client IP @@ -474,7 +469,7 @@ class multiSlsDetector : public virtual slsDetectorDefs, * @param detPos -1 for all detectors in list or specific detector position * @returns OK or FAIL */ - int execCommand(const std::string& cmd, int detPos); + int execCommand(const std::string &cmd, int detPos); /** * Load configuration from a configuration File @@ -545,7 +540,7 @@ class multiSlsDetector : public virtual slsDetectorDefs, * @param detPos -1 for all detectors in list or specific detector position * @returns the trimbit/settings directory */ - std::string setSettingsDir(const std::string& directory, int detPos = -1); + std::string setSettingsDir(const std::string &directory, int detPos = -1); /** * Loads the modules settings/trimbits reading from a specific file @@ -554,7 +549,7 @@ class multiSlsDetector : public virtual slsDetectorDefs, * @param detPos -1 for all detectors in list or specific detector position * returns OK or FAIL */ - int loadSettingsFile(const std::string& fname, int detPos = -1); + int loadSettingsFile(const std::string &fname, int detPos = -1); /** * Saves the modules settings/trimbits to a specific file @@ -563,7 +558,7 @@ class multiSlsDetector : public virtual slsDetectorDefs, * @param detPos -1 for all detectors in list or specific detector position * returns OK or FAIL */ - int saveSettingsFile(const std::string& fname, int detPos = -1); + int saveSettingsFile(const std::string &fname, int detPos = -1); /** * Get Detector run status @@ -872,7 +867,7 @@ class multiSlsDetector : public virtual slsDetectorDefs, * @param detPos -1 for all detectors in list or specific detector position * @returns the detector MAC address */ - std::string setDetectorMAC(const std::string& detectorMAC, int detPos = -1); + std::string setDetectorMAC(const std::string &detectorMAC, int detPos = -1); /** * Returns the detector MAC address @@ -887,7 +882,7 @@ class multiSlsDetector : public virtual slsDetectorDefs, * @param detPos -1 for all detectors in list or specific detector position * @returns the detector IP address */ - std::string setDetectorIP(const std::string& detectorIP, int detPos = -1); + std::string setDetectorIP(const std::string &detectorIP, int detPos = -1); /** * Returns the detector IP address @@ -904,7 +899,7 @@ class multiSlsDetector : public virtual slsDetectorDefs, * @param detPos -1 for all detectors in list or specific detector position * @returns the receiver IP address from shared memory */ - std::string setReceiver(const std::string& receiver, int detPos = -1); + std::string setReceiver(const std::string &receiver, int detPos = -1); /** * Returns the receiver IP address @@ -919,7 +914,7 @@ class multiSlsDetector : public virtual slsDetectorDefs, * @param detPos -1 for all detectors in list or specific detector position * @returns the receiver UDP IP address */ - std::string setReceiverUDPIP(const std::string& udpip, int detPos = -1); + std::string setReceiverUDPIP(const std::string &udpip, int detPos = -1); /** * Returns the receiver UDP IP address @@ -934,7 +929,7 @@ class multiSlsDetector : public virtual slsDetectorDefs, * @param detPos -1 for all detectors in list or specific detector position * @returns the receiver UDP MAC address */ - std::string setReceiverUDPMAC(const std::string& udpmac, int detPos = -1); + std::string setReceiverUDPMAC(const std::string &udpmac, int detPos = -1); /** * Returns the receiver UDP MAC address @@ -951,7 +946,6 @@ class multiSlsDetector : public virtual slsDetectorDefs, */ int setReceiverUDPPort(int udpport, int detPos = -1); - /** * Returns the receiver UDP port * @param detPos -1 for all detectors in list or specific detector position @@ -984,13 +978,13 @@ class multiSlsDetector : public virtual slsDetectorDefs, */ void setClientDataStreamingInPort(int i = -1, int detPos = -1); - /** + /** * Returns the client zmq port * If detPos is -1(multi module), port returns client streaming port of first module * @param detPos -1 for all detectors in list or specific detector position * @returns the client zmq port */ - int getClientStreamingPort(int detPos = -1); + int getClientStreamingPort(int detPos = -1); /** * (advanced users) @@ -1002,13 +996,13 @@ class multiSlsDetector : public virtual slsDetectorDefs, */ void setReceiverDataStreamingOutPort(int i = -1, int detPos = -1); - /** + /** * Returns the receiver zmq port * If detPos is -1(multi module), port returns receiver streaming port of first module * @param detPos -1 for all detectors in list or specific detector position * @returns the receiver zmq port */ - int getReceiverStreamingPort(int detPos = -1); + int getReceiverStreamingPort(int detPos = -1); /** * (advanced users) @@ -1017,8 +1011,8 @@ class multiSlsDetector : public virtual slsDetectorDefs, * By default, it is the IP of receiver hostname * @param detPos -1 for all detectors in list or specific detector position */ - void setClientDataStreamingInIP(const std::string& ip = "", - int detPos = -1); + void setClientDataStreamingInIP(const std::string &ip = "", + int detPos = -1); /** * Returns the client zmq ip @@ -1026,7 +1020,7 @@ class multiSlsDetector : public virtual slsDetectorDefs, * @param detPos -1 for all detectors in list or specific detector position * @returns the client zmq ip */ - std::string getClientStreamingIP(int detPos = -1); + std::string getClientStreamingIP(int detPos = -1); /** * (advanced users) @@ -1035,8 +1029,8 @@ class multiSlsDetector : public virtual slsDetectorDefs, * By default, it is the IP of receiver hostname * @param detPos -1 for all detectors in list or specific detector position */ - void setReceiverDataStreamingOutIP(const std::string& ip = "", - int detPos = -1); + void setReceiverDataStreamingOutIP(const std::string &ip = "", + int detPos = -1); /** * Returns the receiver zmq ip @@ -1044,7 +1038,7 @@ class multiSlsDetector : public virtual slsDetectorDefs, * @param detPos -1 for all detectors in list or specific detector position * @returns the receiver zmq ip */ - std::string getReceiverStreamingIP(int detPos = -1); + std::string getReceiverStreamingIP(int detPos = -1); /** * Sets the transmission delay for left, right or entire frame @@ -1062,7 +1056,7 @@ class multiSlsDetector : public virtual slsDetectorDefs, * @param detPos -1 for all detectors in list or specific detector position * @returns additional json header, default is empty */ - std::string setAdditionalJsonHeader(const std::string& jsonheader, int detPos = -1); + std::string setAdditionalJsonHeader(const std::string &jsonheader, int detPos = -1); /** * Returns the additional json header @@ -1079,7 +1073,7 @@ class multiSlsDetector : public virtual slsDetectorDefs, * @returns the additional json header parameter value, * empty if no parameter found in additional json header */ - std::string setAdditionalJsonParameter(const std::string& key, const std::string& value, int detPos = -1); + std::string setAdditionalJsonParameter(const std::string &key, const std::string &value, int detPos = -1); /** * Returns the additional json header parameter value @@ -1088,7 +1082,7 @@ class multiSlsDetector : public virtual slsDetectorDefs, * @returns the additional json header parameter value, * empty if no parameter found in additional json header */ - std::string getAdditionalJsonParameter(const std::string& key, int detPos = -1); + std::string getAdditionalJsonParameter(const std::string &key, int detPos = -1); /** * Sets the detector minimum/maximum energy threshold in processor (for Moench only) @@ -1120,14 +1114,14 @@ class multiSlsDetector : public virtual slsDetectorDefs, * @param detPos -1 for all detectors in list or specific detector position * @returns receiver udp socket buffer size */ - uint64_t setReceiverUDPSocketBufferSize(uint64_t udpsockbufsize=-1, int detPos = -1); + uint64_t setReceiverUDPSocketBufferSize(uint64_t udpsockbufsize = -1, int detPos = -1); /** * Returns the receiver UDP socket buffer size * @param detPos -1 for all detectors in list or specific detector position * @returns the receiver UDP socket buffer size */ - uint64_t getReceiverUDPSocketBufferSize(int detPos = -1) ; + uint64_t getReceiverUDPSocketBufferSize(int detPos = -1); /** * Returns the receiver real UDP socket buffer size @@ -1363,7 +1357,7 @@ class multiSlsDetector : public virtual slsDetectorDefs, * @param detPos -1 for all detectors in list or specific detector position * @returns OK or FAIL */ - int programFPGA(const std::string& fname, int detPos = -1); + int programFPGA(const std::string &fname, int detPos = -1); /** * Resets FPGA (Jungfrau) @@ -1464,7 +1458,7 @@ class multiSlsDetector : public virtual slsDetectorDefs, * @param detPos -1 for all detectors in list or specific detector position * @returns OK or FAIL */ - int execReceiverCommand(const std::string& cmd, int detPos = -1); + int execReceiverCommand(const std::string &cmd, int detPos = -1); /** * Returns output file directory @@ -1479,7 +1473,7 @@ class multiSlsDetector : public virtual slsDetectorDefs, * @param s file directory * @returns file dir */ - std::string setFilePath(const std::string& path, int detPos = -1); + std::string setFilePath(const std::string &path, int detPos = -1); /** * Returns file name prefix @@ -1494,7 +1488,7 @@ class multiSlsDetector : public virtual slsDetectorDefs, * @param s file name prefix * @returns file name prefix */ - std::string setFileName(const std::string& fname, int detPos = -1); + std::string setFileName(const std::string &fname, int detPos = -1); /** * Sets the max frames per file in receiver @@ -1696,7 +1690,7 @@ class multiSlsDetector : public virtual slsDetectorDefs, * @param detPos -1 for all detectors in list or specific detector position * @returns OK/FAIL */ - int setPattern(const std::string& fname, int detPos = -1); + int setPattern(const std::string &fname, int detPos = -1); /** * Writes a pattern word to the CTB @@ -1718,7 +1712,7 @@ class multiSlsDetector : public virtual slsDetectorDefs, * @returns OK/FAIL */ int setPatternLoops(int level, int &start, int &stop, int &n, - int detPos = -1); + int detPos = -1); /** * Sets the wait address in the CTB @@ -1900,7 +1894,7 @@ class multiSlsDetector : public virtual slsDetectorDefs, * Add sls detector * @param s hostname of the single detector */ - void addSlsDetector(const std::string& hostname); + void addSlsDetector(const std::string &hostname); /** * add gap pixels to the image (only for Eiger in 4 bit mode) @@ -1966,14 +1960,13 @@ class multiSlsDetector : public virtual slsDetectorDefs, int detId; /** Shared Memory object */ - SharedMemory sharedMemory{0,-1}; - + SharedMemory sharedMemory{0, -1}; /** pointers to the slsDetector structures */ std::vector> detectors; /** data streaming (down stream) enabled in client (zmq sckets created) */ - bool client_downstream {false}; + bool client_downstream{false}; /** ZMQ Socket - Receiver to Client */ std::vector> zmqSocket; @@ -1987,10 +1980,10 @@ class multiSlsDetector : public virtual slsDetectorDefs, sem_t sem_endRTAcquisition; /** Total number of frames/images for next acquisition */ - int totalProgress {0}; + int totalProgress{0}; /** Current progress or frames/images processed in current acquisition */ - int progressIndex {0}; + int progressIndex{0}; /** mutex to synchronize main and data processing threads */ mutable std::mutex mp; @@ -1999,26 +1992,26 @@ class multiSlsDetector : public virtual slsDetectorDefs, mutable std::mutex mg; /** sets when the acquisition is finished */ - bool jointhread {false}; + bool jointhread{false}; /** the data processing thread */ // pthread_t dataProcessingThread; std::thread dataProcessingThread; /** detector data packed for the gui */ - detectorData *thisData {nullptr}; + detectorData *thisData{nullptr}; - int (*acquisition_finished)(double, int, void *) {nullptr}; - void *acqFinished_p {nullptr}; + int (*acquisition_finished)(double, int, void *){nullptr}; + void *acqFinished_p{nullptr}; - int (*measurement_finished)(int, int, void *) {nullptr}; - void *measFinished_p {nullptr}; + int (*measurement_finished)(int, int, void *){nullptr}; + void *measFinished_p{nullptr}; int (*progress_call)(double, void *); - void *pProgressCallArg {nullptr}; + void *pProgressCallArg{nullptr}; int (*dataReady)(detectorData *, int, int, void *){nullptr}; - void *pCallbackArg {nullptr}; + void *pCallbackArg{nullptr}; }; #endif diff --git a/slsDetectorSoftware/slsDetector/slsDetector.h b/slsDetectorSoftware/slsDetector/slsDetector.h index dabc95bd7..346db690c 100644 --- a/slsDetectorSoftware/slsDetector/slsDetector.h +++ b/slsDetectorSoftware/slsDetector/slsDetector.h @@ -9,11 +9,11 @@ * @author Anna Bergamaschi */ -#include "sls_detector_defs.h" -#include "error_defs.h" -#include "logger.h" #include "ClientSocket.h" #include "SharedMemory.h" +#include "error_defs.h" +#include "logger.h" +#include "sls_detector_defs.h" class ClientInterface; #include @@ -23,295 +23,289 @@ class multiSlsDetector; class ServerInterface; class MySocketTCP; -#define SLS_SHMVERSION 0x181005 +#define SLS_SHMVERSION 0x181005 #define NCHIPSMAX 10 #define NCHANSMAX 65536 #define NDACSMAX 16 /** * parameter list that has to be initialized depending on the detector type */ -typedef struct detParameterList { - int nChanX; - int nChanY; - int nChipX; - int nChipY; - int nDacs; - int dynamicRange; - int nGappixelsX; - int nGappixelsY; +typedef struct detParameterList { + int nChanX; + int nChanY; + int nChipX; + int nChipY; + int nDacs; + int dynamicRange; + int nGappixelsX; + int nGappixelsY; } detParameterList; - - /** +/** * @short structure allocated in shared memory to store detector settings for IPC and cache */ - typedef struct sharedSlsDetector { +struct sharedSlsDetector { - /* FIXED PATTERN FOR STATIC FUNCTIONS. DO NOT CHANGE, ONLY APPEND ------*/ + /* FIXED PATTERN FOR STATIC FUNCTIONS. DO NOT CHANGE, ONLY APPEND ------*/ - /** shared memory version */ - int shmversion; + /** shared memory version */ + int shmversion; - /** online flag - is set if the detector is connected, unset if socket + /** online flag - is set if the detector is connected, unset if socket * connection is not possible */ - int onlineFlag; + int onlineFlag; - /** stopped flag - is set if an acquisition error occurs or the detector + /** stopped flag - is set if an acquisition error occurs or the detector * is stopped manually. Is reset to 0 at the start of the acquisition */ - int stoppedFlag; + int stoppedFlag; - /** is the hostname (or IP address) of the detector. needs to be set + /** is the hostname (or IP address) of the detector. needs to be set * before starting the communication */ - char hostname[MAX_STR_LENGTH]; + char hostname[MAX_STR_LENGTH]; - /** detector type \ see :: detectorType*/ - slsDetectorDefs::detectorType myDetectorType; + /** detector type \ see :: detectorType*/ + slsDetectorDefs::detectorType myDetectorType; - /** END OF FIXED PATTERN -----------------------------------------------*/ + /** END OF FIXED PATTERN -----------------------------------------------*/ + /** Detector offset in the X & Y direction in the multi detector structure */ + int offset[2]; + /** Number of detectors in multi list in x dir and y dir */ + int multiSize[2]; + /** is the port used for control functions */ + int controlPort; - /** Detector offset in the X & Y direction in the multi detector structure */ - int offset[2]; + /** is the port used to stop the acquisition */ + int stopPort; - /** Number of detectors in multi list in x dir and y dir */ - int multiSize[2]; + /** path of the trimbits/settings files */ + char settingsDir[MAX_STR_LENGTH]; - /** is the port used for control functions */ - int controlPort; + /** number of energies at which the detector has been trimmed */ + int nTrimEn; - /** is the port used to stop the acquisition */ - int stopPort; + /** list of the energies at which the detector has been trimmed */ + int trimEnergies[MAX_TRIMEN]; - /** path of the trimbits/settings files */ - char settingsDir[MAX_STR_LENGTH]; + /** number of channels per chip */ + int nChans; - /** number of energies at which the detector has been trimmed */ - int nTrimEn; + /** number of channels per chip in one direction */ + int nChan[2]; - /** list of the energies at which the detector has been trimmed */ - int trimEnergies[MAX_TRIMEN]; + /** number of chips per module*/ + int nChips; - /** number of channels per chip */ - int nChans; + /** number of chips per module in one direction */ + int nChip[2]; - /** number of channels per chip in one direction */ - int nChan[2]; + /** number of dacs per module*/ + int nDacs; - /** number of chips per module*/ - int nChips; + /** dynamic range of the detector data */ + int dynamicRange; - /** number of chips per module in one direction */ - int nChip[2]; + /** size of the data that are transfered from the detector */ + int dataBytes; - /** number of dacs per module*/ - int nDacs; - - /** dynamic range of the detector data */ - int dynamicRange; - - /** size of the data that are transfered from the detector */ - int dataBytes; - - /** threaded processing flag + /** threaded processing flag * (i.e. if data are processed in a separate thread) */ - // int threadedProcessing; + // int threadedProcessing; - /** number of rois defined */ - int nROI; + /** number of rois defined */ + int nROI; - /** list of rois */ - slsDetectorDefs::ROI roiLimits[MAX_ROIS]; + /** list of rois */ + slsDetectorDefs::ROI roiLimits[MAX_ROIS]; - /** readout flags */ - slsDetectorDefs::readOutFlags roFlags; + /** readout flags */ + slsDetectorDefs::readOutFlags roFlags; - /** name root of the output files */ - char settingsFile[MAX_STR_LENGTH]; + /** name root of the output files */ + char settingsFile[MAX_STR_LENGTH]; - /** detector settings (standard, fast, etc.) */ - slsDetectorDefs::detectorSettings currentSettings; + /** detector settings (standard, fast, etc.) */ + slsDetectorDefs::detectorSettings currentSettings; - /** detector threshold (eV) */ - int currentThresholdEV; + /** detector threshold (eV) */ + int currentThresholdEV; - /** timer values */ - int64_t timerValue[slsDetectorDefs::timerIndex::MAX_TIMERS]; + /** timer values */ + int64_t timerValue[slsDetectorDefs::timerIndex::MAX_TIMERS]; - /** memory offsets for the module structures */ - int modoff; + /** memory offsets for the module structures */ + int modoff; - /** memory offsets for the dac arrays */ - int dacoff; + /** memory offsets for the dac arrays */ + int dacoff; - /** memory offsets for the channel register arrays -trimbits*/ - int chanoff; + /** memory offsets for the channel register arrays -trimbits*/ + int chanoff; - /** ip address/hostname of the receiver for client control via TCP */ - char receiver_hostname[MAX_STR_LENGTH]; + /** ip address/hostname of the receiver for client control via TCP */ + char receiver_hostname[MAX_STR_LENGTH]; - /** is the TCP port used to communicate between client and the receiver */ - int receiverTCPPort; + /** is the TCP port used to communicate between client and the receiver */ + int receiverTCPPort; - /** is the UDP port used to send data from detector to receiver */ - int receiverUDPPort; + /** is the UDP port used to send data from detector to receiver */ + int receiverUDPPort; - /** is the port used to communicate between second half module of + /** is the port used to communicate between second half module of * Eiger detector and the receiver*/ - int receiverUDPPort2; + int receiverUDPPort2; - /** ip address of the receiver for the detector to send packets to**/ - char receiverUDPIP[MAX_STR_LENGTH]; + /** ip address of the receiver for the detector to send packets to**/ + char receiverUDPIP[MAX_STR_LENGTH]; - /** mac address of receiver for the detector to send packets to **/ - char receiverUDPMAC[MAX_STR_LENGTH]; + /** mac address of receiver for the detector to send packets to **/ + char receiverUDPMAC[MAX_STR_LENGTH]; - /** mac address of the detector **/ - char detectorMAC[MAX_STR_LENGTH]; + /** mac address of the detector **/ + char detectorMAC[MAX_STR_LENGTH]; - /** ip address of the detector **/ - char detectorIP[MAX_STR_LENGTH]; + /** ip address of the detector **/ + char detectorIP[MAX_STR_LENGTH]; - /** online flag - is set if the receiver is connected, + /** online flag - is set if the receiver is connected, * unset if socket connection is not possible */ - int receiverOnlineFlag; + int receiverOnlineFlag; - /** 10 Gbe enable*/ - int tenGigaEnable; + /** 10 Gbe enable*/ + int tenGigaEnable; - /** flipped data across x or y axis */ - int flippedData[2]; + /** flipped data across x or y axis */ + int flippedData[2]; - /** tcp port from gui/different process to receiver (only data) */ - int zmqport; + /** tcp port from gui/different process to receiver (only data) */ + int zmqport; - /** tcp port from receiver to gui/different process (only data) */ - int receiver_zmqport; + /** tcp port from receiver to gui/different process (only data) */ + int receiver_zmqport; - /** data streaming (up stream) enable in receiver */ - bool receiver_upstream; + /** data streaming (up stream) enable in receiver */ + bool receiver_upstream; - /* Receiver read frequency */ - int receiver_read_freq; + /* Receiver read frequency */ + int receiver_read_freq; - /** zmq tcp src ip address in client (only data) **/ - char zmqip[MAX_STR_LENGTH]; + /** zmq tcp src ip address in client (only data) **/ + char zmqip[MAX_STR_LENGTH]; - /** zmq tcp src ip address in receiver (only data) **/ - char receiver_zmqip[MAX_STR_LENGTH]; + /** zmq tcp src ip address in receiver (only data) **/ + char receiver_zmqip[MAX_STR_LENGTH]; - /** gap pixels enable */ - int gappixels; + /** gap pixels enable */ + int gappixels; - /** gap pixels in each direction */ - int nGappixels[2]; + /** gap pixels in each direction */ + int nGappixels[2]; - /** data bytes including gap pixels */ - int dataBytesInclGapPixels; + /** data bytes including gap pixels */ + int dataBytesInclGapPixels; - /** additional json header */ - char receiver_additionalJsonHeader[MAX_STR_LENGTH]; + /** additional json header */ + char receiver_additionalJsonHeader[MAX_STR_LENGTH]; - /** detector control server software API version */ - int64_t detectorControlAPIVersion; + /** detector control server software API version */ + int64_t detectorControlAPIVersion; - /** detector stop server software API version */ - int64_t detectorStopAPIVersion; + /** detector stop server software API version */ + int64_t detectorStopAPIVersion; - /** receiver server software API version */ - int64_t receiverAPIVersion; + /** receiver server software API version */ + int64_t receiverAPIVersion; - /** receiver frames discard policy */ - slsDetectorDefs::frameDiscardPolicy receiver_frameDiscardMode; + /** receiver frames discard policy */ + slsDetectorDefs::frameDiscardPolicy receiver_frameDiscardMode; - /** receiver partial frames padding enable */ - bool receiver_framePadding; + /** receiver partial frames padding enable */ + bool receiver_framePadding; - /** activated receiver */ - bool activated; + /** activated receiver */ + bool activated; - /** padding enable in deactivated receiver */ - bool receiver_deactivatedPaddingEnable; + /** padding enable in deactivated receiver */ + bool receiver_deactivatedPaddingEnable; - /** silent receiver */ - bool receiver_silentMode; + /** silent receiver */ + bool receiver_silentMode; - /** path of the output files */ - char receiver_filePath[MAX_STR_LENGTH]; + /** path of the output files */ + char receiver_filePath[MAX_STR_LENGTH]; - /** file name prefix */ - char receiver_fileName[MAX_STR_LENGTH]; + /** file name prefix */ + char receiver_fileName[MAX_STR_LENGTH]; - /** file index */ - int receiver_fileIndex; + /** file index */ + int receiver_fileIndex; - /** file format */ - slsDetectorDefs::fileFormat receiver_fileFormatType; + /** file format */ + slsDetectorDefs::fileFormat receiver_fileFormatType; - /** frames per file */ - int receiver_framesPerFile; + /** frames per file */ + int receiver_framesPerFile; - /** filewriteenable */ - bool receiver_fileWriteEnable; + /** filewriteenable */ + bool receiver_fileWriteEnable; - /** overwriteenable */ - bool receiver_overWriteEnable; - - } sharedSlsDetector; + /** overwriteenable */ + bool receiver_overWriteEnable; +}; class slsDetector : public virtual slsDetectorDefs, public virtual errorDefs { -public: - - /** + public: + /** * Constructor called when creating new shared memory * @param type detector type * @param multiId multi detector shared memory id * @param id sls detector id (position in detectors list) * @param verify true to verify if shared memory version matches existing one */ - explicit slsDetector(detectorType type, - int multiId = 0, - int id = 0, - bool verify = true); + explicit slsDetector(detectorType type, + int multiId = 0, + int id = 0, + bool verify = true); - /** + /** * Constructor called when opening existing shared memory * @param multiId multi detector shared memory id * @param id sls detector id (position in detectors list) * @param verify true to verify if shared memory version matches existing one */ - explicit slsDetector(int multiId = 0, - int id = 0, - bool verify = true); + explicit slsDetector(int multiId = 0, + int id = 0, + bool verify = true); - /** + /** * Destructor */ - virtual ~slsDetector(); + virtual ~slsDetector(); - /** + /** * Check version compatibility with receiver software * (if hostname/rx_hostname has been set/ sockets created) * @param p port type control port or receiver port * @returns FAIL for incompatibility, OK for compatibility */ - int checkReceiverVersionCompatibility(); + int checkReceiverVersionCompatibility(); - /** + /** * Check version compatibility with detector software * @returns FAIL for incompatibility, OK for compatibility */ - int checkDetectorVersionCompatibility(); + int checkDetectorVersionCompatibility(); - /** + /** * Get ID or version numbers * @param mode version type * @returns Id or version number of that type */ - int64_t getId(idMode mode); + int64_t getId(idMode mode); - /** + /** * Free shared memory without creating objects * If this is called, must take care to update * multiSlsDetectors thisMultiDetector->numberofDetectors @@ -319,134 +313,134 @@ public: * @param multiId multi detector Id * @param slsId slsDetectorId or position of slsDetector in detectors list */ - static void freeSharedMemory(int multiId, int slsId); + static void freeSharedMemory(int multiId, int slsId); - /** + /** * Free shared memory and delete shared memory structure * occupied by the sharedSlsDetector structure * Is only safe to call if one deletes the slsDetector object afterward * and frees multi shared memory/updates thisMultiDetector->numberOfDetectors */ - void freeSharedMemory(); + void freeSharedMemory(); - /** + /** * Sets the hostname, if online flag is set connects to update the detector * @param name hostname */ - void setHostname(const std::string& hostname); + void setHostname(const std::string &hostname); - /** + /** * Gets the hostname of detector * @returns hostname */ - std::string getHostname(); + std::string getHostname(); - /** + /** * Could not connect to receiver, log error */ void connectDataError(); - /** + /** * Get detector type by connecting to the detector * @returns detector tpe or GENERIC if failed */ - static detectorType getTypeFromDetector(const std::string& hostname, int cport=DEFAULT_PORTNO); + static detectorType getTypeFromDetector(const std::string &hostname, int cport = DEFAULT_PORTNO); - /** + /** * Get Detector type from shared memory variable * @returns detector type from shared memory variable */ - detectorType getDetectorTypeAsEnum(); + detectorType getDetectorTypeAsEnum(); - /** + /** * Gets string version of detector type from shared memory variable * @returns string version of detector type from shared memory variable */ - std::string getDetectorTypeAsString(); + std::string getDetectorTypeAsString(); - /** + /** * Gets detector type from detector and set it in receiver * @param type the detector type * @returns detector type in receiver */ - int setDetectorType(detectorType type=GET_DETECTOR_TYPE); + int setDetectorType(detectorType type = GET_DETECTOR_TYPE); - /** + /** * Returns the total number of channels from shared memory * @returns the total number of channels */ - int getTotalNumberOfChannels(); + int getTotalNumberOfChannels(); - /** + /** * Update total number of channels (chiptestboard or moench) * depending on the number of samples, roi, readout flags(ctb) */ - void updateTotalNumberOfChannels(); + void updateTotalNumberOfChannels(); - /** + /** * Returns the total number of channels in dimension d from shared memory * @param d dimension d * @returns the total number of channels in dimension d */ - int getTotalNumberOfChannels(dimension d); + int getTotalNumberOfChannels(dimension d); - /** + /** * Returns the total number of channels of in dimension d including gap pixels * from shared memory * @param d dimension d * @returns the total number of channels including gap pixels in dimension d * including gap pixels */ - int getTotalNumberOfChannelsInclGapPixels(dimension d); + int getTotalNumberOfChannelsInclGapPixels(dimension d); - /** + /** * returns the number of channels per chip from shared memory (Mythen) * @returns number of channels per chip */ - int getNChans(); + int getNChans(); - /** + /** * returns the number of channels per chip in dimension d from shared memory (Mythen) * @param d dimension d * @returns number of channels per chip in dimension d */ - int getNChans(dimension d); + int getNChans(dimension d); - /** + /** * returns the number of chips per module from shared memory (Mythen) * @returns number of chips per module */ - int getNChips(); + int getNChips(); - /** + /** * returns the number of chips per module in dimension d from shared memory (Mythen) * @param d dimension d * @returns number of chips per module in dimension d */ - int getNChips(dimension d); + int getNChips(dimension d); - /** + /** * Get Detector offset from shared memory in dimension d * @param d dimension d * @returns offset in dimension d */ - int getDetectorOffset(dimension d); + int getDetectorOffset(dimension d); - /** + /** * Set Detector offset in shared memory in dimension d * @param d dimension d * @param off offset for detector */ - void setDetectorOffset(dimension d, int off); + void setDetectorOffset(dimension d, int off); - /** + /** * Set Detector offset in shared memory in dimension d * @param detx number of detectors in X dir in multi list * @param dety number of detectors in Y dir in multi list */ - void updateMultiSize(int detx, int dety); + void updateMultiSize(int detx, int dety); - /** + /** * Checks if the detector is online and sets the online flag * @param online if GET_ONLINE_FLAG, only returns shared memory online flag, * else sets the detector in online/offline state @@ -454,124 +448,123 @@ public: * if ONLINE_FLAG, detector in online state (i.e. communication to the detector updating the local structure) * @returns online/offline status */ - int setOnline(int value=GET_ONLINE_FLAG); + int setOnline(int value = GET_ONLINE_FLAG); - - /** + /** * Returns the online flag */ - int getOnlineFlag() const; + int getOnlineFlag() const; - /** + /** * Checks if each of the detector is online/offline * @returns empty string if it is online * else returns hostname if it is offline */ - std::string checkOnline(); + std::string checkOnline(); - int setControlPort(int port_number); + int setControlPort(int port_number); - /** + /** * Returns the detector TCP control port \sa sharedSlsDetector * @returns the detector TCP control port */ - int getControlPort() const; + int getControlPort() const; - int setStopPort(int port_number); + int setStopPort(int port_number); - /** + /** * Returns the detector TCP stop port \sa sharedSlsDetector * @returns the detector TCP stop port */ - int getStopPort() const; + int getStopPort() const; - int setReceiverPort(int port_number); + int setReceiverPort(int port_number); - /** + /** * Returns the receiver TCP port \sa sharedSlsDetector * @returns the receiver TCP port */ - int getReceiverPort() const ; + int getReceiverPort() const; - /** + /** * Lock server for this client IP * @param p 0 to unlock, 1 to lock (-1 gets) * @returns 1 for locked or 0 for unlocked */ - int lockServer(int lock=-1); + int lockServer(int lock = -1); - /** + /** * Get last client IP saved on detector server * @returns last client IP saved on detector server */ - std::string getLastClientIP(); + std::string getLastClientIP(); - /** + /** * Exit detector server * @returns OK or FAIL */ - int exitServer(); + int exitServer(); - /** + /** * Executes a system command on the detector server * e.g. mount an nfs disk, reboot and returns answer etc. * @param cmd command to be executed * @returns OK or FAIL */ - int execCommand(const std::string& cmd); + int execCommand(const std::string &cmd); - /** + /** * Updates some of the shared memory receiving the data from the detector * @returns OK */ - int updateDetectorNoWait( sls::ClientSocket &client); + int updateDetectorNoWait(sls::ClientSocket &client); - /** + /** * Updates some of the shared memory receiving the data from the detector * calls updateDetectorNoWait * @returns OK or FAIL or FORCE_RET */ - int updateDetector(); + int updateDetector(); - /** + /** * Write current configuration to a file * calls writeConfigurationFile giving it a stream to write to * @param fname configuration file name * @param m multiSlsDetector reference to parse commands * @returns OK or FAIL */ - int writeConfigurationFile(const std::string& fname, multiSlsDetector* m); + int writeConfigurationFile(const std::string &fname, multiSlsDetector *m); - /** + /** * Write current configuration to a stream * @param outfile outstream * @param m multiSlsDetector reference to parse commands * @returns OK or FAIL */ - int writeConfigurationFile(std::ofstream &outfile, multiSlsDetector* m); + int writeConfigurationFile(std::ofstream &outfile, multiSlsDetector *m); - /** + /** * Returns the trimfile or settings file name (Useless??) * @returns the trimfile or settings file name */ - std::string getSettingsFile(); + std::string getSettingsFile(); - /** + /** * Writes a trim/settings file for module number * the values will be read from the current detector structure * @param fname name of the file to be written * @returns OK or FAIL if the file could not be written * \sa ::sls_detector_module sharedSlsDetector mythenDetector::writeSettingsFile(string, int) */ - int writeSettingsFile(const std::string& fname); + int writeSettingsFile(const std::string &fname); - /** + /** * Get detector settings * @returns current settings */ - detectorSettings getSettings(); + detectorSettings getSettings(); - /** + /** * Load detector settings from the settings file picked from the trimdir/settingsdir * Eiger only stores in shared memory ( a get will overwrite this) * For Eiger, one must use threshold @@ -579,25 +572,24 @@ public: * @param isettings settings * @returns current settings */ - detectorSettings setSettings(detectorSettings isettings); + detectorSettings setSettings(detectorSettings isettings); - /** + /** * Send detector settings only (set only for Jungfrau, Gotthard, Moench, get for all) * Only the settings enum is sent to the detector, where it will * initialize al the dacs already hard coded in the detector server * @param isettings settings * @returns current settings */ - detectorSettings sendSettingsOnly(detectorSettings isettings); + detectorSettings sendSettingsOnly(detectorSettings isettings); - /** + /** * Get threshold energy (Mythen and Eiger) * @returns current threshold value in ev (-1 failed) */ - int getThresholdEnergy(); + int getThresholdEnergy(); - - /** + /** * Set threshold energy (Mythen and Eiger) * For Eiger, calls setThresholdEneryAndSettings * @param e_eV threshold in eV @@ -605,663 +597,662 @@ public: * @param tb 1 to include trimbits, 0 to exclude * @returns current threshold value in ev (-1 failed) */ - int setThresholdEnergy(int e_eV, detectorSettings isettings=GET_SETTINGS, int tb=1); + int setThresholdEnergy(int e_eV, detectorSettings isettings = GET_SETTINGS, int tb = 1); - /** + /** * Set threshold energy and settings (Eiger only) * @param e_eV threshold in eV * @param isettings ev. change settings * @param tb 1 to include trimbits, 0 to exclude * @returns OK if successful, else FAIL */ - int setThresholdEnergyAndSettings(int e_eV, detectorSettings isettings, int tb=1); + int setThresholdEnergyAndSettings(int e_eV, detectorSettings isettings, int tb = 1); - /** + /** * Returns the detector trimbit/settings directory \sa sharedSlsDetector * @returns the trimbit/settings directory */ - std::string getSettingsDir(); + std::string getSettingsDir(); - /** + /** * Sets the detector trimbit/settings directory \sa sharedSlsDetector * @param s trimbits/settings directory * @returns the trimbit/settings directory */ - std::string setSettingsDir(const std::string& dir); + std::string setSettingsDir(const std::string &dir); - /** + /** * Loads the modules settings/trimbits reading from a specific file * file name extension is automatically generated. * @param fname specific settings/trimbits file * returns OK or FAIL */ - int loadSettingsFile(const std::string& fname); + int loadSettingsFile(const std::string &fname); - /** + /** * Saves the modules settings/trimbits to a specific file * file name extension is automatically generated. * @param fname specific settings/trimbits file * returns OK or FAIL */ - int saveSettingsFile(const std::string& fname); + int saveSettingsFile(const std::string &fname); - /** + /** * Get run status of the detector * @returns the status of the detector */ - runStatus getRunStatus(); + runStatus getRunStatus(); - /** + /** * Prepares detector for acquisition (Eiger) * @returns OK or FAIL */ - int prepareAcquisition(); + int prepareAcquisition(); - /** + /** * Start detector acquisition (Non blocking) * @returns OK or FAIL if even one does not start properly */ - int startAcquisition(); + int startAcquisition(); - /** + /** * Stop detector acquisition * @returns OK or FAIL */ - int stopAcquisition(); + int stopAcquisition(); - /** + /** * Give an internal software trigger to the detector (Eiger only) * @return OK or FAIL */ - int sendSoftwareTrigger(); + int sendSoftwareTrigger(); - /** + /** * Start detector acquisition and read all data (Blocking until end of acquisition) * @returns OK or FAIL */ - int startAndReadAll(); + int startAndReadAll(); - /** + /** * Start readout (without exposure or interrupting exposure) (Eiger store in ram) * @returns OK or FAIL */ - int startReadOut(); + int startReadOut(); - /** + /** * Requests and receives all data from the detector (Eiger store in ram) * @returns OK or FAIL */ - int readAll(); + int readAll(); - /** + /** * Configures in detector the destination for UDP packets * @returns OK or FAIL */ - int configureMAC(); + int configureMAC(); - /** + /** * Set/get timer value (not all implemented for all detectors) * @param index timer index * @param t time in ns or number of...(e.g. frames, gates, probes) * @returns timer set value in ns or number of...(e.g. frames, gates, probes) */ - int64_t setTimer(timerIndex index, int64_t t=-1); + int64_t setTimer(timerIndex index, int64_t t = -1); - /** + /** * Set/get timer value left in acquisition (not all implemented for all detectors) * @param index timer index * @param t time in ns or number of...(e.g. frames, gates, probes) * @returns timer set value in ns or number of...(e.g. frames, gates, probes) */ - int64_t getTimeLeft(timerIndex index); + int64_t getTimeLeft(timerIndex index); - /** + /** * Set speed * @param sp speed type (clkdivider option for Jungfrau and Eiger, others for Mythen/Gotthard) * @param value (clkdivider 0,1,2 for full, half and quarter speed). Other values check manual * @returns value of speed set */ - int setSpeed(speedVariable sp, int value=-1); + int setSpeed(speedVariable sp, int value = -1); - /** + /** * Set/get dynamic range and updates the number of dataBytes * (Eiger: If i is 32, also sets clkdivider to 2, if 16, sets clkdivider to 1) * @param i dynamic range (-1 get) * @returns current dynamic range * \sa sharedSlsDetector */ - int setDynamicRange(int n=-1); + int setDynamicRange(int n = -1); - /** + /** * Recalculated number of data bytes * @returns tota number of data bytes */ - int getDataBytes(); + int getDataBytes(); - /** + /** * Recalculated number of data bytes including gap pixels * @returns tota number of data bytes including gap pixels */ - int getDataBytesInclGapPixels(); + int getDataBytesInclGapPixels(); - /** + /** * Set/get dacs value * @param val value (in V) * @param index DAC index * @param mV 0 in dac units or 1 in mV * @returns current DAC value */ - int setDAC(int val, dacIndex index, int mV); + int setDAC(int val, dacIndex index, int mV); - /** + /** * Get adc value * @param index adc(DAC) index * @returns current adc value (temperature for eiger and jungfrau in millidegrees) */ - int getADC(dacIndex index); + int getADC(dacIndex index); - /** + /** * Set/get timing mode * @param pol timing mode (-1 gets) * @returns current timing mode */ - externalCommunicationMode setExternalCommunicationMode(externalCommunicationMode pol=GET_EXTERNAL_COMMUNICATION_MODE); + externalCommunicationMode setExternalCommunicationMode(externalCommunicationMode pol = GET_EXTERNAL_COMMUNICATION_MODE); - /** + /** * Set/get external signal flags (to specify triggerinrising edge etc) (Gotthard, Mythen) * @param pol external signal flag (-1 gets) * @param signalindex singal index (0 - 3) * @returns current timing mode */ - externalSignalFlag setExternalSignalFlags(externalSignalFlag pol=GET_EXTERNAL_SIGNAL_FLAG , int signalindex=0); + externalSignalFlag setExternalSignalFlags(externalSignalFlag pol = GET_EXTERNAL_SIGNAL_FLAG, int signalindex = 0); - /** + /** * Set/get readout flags (Eiger, Mythen) * @param flag readout flag (Eiger options: parallel, nonparallel, safe etc.) (-1 gets) * @returns readout flag */ - int setReadOutFlags(readOutFlags flag=GET_READOUT_FLAGS); + int setReadOutFlags(readOutFlags flag = GET_READOUT_FLAGS); - /** + /** * Write in a register. For Advanced users * @param addr address of register * @param val value to write into register * @returns value read after writing */ - uint32_t writeRegister(uint32_t addr, uint32_t val); + uint32_t writeRegister(uint32_t addr, uint32_t val); - /** + /** * Read from a register. For Advanced users * @param addr address of register * @returns value read from register */ - uint32_t readRegister(uint32_t addr); + uint32_t readRegister(uint32_t addr); - /** + /** * Set bit in a register. For Advanced users * @param addr address of register * @param n nth bit * @returns value read from register */ - uint32_t setBit(uint32_t addr, int n); + uint32_t setBit(uint32_t addr, int n); - /** + /** * Clear bit in a register. For Advanced users * @param addr address of register * @param n nth bit * @returns value read from register */ - uint32_t clearBit(uint32_t addr, int n); + uint32_t clearBit(uint32_t addr, int n); - /** + /** * Validates the format of the detector MAC address and sets it \sa sharedSlsDetector * @param detectorMAC detector MAC address * @returns the detector MAC address */ - std::string setDetectorMAC(const std::string& detectorMAC); + std::string setDetectorMAC(const std::string &detectorMAC); - /** + /** * Returns the detector MAC address\sa sharedSlsDetector * @returns the detector MAC address */ - std::string getDetectorMAC(); + std::string getDetectorMAC(); - /** + /** * Validates the format of the detector IP address and sets it \sa sharedSlsDetector * @param detectorIP detector IP address * @returns the detector IP address */ - std::string setDetectorIP(const std::string& detectorIP); + std::string setDetectorIP(const std::string &detectorIP); - /** + /** * Returns the detector IP address\sa sharedSlsDetector * @returns the detector IP address */ - std::string getDetectorIP(); + std::string getDetectorIP(); - /** + /** * Validates and sets the receiver. * Also updates the receiver with all the shared memory parameters significant for the receiver * Also configures the detector to the receiver as UDP destination * @param receiver receiver hostname or IP address * @returns the receiver IP address from shared memory */ - std::string setReceiver(const std::string& receiver); + std::string setReceiver(const std::string &receiver); - /** + /** * Returns the receiver IP address\sa sharedSlsDetector * @returns the receiver IP address */ - std::string getReceiver(); + std::string getReceiver(); - /** + /** * Validates the format of the receiver UDP IP address and sets it \sa sharedSlsDetector * @param udpip receiver UDP IP address * @returns the receiver UDP IP address */ - std::string setReceiverUDPIP(const std::string& udpip); + std::string setReceiverUDPIP(const std::string &udpip); - /** + /** * Returns the receiver UDP IP address\sa sharedSlsDetector * @returns the receiver UDP IP address */ - std::string getReceiverUDPIP(); + std::string getReceiverUDPIP(); - /** + /** * Validates the format of the receiver UDP MAC address and sets it \sa sharedSlsDetector * @param udpmac receiver UDP MAC address * @returns the receiver UDP MAC address */ - std::string setReceiverUDPMAC(const std::string& udpmac); + std::string setReceiverUDPMAC(const std::string &udpmac); - /** + /** * Returns the receiver UDP MAC address\sa sharedSlsDetector * @returns the receiver UDP MAC address */ - std::string getReceiverUDPMAC(); + std::string getReceiverUDPMAC(); - /** + /** * Sets the receiver UDP port\sa sharedSlsDetector * @param udpport receiver UDP port * @returns the receiver UDP port */ - int setReceiverUDPPort(int udpport); + int setReceiverUDPPort(int udpport); - /** + /** * Returns the receiver UDP port\sa sharedSlsDetector * @returns the receiver UDP port */ - int getReceiverUDPPort(); + int getReceiverUDPPort(); - /** + /** * Sets the receiver UDP port 2\sa sharedSlsDetector * @param udpport receiver UDP port 2 * @returns the receiver UDP port 2 */ - int setReceiverUDPPort2(int udpport); + int setReceiverUDPPort2(int udpport); - /** + /** * Returns the receiver UDP port 2 of same interface\sa sharedSlsDetector * @returns the receiver UDP port 2 of same interface */ - int getReceiverUDPPort2(); + int getReceiverUDPPort2(); - /** + /** * Sets the client zmq port\sa sharedSlsDetector * @param port client zmq port */ - void setClientStreamingPort(int port); + void setClientStreamingPort(int port); - /** + /** * Returns the client zmq port \sa sharedSlsDetector * @returns the client zmq port */ - int getClientStreamingPort(); + int getClientStreamingPort(); - /** + /** * Sets the receiver zmq port\sa sharedSlsDetector * @param port receiver zmq port */ - void setReceiverStreamingPort(int port); + void setReceiverStreamingPort(int port); - /** + /** * Returns the receiver zmq port \sa sharedSlsDetector * @returns the receiver zmq port */ - int getReceiverStreamingPort(); + int getReceiverStreamingPort(); - /** + /** * Sets the client zmq ip\sa sharedSlsDetector * @param sourceIP client zmq ip */ - void setClientStreamingIP(const std::string& sourceIP); + void setClientStreamingIP(const std::string &sourceIP); - /** + /** * Returns the client zmq ip \sa sharedSlsDetector * @returns the client zmq ip, returns "none" if default setting and no custom ip set */ - std::string getClientStreamingIP(); + std::string getClientStreamingIP(); - /** + /** * Sets the receiver zmq ip\sa sharedSlsDetector * @param sourceIP receiver zmq ip. If empty, uses rx_hostname */ - void setReceiverStreamingIP(std::string sourceIP); + void setReceiverStreamingIP(std::string sourceIP); - /** + /** * Returns the receiver zmq ip \sa sharedSlsDetector * @returns the receiver zmq ip, returns "none" if default setting and no custom ip set */ - std::string getReceiverStreamingIP(); + std::string getReceiverStreamingIP(); - /** + /** * Sets the transmission delay for left, right or entire frame * (Eiger, Jungfrau(only entire frame)) * @param index type of delay * @param delay delay * @returns transmission delay */ - int setDetectorNetworkParameter(networkParameter index, int delay); + int setDetectorNetworkParameter(networkParameter index, int delay); - /** + /** * Sets the additional json header\sa sharedSlsDetector * @param jsonheader additional json header * @returns additional json header, returns "none" if default setting and no custom ip set */ - std::string setAdditionalJsonHeader(const std::string& jsonheader); + std::string setAdditionalJsonHeader(const std::string &jsonheader); - /** + /** * Returns the additional json header \sa sharedSlsDetector * @returns the additional json header, returns "none" if default setting and no custom ip set */ - std::string getAdditionalJsonHeader(); + std::string getAdditionalJsonHeader(); - /** + /** * Sets the value for the additional json header parameter if found, else append it * @param key additional json header parameter * @param value additional json header parameter value (cannot be empty) * @returns the additional json header parameter value, * empty if no parameter found in additional json header */ - std::string setAdditionalJsonParameter(const std::string& key, const std::string& value); + std::string setAdditionalJsonParameter(const std::string &key, const std::string &value); - /** + /** * Returns the additional json header parameter value * @param key additional json header parameter * @returns the additional json header parameter value, * empty if no parameter found in additional json header */ - std::string getAdditionalJsonParameter(const std::string& key); + std::string getAdditionalJsonParameter(const std::string &key); - /** + /** * Sets the receiver UDP socket buffer size * @param udpsockbufsize additional json header * @returns receiver udp socket buffer size */ - uint64_t setReceiverUDPSocketBufferSize(uint64_t udpsockbufsize=-1); + uint64_t setReceiverUDPSocketBufferSize(uint64_t udpsockbufsize = -1); - /** + /** * Returns the receiver UDP socket buffer size\sa sharedSlsDetector * @returns the receiver UDP socket buffer size */ - uint64_t getReceiverUDPSocketBufferSize() ; + uint64_t getReceiverUDPSocketBufferSize(); - /** + /** * Returns the receiver real UDP socket buffer size\sa sharedSlsDetector * @returns the receiver real UDP socket buffer size */ - uint64_t getReceiverRealUDPSocketBufferSize(); + uint64_t getReceiverRealUDPSocketBufferSize(); - /** + /** * Execute a digital test (Gotthard, Mythen) * @param mode testmode type * @param value 1 to set or 0 to clear the digital test bit * @returns result of test */ - int digitalTest(digitalTestMode mode, int ival=-1); + int digitalTest(digitalTestMode mode, int ival = -1); - /** + /** * Load dark or gain image to detector (Gotthard) * @param index image type, 0 for dark image and 1 for gain image * @param fname file name from which to load image * @returns OK or FAIL */ - int loadImageToDetector(imageType index, const std::string& fname); + int loadImageToDetector(imageType index, const std::string &fname); - /** + /** * Called from loadImageToDetector to send the image to detector * @param index image type, 0 for dark image and 1 for gain image * @param imageVals image * @returns OK or FAIL */ - int sendImageToDetector(imageType index, int16_t imageVals[]); + int sendImageToDetector(imageType index, int16_t imageVals[]); - /** + /** * Writes the counter memory block from the detector (Gotthard) * @param fname file name to load data from * @param startACQ is 1 to start acquisition after reading counter * @returns OK or FAIL */ - int writeCounterBlockFile(const std::string& fname,int startACQ=0); + int writeCounterBlockFile(const std::string &fname, int startACQ = 0); - /** + /** * Gets counter memory block in detector (Gotthard) * @param image counter memory block from detector * @param startACQ 1 to start acquisition afterwards, else 0 * @returns OK or FAIL */ - int getCounterBlock(int16_t image[],int startACQ=0); + int getCounterBlock(int16_t image[], int startACQ = 0); - /** + /** * Resets counter in detector * @param startACQ is 1 to start acquisition after resetting counter * @returns OK or FAIL */ - int resetCounterBlock(int startACQ=0); + int resetCounterBlock(int startACQ = 0); - /** + /** * Set/get counter bit in detector (Gotthard) * @param i is -1 to get, 0 to reset and any other value to set the counter bit * @returns the counter bit in detector */ - int setCounterBit(int i = -1); + int setCounterBit(int i = -1); - /** + /** * send ROI to processor (moench only) * @returns OK or FAIL */ - int sendROIToProcessor(); + int sendROIToProcessor(); - /** + /** * Set ROI (Gotthard) * At the moment only one set allowed * @param n number of rois * @param roiLimits array of roi * @returns OK or FAIL */ - int setROI(int n=-1,ROI roiLimits[]=nullptr); + int setROI(int n = -1, ROI roiLimits[] = nullptr); - /** + /** * Get ROI from each detector and convert it to the multi detector scale (Gotthard) * @param n number of rois * @returns OK or FAIL */ - slsDetectorDefs::ROI* getROI(int &n); + slsDetectorDefs::ROI *getROI(int &n); - /** + /** * Returns number of rois * @returns number of ROIs */ - int getNRoi(); + int getNRoi(); - /** + /** * Send ROI to the detector after calculating * from setROI * @param n number of ROIs (-1 to get) * @param roiLimits ROI * @returns OK or FAIL */ - int sendROI(int n=-1,ROI roiLimits[]=nullptr); + int sendROI(int n = -1, ROI roiLimits[] = nullptr); - /** + /** * Write to ADC register (Gotthard, Jungfrau, ChipTestBoard). For expert users * @param addr address of adc register * @param val value * @returns return value (mostly -1 as it can't read adc register) */ - int writeAdcRegister(int addr, int val); + int writeAdcRegister(int addr, int val); - /** + /** * Activates/Deactivates the detector (Eiger only) * @param enable active (1) or inactive (0), -1 gets * @returns 0 (inactive) or 1 (active)for activate mode */ - int activate(int const enable=-1); + int activate(int const enable = -1); - /** + /** * Set deactivated Receiver padding mode (Eiger only) * @param padding padding option for deactivated receiver. Can be 1 (padding), 0 (no padding), -1 (gets) * @returns 1 (padding), 0 (no padding), -1 (inconsistent values) for padding option */ - int setDeactivatedRxrPaddingMode(int padding=-1); + int setDeactivatedRxrPaddingMode(int padding = -1); - /** + /** * Returns the enable if data will be flipped across x or y axis (Eiger) * @param d axis across which data is flipped * @returns 1 for flipped, else 0 */ - int getFlippedData(dimension d=X); + int getFlippedData(dimension d = X); - /** + /** * Sets the enable which determines if * data will be flipped across x or y axis (Eiger) * @param d axis across which data is flipped * @param value 0 or 1 to reset/set or -1 to get value * @returns enable flipped data across x or y axis */ - int setFlippedData(dimension d=X, int value=-1); + int setFlippedData(dimension d = X, int value = -1); - /** + /** * Sets all the trimbits to a particular value (Eiger) * @param val trimbit value * @returns OK or FAIL */ - int setAllTrimbits(int val); + int setAllTrimbits(int val); - /** + /** * Enable gap pixels, only for Eiger and for 8,16 and 32 bit mode. (Eiger) * 4 bit mode gap pixels only in gui call back * @param val 1 sets, 0 unsets, -1 gets * @returns gap pixel enable or -1 for error */ - int enableGapPixels(int val=-1); + int enableGapPixels(int val = -1); - /** + /** * Sets the number of trim energies and their value (Eiger) * \sa sharedSlsDetector * @param nen number of energies * @param en array of energies * @returns number of trim energies */ - int setTrimEn(int nen, int *en=nullptr); + int setTrimEn(int nen, int *en = nullptr); - /** + /** * Returns the number of trim energies and their value (Eiger) * \sa sharedSlsDetector * @param en array of energies * @returns number of trim energies */ - int getTrimEn(int *en=nullptr); + int getTrimEn(int *en = nullptr); - /** + /** * Pulse Pixel (Eiger) * @param n is number of times to pulse * @param x is x coordinate * @param y is y coordinate * @returns OK or FAIL */ - int pulsePixel(int n=0,int x=0,int y=0); + int pulsePixel(int n = 0, int x = 0, int y = 0); - /** + /** * Pulse Pixel and move by a relative value (Eiger) * @param n is number of times to pulse * @param x is relative x value * @param y is relative y value * @returns OK or FAIL */ - int pulsePixelNMove(int n=0,int x=0,int y=0); + int pulsePixelNMove(int n = 0, int x = 0, int y = 0); - /** + /** * Pulse Chip (Eiger) * @param n is number of times to pulse * @returns OK or FAIL */ - int pulseChip(int n=0); + int pulseChip(int n = 0); - /** + /** * Set/gets threshold temperature (Jungfrau) * @param val value in millidegrees, -1 gets * @returns threshold temperature in millidegrees */ - int setThresholdTemperature(int val=-1); + int setThresholdTemperature(int val = -1); - /** + /** * Enables/disables temperature control (Jungfrau) * @param val value, -1 gets * @returns temperature control enable */ - int setTemperatureControl(int val=-1); + int setTemperatureControl(int val = -1); - /** + /** * Resets/ gets over-temperature event (Jungfrau) * @param val value, -1 gets * @returns over-temperature event */ - int setTemperatureEvent(int val=-1); + int setTemperatureEvent(int val = -1); - /** + /** * Set storage cell that stores first acquisition of the series (Jungfrau) * @param value storage cell index. Value can be 0 to 15. (-1 gets) * @returns the storage cell that stores the first acquisition of the series */ - int setStoragecellStart(int pos=-1); + int setStoragecellStart(int pos = -1); - /** + /** * Programs FPGA with pof file (Jungfrau) * @param fname file name * @returns OK or FAIL */ - int programFPGA(const std::string& fname); + int programFPGA(const std::string &fname); - /** + /** * Resets FPGA (Jungfrau) * @returns OK or FAIL */ - int resetFPGA(); + int resetFPGA(); - /** + /** * Power on/off Chip (Jungfrau) * @param ival on is 1, off is 0, -1 to get * @returns OK or FAIL */ - int powerChip(int ival= -1); + int powerChip(int ival = -1); - /** + /** * Automatic comparator disable (Jungfrau) * @param ival on is 1, off is 0, -1 to get * @returns OK or FAIL */ - int setAutoComparatorDisableMode(int ival= -1); + int setAutoComparatorDisableMode(int ival = -1); - - /** + /** * Returns the trimbits from the detector's shared memmory (Eiger) * @param retval is the array with the trimbits * @returns total number of channels for the detector */ - int getChanRegs(double* retval); + int getChanRegs(double *retval); - /** + /** * Configure Module (Eiger) * Called for loading trimbits and settings settings to the detector * @param module module to be set - must contain correct module number and @@ -1270,250 +1261,249 @@ public: * @returns ok or fail * \sa ::sls_detector_module */ - int setModule(sls_detector_module module, int tb = 1); + int setModule(sls_detector_module module, int tb = 1); - - /** + /** * Get module structure from detector (all detectors) * @returns pointer to module structure (which has been created and must then be deleted) */ - sls_detector_module *getModule(); + sls_detector_module *getModule(); - /** + /** * Set Rate correction (Mythen, Eiger) * @param t dead time in ns - if 0 disable correction, * if >0 set dead time to t, if < 0 set deadtime to default dead time * for current settings * @returns 0 if rate correction disabled, >0 otherwise */ - int setRateCorrection(int64_t t = 0); + int setRateCorrection(int64_t t = 0); - /** + /** * Get rate correction Eiger) * @returns 0 if rate correction disabled, > 0 otherwise */ - int64_t getRateCorrection(); + int64_t getRateCorrection(); - /** + /** * Prints receiver configuration * #param level print level */ - void printReceiverConfiguration(TLogLevel level = logINFO); + void printReceiverConfiguration(TLogLevel level = logINFO); - /** + /** * Checks if receiver is online and set flag * Also initializes the data socekt * @param online 1 to set online, 0 to set offline, -1 gets * @returns online, offline (from shared memory) */ - int setReceiverOnline(int value=GET_ONLINE_FLAG); + int setReceiverOnline(int value = GET_ONLINE_FLAG); - int getReceiverOnline() const; + int getReceiverOnline() const; - /** + /** * Checks if the receiver is really online * @returns empty string if online, else returns receiver hostname */ - std::string checkReceiverOnline(); + std::string checkReceiverOnline(); - /** + /** * Locks/Unlocks the connection to the receiver * @param lock sets (1), usets (0), gets (-1) the lock * @returns lock status of the receiver */ - int lockReceiver(int lock=-1); + int lockReceiver(int lock = -1); - /** + /** * Returns the IP of the last client connecting to the receiver * @returns the IP of the last client connecting to the receiver */ - std::string getReceiverLastClientIP(); + std::string getReceiverLastClientIP(); - /** + /** * Exits the receiver TCP server * @retutns OK or FAIL */ - int exitReceiver(); + int exitReceiver(); - /** + /** * Executes a system command on the receiver server * e.g. mount an nfs disk, reboot and returns answer etc. * @param cmd command to be executed * @returns OK or FAIL */ - int execReceiverCommand(const std::string& cmd); + int execReceiverCommand(const std::string &cmd); - /** + /** updates the shared memory receiving the data from the detector (without asking and closing the connection /returns OK */ - int updateReceiverNoWait(sls::ClientSocket& receiver); + int updateReceiverNoWait(sls::ClientSocket &receiver); - /** + /** * Updates the shared memory receiving the data from the detector * @returns OK or FAIL */ - int updateReceiver(); + int updateReceiver(); - /** + /** * Send the multi detector size to the detector * @param detx number of detectors in x dir * @param dety number of detectors in y dir */ - void sendMultiDetectorSize(); + void sendMultiDetectorSize(); - /** + /** * Send the detector pos id to the receiver * for various file naming conventions for multi detectors in receiver */ - void setDetectorId(); + void setDetectorId(); - /** + /** * Send the detector host name to the receiver * for various handshaking required with the detector */ - void setDetectorHostname(); + void setDetectorHostname(); - /** + /** * Returns output file directory * @returns output file directory */ - std::string getFilePath(); + std::string getFilePath(); - /** + /** * Sets up the file directory * @param s file directory * @returns file dir */ - std::string setFilePath(const std::string& path); + std::string setFilePath(const std::string &path); - /** + /** * Returns file name prefix * @returns file name prefix */ - std::string getFileName(); + std::string getFileName(); - /** + /** * Sets up the file name prefix * @param s file name prefix * @returns file name prefix */ - std::string setFileName(const std::string& fname); + std::string setFileName(const std::string &fname); - /** + /** * Sets the max frames per file in receiver * @param f max frames per file * @returns max frames per file in receiver */ - int setReceiverFramesPerFile(int f=-1); + int setReceiverFramesPerFile(int f = -1); - /** + /** * Sets the frames discard policy in receiver * @param f frames discard policy * @returns frames discard policy set in receiver */ - frameDiscardPolicy setReceiverFramesDiscardPolicy(frameDiscardPolicy f = GET_FRAME_DISCARD_POLICY); + frameDiscardPolicy setReceiverFramesDiscardPolicy(frameDiscardPolicy f = GET_FRAME_DISCARD_POLICY); - /** + /** * Sets the partial frames padding enable in receiver * @param f partial frames padding enable * @returns partial frames padding enable in receiver */ - int setReceiverPartialFramesPadding(int f = -1); + int setReceiverPartialFramesPadding(int f = -1); - /** + /** * Returns file format * @returns file name */ - fileFormat getFileFormat(); + fileFormat getFileFormat(); - /** + /** * Sets up the file format * @param f file format * @returns file format */ - fileFormat setFileFormat(fileFormat f); + fileFormat setFileFormat(fileFormat f); - /** + /** * Returns file index * @returns file index */ - int getFileIndex(); + int getFileIndex(); - /** + /** * Sets up the file index * @param i file index * @returns file index */ - int setFileIndex(int i); + int setFileIndex(int i); - /** + /** * increments file index * @returns the file index */ - int incrementFileIndex(); + int incrementFileIndex(); - /** + /** * Receiver starts listening to packets * @returns OK or FAIL */ - int startReceiver(); + int startReceiver(); - /** + /** * Stops the listening mode of receiver * @returns OK or FAIL */ - int stopReceiver(); + int stopReceiver(); - /** + /** * Gets the status of the listening mode of receiver * @returns status */ - runStatus getReceiverStatus(); + runStatus getReceiverStatus(); - /** + /** * Gets the number of frames caught by receiver * @returns number of frames caught by receiver */ - int getFramesCaughtByReceiver(); + int getFramesCaughtByReceiver(); - /** + /** * Gets the current frame index of receiver * @returns current frame index of receiver */ - int getReceiverCurrentFrameIndex(); + int getReceiverCurrentFrameIndex(); - /** + /** * Resets framescaught in receiver * Use this when using startAcquisition instead of acquire * @returns OK or FAIL */ - int resetFramesCaught(); + int resetFramesCaught(); - /** + /** * Sets/Gets receiver file write enable * @param enable 1 or 0 to set/reset file write enable * @returns file write enable */ - int enableWriteToFile(int enable=-1); + int enableWriteToFile(int enable = -1); - /** + /** * Sets/Gets file overwrite enable * @param enable 1 or 0 to set/reset file overwrite enable * @returns file overwrite enable */ - int overwriteFile(int enable=-1); + int overwriteFile(int enable = -1); - /** + /** * (previously setReadReceiverFrequency) * Sets the receiver streaming frequency * @param freq nth frame streamed out, if 0, streamed out at a timer of 200 ms * @param detPos -1 for all detectors in list or specific detector position * @returns receiver streaming frequency */ - int setReceiverStreamingFrequency(int freq=-1); + int setReceiverStreamingFrequency(int freq = -1); - /** + /** * (previously setReceiverReadTimer) * Sets the receiver streaming timer * If receiver streaming frequency is 0, then this timer between each @@ -1521,61 +1511,61 @@ public: * @param time_in_ms timer between frames * @returns receiver streaming timer in ms */ - int setReceiverStreamingTimer(int time_in_ms=500); + int setReceiverStreamingTimer(int time_in_ms = 500); - /** + /** * Enable or disable streaming data from receiver to client * @param enable 0 to disable 1 to enable -1 to only get the value * @returns data streaming from receiver enable */ - int enableDataStreamingFromReceiver(int enable=-1); + int enableDataStreamingFromReceiver(int enable = -1); - /** + /** * Enable/disable or 10Gbe * @param i is -1 to get, 0 to disable and 1 to enable * @returns if 10Gbe is enabled */ - int enableTenGigabitEthernet(int i = -1); + int enableTenGigabitEthernet(int i = -1); - /** + /** * Set/get receiver fifo depth * @param i is -1 to get, any other value to set the fifo deph * @returns the receiver fifo depth */ - int setReceiverFifoDepth(int i = -1); + int setReceiverFifoDepth(int i = -1); - /** + /** * Set/get receiver silent mode * @param i is -1 to get, 0 unsets silent mode, 1 sets silent mode * @returns the receiver silent mode enable */ - int setReceiverSilentMode(int i = -1); + int setReceiverSilentMode(int i = -1); - /** + /** * If data streaming in receiver is enabled, * restream the stop dummy packet from receiver * Used usually for Moench, * in case it is lost in network due to high data rate * @returns OK if success else FAIL */ - int restreamStopFromReceiver(); + int restreamStopFromReceiver(); - /** + /** * Opens pattern file and sends pattern to CTB * @param fname pattern file to open * @returns OK/FAIL */ - int setPattern(const std::string& fname); + int setPattern(const std::string &fname); - /** + /** * Writes a pattern word to the CTB * @param addr address of the word, -1 is I/O control register, -2 is clk control register * @param word 64bit word to be written, -1 gets * @returns actual value */ - uint64_t setPatternWord(int addr,uint64_t word=-1); + uint64_t setPatternWord(int addr, uint64_t word = -1); - /** + /** * Sets the pattern or loop limits in the CTB * @param level -1 complete pattern, 0,1,2, loop level * @param start start address if >=0 @@ -1583,23 +1573,23 @@ public: * @param n number of loops (if level >=0) * @returns OK/FAIL */ - int setPatternLoops(int level,int &start, int &stop, int &n); + int setPatternLoops(int level, int &start, int &stop, int &n); - /** + /** * Sets the wait address in the CTB * @param level 0,1,2, wait level * @param addr wait address, -1 gets * @returns actual value */ - int setPatternWaitAddr(uint64_t level, uint64_t addr=-1); + int setPatternWaitAddr(uint64_t level, uint64_t addr = -1); - /** + /** * Sets the wait time in the CTB * @param level 0,1,2, wait level * @param t wait time, -1 gets * @returns actual value */ - uint64_t setPatternWaitTime(uint64_t level, uint64_t t=-1); + uint64_t setPatternWaitTime(uint64_t level, uint64_t t = -1); /** * Sets the mask applied to every pattern @@ -1642,17 +1632,16 @@ public: */ int setDigitalIODelay(uint64_t pinMask, int delay); -private: - - /** + private: + /** * Get Detector Type from Shared Memory (opening shm without verifying size) * @param multiId multi detector Id * @param verify true to verify if shm size matches existing one * @returns detector type */ - detectorType getDetectorTypeFromShm(int multiId, bool verify = true); + detectorType getDetectorTypeFromShm(int multiId, bool verify = true); - /** + /** * Initialize shared memory * @param created true if shared memory must be created, else false to open * @param type type of detector @@ -1660,97 +1649,97 @@ private: * @param verify true to verify if shm size matches existing one * @returns true if the shared memory was created now */ - void initSharedMemory(bool created, detectorType type, int multiId, bool verify = true); + void initSharedMemory(bool created, detectorType type, int multiId, bool verify = true); - /** + /** * Sets detector parameters depending detector type * @param type detector type * @param list structure of parameters to initialize depending on detector type */ - void setDetectorSpecificParameters(detectorType type, detParameterList& list); + void setDetectorSpecificParameters(detectorType type, detParameterList &list); - /** + /** * Calculate shared memory size based on detector type * @param type type of detector * @returns size of shared memory of sharedSlsDetector structure */ - int calculateSharedMemorySize(detectorType type); + int calculateSharedMemorySize(detectorType type); - /** + /** * Initialize detector structure to defaults * Called when new shared memory is created * @param type type of detector */ - void initializeDetectorStructure(detectorType type); + void initializeDetectorStructure(detectorType type); - /** + /** * Initialize class members (and from parent classes) * Also connect member pointers to detector structure pointers * Called when shared memory created/existed */ - void initializeMembers(); + void initializeMembers(); - /** + /** * Initialize detector structure * Called when new shared memory created * Initializes the member pointers to defaults as well */ - void initializeDetectorStructurePointers(); + void initializeDetectorStructurePointers(); - /** + /** * Allocates the memory for a sls_detector_module structure and initializes it * Uses current detector type * @returns myMod the pointer to the allocate dmemory location */ - sls_detector_module* createModule(); + sls_detector_module *createModule(); - /** + /** * Allocates the memory for a sls_detector_module structure and initializes it * Has detector type * @param type detector type * @returns myMod the pointer to the allocate dmemory location */ - sls_detector_module* createModule(detectorType type); + sls_detector_module *createModule(detectorType type); - /** + /** * Frees the memory for a sls_detector_module structure * @param myMod the pointer to the memory to be freed */ - void deleteModule(sls_detector_module *myMod); + void deleteModule(sls_detector_module *myMod); - /** + /** * Send a sls_detector_module structure over socket * @param myMod module structure to send * @returns number of bytes sent to the detector */ - int sendModule(sls_detector_module* myMod); + int sendModule(sls_detector_module *myMod); - /** + /** * Receive a sls_detector_module structure over socket * @param myMod module structure to receive * @returns number of bytes received from the detector */ - int receiveModule(sls_detector_module* myMod); + int receiveModule(sls_detector_module *myMod); - /** + /** * Get MAC from the receiver using udpip and * set up UDP connection in detector * @returns Ok or FAIL */ - int setUDPConnection(); + int setUDPConnection(); - /* + /* * Template function to do linear interpolation between two points (Eiger only) */ - template - V linearInterpolation(const E x, const E x1, const E x2, const V y1, const V y2){ - double k = static_cast(y2-y1)/(x2-x1); - double m = y1-k*x1; - int y = round( k*x+m ); - return static_cast(y); - } + template + V linearInterpolation(const E x, const E x1, const E x2, const V y1, const V y2) { + double k = static_cast(y2 - y1) / (x2 - x1); + double m = y1 - k * x1; + int y = round(k * x + m); + return static_cast(y); + } - /** + /** * interpolates dacs and trimbits between 2 trim files * @param a first module structure * @param b second module structure @@ -1760,11 +1749,11 @@ private: * @param tb 1 to include trimbits, 0 to exclude (used for eiger) * @returns the pointer to the module structure with interpolated values or NULL if error */ - sls_detector_module* interpolateTrim( - sls_detector_module* a, sls_detector_module* b, const int energy, - const int e1, const int e2, int tb=1); + sls_detector_module *interpolateTrim( + sls_detector_module *a, sls_detector_module *b, const int energy, + const int e1, const int e2, int tb = 1); - /** + /** * reads a trim/settings file * @param fname name of the file to be read * @param myMod pointer to the module structure which has to be set.
@@ -1773,34 +1762,33 @@ private: * @returns the pointer to myMod or NULL if reading the file failed */ - sls_detector_module* readSettingsFile(const std::string& fname, sls_detector_module* myMod=nullptr, int tb=1); + sls_detector_module *readSettingsFile(const std::string &fname, sls_detector_module *myMod = nullptr, int tb = 1); - /** + /** * writes a trim/settings file * @param fname name of the file to be written * @param mod module structure which has to be written to file * @returns OK or FAIL if the file could not be written */ - int writeSettingsFile(const std::string& fname, sls_detector_module mod); + int writeSettingsFile(const std::string &fname, sls_detector_module mod); + /** slsDetector Id or position in the detectors list */ + int detId; - /** slsDetector Id or position in the detectors list */ - int detId; + /** Shared Memory object */ + SharedMemory *sharedMemory{nullptr}; - /** Shared Memory object */ - SharedMemory* sharedMemory {nullptr}; + /** Shared memory structure */ + sharedSlsDetector *thisDetector{nullptr}; - /** Shared memory structure */ - sharedSlsDetector *thisDetector {nullptr}; + /** pointer to detector module structures in shared memory */ + sls_detector_module *detectorModules{nullptr}; - /** pointer to detector module structures in shared memory */ - sls_detector_module *detectorModules {nullptr}; + /** pointer to dac valuse in shared memory */ + int *dacs{nullptr}; - /** pointer to dac valuse in shared memory */ - int *dacs {nullptr}; - - /** pointer to channel registers in shared memory */ - int *chanregs {nullptr}; + /** pointer to channel registers in shared memory */ + int *chanregs{nullptr}; }; #endif From f8aa0e3d6dbf8c6009e26e666b15a9f2cf1d80ea Mon Sep 17 00:00:00 2001 From: Dhanya Thattil Date: Wed, 13 Mar 2019 15:19:32 +0100 Subject: [PATCH 7/7] removed minor commented lines --- slsDetectorSoftware/multiSlsDetector/multiSlsDetector.cpp | 4 ++-- slsDetectorSoftware/multiSlsDetector/multiSlsDetector.h | 1 - slsDetectorSoftware/slsDetector/slsDetector.cpp | 3 --- slsDetectorSoftware/slsDetector/slsDetector.h | 1 - 4 files changed, 2 insertions(+), 7 deletions(-) diff --git a/slsDetectorSoftware/multiSlsDetector/multiSlsDetector.cpp b/slsDetectorSoftware/multiSlsDetector/multiSlsDetector.cpp index a773ec868..cd9f77b0d 100644 --- a/slsDetectorSoftware/multiSlsDetector/multiSlsDetector.cpp +++ b/slsDetectorSoftware/multiSlsDetector/multiSlsDetector.cpp @@ -244,7 +244,7 @@ void multiSlsDetector::freeSharedMemory(int multiId, int detPos) { return; } - // multi + // multi - get number of detectors from shm SharedMemory multiShm(multiId, -1); int numDetectors = 0; @@ -276,7 +276,7 @@ void multiSlsDetector::freeSharedMemory(int detPos) { detectors.clear(); // clear multi detector shm - sharedMemory.RemoveSharedMemory(); //TODO verify use + sharedMemory.RemoveSharedMemory(); client_downstream = false; } diff --git a/slsDetectorSoftware/multiSlsDetector/multiSlsDetector.h b/slsDetectorSoftware/multiSlsDetector/multiSlsDetector.h index 14e2b1d6f..310113574 100644 --- a/slsDetectorSoftware/multiSlsDetector/multiSlsDetector.h +++ b/slsDetectorSoftware/multiSlsDetector/multiSlsDetector.h @@ -12,7 +12,6 @@ #include "logger.h" #include "sls_detector_defs.h" class slsDetector; -// class SharedMemory; class ZmqSocket; class detectorData; diff --git a/slsDetectorSoftware/slsDetector/slsDetector.cpp b/slsDetectorSoftware/slsDetector/slsDetector.cpp index 179882e62..e5225b0b3 100644 --- a/slsDetectorSoftware/slsDetector/slsDetector.cpp +++ b/slsDetectorSoftware/slsDetector/slsDetector.cpp @@ -240,13 +240,11 @@ void slsDetector::initSharedMemory(bool created, detectorType type, int multiId, // create if (created) { - // thisDetector = (sharedSlsDetector *)sharedMemory->CreateSharedMemory(sz); sharedMemory->CreateSharedMemory(sz); thisDetector = (*sharedMemory)(); } // open and verify version else { - // thisDetector = (sharedSlsDetector *)sharedMemory->OpenSharedMemory(sz); sharedMemory->OpenSharedMemory(sz); thisDetector = (*sharedMemory)(); if (verify && thisDetector->shmversion != SLS_SHMVERSION) { @@ -648,7 +646,6 @@ slsDetectorDefs::detectorType slsDetector::getDetectorTypeFromShm(int multiId, b } // open, map, verify version - // auto sdet = (sharedSlsDetector *)shm.OpenSharedMemory(sz); shm.OpenSharedMemory(); auto sdet = shm(); if (verify && sdet->shmversion != SLS_SHMVERSION) { diff --git a/slsDetectorSoftware/slsDetector/slsDetector.h b/slsDetectorSoftware/slsDetector/slsDetector.h index 346db690c..14bb12ff1 100644 --- a/slsDetectorSoftware/slsDetector/slsDetector.h +++ b/slsDetectorSoftware/slsDetector/slsDetector.h @@ -19,7 +19,6 @@ class ClientInterface; #include class multiSlsDetector; -// class SharedMemory; class ServerInterface; class MySocketTCP;