From 5b8dfd79436b6657de907d695794940ed7721794 Mon Sep 17 00:00:00 2001 From: Erik Frojdh Date: Tue, 16 Oct 2018 14:34:34 +0200 Subject: [PATCH 01/18] range based for loops for reset acq count --- .../src/slsReceiverImplementation.cpp | 14 ++++++-------- 1 file changed, 6 insertions(+), 8 deletions(-) diff --git a/slsReceiverSoftware/src/slsReceiverImplementation.cpp b/slsReceiverSoftware/src/slsReceiverImplementation.cpp index 0b428937f..c4779c99c 100644 --- a/slsReceiverSoftware/src/slsReceiverImplementation.cpp +++ b/slsReceiverSoftware/src/slsReceiverImplementation.cpp @@ -1003,14 +1003,12 @@ void slsReceiverImplementation::setDetectorPositionId(const int i){ /***acquisition functions***/ void slsReceiverImplementation::resetAcquisitionCount() { - for (std::vector::const_iterator it = listener.begin(); it != listener.end(); ++it) - (*it)->ResetParametersforNewAcquisition(); - - for (std::vector::const_iterator it = dataProcessor.begin(); it != dataProcessor.end(); ++it) - (*it)->ResetParametersforNewAcquisition(); - - for (std::vector::const_iterator it = dataStreamer.begin(); it != dataStreamer.end(); ++it) - (*it)->ResetParametersforNewAcquisition(); + for (const auto& it : listener) + it->ResetParametersforNewAcquisition(); + for (const auto& it : dataProcessor) + it->ResetParametersforNewAcquisition(); + for (const auto& it: dataStreamer) + it->ResetParametersforNewAcquisition(); FILE_LOG(logINFO) << "Acquisition Count has been reset"; } From 66e79dc9a97bf82cdad11c93e94e10cfbeb33bd3 Mon Sep 17 00:00:00 2001 From: Erik Frojdh Date: Tue, 16 Oct 2018 15:08:59 +0200 Subject: [PATCH 02/18] refactoring startReadout --- .../src/slsReceiverImplementation.cpp | 40 ++++++++----------- 1 file changed, 16 insertions(+), 24 deletions(-) diff --git a/slsReceiverSoftware/src/slsReceiverImplementation.cpp b/slsReceiverSoftware/src/slsReceiverImplementation.cpp index c4779c99c..cc89be390 100644 --- a/slsReceiverSoftware/src/slsReceiverImplementation.cpp +++ b/slsReceiverSoftware/src/slsReceiverImplementation.cpp @@ -1144,43 +1144,35 @@ void slsReceiverImplementation::stopReceiver(){ void slsReceiverImplementation::startReadout(){ if(status == RUNNING){ - // wait for incoming delayed packets - //current packets caught - volatile int totalP = 0,prev=-1; - for (std::vector::const_iterator it = listener.begin(); it != listener.end(); ++it) - totalP += (*it)->GetPacketsCaught(); + int totalPacketsReceived = 0; + int previousValue=-1; + for(const auto& it : listener) + totalPacketsReceived += it->GetPacketsCaught(); //wait for all packets - if((unsigned long long int)totalP!=numberOfFrames*generalData->packetsPerFrame*listener.size()){ - - //wait as long as there is change from prev totalP, - while(prev != totalP){ + const auto numPacketsToReceive = numberOfFrames*generalData->packetsPerFrame*listener.size(); + if(totalPacketsReceived != numPacketsToReceive){ + while(totalPacketsReceived != previousValue){ #ifdef VERY_VERBOSE - cprintf(MAGENTA,"waiting for all packets prevP:%d totalP:%d\n", - prev,totalP); - + cprintf(MAGENTA,"waiting for all packets previousValue:%d totalPacketsReceived:%d\n", + previousValue,totalPacketsReceived); #endif - //usleep(1*1000*1000);usleep(1*1000*1000);usleep(1*1000*1000);usleep(1*1000*1000); - usleep(5*1000);/* Need to find optimal time **/ + usleep(5*1000);/* TODO! Need to find optimal time **/ + previousValue = totalPacketsReceived; + totalPacketsReceived = 0; + for(const auto& it : listener) + totalPacketsReceived += it->GetPacketsCaught(); - prev = totalP; - totalP = 0; - - for (std::vector::const_iterator it = listener.begin(); it != listener.end(); ++it) - totalP += (*it)->GetPacketsCaught(); #ifdef VERY_VERBOSE - cprintf(MAGENTA,"\tupdated: totalP:%d\n",totalP); + cprintf(MAGENTA,"\tupdated: totalP:%d\n",totalPacketsReceived); #endif } } - - - //set status status = TRANSMITTING; FILE_LOG(logINFO) << "Status: Transmitting"; } - //shut down udp sockets so as to make listeners push dummy (end) packets for processors + //shut down udp sockets to make listeners push dummy (end) packets for processors shutDownUDPSockets(); } From 3c9b1884d3fd0116fc9cd06099851e6b4c588a87 Mon Sep 17 00:00:00 2001 From: Erik Frojdh Date: Tue, 16 Oct 2018 15:25:15 +0200 Subject: [PATCH 03/18] removed conditional operator and moved to range for --- .../src/slsReceiverImplementation.cpp | 33 +++++++++---------- 1 file changed, 16 insertions(+), 17 deletions(-) diff --git a/slsReceiverSoftware/src/slsReceiverImplementation.cpp b/slsReceiverSoftware/src/slsReceiverImplementation.cpp index cc89be390..f5b5a9002 100644 --- a/slsReceiverSoftware/src/slsReceiverImplementation.cpp +++ b/slsReceiverSoftware/src/slsReceiverImplementation.cpp @@ -238,15 +238,14 @@ uint64_t slsReceiverImplementation::getTotalFramesCaught() const { uint64_t sum = 0; uint32_t flagsum = 0; - std::vector::const_iterator it; - for (std::vector::const_iterator it = dataProcessor.begin(); it != dataProcessor.end(); ++it) { - flagsum += ((*it)->GetMeasurementStartedFlag() ? 1 : 0); - sum += (*it)->GetNumTotalFramesCaught(); + for (const auto& it : dataProcessor){ + flagsum += it->GetMeasurementStartedFlag(); + sum += it->GetNumTotalFramesCaught(); } - //no data processed - if (flagsum != dataProcessor.size()) return 0; - + if (flagsum != dataProcessor.size()) + return 0; + return (sum/dataProcessor.size()); } @@ -254,13 +253,13 @@ uint64_t slsReceiverImplementation::getFramesCaught() const { uint64_t sum = 0; uint32_t flagsum = 0; - for (std::vector::const_iterator it = dataProcessor.begin(); it != dataProcessor.end(); ++it) { - flagsum += ((*it)->GetAcquisitionStartedFlag() ? 1 : 0); - sum += (*it)->GetNumFramesCaught(); + for (const auto& it : dataProcessor){ + flagsum += it->GetMeasurementStartedFlag(); + sum += it->GetNumFramesCaught(); } - //no data processed - if (flagsum != dataProcessor.size()) return 0; + if (flagsum != dataProcessor.size()) + return 0; return (sum/dataProcessor.size()); } @@ -269,13 +268,13 @@ int64_t slsReceiverImplementation::getAcquisitionIndex() const { uint64_t sum = 0; uint32_t flagsum = 0; - for (std::vector::const_iterator it = dataProcessor.begin(); it != dataProcessor.end(); ++it){ - flagsum += ((*it)->GetAcquisitionStartedFlag() ? 1 : 0); - sum += (*it)->GetActualProcessedAcquisitionIndex(); + for (const auto& it : dataProcessor){ + flagsum += it->GetMeasurementStartedFlag(); + sum += it->GetActualProcessedAcquisitionIndex(); } - //no data processed - if (flagsum != dataProcessor.size()) return -1; + if (flagsum != dataProcessor.size()) + return -1; return (sum/dataProcessor.size()); } From b5a2c91873383dbf308c5bf53ba488f855dbaf59 Mon Sep 17 00:00:00 2001 From: Erik Frojdh Date: Tue, 16 Oct 2018 15:50:51 +0200 Subject: [PATCH 04/18] removed printf with same source and dest --- slsReceiverSoftware/src/slsReceiverImplementation.cpp | 9 ++++----- 1 file changed, 4 insertions(+), 5 deletions(-) diff --git a/slsReceiverSoftware/src/slsReceiverImplementation.cpp b/slsReceiverSoftware/src/slsReceiverImplementation.cpp index f5b5a9002..afc8c9f31 100644 --- a/slsReceiverSoftware/src/slsReceiverImplementation.cpp +++ b/slsReceiverSoftware/src/slsReceiverImplementation.cpp @@ -442,18 +442,17 @@ void slsReceiverImplementation::setDetectorHostname(const char *c){ void slsReceiverImplementation::setMultiDetectorSize(const int* size) { FILE_LOG(logDEBUG) << __AT__ << " starting"; - char message[100]; - strcpy(message, "Detector Size: ("); + std::string message = "Detector Size: ("; for (int i = 0; i < MAX_DIMENSIONS; ++i) { if (myDetectorType == EIGER && (!i)) numDet[i] = size[i]*2; else numDet[i] = size[i]; - sprintf(message,"%s%d",message,numDet[i]); + message += std::to_string(numDet[i]); if (i < MAX_DIMENSIONS-1 ) - strcat(message,","); + message += ", "; } - strcat(message,")"); + message += ")"; FILE_LOG(logINFO) << message; } From b50d359ee6a40340cc5f61b15d2e55a9671ac537 Mon Sep 17 00:00:00 2001 From: Erik Frojdh Date: Tue, 16 Oct 2018 15:53:01 +0200 Subject: [PATCH 05/18] better name --- slsReceiverSoftware/src/slsReceiverImplementation.cpp | 10 +++++----- 1 file changed, 5 insertions(+), 5 deletions(-) diff --git a/slsReceiverSoftware/src/slsReceiverImplementation.cpp b/slsReceiverSoftware/src/slsReceiverImplementation.cpp index afc8c9f31..189994a82 100644 --- a/slsReceiverSoftware/src/slsReceiverImplementation.cpp +++ b/slsReceiverSoftware/src/slsReceiverImplementation.cpp @@ -442,18 +442,18 @@ void slsReceiverImplementation::setDetectorHostname(const char *c){ void slsReceiverImplementation::setMultiDetectorSize(const int* size) { FILE_LOG(logDEBUG) << __AT__ << " starting"; - std::string message = "Detector Size: ("; + std::string log_message = "Detector Size: ("; for (int i = 0; i < MAX_DIMENSIONS; ++i) { if (myDetectorType == EIGER && (!i)) numDet[i] = size[i]*2; else numDet[i] = size[i]; - message += std::to_string(numDet[i]); + log_message += std::to_string(numDet[i]); if (i < MAX_DIMENSIONS-1 ) - message += ", "; + log_message += ", "; } - message += ")"; - FILE_LOG(logINFO) << message; + log_message += ")"; + FILE_LOG(logINFO) << log_message; } From 014dfaa251e7c68c13a0cd79d33172ba433bb766 Mon Sep 17 00:00:00 2001 From: Erik Frojdh Date: Tue, 16 Oct 2018 17:30:43 +0200 Subject: [PATCH 06/18] moved to vector of unique pointer in slsReceiverImplementation --- slsReceiverSoftware/include/DataProcessor.h | 4 +- slsReceiverSoftware/include/DataStreamer.h | 4 +- slsReceiverSoftware/include/Listener.h | 4 +- .../include/slsReceiverImplementation.h | 11 +- slsReceiverSoftware/src/DataProcessor.cpp | 4 +- slsReceiverSoftware/src/DataStreamer.cpp | 4 +- slsReceiverSoftware/src/Listener.cpp | 4 +- slsReceiverSoftware/src/main.cpp | 2 +- .../src/slsReceiverImplementation.cpp | 205 ++++++++++-------- slsSupportLib/include/container_utils.h | 4 +- 10 files changed, 133 insertions(+), 113 deletions(-) diff --git a/slsReceiverSoftware/include/DataProcessor.h b/slsReceiverSoftware/include/DataProcessor.h index 6e26f427d..8d259d752 100644 --- a/slsReceiverSoftware/include/DataProcessor.h +++ b/slsReceiverSoftware/include/DataProcessor.h @@ -42,7 +42,7 @@ class DataProcessor : private virtual slsDetectorDefs, public ThreadObject { * @param dataModifyReadycb pointer to data ready call back function with modified * @param pDataReadycb pointer to arguments of data ready call back function. To write/stream a smaller size of processed data, change this value (only smaller value is allowed). */ - DataProcessor(int ind, detectorType dtype, Fifo*& f, fileFormat* ftype, + DataProcessor(int ind, detectorType dtype, Fifo* f, fileFormat* ftype, bool fwenable, bool* dsEnable, bool* gpEnable, uint32_t* dr, uint32_t* freq, uint32_t* timer, bool* fp, bool* act, bool* depaden, bool* sm, @@ -121,7 +121,7 @@ class DataProcessor : private virtual slsDetectorDefs, public ThreadObject { * Set Fifo pointer to the one given * @param f address of Fifo pointer */ - void SetFifo(Fifo*& f); + void SetFifo(Fifo* f); /** * Reset parameters for new acquisition (including all scans) diff --git a/slsReceiverSoftware/include/DataStreamer.h b/slsReceiverSoftware/include/DataStreamer.h index 834b95f08..8f5720490 100644 --- a/slsReceiverSoftware/include/DataStreamer.h +++ b/slsReceiverSoftware/include/DataStreamer.h @@ -31,7 +31,7 @@ class DataStreamer : private virtual slsDetectorDefs, public ThreadObject { * @param ajh additional json header * @param sm pointer to silent mode */ - DataStreamer(int ind, Fifo*& f, uint32_t* dr, std::vector* r, + DataStreamer(int ind, Fifo* f, uint32_t* dr, std::vector* r, uint64_t* fi, int* fd, char* ajh, bool* sm); /** @@ -63,7 +63,7 @@ class DataStreamer : private virtual slsDetectorDefs, public ThreadObject { * Set Fifo pointer to the one given * @param f address of Fifo pointer */ - void SetFifo(Fifo*& f); + void SetFifo(Fifo* f); /** * Reset parameters for new acquisition (including all scans) diff --git a/slsReceiverSoftware/include/Listener.h b/slsReceiverSoftware/include/Listener.h index da8280a1c..f57f9e263 100644 --- a/slsReceiverSoftware/include/Listener.h +++ b/slsReceiverSoftware/include/Listener.h @@ -37,7 +37,7 @@ class Listener : private virtual slsDetectorDefs, public ThreadObject { * @param depaden pointer to deactivated padding enable * @param sm pointer to silent mode */ - Listener(int ind, detectorType dtype, Fifo*& f, runStatus* s, + Listener(int ind, detectorType dtype, Fifo* f, runStatus* s, uint32_t* portno, char* e, uint64_t* nf, uint32_t* dr, uint32_t* us, uint32_t* as, uint32_t* fpf, frameDiscardPolicy* fdp, bool* act, bool* depaden, bool* sm); @@ -96,7 +96,7 @@ class Listener : private virtual slsDetectorDefs, public ThreadObject { * Set Fifo pointer to the one given * @param f address of Fifo pointer */ - void SetFifo(Fifo*& f); + void SetFifo(Fifo* f); /** * Reset parameters for new acquisition (including all scans) diff --git a/slsReceiverSoftware/include/slsReceiverImplementation.h b/slsReceiverSoftware/include/slsReceiverImplementation.h index b57176962..fcbb298d9 100644 --- a/slsReceiverSoftware/include/slsReceiverImplementation.h +++ b/slsReceiverSoftware/include/slsReceiverImplementation.h @@ -9,7 +9,7 @@ #include "sls_detector_defs.h" #include "receiver_defs.h" #include "logger.h" - +#include "container_utils.h" class GeneralData; class Listener; class DataProcessor; @@ -18,6 +18,7 @@ class Fifo; #include #include +#include class slsReceiverImplementation: private virtual slsDetectorDefs { public: @@ -832,13 +833,13 @@ private: /** General Data Properties */ GeneralData* generalData; /** Listener Objects that listen to UDP and push into fifo */ - std::vector listener; + std::vector> listener; /** DataProcessor Objects that pull from fifo and process data */ - std::vector dataProcessor; + std::vector> dataProcessor; /** DataStreamer Objects that stream data via ZMQ */ - std::vector dataStreamer; + std::vector> dataStreamer; /** Fifo Structure to store addresses of memory writes */ - std::vector fifo; + std::vector> fifo; //***callback parameters*** /** diff --git a/slsReceiverSoftware/src/DataProcessor.cpp b/slsReceiverSoftware/src/DataProcessor.cpp index bce6e0379..1855fa3a1 100644 --- a/slsReceiverSoftware/src/DataProcessor.cpp +++ b/slsReceiverSoftware/src/DataProcessor.cpp @@ -22,7 +22,7 @@ const std::string DataProcessor::TypeName = "DataProcessor"; -DataProcessor::DataProcessor(int ind, detectorType dtype, Fifo*& f, +DataProcessor::DataProcessor(int ind, detectorType dtype, Fifo* f, fileFormat* ftype, bool fwenable, bool* dsEnable, bool* gpEnable, uint32_t* dr, uint32_t* freq, uint32_t* timer, @@ -125,7 +125,7 @@ void DataProcessor::StopRunning() { runningFlag = false; } -void DataProcessor::SetFifo(Fifo*& f) { +void DataProcessor::SetFifo(Fifo* f) { fifo = f; } diff --git a/slsReceiverSoftware/src/DataStreamer.cpp b/slsReceiverSoftware/src/DataStreamer.cpp index fee9fca24..bb1f6a23d 100644 --- a/slsReceiverSoftware/src/DataStreamer.cpp +++ b/slsReceiverSoftware/src/DataStreamer.cpp @@ -15,7 +15,7 @@ const std::string DataStreamer::TypeName = "DataStreamer"; -DataStreamer::DataStreamer(int ind, Fifo*& f, uint32_t* dr, std::vector* r, +DataStreamer::DataStreamer(int ind, Fifo* f, uint32_t* dr, std::vector* r, uint64_t* fi, int* fd, char* ajh, bool* sm) : ThreadObject(ind), runningFlag(0), @@ -70,7 +70,7 @@ void DataStreamer::StopRunning() { runningFlag = false; } -void DataStreamer::SetFifo(Fifo*& f) { +void DataStreamer::SetFifo(Fifo* f) { fifo = f; } diff --git a/slsReceiverSoftware/src/Listener.cpp b/slsReceiverSoftware/src/Listener.cpp index b28b86377..8e1c05ecf 100644 --- a/slsReceiverSoftware/src/Listener.cpp +++ b/slsReceiverSoftware/src/Listener.cpp @@ -18,7 +18,7 @@ const std::string Listener::TypeName = "Listener"; -Listener::Listener(int ind, detectorType dtype, Fifo*& f, runStatus* s, +Listener::Listener(int ind, detectorType dtype, Fifo* f, runStatus* s, uint32_t* portno, char* e, uint64_t* nf, uint32_t* dr, uint32_t* us, uint32_t* as, uint32_t* fpf, frameDiscardPolicy* fdp, bool* act, bool* depaden, bool* sm) : @@ -108,7 +108,7 @@ void Listener::StopRunning() { } -void Listener::SetFifo(Fifo*& f) { +void Listener::SetFifo(Fifo* f) { fifo = f; } diff --git a/slsReceiverSoftware/src/main.cpp b/slsReceiverSoftware/src/main.cpp index 500c01748..aea006a59 100644 --- a/slsReceiverSoftware/src/main.cpp +++ b/slsReceiverSoftware/src/main.cpp @@ -153,7 +153,7 @@ int main(int argc, char *argv[]) { delete receiver; cprintf(BLUE,"Exiting [ Tid: %ld ]\n", (long)syscall(SYS_gettid)); - FILE_LOG(logINFO) << "Goodbye!"; + // FILE_LOG(logINFO) << "Goodbye!"; return 0; } diff --git a/slsReceiverSoftware/src/slsReceiverImplementation.cpp b/slsReceiverSoftware/src/slsReceiverImplementation.cpp index 189994a82..f5a16fa0e 100644 --- a/slsReceiverSoftware/src/slsReceiverImplementation.cpp +++ b/slsReceiverSoftware/src/slsReceiverImplementation.cpp @@ -39,20 +39,9 @@ void slsReceiverImplementation::DeleteMembers() { generalData=0; } - for (auto* it : listener) - delete it; listener.clear(); - - for (auto* it : dataProcessor) - delete it; dataProcessor.clear(); - - for (auto* it : dataStreamer) - delete it; dataStreamer.clear(); - - for (auto* it : fifo) - delete it; fifo.clear(); } @@ -472,8 +461,10 @@ int slsReceiverImplementation::setGapPixelsEnable(const bool b) { // side effects generalData->SetGapPixelsEnable(b, dynamicRange); // to update npixelsx, npixelsy in file writer - for (std::vector::const_iterator it = dataProcessor.begin(); it != dataProcessor.end(); ++it) - (*it)->SetPixelDimension(); + // for (std::vector::const_iterator it = dataProcessor.begin(); it != dataProcessor.end(); ++it) + // (*it)->SetPixelDimension(); + for (const auto& it : dataProcessor) + it->SetPixelDimension(); numberofJobs = -1; //changes to imagesize has to be noted to recreate fifo structure if (SetupFifoStructure() == FAIL) @@ -496,8 +487,10 @@ void slsReceiverImplementation::setFileFormat(const fileFormat f){ break; } //destroy file writer, set file format and create file writer - for (std::vector::const_iterator it = dataProcessor.begin(); it != dataProcessor.end(); ++it) - (*it)->SetFileFormat(f); + // for (std::vector::const_iterator it = dataProcessor.begin(); it != dataProcessor.end(); ++it) + // (*it)->SetFileFormat(f); + for(const auto& it : dataProcessor) + it->SetFileFormat(f); FILE_LOG(logINFO) << "File Format:" << getFileFormatType(fileFormatType); } @@ -649,12 +642,13 @@ int slsReceiverImplementation::setROI(const std::vector i) if (SetupFifoStructure() == FAIL) return FAIL; - for (std::vector::const_iterator it = listener.begin(); it != listener.end(); ++it) - (*it)->SetGeneralData(generalData); - for (std::vector::const_iterator it = dataProcessor.begin(); it != dataProcessor.end(); ++it) - (*it)->SetGeneralData(generalData); - for (std::vector::const_iterator it = dataStreamer.begin(); it != dataStreamer.end(); ++it) - (*it)->SetGeneralData(generalData); + + for (const auto& it : listener) + it->SetGeneralData(generalData); + for (const auto& it : dataProcessor) + it->SetGeneralData(generalData); + for (const auto& it : dataStreamer) + it->SetGeneralData(generalData); } @@ -699,22 +693,17 @@ int slsReceiverImplementation::setDataStreamEnable(const bool enable) { dataStreamEnable = enable; //data sockets have to be created again as the client ones are - for (std::vector::const_iterator it = dataStreamer.begin(); it != dataStreamer.end(); ++it) - delete(*it); dataStreamer.clear(); if (enable) { for ( int i = 0; i < numThreads; ++i ) { try { - DataStreamer* s = new DataStreamer(i, fifo[i], &dynamicRange, - &roi, &fileIndex, flippedData, additionalJsonHeader, &silentMode); - dataStreamer.push_back(s); + dataStreamer.push_back(sls::make_unique(i, fifo[i].get(), &dynamicRange, + &roi, &fileIndex, flippedData, additionalJsonHeader, &silentMode)); dataStreamer[i]->SetGeneralData(generalData); dataStreamer[i]->CreateZmqSockets(&numThreads, streamingPort, streamingSrcIP); } catch(...) { - for (std::vector::const_iterator it = dataStreamer.begin(); it != dataStreamer.end(); ++it) - delete(*it); dataStreamer.clear(); dataStreamEnable = false; return FAIL; @@ -817,8 +806,10 @@ int slsReceiverImplementation::setDynamicRange(const uint32_t i) { generalData->SetDynamicRange(i,tengigaEnable); generalData->SetGapPixelsEnable(gapPixelsEnable, dynamicRange); // to update npixelsx, npixelsy in file writer - for (std::vector::const_iterator it = dataProcessor.begin(); it != dataProcessor.end(); ++it) - (*it)->SetPixelDimension(); + // for (std::vector::const_iterator it = dataProcessor.begin(); it != dataProcessor.end(); ++it) + // (*it)->SetPixelDimension(); + for (const auto& it : dataProcessor) + it->SetPixelDimension(); numberofJobs = -1; //changes to imagesize has to be noted to recreate fifo structure if (SetupFifoStructure() == FAIL) @@ -937,37 +928,31 @@ int slsReceiverImplementation::setDetectorType(const detectorType d) { for ( int i = 0; i < numThreads; ++i ) { try { - Listener* l = new Listener(i, myDetectorType, fifo[i], &status, + auto fifo_ptr = fifo[i].get(); + listener.push_back(sls::make_unique(i, myDetectorType, fifo_ptr, &status, &udpPortNum[i], eth, &numberOfFrames, &dynamicRange, &udpSocketBufferSize, &actualUDPSocketBufferSize, &framesPerFile, - &frameDiscardMode, &activated, &deactivatedPaddingEnable, &silentMode); - listener.push_back(l); - - DataProcessor* p = new DataProcessor(i, myDetectorType, fifo[i], &fileFormatType, + &frameDiscardMode, &activated, &deactivatedPaddingEnable, &silentMode)); + dataProcessor.push_back(sls::make_unique(i, myDetectorType, fifo_ptr, &fileFormatType, fileWriteEnable, &dataStreamEnable, &gapPixelsEnable, &dynamicRange, &streamingFrequency, &streamingTimerInMs, &framePadding, &activated, &deactivatedPaddingEnable, &silentMode, - rawDataReadyCallBack, rawDataModifyReadyCallBack, pRawDataReady); - dataProcessor.push_back(p); + rawDataReadyCallBack, rawDataModifyReadyCallBack, pRawDataReady)); } catch (...) { FILE_LOG(logERROR) << "Could not create listener/dataprocessor threads (index:" << i << ")"; - for (std::vector::const_iterator it = listener.begin(); it != listener.end(); ++it) - delete(*it); listener.clear(); - for (std::vector::const_iterator it = dataProcessor.begin(); it != dataProcessor.end(); ++it) - delete(*it); dataProcessor.clear(); return FAIL; } } //set up writer and callbacks - for (std::vector::const_iterator it = listener.begin(); it != listener.end(); ++it) - (*it)->SetGeneralData(generalData); - for (std::vector::const_iterator it = dataProcessor.begin(); it != dataProcessor.end(); ++it) - (*it)->SetGeneralData(generalData); + for (const auto& it : listener) + it->SetGeneralData(generalData); + for (const auto& it : dataProcessor) + it->SetGeneralData(generalData); SetThreadPriorities(); // check udp socket buffer size @@ -1069,12 +1054,19 @@ void slsReceiverImplementation::stopReceiver(){ bool running = true; while(running) { running = false; - for (std::vector::const_iterator it = listener.begin(); it != listener.end(); ++it) - if ((*it)->IsRunning()) - running = true; - for (std::vector::const_iterator it = dataProcessor.begin(); it != dataProcessor.end(); ++it) - if ((*it)->IsRunning()) - running = true; + // for (std::vector::const_iterator it = listener.begin(); it != listener.end(); ++it) + // if ((*it)->IsRunning()) + // running = true; + for (const auto& it : listener) + if (it->IsRunning()) + running = true; + + // for (std::vector::const_iterator it = dataProcessor.begin(); it != dataProcessor.end(); ++it) + // if ((*it)->IsRunning()) + // running = true; + for (const auto& it : dataProcessor) + if (it->IsRunning()) + running = true; usleep(5000); } @@ -1083,9 +1075,14 @@ void slsReceiverImplementation::stopReceiver(){ if (fileWriteEnable && fileFormatType == HDF5) { uint64_t maxIndexCaught = 0; bool anycaught = false; - for (std::vector::const_iterator it = dataProcessor.begin(); it != dataProcessor.end(); ++it) { - maxIndexCaught = std::max(maxIndexCaught, (*it)->GetProcessedMeasurementIndex()); - if((*it)->GetMeasurementStartedFlag()) + // for (std::vector::const_iterator it = dataProcessor.begin(); it != dataProcessor.end(); ++it) { + // maxIndexCaught = std::max(maxIndexCaught, (*it)->GetProcessedMeasurementIndex()); + // if((*it)->GetMeasurementStartedFlag()) + // anycaught = true; + // } + for (const auto& it : dataProcessor) { + maxIndexCaught = std::max(maxIndexCaught, it->GetProcessedMeasurementIndex()); + if(it->GetMeasurementStartedFlag()) anycaught = true; } //to create virtual file & set files/acquisition to 0 (only hdf5 at the moment) @@ -1096,9 +1093,12 @@ void slsReceiverImplementation::stopReceiver(){ running = true; while(running) { running = false; - for (std::vector::const_iterator it = dataStreamer.begin(); it != dataStreamer.end(); ++it) - if ((*it)->IsRunning()) - running = true; + // for (std::vector::const_iterator it = dataStreamer.begin(); it != dataStreamer.end(); ++it) + // if ((*it)->IsRunning()) + // running = true; + for (const auto& it : dataStreamer) + if (it->IsRunning()) + running = true; usleep(5000); } @@ -1176,8 +1176,10 @@ void slsReceiverImplementation::startReadout(){ void slsReceiverImplementation::shutDownUDPSockets() { - for (std::vector::const_iterator it = listener.begin(); it != listener.end(); ++it) - (*it)->ShutDownUDPSocket(); + // for (std::vector::const_iterator it = listener.begin(); it != listener.end(); ++it) + // (*it)->ShutDownUDPSocket(); + for (const auto& it : listener) + it->ShutDownUDPSocket(); } @@ -1185,10 +1187,16 @@ void slsReceiverImplementation::shutDownUDPSockets() { void slsReceiverImplementation::closeFiles() { uint64_t maxIndexCaught = 0; bool anycaught = false; - for (std::vector::const_iterator it = dataProcessor.begin(); it != dataProcessor.end(); ++it) { - (*it)->CloseFiles(); - maxIndexCaught = std::max(maxIndexCaught, (*it)->GetProcessedMeasurementIndex()); - if((*it)->GetMeasurementStartedFlag()) + // for (std::vector::const_iterator it = dataProcessor.begin(); it != dataProcessor.end(); ++it) { + // (*it)->CloseFiles(); + // maxIndexCaught = std::max(maxIndexCaught, (*it)->GetProcessedMeasurementIndex()); + // if((*it)->GetMeasurementStartedFlag()) + // anycaught = true; + // } + for (const auto& it : dataProcessor) { + it->CloseFiles(); + maxIndexCaught = std::max(maxIndexCaught, it->GetProcessedMeasurementIndex()); + if(it->GetMeasurementStartedFlag()) anycaught = true; } //to create virtual file & set files/acquisition to 0 (only hdf5 at the moment) @@ -1198,11 +1206,14 @@ void slsReceiverImplementation::closeFiles() { int slsReceiverImplementation::restreamStop() { bool ret = OK; - for (std::vector::const_iterator it = dataStreamer.begin(); it != dataStreamer.end(); ++it) { - if ((*it)->RestreamStop() == FAIL) + // for (std::vector::const_iterator it = dataStreamer.begin(); it != dataStreamer.end(); ++it) { + // if ((*it)->RestreamStop() == FAIL) + // ret = FAIL; + // } + for (const auto& it : dataStreamer){ + if (it->RestreamStop() == FAIL) ret = FAIL; } - // if fail, prints in datastreamer if (ret == OK) { FILE_LOG(logINFO) << "Restreaming Dummy Header via ZMQ successful"; @@ -1266,8 +1277,14 @@ void slsReceiverImplementation::SetLocalNetworkParameters() { void slsReceiverImplementation::SetThreadPriorities() { - for (std::vector::const_iterator it = listener.begin(); it != listener.end(); ++it){ - if ((*it)->SetThreadPriority(LISTENER_PRIORITY) == FAIL) { + // for (std::vector::const_iterator it = listener.begin(); it != listener.end(); ++it){ + // if ((*it)->SetThreadPriority(LISTENER_PRIORITY) == FAIL) { + // FILE_LOG(logWARNING) << "Could not prioritize listener threads. (No Root Privileges?)"; + // return; + // } + // } + for (const auto& it : listener){ + if (it->SetThreadPriority(LISTENER_PRIORITY) == FAIL) { FILE_LOG(logWARNING) << "Could not prioritize listener threads. (No Root Privileges?)"; return; } @@ -1283,29 +1300,27 @@ void slsReceiverImplementation::SetThreadPriorities() { int slsReceiverImplementation::SetupFifoStructure() { numberofJobs = 1; - - for (std::vector::const_iterator it = fifo.begin(); it != fifo.end(); ++it) - delete(*it); fifo.clear(); for ( int i = 0; i < numThreads; ++i ) { //create fifo structure try { - Fifo* f = new Fifo (i, + // Fifo* f = new Fifo (i, + // (generalData->imageSize) * numberofJobs + (generalData->fifoBufferHeaderSize), + // fifoDepth); + // fifo.push_back(f); + fifo.push_back(sls::make_unique(i, (generalData->imageSize) * numberofJobs + (generalData->fifoBufferHeaderSize), - fifoDepth); - fifo.push_back(f); + fifoDepth)); } catch (...) { cprintf(RED,"Error: Could not allocate memory for fifo structure of index %d\n", i); - for (std::vector::const_iterator it = fifo.begin(); it != fifo.end(); ++it) - delete(*it); fifo.clear(); return FAIL; } //set the listener & dataprocessor threads to point to the right fifo - if(listener.size())listener[i]->SetFifo(fifo[i]); - if(dataProcessor.size())dataProcessor[i]->SetFifo(fifo[i]); - if(dataStreamer.size())dataStreamer[i]->SetFifo(fifo[i]); + if(listener.size())listener[i]->SetFifo(fifo[i].get()); + if(dataProcessor.size())dataProcessor[i]->SetFifo(fifo[i].get()); + if(dataStreamer.size())dataStreamer[i]->SetFifo(fifo[i].get()); } FILE_LOG(logINFO) << "Memory Allocated Per Fifo: " << ( ((generalData->imageSize) * numberofJobs + (generalData->fifoBufferHeaderSize)) * fifoDepth) << " bytes" ; @@ -1316,16 +1331,18 @@ int slsReceiverImplementation::SetupFifoStructure() { void slsReceiverImplementation::ResetParametersforNewMeasurement() { - for (std::vector::const_iterator it = listener.begin(); it != listener.end(); ++it) - (*it)->ResetParametersforNewMeasurement(); - for (std::vector::const_iterator it = dataProcessor.begin(); it != dataProcessor.end(); ++it) - (*it)->ResetParametersforNewMeasurement(); + for (const auto& it : listener) + it->ResetParametersforNewMeasurement(); + for (const auto& it : dataProcessor) + it->ResetParametersforNewMeasurement(); if (dataStreamEnable) { char fnametostream[MAX_STR_LENGTH]; snprintf(fnametostream, MAX_STR_LENGTH, "%s/%s", filePath, fileName); - for (std::vector::const_iterator it = dataStreamer.begin(); it != dataStreamer.end(); ++it) - (*it)->ResetParametersforNewMeasurement(fnametostream); + // for (std::vector::const_iterator it = dataStreamer.begin(); it != dataStreamer.end(); ++it) + // (*it)->ResetParametersforNewMeasurement(fnametostream); + for (const auto& it : dataStreamer) + it->ResetParametersforNewMeasurement(fnametostream); } } @@ -1368,16 +1385,16 @@ int slsReceiverImplementation::SetupWriter() { void slsReceiverImplementation::StartRunning() { //set running mask and post semaphore to start the inner loop in execution thread - for (std::vector::const_iterator it = listener.begin(); it != listener.end(); ++it) { - (*it)->StartRunning(); - (*it)->Continue(); + for (const auto& it : listener){ + it->StartRunning(); + it->Continue(); } - for (std::vector::const_iterator it = dataProcessor.begin(); it != dataProcessor.end(); ++it){ - (*it)->StartRunning(); - (*it)->Continue(); + for (const auto& it : dataProcessor){ + it->StartRunning(); + it->Continue(); } - for (std::vector::const_iterator it = dataStreamer.begin(); it != dataStreamer.end(); ++it){ - (*it)->StartRunning(); - (*it)->Continue(); + for (const auto& it : dataStreamer){ + it->StartRunning(); + it->Continue(); } } diff --git a/slsSupportLib/include/container_utils.h b/slsSupportLib/include/container_utils.h index 66a5d3911..5bdd50046 100644 --- a/slsSupportLib/include/container_utils.h +++ b/slsSupportLib/include/container_utils.h @@ -99,6 +99,7 @@ T minusOneIfDifferent(const std::vector& container) } //TODO!(Erik)Should try to move away from using this in the slsDetectorPackage +inline std::string concatenateIfDifferent(std::vector container) { if (allEqual(container)) { @@ -110,7 +111,7 @@ std::string concatenateIfDifferent(std::vector container) return result; } } - +inline std::vector split(const std::string& strToSplit, char delimeter) { std::stringstream ss(strToSplit); @@ -122,6 +123,7 @@ std::vector split(const std::string& strToSplit, char delimeter) return splittedStrings; } +inline std::string concatenateNonEmptyStrings(const std::vector& vec){ std::string ret; for (const auto& s : vec) From 42c4e3e1a168fda0af198ca400e62393ded4e22f Mon Sep 17 00:00:00 2001 From: Erik Frojdh Date: Tue, 16 Oct 2018 17:47:48 +0200 Subject: [PATCH 07/18] cleanup --- .../src/slsReceiverImplementation.cpp | 50 ++----------------- 1 file changed, 3 insertions(+), 47 deletions(-) diff --git a/slsReceiverSoftware/src/slsReceiverImplementation.cpp b/slsReceiverSoftware/src/slsReceiverImplementation.cpp index f5a16fa0e..78616755d 100644 --- a/slsReceiverSoftware/src/slsReceiverImplementation.cpp +++ b/slsReceiverSoftware/src/slsReceiverImplementation.cpp @@ -448,7 +448,8 @@ void slsReceiverImplementation::setMultiDetectorSize(const int* size) { void slsReceiverImplementation::setFlippedData(int axis, int enable){ FILE_LOG(logDEBUG) << __AT__ << " starting"; - if(axis<0 || axis>1) return; + if(axis<0 || axis>1) + return; flippedData[axis] = enable==0?0:1; FILE_LOG(logINFO) << "Flipped Data: " << flippedData[0] << " , " << flippedData[1]; } @@ -460,9 +461,6 @@ int slsReceiverImplementation::setGapPixelsEnable(const bool b) { // side effects generalData->SetGapPixelsEnable(b, dynamicRange); - // to update npixelsx, npixelsy in file writer - // for (std::vector::const_iterator it = dataProcessor.begin(); it != dataProcessor.end(); ++it) - // (*it)->SetPixelDimension(); for (const auto& it : dataProcessor) it->SetPixelDimension(); @@ -486,9 +484,7 @@ void slsReceiverImplementation::setFileFormat(const fileFormat f){ fileFormatType = BINARY; break; } - //destroy file writer, set file format and create file writer - // for (std::vector::const_iterator it = dataProcessor.begin(); it != dataProcessor.end(); ++it) - // (*it)->SetFileFormat(f); + for(const auto& it : dataProcessor) it->SetFileFormat(f); @@ -806,8 +802,6 @@ int slsReceiverImplementation::setDynamicRange(const uint32_t i) { generalData->SetDynamicRange(i,tengigaEnable); generalData->SetGapPixelsEnable(gapPixelsEnable, dynamicRange); // to update npixelsx, npixelsy in file writer - // for (std::vector::const_iterator it = dataProcessor.begin(); it != dataProcessor.end(); ++it) - // (*it)->SetPixelDimension(); for (const auto& it : dataProcessor) it->SetPixelDimension(); @@ -1054,16 +1048,10 @@ void slsReceiverImplementation::stopReceiver(){ bool running = true; while(running) { running = false; - // for (std::vector::const_iterator it = listener.begin(); it != listener.end(); ++it) - // if ((*it)->IsRunning()) - // running = true; for (const auto& it : listener) if (it->IsRunning()) running = true; - // for (std::vector::const_iterator it = dataProcessor.begin(); it != dataProcessor.end(); ++it) - // if ((*it)->IsRunning()) - // running = true; for (const auto& it : dataProcessor) if (it->IsRunning()) running = true; @@ -1075,11 +1063,6 @@ void slsReceiverImplementation::stopReceiver(){ if (fileWriteEnable && fileFormatType == HDF5) { uint64_t maxIndexCaught = 0; bool anycaught = false; - // for (std::vector::const_iterator it = dataProcessor.begin(); it != dataProcessor.end(); ++it) { - // maxIndexCaught = std::max(maxIndexCaught, (*it)->GetProcessedMeasurementIndex()); - // if((*it)->GetMeasurementStartedFlag()) - // anycaught = true; - // } for (const auto& it : dataProcessor) { maxIndexCaught = std::max(maxIndexCaught, it->GetProcessedMeasurementIndex()); if(it->GetMeasurementStartedFlag()) @@ -1093,9 +1076,6 @@ void slsReceiverImplementation::stopReceiver(){ running = true; while(running) { running = false; - // for (std::vector::const_iterator it = dataStreamer.begin(); it != dataStreamer.end(); ++it) - // if ((*it)->IsRunning()) - // running = true; for (const auto& it : dataStreamer) if (it->IsRunning()) running = true; @@ -1176,8 +1156,6 @@ void slsReceiverImplementation::startReadout(){ void slsReceiverImplementation::shutDownUDPSockets() { - // for (std::vector::const_iterator it = listener.begin(); it != listener.end(); ++it) - // (*it)->ShutDownUDPSocket(); for (const auto& it : listener) it->ShutDownUDPSocket(); } @@ -1187,12 +1165,6 @@ void slsReceiverImplementation::shutDownUDPSockets() { void slsReceiverImplementation::closeFiles() { uint64_t maxIndexCaught = 0; bool anycaught = false; - // for (std::vector::const_iterator it = dataProcessor.begin(); it != dataProcessor.end(); ++it) { - // (*it)->CloseFiles(); - // maxIndexCaught = std::max(maxIndexCaught, (*it)->GetProcessedMeasurementIndex()); - // if((*it)->GetMeasurementStartedFlag()) - // anycaught = true; - // } for (const auto& it : dataProcessor) { it->CloseFiles(); maxIndexCaught = std::max(maxIndexCaught, it->GetProcessedMeasurementIndex()); @@ -1206,10 +1178,6 @@ void slsReceiverImplementation::closeFiles() { int slsReceiverImplementation::restreamStop() { bool ret = OK; - // for (std::vector::const_iterator it = dataStreamer.begin(); it != dataStreamer.end(); ++it) { - // if ((*it)->RestreamStop() == FAIL) - // ret = FAIL; - // } for (const auto& it : dataStreamer){ if (it->RestreamStop() == FAIL) ret = FAIL; @@ -1277,12 +1245,6 @@ void slsReceiverImplementation::SetLocalNetworkParameters() { void slsReceiverImplementation::SetThreadPriorities() { - // for (std::vector::const_iterator it = listener.begin(); it != listener.end(); ++it){ - // if ((*it)->SetThreadPriority(LISTENER_PRIORITY) == FAIL) { - // FILE_LOG(logWARNING) << "Could not prioritize listener threads. (No Root Privileges?)"; - // return; - // } - // } for (const auto& it : listener){ if (it->SetThreadPriority(LISTENER_PRIORITY) == FAIL) { FILE_LOG(logWARNING) << "Could not prioritize listener threads. (No Root Privileges?)"; @@ -1305,10 +1267,6 @@ int slsReceiverImplementation::SetupFifoStructure() { //create fifo structure try { - // Fifo* f = new Fifo (i, - // (generalData->imageSize) * numberofJobs + (generalData->fifoBufferHeaderSize), - // fifoDepth); - // fifo.push_back(f); fifo.push_back(sls::make_unique(i, (generalData->imageSize) * numberofJobs + (generalData->fifoBufferHeaderSize), fifoDepth)); @@ -1339,8 +1297,6 @@ void slsReceiverImplementation::ResetParametersforNewMeasurement() { if (dataStreamEnable) { char fnametostream[MAX_STR_LENGTH]; snprintf(fnametostream, MAX_STR_LENGTH, "%s/%s", filePath, fileName); - // for (std::vector::const_iterator it = dataStreamer.begin(); it != dataStreamer.end(); ++it) - // (*it)->ResetParametersforNewMeasurement(fnametostream); for (const auto& it : dataStreamer) it->ResetParametersforNewMeasurement(fnametostream); } From 5c2ff84c0ec531d8aa84f102930bdc3bb1b69ad0 Mon Sep 17 00:00:00 2001 From: Erik Frojdh Date: Wed, 17 Oct 2018 11:39:27 +0200 Subject: [PATCH 08/18] removed unused variable numberofJobs in receiver implementation --- .../include/slsReceiverImplementation.h | 2 -- .../src/slsReceiverImplementation.cpp | 27 +++---------------- 2 files changed, 3 insertions(+), 26 deletions(-) diff --git a/slsReceiverSoftware/include/slsReceiverImplementation.h b/slsReceiverSoftware/include/slsReceiverImplementation.h index fcbb298d9..d512210c3 100644 --- a/slsReceiverSoftware/include/slsReceiverImplementation.h +++ b/slsReceiverSoftware/include/slsReceiverImplementation.h @@ -768,8 +768,6 @@ private: //*** receiver parameters *** /** Number of Threads */ int numThreads; - /** Number of Jobs */ - int numberofJobs; /** Number of channels in roi for jungfrauctb */ uint32_t nroichannels; /** Maximum Number of Listening Threads/ UDP Ports */ diff --git a/slsReceiverSoftware/src/slsReceiverImplementation.cpp b/slsReceiverSoftware/src/slsReceiverImplementation.cpp index 78616755d..59dc14f84 100644 --- a/slsReceiverSoftware/src/slsReceiverImplementation.cpp +++ b/slsReceiverSoftware/src/slsReceiverImplementation.cpp @@ -69,7 +69,6 @@ void slsReceiverImplementation::InitializeMembers() { //*** receiver parameters *** numThreads = 1; - numberofJobs = 1; nroichannels = 0; status = IDLE; activated = true; @@ -463,8 +462,6 @@ int slsReceiverImplementation::setGapPixelsEnable(const bool b) { generalData->SetGapPixelsEnable(b, dynamicRange); for (const auto& it : dataProcessor) it->SetPixelDimension(); - - numberofJobs = -1; //changes to imagesize has to be noted to recreate fifo structure if (SetupFifoStructure() == FAIL) return FAIL; } @@ -633,12 +630,9 @@ int slsReceiverImplementation::setROI(const std::vector i) generalData->SetROI(i); framesPerFile = generalData->maxFramesPerFile; - - numberofJobs = -1; //changes to imagesize has to be noted to recreate fifo structure if (SetupFifoStructure() == FAIL) return FAIL; - for (const auto& it : listener) it->SetGeneralData(generalData); for (const auto& it : dataProcessor) @@ -784,7 +778,6 @@ int slsReceiverImplementation::setNumberofSamples(const uint64_t i) { numberOfSamples = i; generalData->setNumberofSamples(i, nroichannels); - numberofJobs = -1; //changes to imagesize has to be noted to recreate fifo structure if (SetupFifoStructure() == FAIL) return FAIL; } @@ -797,15 +790,11 @@ int slsReceiverImplementation::setNumberofSamples(const uint64_t i) { int slsReceiverImplementation::setDynamicRange(const uint32_t i) { if (dynamicRange != i) { dynamicRange = i; - - //side effects generalData->SetDynamicRange(i,tengigaEnable); generalData->SetGapPixelsEnable(gapPixelsEnable, dynamicRange); // to update npixelsx, npixelsy in file writer for (const auto& it : dataProcessor) it->SetPixelDimension(); - - numberofJobs = -1; //changes to imagesize has to be noted to recreate fifo structure if (SetupFifoStructure() == FAIL) return FAIL; } @@ -819,8 +808,6 @@ int slsReceiverImplementation::setTenGigaEnable(const bool b) { tengigaEnable = b; //side effects generalData->SetTenGigaEnable(b,dynamicRange); - - numberofJobs = -1; //changes to imagesize has to be noted to recreate fifo structure if (SetupFifoStructure() == FAIL) return FAIL; } @@ -832,8 +819,6 @@ int slsReceiverImplementation::setTenGigaEnable(const bool b) { int slsReceiverImplementation::setFifoDepth(const uint32_t i) { if (fifoDepth != i) { fifoDepth = i; - - numberofJobs = -1; //changes to imagesize has to be noted to recreate fifo structure if (SetupFifoStructure() == FAIL) return FAIL; } @@ -908,11 +893,7 @@ int slsReceiverImplementation::setDetectorType(const detectorType d) { udpSocketBufferSize = generalData->defaultUdpSocketBufferSize; framesPerFile = generalData->maxFramesPerFile; - //local network parameters SetLocalNetworkParameters(); - - //create fifo structure - numberofJobs = -1; if (SetupFifoStructure() == FAIL) { FILE_LOG(logERROR) << "Could not allocate memory for fifo structure"; return FAIL; @@ -1007,7 +988,7 @@ int slsReceiverImplementation::startReceiver(char *c) { //callbacks if (startAcquisitionCallBack) { startAcquisitionCallBack(filePath, fileName, fileIndex, - (generalData->imageSize) * numberofJobs + (generalData->fifoBufferHeaderSize), pStartAcquisition); + (generalData->imageSize) + (generalData->fifoBufferHeaderSize), pStartAcquisition); if (rawDataReadyCallBack != NULL) { FILE_LOG(logINFO) << "Data Write has been defined externally"; } @@ -1260,15 +1241,13 @@ void slsReceiverImplementation::SetThreadPriorities() { int slsReceiverImplementation::SetupFifoStructure() { - numberofJobs = 1; - fifo.clear(); for ( int i = 0; i < numThreads; ++i ) { //create fifo structure try { fifo.push_back(sls::make_unique(i, - (generalData->imageSize) * numberofJobs + (generalData->fifoBufferHeaderSize), + (generalData->imageSize) + (generalData->fifoBufferHeaderSize), fifoDepth)); } catch (...) { cprintf(RED,"Error: Could not allocate memory for fifo structure of index %d\n", i); @@ -1281,7 +1260,7 @@ int slsReceiverImplementation::SetupFifoStructure() { if(dataStreamer.size())dataStreamer[i]->SetFifo(fifo[i].get()); } - FILE_LOG(logINFO) << "Memory Allocated Per Fifo: " << ( ((generalData->imageSize) * numberofJobs + (generalData->fifoBufferHeaderSize)) * fifoDepth) << " bytes" ; + FILE_LOG(logINFO) << "Memory Allocated Per Fifo: " << ( ((generalData->imageSize) + (generalData->fifoBufferHeaderSize)) * fifoDepth) << " bytes" ; FILE_LOG(logINFO) << numThreads << " Fifo structure(s) reconstructed"; return OK; } From 1d65063088abc57a0e9ecf74d3f112360fa1ccfe Mon Sep 17 00:00:00 2001 From: Erik Frojdh Date: Wed, 17 Oct 2018 16:56:01 +0200 Subject: [PATCH 09/18] using std::mutex and std::thread in multi detector --- .../multiSlsDetector/multiSlsDetector.cpp | 174 +++--------------- .../multiSlsDetector/multiSlsDetector.h | 17 +- 2 files changed, 40 insertions(+), 151 deletions(-) diff --git a/slsDetectorSoftware/multiSlsDetector/multiSlsDetector.cpp b/slsDetectorSoftware/multiSlsDetector/multiSlsDetector.cpp index ae4e2f10c..1d66e1816 100644 --- a/slsDetectorSoftware/multiSlsDetector/multiSlsDetector.cpp +++ b/slsDetectorSoftware/multiSlsDetector/multiSlsDetector.cpp @@ -44,14 +44,7 @@ multiSlsDetector::multiSlsDetector(int id, bool verify, bool update) dataReady(0), pCallbackArg(0) { - pthread_mutex_t mp1 = PTHREAD_MUTEX_INITIALIZER; - mp=mp1; - pthread_mutex_init(&mp, NULL); - mg=mp1; - pthread_mutex_init(&mg, NULL); - setupMultiDetector(verify, update); - } @@ -93,20 +86,6 @@ std::vector multiSlsDetector::parallelCall(RT (slsDetector::*somefunc)(CT... return result; } - -// std::string multiSlsDetector::concatResultOrPos(std::string (slsDetector::*somefunc)(int), int pos) { -// if (pos >= 0 && pos < (int)detectors.size()) { -// return (detectors[pos].get()->*somefunc)(pos); -// } else { -// std::string s; -// for (auto& d : detectors) { -// s += (d.get()->*somefunc)(pos) + "+"; -// } -// return s; -// } -// } - - int multiSlsDetector::decodeNChannel(int offsetX, int offsetY, int& channelX, int& channelY) { channelX = -1; channelY = -1; @@ -138,7 +117,6 @@ int multiSlsDetector::decodeNChannel(int offsetX, int offsetY, int& channelX, in std::string multiSlsDetector::getErrorMessage(int& critical, int detPos) { int64_t multiMask = 0, slsMask = 0; std::string retval = ""; - // char sNumber[100]; critical = 0; size_t posmin = 0, posmax = detectors.size(); @@ -842,24 +820,18 @@ int multiSlsDetector::setOnline(int off, int detPos) { std::string multiSlsDetector::checkOnline(int detPos) { - // single - if (detPos >= 0) { + if (detPos >= 0) return detectors[detPos]->checkOnline(); - } - // multi auto r = parallelCall(&slsDetector::checkOnline); return sls::concatenateNonEmptyStrings(r); } int multiSlsDetector::setPort(portType t, int num, int detPos) { - // single - if (detPos >= 0) { + if (detPos >= 0) return detectors[detPos]->setPort(t, num); - } - - // multi + auto r = serialCall(&slsDetector::setPort, t, num); return sls::minusOneIfDifferent(r); } @@ -1194,33 +1166,20 @@ int multiSlsDetector::startAcquisition(int detPos) { int multiSlsDetector::stopAcquisition(int detPos) { - int ret = OK; - // locks to synchronize using client->receiver simultaneously (processing thread) - pthread_mutex_lock(&mg); - - // single + std::lock_guard lock(mg); if (detPos >= 0) { - // if only 1 detector, set flag to stop current acquisition if (detectors.size() == 1) thisMultiDetector->stoppedFlag = 1; - ret = detectors[detPos]->stopAcquisition(); + return detectors[detPos]->stopAcquisition(); } - - // multi else { - - // set flag to stop current acquisition thisMultiDetector->stoppedFlag = 1; - auto r = parallelCall(&slsDetector::stopAcquisition); - ret = sls::allEqualTo(r, static_cast(OK)) ? OK : FAIL; + return sls::allEqualTo(r, static_cast(OK)) ? OK : FAIL; } - - pthread_mutex_unlock(&mg); - return ret; } @@ -3678,43 +3637,26 @@ int multiSlsDetector::setTotalProgress() { double multiSlsDetector::getCurrentProgress() { - pthread_mutex_lock(&mp); -#ifdef VERBOSE - std::cout << progressIndex << " / " << totalProgress << std::endl; -#endif - - double p=100.*((double)progressIndex)/((double)totalProgress); - pthread_mutex_unlock(&mp); - return p; + std::lock_guard lock(mp); + return 100.*((double)progressIndex)/((double)totalProgress); } void multiSlsDetector::incrementProgress() { - pthread_mutex_lock(&mp); + std::lock_guard lock(mp); progressIndex++; std::cout << std::fixed << std::setprecision(2) << std::setw (6) << 100.*((double)progressIndex)/((double)totalProgress) << " \%"; - pthread_mutex_unlock(&mp); -#ifdef VERBOSE - std::cout << std::endl; -#else - std::cout << "\r" << std::flush; -#endif - + std::cout << '\r' << std::flush; } void multiSlsDetector::setCurrentProgress(int i){ - pthread_mutex_lock(&mp); + std::lock_guard lock(mp); progressIndex=i; std::cout << std::fixed << std::setprecision(2) << std::setw (6) << 100.*((double)progressIndex)/((double)totalProgress) << " \%"; - pthread_mutex_unlock(&mp); -#ifdef VERBOSE - std::cout << std::endl; -#else - std::cout << "\r" << std::flush; -#endif + std::cout << '\r' << std::flush; } @@ -3748,45 +3690,37 @@ int multiSlsDetector::acquire(){ // verify receiver is idle if(receiver){ - pthread_mutex_lock(&mg); + std::lock_guard lock(mg); if(getReceiverStatus()!=IDLE) if(stopReceiver() == FAIL) thisMultiDetector->stoppedFlag=1; - pthread_mutex_unlock(&mg); } // start processing thread if (thisMultiDetector->threadedProcessing) startProcessingThread(); - //resets frames caught in receiver if(receiver){ - pthread_mutex_lock(&mg); + std::lock_guard lock(mg); if (resetFramesCaught() == FAIL) thisMultiDetector->stoppedFlag=1; - pthread_mutex_unlock(&mg); } // loop through measurements for(int im=0;imstoppedFlag) break; // start receiver if(receiver){ - - pthread_mutex_lock(&mg); + std::lock_guard lock(mg); if(startReceiver() == FAIL) { std::cout << "Start receiver failed " << std::endl; stopReceiver(); thisMultiDetector->stoppedFlag=1; - pthread_mutex_unlock(&mg); break; } - pthread_mutex_unlock(&mg); - //let processing thread listen to these packets sem_post(&sem_newRTAcquisition); } @@ -3798,31 +3732,22 @@ int multiSlsDetector::acquire(){ processData(); } - // stop receiver + std::lock_guard lock(mg); if(receiver){ - pthread_mutex_lock(&mg); if (stopReceiver() == FAIL) { thisMultiDetector->stoppedFlag = 1; - pthread_mutex_unlock(&mg); } else { - pthread_mutex_unlock(&mg); if (thisMultiDetector->threadedProcessing && dataReady) sem_wait(&sem_endRTAcquisition); // waits for receiver's external process to be done sending data to gui } } - int findex = 0; - pthread_mutex_lock(&mg); findex = incrementFileIndex(); - pthread_mutex_unlock(&mg); if (measurement_finished){ - pthread_mutex_lock(&mg); measurement_finished(im,findex,measFinished_p); - pthread_mutex_unlock(&mg); } - if (thisMultiDetector->stoppedFlag) { break; } @@ -3837,7 +3762,8 @@ int multiSlsDetector::acquire(){ //let processing thread continue and checkjointhread sem_post(&sem_newRTAcquisition); - pthread_join(dataProcessingThread, &status); + // pthread_join(dataProcessingThread, &status); + dataProcessingThread.join(); } @@ -3873,55 +3799,27 @@ int multiSlsDetector::setThreadedProcessing(int enable) { void multiSlsDetector::startProcessingThread() { setTotalProgress(); -#ifdef VERBOSE - std::cout << "start thread stuff" << std::endl; -#endif - - pthread_attr_t tattr; - int ret; - sched_param param, mparam; - int policy= SCHED_OTHER; - - // set the priority; others are unchanged - //newprio = 30; - mparam.sched_priority =1; - param.sched_priority =1; - - /* Initialize and set thread detached attribute */ - pthread_attr_init(&tattr); - pthread_attr_setdetachstate(&tattr, PTHREAD_CREATE_JOINABLE); - pthread_setschedparam(pthread_self(), policy, &mparam); - ret = pthread_create(&dataProcessingThread, &tattr,startProcessData, (void*)this); - if (ret) - printf("ret %d\n", ret); - pthread_attr_destroy(&tattr); - - // scheduling parameters of target thread - pthread_setschedparam(dataProcessingThread, policy, ¶m); + dataProcessingThread = std::thread(&multiSlsDetector::processData, this); } -void* multiSlsDetector::startProcessData(void *n) { - ((multiSlsDetector*)n)->processData(); - return n; -} +// void* multiSlsDetector::startProcessData(void *n) { +// ((multiSlsDetector*)n)->processData(); +// return n; +// } void* multiSlsDetector::processData() { if(setReceiverOnline()==OFFLINE_FLAG){ return 0; - } //receiver + } else{ - //cprintf(RED,"In post processing threads\n"); - if(dataReady) { readFrameFromReceiver(); } //only update progress else{ int caught = -1; - char c; - int ifp; while(true){ // set only in startThread @@ -3929,9 +3827,8 @@ void* multiSlsDetector::processData() { setTotalProgress(); // to exit acquire by typing q - ifp=kbhit(); - if (ifp!=0){ - c=fgetc(stdin); + if (kbhit()!=0){ + char c = fgetc(stdin); if (c=='q') { std::cout<<"Caught the command to stop acquisition"< lock(mg); caught = getFramesCaughtByReceiver(0); - pthread_mutex_unlock(&mg); } - //updating progress if(caught!= -1){ setCurrentProgress(caught); -#ifdef VERY_VERY_DEBUG - std::cout << "caught:" << caught << std::endl; -#endif } // exiting loop @@ -3961,28 +3853,22 @@ void* multiSlsDetector::processData() { if (checkJoinThread()){ break; } - usleep(100 * 1000); //20ms need this else connecting error to receiver (too fast) } } } - return 0; } int multiSlsDetector::checkJoinThread() { - int retval; - pthread_mutex_lock(&mp); - retval=jointhread; - pthread_mutex_unlock(&mp); - return retval; + std::lock_guard lock(mp); + return jointhread; } void multiSlsDetector::setJoinThread( int v) { - pthread_mutex_lock(&mp); + std::lock_guard lock(mp); jointhread=v; - pthread_mutex_unlock(&mp); } diff --git a/slsDetectorSoftware/multiSlsDetector/multiSlsDetector.h b/slsDetectorSoftware/multiSlsDetector/multiSlsDetector.h index 7dd5d5c49..e4ccd0919 100644 --- a/slsDetectorSoftware/multiSlsDetector/multiSlsDetector.h +++ b/slsDetectorSoftware/multiSlsDetector/multiSlsDetector.h @@ -18,6 +18,8 @@ class detectorData; #include #include #include +#include +#include #include @@ -1662,10 +1664,10 @@ private: */ void startProcessingThread(); - /** - * Static function to call processing thread - */ - static void* startProcessData(void *n); + // /** + // * Static function to call processing thread + // */ + // static void* startProcessData(void *n); /** * Check if processing thread is ready to join main thread @@ -1718,10 +1720,10 @@ private: int progressIndex; /** mutex to synchronize main and data processing threads */ - pthread_mutex_t mp; + std::mutex mp; /** mutex to synchronizedata processing and plotting threads */ - pthread_mutex_t mg; + std::mutex mg; /** sets when the acquisition is finished */ int jointhread; @@ -1730,7 +1732,8 @@ private: int acquiringDone; /** the data processing thread */ - pthread_t dataProcessingThread; + // pthread_t dataProcessingThread; + std::thread dataProcessingThread; /** gui data */ double *fdata; From 1d14dc6ff431a73f1cc779b7d0eeec21c64ea669 Mon Sep 17 00:00:00 2001 From: Erik Frojdh Date: Wed, 17 Oct 2018 16:58:09 +0200 Subject: [PATCH 10/18] void signature of processData --- slsDetectorSoftware/multiSlsDetector/multiSlsDetector.cpp | 6 +++--- slsDetectorSoftware/multiSlsDetector/multiSlsDetector.h | 2 +- 2 files changed, 4 insertions(+), 4 deletions(-) diff --git a/slsDetectorSoftware/multiSlsDetector/multiSlsDetector.cpp b/slsDetectorSoftware/multiSlsDetector/multiSlsDetector.cpp index 1d66e1816..69e10c3c7 100644 --- a/slsDetectorSoftware/multiSlsDetector/multiSlsDetector.cpp +++ b/slsDetectorSoftware/multiSlsDetector/multiSlsDetector.cpp @@ -3809,9 +3809,9 @@ void multiSlsDetector::startProcessingThread() { // } -void* multiSlsDetector::processData() { +void multiSlsDetector::processData() { if(setReceiverOnline()==OFFLINE_FLAG){ - return 0; + return; } else{ if(dataReady) { @@ -3857,7 +3857,7 @@ void* multiSlsDetector::processData() { } } } - return 0; + return; } diff --git a/slsDetectorSoftware/multiSlsDetector/multiSlsDetector.h b/slsDetectorSoftware/multiSlsDetector/multiSlsDetector.h index e4ccd0919..1c2bcffd0 100644 --- a/slsDetectorSoftware/multiSlsDetector/multiSlsDetector.h +++ b/slsDetectorSoftware/multiSlsDetector/multiSlsDetector.h @@ -1588,7 +1588,7 @@ public: * Combines data from all readouts and gives it to the gui * or just gives progress of acquisition by polling receivers */ - void* processData(); + void processData(); private: /** From 0070a79838ac278ec11a4d83c673e99686a3435b Mon Sep 17 00:00:00 2001 From: Erik Frojdh Date: Wed, 17 Oct 2018 17:35:55 +0200 Subject: [PATCH 11/18] removed command threaded --- CMakeLists.txt | 4 +- .../multiSlsDetector/multiSlsDetector.cpp | 51 +++--------------- .../multiSlsDetector/multiSlsDetector.h | 9 +--- .../slsDetector/slsDetector.cpp | 2 +- slsDetectorSoftware/slsDetector/slsDetector.h | 2 +- .../slsDetector/slsDetectorCommand.cpp | 54 +++++++++---------- .../slsDetector/slsDetectorCommand.h | 2 +- 7 files changed, 40 insertions(+), 84 deletions(-) diff --git a/CMakeLists.txt b/CMakeLists.txt index 056a65561..7373a7ea2 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -14,8 +14,8 @@ else () set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -Wall -std=c++11") endif () -set (CMAKE_CXX_FLAGS_DEBUG "${CMAKE_CXX_FLAGS_DEBUG} -fno-omit-frame-pointer -fsanitize=address") -set (CMAKE_LINKER_FLAGS_DEBUG "${CMAKE_LINKER_FLAGS_DEBUG} -fno-omit-frame-pointer -fsanitize=address") +set (CMAKE_CXX_FLAGS_DEBUG "${CMAKE_CXX_FLAGS_DEBUG} -fno-omit-frame-pointer -fsanitize=thread") +set (CMAKE_LINKER_FLAGS_DEBUG "${CMAKE_LINKER_FLAGS_DEBUG} -fno-omit-frame-pointer -fsanitize=thread") find_package(Qt4) find_package(Qwt 6) diff --git a/slsDetectorSoftware/multiSlsDetector/multiSlsDetector.cpp b/slsDetectorSoftware/multiSlsDetector/multiSlsDetector.cpp index 69e10c3c7..ff4bd6df6 100644 --- a/slsDetectorSoftware/multiSlsDetector/multiSlsDetector.cpp +++ b/slsDetectorSoftware/multiSlsDetector/multiSlsDetector.cpp @@ -406,7 +406,7 @@ void multiSlsDetector::initializeDetectorStructure() { for (int i = 0; i < MAX_TIMERS; ++i) { thisMultiDetector->timerValue[i] = 0; } - thisMultiDetector->threadedProcessing = 1; + thisMultiDetector->acquiringFlag = false; thisMultiDetector->receiverOnlineFlag = OFFLINE_FLAG; thisMultiDetector->receiver_upstream = false; @@ -3661,7 +3661,6 @@ void multiSlsDetector::setCurrentProgress(int i){ int multiSlsDetector::acquire(){ - //ensure acquire isnt started multiple times by same client if (isAcquireReady() == FAIL) return FAIL; @@ -3676,12 +3675,9 @@ int multiSlsDetector::acquire(){ //in the real time acquistion loop, main thread will wait for processing thread to be done each time (which in turn waits for receiver/ext process) sem_init(&sem_endRTAcquisition,1,0); - bool receiver = (setReceiverOnline()==ONLINE_FLAG); - progressIndex=0; thisMultiDetector->stoppedFlag=0; - void *status; setJoinThread(0); int nm=thisMultiDetector->timerValue[MEASUREMENTS_NUMBER]; @@ -3696,9 +3692,7 @@ int multiSlsDetector::acquire(){ thisMultiDetector->stoppedFlag=1; } - // start processing thread - if (thisMultiDetector->threadedProcessing) - startProcessingThread(); + startProcessingThread(); //resets frames caught in receiver if(receiver){ @@ -3725,20 +3719,15 @@ int multiSlsDetector::acquire(){ sem_post(&sem_newRTAcquisition); } - // detector start startAndReadAll(); - if (thisMultiDetector->threadedProcessing==0){ - processData(); - } - // stop receiver std::lock_guard lock(mg); if(receiver){ if (stopReceiver() == FAIL) { thisMultiDetector->stoppedFlag = 1; } else { - if (thisMultiDetector->threadedProcessing && dataReady) + if (dataReady) sem_wait(&sem_endRTAcquisition); // waits for receiver's external process to be done sending data to gui } } @@ -3754,17 +3743,10 @@ int multiSlsDetector::acquire(){ }//end measurements loop im - // waiting for the data processing thread to finish! - if (thisMultiDetector->threadedProcessing) { - setJoinThread(1); - - //let processing thread continue and checkjointhread - sem_post(&sem_newRTAcquisition); - - // pthread_join(dataProcessingThread, &status); - dataProcessingThread.join(); - } + setJoinThread(1); + sem_post(&sem_newRTAcquisition); + dataProcessingThread.join(); if(progress_call) @@ -3790,13 +3772,6 @@ int multiSlsDetector::acquire(){ -int multiSlsDetector::setThreadedProcessing(int enable) { - if (enable>=0) - thisMultiDetector->threadedProcessing=enable; - return thisMultiDetector->threadedProcessing; -} - - void multiSlsDetector::startProcessingThread() { setTotalProgress(); dataProcessingThread = std::thread(&multiSlsDetector::processData, this); @@ -3821,35 +3796,23 @@ void multiSlsDetector::processData() { else{ int caught = -1; while(true){ - - // set only in startThread - if (thisMultiDetector->threadedProcessing==0) - setTotalProgress(); - // to exit acquire by typing q if (kbhit()!=0){ - char c = fgetc(stdin); - if (c=='q') { + if (fgetc(stdin) == 'q') { std::cout<<"Caught the command to stop acquisition"< lock(mg); caught = getFramesCaughtByReceiver(0); } - //updating progress if(caught!= -1){ setCurrentProgress(caught); } - // exiting loop - if (thisMultiDetector->threadedProcessing==0) - break; if (checkJoinThread()){ break; } diff --git a/slsDetectorSoftware/multiSlsDetector/multiSlsDetector.h b/slsDetectorSoftware/multiSlsDetector/multiSlsDetector.h index 1c2bcffd0..daaedc3e5 100644 --- a/slsDetectorSoftware/multiSlsDetector/multiSlsDetector.h +++ b/slsDetectorSoftware/multiSlsDetector/multiSlsDetector.h @@ -102,9 +102,6 @@ private: /** timer values */ int64_t timerValue[MAX_TIMERS]; - /** threaded processing flag (i.e. if data are processed and written to - * file in a separate thread) */ - int threadedProcessing; /** flag for acquiring */ bool acquiringFlag; @@ -1573,11 +1570,7 @@ public: */ int acquire(); - /** - * Set/get if the data processing thread si enabled - * @param enable 0 no data processing thread, 1 separate thread, -1 get - */ - int setThreadedProcessing(int enable=-1); + /** * Returns true if detector position is out of bounds diff --git a/slsDetectorSoftware/slsDetector/slsDetector.cpp b/slsDetectorSoftware/slsDetector/slsDetector.cpp index 07a994a58..942dd67de 100644 --- a/slsDetectorSoftware/slsDetector/slsDetector.cpp +++ b/slsDetectorSoftware/slsDetector/slsDetector.cpp @@ -439,7 +439,7 @@ void slsDetector::initializeDetectorStructure(detectorType type) { thisDetector->nTrimEn = 0; for(int i = 0; i < MAX_TRIMEN; ++i) thisDetector->trimEnergies[i] = 0; - thisDetector->threadedProcessing = 1; + // thisDetector->threadedProcessing = 1; thisDetector->nROI = 0; memset(thisDetector->roiLimits, 0, MAX_ROIS * sizeof(ROI)); thisDetector->roFlags = NORMAL_READOUT; diff --git a/slsDetectorSoftware/slsDetector/slsDetector.h b/slsDetectorSoftware/slsDetector/slsDetector.h index 13f7ef752..1c783fdf8 100644 --- a/slsDetectorSoftware/slsDetector/slsDetector.h +++ b/slsDetectorSoftware/slsDetector/slsDetector.h @@ -126,7 +126,7 @@ private: /** threaded processing flag * (i.e. if data are processed in a separate thread) */ - int threadedProcessing; + // int threadedProcessing; /** number of rois defined */ int nROI; diff --git a/slsDetectorSoftware/slsDetector/slsDetectorCommand.cpp b/slsDetectorSoftware/slsDetector/slsDetectorCommand.cpp index ffc9de7a3..2e94bd16b 100644 --- a/slsDetectorSoftware/slsDetector/slsDetectorCommand.cpp +++ b/slsDetectorSoftware/slsDetector/slsDetectorCommand.cpp @@ -812,12 +812,12 @@ slsDetectorCommand::slsDetectorCommand(multiSlsDetector *det) { descrToFuncMap[i].m_pFuncPtr=&slsDetectorCommand::cmdRateCorr; ++i; - /*! \page data - - threaded [i] Sets/gets the data processing threaded flag. 1 is threaded, 0 unthreaded. - */ - descrToFuncMap[i].m_pFuncName="threaded"; // - descrToFuncMap[i].m_pFuncPtr=&slsDetectorCommand::cmdThreaded; - ++i; +// /*! \page data +// - threaded [i] Sets/gets the data processing threaded flag. 1 is threaded, 0 unthreaded. +// */ +// descrToFuncMap[i].m_pFuncName="threaded"; // +// descrToFuncMap[i].m_pFuncPtr=&slsDetectorCommand::cmdThreaded; +// ++i; /*! \page data - darkimage fn Loads the dark image to the detector from file fn (pedestal image). Cannot get. For Gotthard only. @@ -2161,15 +2161,15 @@ string slsDetectorCommand::cmdData(int narg, char *args[], int action, int detPo } else if (action==HELP_ACTION) { return helpData(HELP_ACTION); } else { - b=myDet->setThreadedProcessing(-1); - myDet->setThreadedProcessing(0); - myDet->setOnline(ONLINE_FLAG, detPos); - myDet->setReceiverOnline(ONLINE_FLAG, detPos); - myDet->readAll(detPos); - //processdata in receiver is useful only for gui purposes - if(myDet->setReceiverOnline(detPos)==OFFLINE_FLAG) - myDet->processData(); - myDet->setThreadedProcessing(b); + // b=myDet->setThreadedProcessing(-1); + // myDet->setThreadedProcessing(0); + // myDet->setOnline(ONLINE_FLAG, detPos); + // myDet->setReceiverOnline(ONLINE_FLAG, detPos); + // myDet->readAll(detPos); + // //processdata in receiver is useful only for gui purposes + // if(myDet->setReceiverOnline(detPos)==OFFLINE_FLAG) + // myDet->processData(); + // myDet->setThreadedProcessing(b); return string(""); } } @@ -2744,21 +2744,21 @@ string slsDetectorCommand::helpRateCorr(int action){ -string slsDetectorCommand::cmdThreaded(int narg, char *args[], int action, int detPos){ - int ival; - char answer[1000]; +// string slsDetectorCommand::cmdThreaded(int narg, char *args[], int action, int detPos){ +// int ival; +// char answer[1000]; - if (action==HELP_ACTION) - return helpThreaded(action); +// if (action==HELP_ACTION) +// return helpThreaded(action); - if (action==PUT_ACTION) { - if (sscanf(args[1],"%d",&ival)) - myDet->setThreadedProcessing(ival); - } - sprintf(answer,"%d",myDet->setThreadedProcessing()); - return string(answer); +// if (action==PUT_ACTION) { +// if (sscanf(args[1],"%d",&ival)) +// myDet->setThreadedProcessing(ival); +// } +// sprintf(answer,"%d",myDet->setThreadedProcessing()); +// return string(answer); -} +// } string slsDetectorCommand::helpThreaded(int action){ diff --git a/slsDetectorSoftware/slsDetector/slsDetectorCommand.h b/slsDetectorSoftware/slsDetector/slsDetectorCommand.h index ce7ca999d..d5afb3fc0 100644 --- a/slsDetectorSoftware/slsDetector/slsDetectorCommand.h +++ b/slsDetectorSoftware/slsDetector/slsDetectorCommand.h @@ -113,7 +113,7 @@ class slsDetectorCommand : public virtual slsDetectorDefs { std::string cmdFileName(int narg, char *args[], int action, int detPos = -1); std::string cmdFileIndex(int narg, char *args[], int action, int detPos = -1); std::string cmdRateCorr(int narg, char *args[], int action, int detPos = -1); - std::string cmdThreaded(int narg, char *args[], int action, int detPos = -1); + // std::string cmdThreaded(int narg, char *args[], int action, int detPos = -1); std::string cmdNetworkParameter(int narg, char *args[], int action, int detPos = -1); std::string cmdPort(int narg, char *args[], int action, int detPos = -1); std::string cmdLock(int narg, char *args[], int action, int detPos = -1); From b44039361d96f71dd1470fe3160ce3e79f90a2fc Mon Sep 17 00:00:00 2001 From: Erik Frojdh Date: Wed, 17 Oct 2018 17:47:19 +0200 Subject: [PATCH 12/18] renamed joinThread getter setter --- .../multiSlsDetector/multiSlsDetector.cpp | 22 +++++++++---------- .../multiSlsDetector/multiSlsDetector.h | 6 ++--- 2 files changed, 13 insertions(+), 15 deletions(-) diff --git a/slsDetectorSoftware/multiSlsDetector/multiSlsDetector.cpp b/slsDetectorSoftware/multiSlsDetector/multiSlsDetector.cpp index ff4bd6df6..c4f73f39e 100644 --- a/slsDetectorSoftware/multiSlsDetector/multiSlsDetector.cpp +++ b/slsDetectorSoftware/multiSlsDetector/multiSlsDetector.cpp @@ -2880,12 +2880,11 @@ void multiSlsDetector::readFrameFromReceiver() { //wait for real time acquisition to start bool running = true; sem_wait(&sem_newRTAcquisition); - if (checkJoinThread()) + if (getJoinThreadFlag()) running = false; - //exit when checkJoinThread() (all sockets done) - while (running) { + while (running) { // reset data data = false; if (multiframe != NULL) @@ -3034,7 +3033,7 @@ void multiSlsDetector::readFrameFromReceiver() { // wait for next scan/measurement, else join thread sem_wait(&sem_newRTAcquisition); //done with complete acquisition - if (checkJoinThread()) + if (getJoinThreadFlag()) running = false; else { //starting a new scan/measurement (got dummy data) @@ -3678,7 +3677,7 @@ int multiSlsDetector::acquire(){ bool receiver = (setReceiverOnline()==ONLINE_FLAG); progressIndex=0; thisMultiDetector->stoppedFlag=0; - setJoinThread(0); + setJoinThreadFlag(false); int nm=thisMultiDetector->timerValue[MEASUREMENTS_NUMBER]; if (nm<1) @@ -3744,7 +3743,7 @@ int multiSlsDetector::acquire(){ }//end measurements loop im // waiting for the data processing thread to finish! - setJoinThread(1); + setJoinThreadFlag(true); sem_post(&sem_newRTAcquisition); dataProcessingThread.join(); @@ -3813,7 +3812,7 @@ void multiSlsDetector::processData() { setCurrentProgress(caught); } // exiting loop - if (checkJoinThread()){ + if (getJoinThreadFlag()){ break; } usleep(100 * 1000); //20ms need this else connecting error to receiver (too fast) @@ -3824,17 +3823,16 @@ void multiSlsDetector::processData() { } -int multiSlsDetector::checkJoinThread() { +bool multiSlsDetector::getJoinThreadFlag() { std::lock_guard lock(mp); return jointhread; } -void multiSlsDetector::setJoinThread( int v) { +void multiSlsDetector::setJoinThreadFlag( bool value) { std::lock_guard lock(mp); - jointhread=v; + jointhread=value; } - int multiSlsDetector::kbhit() { struct timeval tv; fd_set fds; @@ -3855,4 +3853,4 @@ bool multiSlsDetector::isDetectorIndexOutOfBounds(int detPos) { return true; } return false; -} +} \ No newline at end of file diff --git a/slsDetectorSoftware/multiSlsDetector/multiSlsDetector.h b/slsDetectorSoftware/multiSlsDetector/multiSlsDetector.h index daaedc3e5..df8a52591 100644 --- a/slsDetectorSoftware/multiSlsDetector/multiSlsDetector.h +++ b/slsDetectorSoftware/multiSlsDetector/multiSlsDetector.h @@ -1666,13 +1666,13 @@ private: * Check if processing thread is ready to join main thread * @returns true if ready, else false */ - int checkJoinThread(); + bool getJoinThreadFlag(); /** * Main thread sets if the processing thread should join it * @param v true if it should join, else false */ - void setJoinThread(int v); + void setJoinThreadFlag(bool value); /** * Listen to key event to stop acquiring @@ -1719,7 +1719,7 @@ private: std::mutex mg; /** sets when the acquisition is finished */ - int jointhread; + bool jointhread; /** set when detector finishes acquiring */ int acquiringDone; From 058de39d4045d01867908ca0567c585b4e48e408 Mon Sep 17 00:00:00 2001 From: Erik Frojdh Date: Wed, 17 Oct 2018 17:51:26 +0200 Subject: [PATCH 13/18] const qualifying --- slsDetectorSoftware/multiSlsDetector/multiSlsDetector.cpp | 2 +- slsDetectorSoftware/multiSlsDetector/multiSlsDetector.h | 6 +++--- 2 files changed, 4 insertions(+), 4 deletions(-) diff --git a/slsDetectorSoftware/multiSlsDetector/multiSlsDetector.cpp b/slsDetectorSoftware/multiSlsDetector/multiSlsDetector.cpp index c4f73f39e..2ba11e11e 100644 --- a/slsDetectorSoftware/multiSlsDetector/multiSlsDetector.cpp +++ b/slsDetectorSoftware/multiSlsDetector/multiSlsDetector.cpp @@ -3823,7 +3823,7 @@ void multiSlsDetector::processData() { } -bool multiSlsDetector::getJoinThreadFlag() { +bool multiSlsDetector::getJoinThreadFlag() const { std::lock_guard lock(mp); return jointhread; } diff --git a/slsDetectorSoftware/multiSlsDetector/multiSlsDetector.h b/slsDetectorSoftware/multiSlsDetector/multiSlsDetector.h index df8a52591..4054390f7 100644 --- a/slsDetectorSoftware/multiSlsDetector/multiSlsDetector.h +++ b/slsDetectorSoftware/multiSlsDetector/multiSlsDetector.h @@ -1666,7 +1666,7 @@ private: * Check if processing thread is ready to join main thread * @returns true if ready, else false */ - bool getJoinThreadFlag(); + bool getJoinThreadFlag() const; /** * Main thread sets if the processing thread should join it @@ -1713,10 +1713,10 @@ private: int progressIndex; /** mutex to synchronize main and data processing threads */ - std::mutex mp; + mutable std::mutex mp; /** mutex to synchronizedata processing and plotting threads */ - std::mutex mg; + mutable std::mutex mg; /** sets when the acquisition is finished */ bool jointhread; From c95bc844587b98508c2de75503b937e92af607cc Mon Sep 17 00:00:00 2001 From: Erik Frojdh Date: Wed, 17 Oct 2018 18:13:01 +0200 Subject: [PATCH 14/18] formatting --- .../multiSlsDetector/multiSlsDetector.cpp | 47 ++++--------------- 1 file changed, 9 insertions(+), 38 deletions(-) diff --git a/slsDetectorSoftware/multiSlsDetector/multiSlsDetector.cpp b/slsDetectorSoftware/multiSlsDetector/multiSlsDetector.cpp index 2ba11e11e..ec468b451 100644 --- a/slsDetectorSoftware/multiSlsDetector/multiSlsDetector.cpp +++ b/slsDetectorSoftware/multiSlsDetector/multiSlsDetector.cpp @@ -208,17 +208,14 @@ void multiSlsDetector::setErrorMaskFromAllDetectors() { } } - void multiSlsDetector::setAcquiringFlag(bool b) { thisMultiDetector->acquiringFlag = b; } - bool multiSlsDetector::getAcquiringFlag() const { return thisMultiDetector->acquiringFlag; } - bool multiSlsDetector::isAcquireReady() { if (thisMultiDetector->acquiringFlag) { std::cout << "Acquire has already started. " @@ -230,26 +227,19 @@ bool multiSlsDetector::isAcquireReady() { return OK; } - int multiSlsDetector::checkVersionCompatibility(portType t, int detPos) { - // single - if (detPos >= 0) { + if (detPos >= 0) return detectors[detPos]->checkVersionCompatibility(t); - } - - // multi + auto r = parallelCall(&slsDetector::checkVersionCompatibility, t); return sls::minusOneIfDifferent(r); } int64_t multiSlsDetector::getId(idMode mode, int detPos) { - // single - if (detPos >= 0) { + if (detPos >= 0) return detectors[detPos]->getId(mode); - } - // multi auto r = parallelCall(&slsDetector::getId, mode); return sls::minusOneIfDifferent(r); } @@ -292,13 +282,8 @@ void multiSlsDetector::freeSharedMemory(int detPos) { } // multi - // clear zmq vector zmqSocket.clear(); - - // should be done before the detector list is deleted clearAllErrorMask(); - - // clear sls detector vector shm for (auto& d : detectors) { d->freeSharedMemory(); } @@ -321,29 +306,20 @@ void multiSlsDetector::freeSharedMemory(int detPos) { std::string multiSlsDetector::getUserDetails() { - std::ostringstream sstream; - - if (!detectors.size()) { + if (detectors.empty()) return std::string("none"); - } - - //hostname + + std::ostringstream sstream; sstream << "\nHostname: " << getHostname(); - - //type sstream<< "\nType: "; - for (auto& d : detectors) { + for (auto& d : detectors) sstream<< d->sgetDetectorsType() << "+"; - } - - //PID + sstream << "\nPID: " << thisMultiDetector->lastPID - //user << "\nUser: " << thisMultiDetector->lastUser << "\nDate: " << thisMultiDetector->lastDate << std::endl; - std::string s = sstream.str(); - return s; + return sstream.str(); } /* @@ -430,7 +406,6 @@ void multiSlsDetector::initializeMembers(bool verify) { updateOffsets(); } - void multiSlsDetector::updateUserdetails() { thisMultiDetector->lastPID = getpid(); memset(thisMultiDetector->lastUser, 0, SHORT_STRING_LENGTH); @@ -446,7 +421,6 @@ void multiSlsDetector::updateUserdetails() { } } - std::string multiSlsDetector::exec(const char* cmd) { int bufsize = 128; char buffer[bufsize]; @@ -467,7 +441,6 @@ std::string multiSlsDetector::exec(const char* cmd) { return result; } - void multiSlsDetector::setHostname(const char* name, int detPos) { // single if (detPos >= 0) { @@ -486,7 +459,6 @@ void multiSlsDetector::setHostname(const char* name, int detPos) { addMultipleDetectors(name); } - std::string multiSlsDetector::getHostname(int detPos) { // single if (detPos >= 0) { @@ -498,7 +470,6 @@ std::string multiSlsDetector::getHostname(int detPos) { return sls::concatenateIfDifferent(r); } - void multiSlsDetector::addMultipleDetectors(const char* name) { size_t p1 = 0; std::string temp = std::string(name); From 500304024d02027c03e63b5e6bb7c55e665ea0ca Mon Sep 17 00:00:00 2001 From: Erik Frojdh Date: Thu, 18 Oct 2018 17:06:43 +0200 Subject: [PATCH 15/18] added base clang format --- .clang-format | 2 ++ 1 file changed, 2 insertions(+) create mode 100644 .clang-format diff --git a/.clang-format b/.clang-format new file mode 100644 index 000000000..5bf2f83a8 --- /dev/null +++ b/.clang-format @@ -0,0 +1,2 @@ +BasedOnStyle: LLVM +IndentWidth: 4 \ No newline at end of file From ff440f13252e8dc5ef66eee87c004e7feb60a7db Mon Sep 17 00:00:00 2001 From: Erik Frojdh Date: Fri, 19 Oct 2018 10:23:06 +0200 Subject: [PATCH 16/18] clang-format on multi detector --- .../multiSlsDetector/multiSlsDetector.cpp | 5752 ++++++++--------- .../multiSlsDetector/multiSlsDetector.h | 3405 +++++----- 2 files changed, 4578 insertions(+), 4579 deletions(-) diff --git a/slsDetectorSoftware/multiSlsDetector/multiSlsDetector.cpp b/slsDetectorSoftware/multiSlsDetector/multiSlsDetector.cpp index ec468b451..21e60e3ad 100644 --- a/slsDetectorSoftware/multiSlsDetector/multiSlsDetector.cpp +++ b/slsDetectorSoftware/multiSlsDetector/multiSlsDetector.cpp @@ -1,325 +1,310 @@ #include "multiSlsDetector.h" #include "SharedMemory.h" -#include "slsDetector.h" -#include "sls_detector_exceptions.h" #include "ZmqSocket.h" -#include "multiSlsDetectorClient.h" -#include "multiSlsDetectorCommand.h" -#include "utilities.h" #include "detectorData.h" #include "logger.h" +#include "multiSlsDetectorClient.h" +#include "multiSlsDetectorCommand.h" +#include "slsDetector.h" +#include "sls_detector_exceptions.h" +#include "utilities.h" -#include +#include #include -#include -#include #include //json header in zmq stream +#include +#include #include #include -#include +#include //#include //clock() #include "container_utils.h" #include #include - multiSlsDetector::multiSlsDetector(int id, bool verify, bool update) -: detId(id), - sharedMemory(0), - thisMultiDetector(0), - client_downstream(false), - totalProgress(0), - progressIndex(0), - jointhread(0), - acquiringDone(0), - fdata(0), - thisData(0), - acquisition_finished(0), - acqFinished_p(0), - measurement_finished(0), - measFinished_p(0), - progress_call(0), - pProgressCallArg(0), - dataReady(0), - pCallbackArg(0) -{ - setupMultiDetector(verify, update); + : detId(id), sharedMemory(0), thisMultiDetector(0), + client_downstream(false), totalProgress(0), progressIndex(0), + jointhread(0), acquiringDone(0), fdata(0), thisData(0), + acquisition_finished(0), acqFinished_p(0), measurement_finished(0), + measFinished_p(0), progress_call(0), pProgressCallArg(0), dataReady(0), + pCallbackArg(0) { + setupMultiDetector(verify, update); } - - multiSlsDetector::~multiSlsDetector() { - if (sharedMemory) { - sharedMemory->UnmapSharedMemory(thisMultiDetector); - delete sharedMemory; - } + if (sharedMemory) { + sharedMemory->UnmapSharedMemory(thisMultiDetector); + delete sharedMemory; + } } - void multiSlsDetector::setupMultiDetector(bool verify, bool update) { - initSharedMemory(verify); - initializeMembers(verify); - if (update) - updateUserdetails(); + initSharedMemory(verify); + initializeMembers(verify); + if (update) + updateUserdetails(); } - template -std::vector multiSlsDetector::serialCall(RT (slsDetector::*somefunc)(CT...), CT... Args) -{ +std::vector multiSlsDetector::serialCall(RT (slsDetector::*somefunc)(CT...), + CT... Args) { std::vector result; - for (auto& d: detectors) + for (auto &d : detectors) result.push_back((d.get()->*somefunc)(Args...)); return result; } template -std::vector multiSlsDetector::parallelCall(RT (slsDetector::*somefunc)(CT...), CT... Args) -{ +std::vector +multiSlsDetector::parallelCall(RT (slsDetector::*somefunc)(CT...), CT... Args) { std::vector> futures; for (auto &d : detectors) - futures.push_back(std::async(std::launch::async, somefunc, d.get(), Args...)); + futures.push_back( + std::async(std::launch::async, somefunc, d.get(), Args...)); std::vector result; - for (auto& i : futures) + for (auto &i : futures) result.push_back(i.get()); return result; } -int multiSlsDetector::decodeNChannel(int offsetX, int offsetY, int& channelX, int& channelY) { - channelX = -1; - channelY = -1; - //loop over - for (size_t i = 0; i < detectors.size(); ++i) { - int x = detectors[i]->getDetectorOffset(X); - int y = detectors[i]->getDetectorOffset(Y); - //check x offset range - if ((offsetX >= x) && - (offsetX < (x + detectors[i]->getTotalNumberOfChannelsInclGapPixels(X)))) { - if (offsetY == -1) { - channelX = offsetX - x; - return i; - } else { - //check y offset range - if ((offsetY >= y) && - (offsetY < (y + detectors[i]->getTotalNumberOfChannelsInclGapPixels(Y)))) { - channelX = offsetX - x; - channelY = offsetY - y; - return i; - } - } - } - } - return -1; +int multiSlsDetector::decodeNChannel(int offsetX, int offsetY, int &channelX, + int &channelY) { + channelX = -1; + channelY = -1; + // loop over + for (size_t i = 0; i < detectors.size(); ++i) { + int x = detectors[i]->getDetectorOffset(X); + int y = detectors[i]->getDetectorOffset(Y); + // check x offset range + if ((offsetX >= x) && + (offsetX < + (x + detectors[i]->getTotalNumberOfChannelsInclGapPixels(X)))) { + if (offsetY == -1) { + channelX = offsetX - x; + return i; + } else { + // check y offset range + if ((offsetY >= y) && + (offsetY < + (y + detectors[i]->getTotalNumberOfChannelsInclGapPixels( + Y)))) { + channelX = offsetX - x; + channelY = offsetY - y; + return i; + } + } + } + } + return -1; } +std::string multiSlsDetector::getErrorMessage(int &critical, int detPos) { + int64_t multiMask = 0, slsMask = 0; + std::string retval = ""; + critical = 0; + size_t posmin = 0, posmax = detectors.size(); -std::string multiSlsDetector::getErrorMessage(int& critical, int detPos) { - int64_t multiMask = 0, slsMask = 0; - std::string retval = ""; - critical = 0; - size_t posmin = 0, posmax = detectors.size(); + // single + if (detPos >= 0) { - // single - if (detPos >= 0) { + slsMask = detectors[detPos]->getErrorMask(); + posmin = (size_t)detPos; + posmax = posmin + 1; + } - slsMask = detectors[detPos]->getErrorMask(); - posmin = (size_t)detPos; - posmax = posmin + 1; - } + multiMask = getErrorMask(); + if (multiMask || slsMask) { + if (multiMask & MULTI_DETECTORS_NOT_ADDED) { + retval.append("Detectors not added:\n" + + std::string(getNotAddedList()) + std::string("\n")); + critical = 1; + } + if (multiMask & MULTI_HAVE_DIFFERENT_VALUES) { + retval.append( + "A previous multi detector command gave different values\n" + "Please check the console\n"); + critical = 0; + } + if (multiMask & MULTI_CONFIG_FILE_ERROR) { + retval.append("Could not load Config File\n"); + critical = 1; + } + if (multiMask & MULTI_POS_EXCEEDS_LIST) { + retval.append("Position exceeds multi detector list\n"); + critical = 0; + } + if (multiMask & MUST_BE_MULTI_CMD) { + retval.append("Must be a multi detector level command.\n"); + critical = 0; + } + if (multiMask & MULTI_OTHER_ERROR) { + retval.append("Some error occured from multi level.\n"); + critical = + 0; // FIXME: with exceptions/appropriate errors wherever used + } - multiMask = getErrorMask(); - if (multiMask || slsMask) { - if (multiMask & MULTI_DETECTORS_NOT_ADDED) { - retval.append("Detectors not added:\n" + std::string(getNotAddedList()) + - std::string("\n")); - critical = 1; - } - if (multiMask & MULTI_HAVE_DIFFERENT_VALUES) { - retval.append("A previous multi detector command gave different values\n" - "Please check the console\n"); - critical = 0; - } - if (multiMask & MULTI_CONFIG_FILE_ERROR) { - retval.append("Could not load Config File\n"); - critical = 1; - } - if (multiMask & MULTI_POS_EXCEEDS_LIST) { - retval.append("Position exceeds multi detector list\n"); - critical = 0; - } - if (multiMask & MUST_BE_MULTI_CMD) { - retval.append("Must be a multi detector level command.\n"); - critical = 0; - } - if (multiMask & MULTI_OTHER_ERROR) { - retval.append("Some error occured from multi level.\n"); - critical = 0;//FIXME: with exceptions/appropriate errors wherever used - } + for (size_t idet = posmin; idet < posmax; ++idet) { + // if the detector has error + if ((multiMask & (1 << idet)) || (detPos >= 0)) { - for (size_t idet = posmin; idet < posmax; ++idet) { - //if the detector has error - if ((multiMask & (1 << idet)) || (detPos >= 0)) { + // append detector id + // sprintf(sNumber, "%ld", idet); + retval.append("Detector " + std::to_string(idet) + + std::string(":\n")); - //append detector id - // sprintf(sNumber, "%ld", idet); - retval.append("Detector " + std::to_string(idet) + std::string(":\n")); - - //get sls det error mask - slsMask = detectors[idet]->getErrorMask(); + // get sls det error mask + slsMask = detectors[idet]->getErrorMask(); #ifdef VERYVERBOSE - //append sls det error mask - // sprintf(sNumber, "0x%lx", slsMask); - retval.append("Error Mask " + std::to_string(slsMask) + std::string("\n")); + // append sls det error mask + // sprintf(sNumber, "0x%lx", slsMask); + retval.append("Error Mask " + std::to_string(slsMask) + + std::string("\n")); #endif - //get the error critical level - if ((slsMask > 0xFFFFFFFF) | critical) - critical = 1; + // get the error critical level + if ((slsMask > 0xFFFFFFFF) | critical) + critical = 1; - //append error message - retval.append(errorDefs::getErrorMessage(slsMask)); - } - } - } - return retval; + // append error message + retval.append(errorDefs::getErrorMessage(slsMask)); + } + } + } + return retval; } - int64_t multiSlsDetector::clearAllErrorMask(int detPos) { - // single - if (detPos >= 0) { - return detectors[detPos]->clearErrorMask(); - } + // single + if (detPos >= 0) { + return detectors[detPos]->clearErrorMask(); + } - // multi - clearErrorMask(); - clearNotAddedList(); - for (auto& d : detectors) - d->clearErrorMask(); - return getErrorMask(); + // multi + clearErrorMask(); + clearNotAddedList(); + for (auto &d : detectors) + d->clearErrorMask(); + return getErrorMask(); } - void multiSlsDetector::setErrorMaskFromAllDetectors() { - for (size_t idet = 0; idet < detectors.size(); ++idet) { - if (detectors[idet]->getErrorMask()) - setErrorMask(getErrorMask() | (1 << idet)); - } + for (size_t idet = 0; idet < detectors.size(); ++idet) { + if (detectors[idet]->getErrorMask()) + setErrorMask(getErrorMask() | (1 << idet)); + } } void multiSlsDetector::setAcquiringFlag(bool b) { - thisMultiDetector->acquiringFlag = b; + thisMultiDetector->acquiringFlag = b; } bool multiSlsDetector::getAcquiringFlag() const { - return thisMultiDetector->acquiringFlag; + return thisMultiDetector->acquiringFlag; } bool multiSlsDetector::isAcquireReady() { - if (thisMultiDetector->acquiringFlag) { - std::cout << "Acquire has already started. " - "If previous acquisition terminated unexpectedly, " - "reset busy flag to restart.(sls_detector_put busy 0)" << std::endl; - return FAIL; - } - thisMultiDetector->acquiringFlag = true; - return OK; + if (thisMultiDetector->acquiringFlag) { + std::cout << "Acquire has already started. " + "If previous acquisition terminated unexpectedly, " + "reset busy flag to restart.(sls_detector_put busy 0)" + << std::endl; + return FAIL; + } + thisMultiDetector->acquiringFlag = true; + return OK; } int multiSlsDetector::checkVersionCompatibility(portType t, int detPos) { - if (detPos >= 0) - return detectors[detPos]->checkVersionCompatibility(t); - - auto r = parallelCall(&slsDetector::checkVersionCompatibility, t); - return sls::minusOneIfDifferent(r); -} + if (detPos >= 0) + return detectors[detPos]->checkVersionCompatibility(t); + auto r = parallelCall(&slsDetector::checkVersionCompatibility, t); + return sls::minusOneIfDifferent(r); +} int64_t multiSlsDetector::getId(idMode mode, int detPos) { - if (detPos >= 0) - return detectors[detPos]->getId(mode); + if (detPos >= 0) + return detectors[detPos]->getId(mode); - auto r = parallelCall(&slsDetector::getId, mode); - return sls::minusOneIfDifferent(r); + auto r = parallelCall(&slsDetector::getId, mode); + return sls::minusOneIfDifferent(r); } - void multiSlsDetector::freeSharedMemory(int multiId, int detPos) { - // single - if (detPos >= 0) { - slsDetector::freeSharedMemory(multiId, detPos); - return; - } + // single + if (detPos >= 0) { + slsDetector::freeSharedMemory(multiId, detPos); + return; + } - // multi - // get number of detectors - int numDetectors = 0; - auto shm = SharedMemory(multiId, -1); + // multi + // get number of detectors + 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)); - numDetectors = mdet->numberOfDetectors; - shm.UnmapSharedMemory(mdet); - shm.RemoveSharedMemory(); - } + // get number of detectors from multi shm + if (shm.IsExisting()) { + sharedMultiSlsDetector *mdet = + (sharedMultiSlsDetector *)shm.OpenSharedMemory( + sizeof(sharedMultiSlsDetector)); + numDetectors = mdet->numberOfDetectors; + shm.UnmapSharedMemory(mdet); + shm.RemoveSharedMemory(); + } - for (int i = 0; i < numDetectors; ++i) { - auto shm = SharedMemory(multiId, i); - shm.RemoveSharedMemory(); - } + for (int i = 0; i < numDetectors; ++i) { + auto shm = SharedMemory(multiId, i); + shm.RemoveSharedMemory(); + } } - - void multiSlsDetector::freeSharedMemory(int detPos) { - // single - if (detPos >= 0) { - detectors[detPos]->freeSharedMemory(); - return; - } + // single + if (detPos >= 0) { + detectors[detPos]->freeSharedMemory(); + return; + } - // multi - zmqSocket.clear(); - clearAllErrorMask(); - for (auto& d : detectors) { - d->freeSharedMemory(); + // multi + zmqSocket.clear(); + clearAllErrorMask(); + for (auto &d : detectors) { + d->freeSharedMemory(); } detectors.clear(); - // clear multi detector shm - if (sharedMemory) { - if (thisMultiDetector) { - sharedMemory->UnmapSharedMemory(thisMultiDetector); - thisMultiDetector = 0; - } - sharedMemory->RemoveSharedMemory(); - delete sharedMemory; - sharedMemory = 0; - } + // clear multi detector shm + if (sharedMemory) { + if (thisMultiDetector) { + sharedMemory->UnmapSharedMemory(thisMultiDetector); + thisMultiDetector = 0; + } + sharedMemory->RemoveSharedMemory(); + delete sharedMemory; + sharedMemory = 0; + } - // zmq - client_downstream = false; + // zmq + client_downstream = false; } - std::string multiSlsDetector::getUserDetails() { - if (detectors.empty()) - return std::string("none"); - - std::ostringstream sstream; - sstream << "\nHostname: " << getHostname(); - sstream<< "\nType: "; - for (auto& d : detectors) - sstream<< d->sgetDetectorsType() << "+"; - - sstream << "\nPID: " << thisMultiDetector->lastPID - << "\nUser: " << thisMultiDetector->lastUser - << "\nDate: " << thisMultiDetector->lastDate << std::endl; + if (detectors.empty()) + return std::string("none"); - return sstream.str(); + std::ostringstream sstream; + sstream << "\nHostname: " << getHostname(); + sstream << "\nType: "; + for (auto &d : detectors) + sstream << d->sgetDetectorsType() << "+"; + + sstream << "\nPID: " << thisMultiDetector->lastPID + << "\nUser: " << thisMultiDetector->lastUser + << "\nDate: " << thisMultiDetector->lastDate << std::endl; + + return sstream.str(); } /* @@ -327,3501 +312,3472 @@ std::string multiSlsDetector::getUserDetails() { * exceptions are caught in calling function, shm unmapped and deleted */ void multiSlsDetector::initSharedMemory(bool verify) { - try { - // shared memory object with name - sharedMemory = new SharedMemory(detId, -1); - size_t sz = sizeof(sharedMultiSlsDetector); + 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); - initializeDetectorStructure(); - } - // open and verify version - else { - thisMultiDetector = (sharedMultiSlsDetector*)sharedMemory->OpenSharedMemory(sz); - if (verify && thisMultiDetector->shmversion != MULTI_SHMVERSION) { - cprintf(RED, "Multi shared memory (%d) version mismatch " - "(expected 0x%x but got 0x%x)\n", detId, - MULTI_SHMVERSION, thisMultiDetector->shmversion); - throw SharedMemoryException(); - } - } - } catch (...) { - if (sharedMemory) { - // unmap - if (thisMultiDetector) { - sharedMemory->UnmapSharedMemory(thisMultiDetector); - thisMultiDetector = 0; - } - // delete - delete sharedMemory; - sharedMemory = 0; - } - throw; - } + // create + if (!sharedMemory->IsExisting()) { + thisMultiDetector = + (sharedMultiSlsDetector *)sharedMemory->CreateSharedMemory(sz); + initializeDetectorStructure(); + } + // open and verify version + else { + thisMultiDetector = + (sharedMultiSlsDetector *)sharedMemory->OpenSharedMemory(sz); + if (verify && thisMultiDetector->shmversion != MULTI_SHMVERSION) { + cprintf(RED, + "Multi shared memory (%d) version mismatch " + "(expected 0x%x but got 0x%x)\n", + detId, MULTI_SHMVERSION, thisMultiDetector->shmversion); + throw SharedMemoryException(); + } + } + } catch (...) { + if (sharedMemory) { + // unmap + if (thisMultiDetector) { + sharedMemory->UnmapSharedMemory(thisMultiDetector); + thisMultiDetector = 0; + } + // delete + delete sharedMemory; + sharedMemory = 0; + } + 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 (int i = 0; i < MAX_TIMERS; ++i) { - thisMultiDetector->timerValue[i] = 0; - } + 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 (int i = 0; i < MAX_TIMERS; ++i) { + thisMultiDetector->timerValue[i] = 0; + } - thisMultiDetector->acquiringFlag = false; - thisMultiDetector->receiverOnlineFlag = OFFLINE_FLAG; - thisMultiDetector->receiver_upstream = false; + thisMultiDetector->acquiringFlag = false; + thisMultiDetector->receiverOnlineFlag = OFFLINE_FLAG; + thisMultiDetector->receiver_upstream = false; } void multiSlsDetector::initializeMembers(bool verify) { - //multiSlsDetector - zmqSocket.clear(); + // multiSlsDetector + zmqSocket.clear(); - // get objects from single det shared memory (open) - for (int i = 0; i < thisMultiDetector->numberOfDetectors; i++) { - try { - detectors.push_back(sls::make_unique(detId, i, verify)); - } catch (...) { - detectors.clear(); - throw; - } - } + // get objects from single det shared memory (open) + for (int i = 0; i < thisMultiDetector->numberOfDetectors; i++) { + try { + detectors.push_back( + sls::make_unique(detId, i, verify)); + } catch (...) { + detectors.clear(); + throw; + } + } - // depend on number of detectors - updateOffsets(); + // depend on number of detectors + updateOffsets(); } void multiSlsDetector::updateUserdetails() { - thisMultiDetector->lastPID = getpid(); - memset(thisMultiDetector->lastUser, 0, SHORT_STRING_LENGTH); - memset(thisMultiDetector->lastDate, 0, SHORT_STRING_LENGTH); - try { - strncpy(thisMultiDetector->lastUser, exec("whoami").c_str(), SHORT_STRING_LENGTH-1); - thisMultiDetector->lastUser[SHORT_STRING_LENGTH-1] = 0; - strncpy(thisMultiDetector->lastDate, exec("date").c_str(), DATE_LENGTH-1); - thisMultiDetector->lastDate[DATE_LENGTH-1] = 0; - } catch(...) { - strcpy(thisMultiDetector->lastUser, "errorreading"); - strcpy(thisMultiDetector->lastDate, "errorreading"); - } + thisMultiDetector->lastPID = getpid(); + memset(thisMultiDetector->lastUser, 0, SHORT_STRING_LENGTH); + memset(thisMultiDetector->lastDate, 0, SHORT_STRING_LENGTH); + try { + strncpy(thisMultiDetector->lastUser, exec("whoami").c_str(), + SHORT_STRING_LENGTH - 1); + thisMultiDetector->lastUser[SHORT_STRING_LENGTH - 1] = 0; + strncpy(thisMultiDetector->lastDate, exec("date").c_str(), + DATE_LENGTH - 1); + thisMultiDetector->lastDate[DATE_LENGTH - 1] = 0; + } catch (...) { + strcpy(thisMultiDetector->lastUser, "errorreading"); + strcpy(thisMultiDetector->lastDate, "errorreading"); + } } -std::string multiSlsDetector::exec(const char* cmd) { - int bufsize = 128; - char buffer[bufsize]; - std::string result = ""; - FILE* pipe = popen(cmd, "r"); - if (!pipe) throw std::exception(); - try { - while (!feof(pipe)) { - if (fgets(buffer, bufsize, pipe) != NULL) - result += buffer; - } - } catch (...) { - pclose(pipe); - throw; - } - pclose(pipe); - result.erase(result.find_last_not_of(" \t\n\r")+1); - return result; +std::string multiSlsDetector::exec(const char *cmd) { + int bufsize = 128; + char buffer[bufsize]; + std::string result = ""; + FILE *pipe = popen(cmd, "r"); + if (!pipe) + throw std::exception(); + try { + while (!feof(pipe)) { + if (fgets(buffer, bufsize, pipe) != NULL) + result += buffer; + } + } catch (...) { + pclose(pipe); + throw; + } + pclose(pipe); + result.erase(result.find_last_not_of(" \t\n\r") + 1); + return result; } -void multiSlsDetector::setHostname(const char* name, int detPos) { - // single - if (detPos >= 0) { - detectors[detPos]->setHostname(name); - return; - } +void multiSlsDetector::setHostname(const char *name, int detPos) { + // single + if (detPos >= 0) { + detectors[detPos]->setHostname(name); + return; + } - // multi - // this check is there only to allow the previous detsizechan command - if (thisMultiDetector->numberOfDetectors) { - cprintf(RED, "Warning: There are already detector(s) in shared memory." - "Freeing Shared memory now.\n"); - freeSharedMemory(); - setupMultiDetector(); - } - addMultipleDetectors(name); + // multi + // this check is there only to allow the previous detsizechan command + if (thisMultiDetector->numberOfDetectors) { + cprintf(RED, "Warning: There are already detector(s) in shared memory." + "Freeing Shared memory now.\n"); + freeSharedMemory(); + setupMultiDetector(); + } + addMultipleDetectors(name); } std::string multiSlsDetector::getHostname(int detPos) { - // single - if (detPos >= 0) { - return detectors[detPos]->getHostname(); - } + // single + if (detPos >= 0) { + return detectors[detPos]->getHostname(); + } - // multi - auto r = serialCall(&slsDetector::getHostname); - return sls::concatenateIfDifferent(r); + // multi + auto r = serialCall(&slsDetector::getHostname); + return sls::concatenateIfDifferent(r); } -void multiSlsDetector::addMultipleDetectors(const char* name) { - size_t p1 = 0; - std::string temp = std::string(name); - size_t p2 = temp.find('+', p1); - //single - if (p2 == std::string::npos) { - addSlsDetector(temp); - } - // multi - else { - while(p2 != std::string::npos) { - addSlsDetector(temp.substr(p1, p2-p1)); - temp = temp.substr(p2 + 1); - p2 = temp.find('+'); - } - } +void multiSlsDetector::addMultipleDetectors(const char *name) { + size_t p1 = 0; + std::string temp = std::string(name); + size_t p2 = temp.find('+', p1); + // single + if (p2 == std::string::npos) { + addSlsDetector(temp); + } + // multi + else { + while (p2 != std::string::npos) { + addSlsDetector(temp.substr(p1, p2 - p1)); + temp = temp.substr(p2 + 1); + p2 = temp.find('+'); + } + } - // a get to update shared memory online flag - setOnline(); - updateOffsets(); + // a get to update shared memory online flag + setOnline(); + updateOffsets(); } -void multiSlsDetector::addSlsDetector (std::string s) { +void multiSlsDetector::addSlsDetector(std::string s) { #ifdef VERBOSE - std::cout << "Adding detector " << s << std::endl; + std::cout << "Adding detector " << s << std::endl; #endif - for (auto& d : detectors) { - if (d->getHostname() == s) { - std::cout << "Detector " << s << "already part of the multiDetector!" << std::endl - << "Remove it before adding it back in a new position!" << std::endl; - return; - } - } + for (auto &d : detectors) { + if (d->getHostname() == s) { + std::cout << "Detector " << s + << "already part of the multiDetector!" << std::endl + << "Remove it before adding it back in a new position!" + << std::endl; + return; + } + } - //check entire shared memory if it doesnt exist?? needed? - //could be that detectors not loaded completely cuz of crash in new slsdetector in initsharedmemory + // check entire shared memory if it doesnt exist?? needed? + // could be that detectors not loaded completely cuz of crash in new + // slsdetector in initsharedmemory - // get type by connecting - detectorType type = slsDetector::getDetectorType(s.c_str(), DEFAULT_PORTNO); - if (type == GENERIC) { - std::cout << "Could not connect to Detector " << s << " to determine the type!" << std::endl; - setErrorMask(getErrorMask() | MULTI_DETECTORS_NOT_ADDED); - appendNotAddedList(s.c_str()); - return; - } + // get type by connecting + detectorType type = slsDetector::getDetectorType(s.c_str(), DEFAULT_PORTNO); + if (type == GENERIC) { + std::cout << "Could not connect to Detector " << s + << " to determine the type!" << std::endl; + setErrorMask(getErrorMask() | MULTI_DETECTORS_NOT_ADDED); + appendNotAddedList(s.c_str()); + return; + } - int pos = (int)detectors.size(); - detectors.push_back(sls::make_unique(type, detId, pos, false)); - thisMultiDetector->numberOfDetectors = detectors.size(); - detectors[pos]->setHostname(s.c_str()); // also updates client - thisMultiDetector->dataBytes += detectors[pos]->getDataBytes(); - thisMultiDetector->dataBytesInclGapPixels += detectors[pos]->getDataBytesInclGapPixels(); - thisMultiDetector->numberOfChannels += detectors[pos]->getTotalNumberOfChannels(); + int pos = (int)detectors.size(); + detectors.push_back(sls::make_unique(type, detId, pos, false)); + thisMultiDetector->numberOfDetectors = detectors.size(); + detectors[pos]->setHostname(s.c_str()); // also updates client + thisMultiDetector->dataBytes += detectors[pos]->getDataBytes(); + thisMultiDetector->dataBytesInclGapPixels += + detectors[pos]->getDataBytesInclGapPixels(); + thisMultiDetector->numberOfChannels += + detectors[pos]->getTotalNumberOfChannels(); } - - slsDetectorDefs::detectorType multiSlsDetector::getDetectorsType(int detPos) { - // single - if (detPos >= 0) { - return detectors[detPos]->getDetectorsType(); - } + // single + if (detPos >= 0) { + return detectors[detPos]->getDetectorsType(); + } - // multi - auto r = serialCall(&slsDetector::getDetectorsType); - return (detectorType)sls::minusOneIfDifferent(r); + // multi + auto r = serialCall(&slsDetector::getDetectorsType); + return (detectorType)sls::minusOneIfDifferent(r); } - std::string multiSlsDetector::sgetDetectorsType(int detPos) { - // single - if (detPos >= 0) { - return detectors[detPos]->sgetDetectorsType(); - } + // single + if (detPos >= 0) { + return detectors[detPos]->sgetDetectorsType(); + } - // multi - auto r = serialCall(&slsDetector::sgetDetectorsType); - return sls::concatenateIfDifferent(r); + // multi + auto r = serialCall(&slsDetector::sgetDetectorsType); + return sls::concatenateIfDifferent(r); } - - std::string multiSlsDetector::getDetectorType(int detPos) { - return sgetDetectorsType(detPos); -} - - -int multiSlsDetector::getNumberOfDetectors() { - return detectors.size(); + return sgetDetectorsType(detPos); } +int multiSlsDetector::getNumberOfDetectors() { return detectors.size(); } int multiSlsDetector::getNumberOfDetectors(dimension d) { - return thisMultiDetector->numberOfDetector[d]; + return thisMultiDetector->numberOfDetector[d]; } - -void multiSlsDetector::getNumberOfDetectors(int& nx, int& ny) { - nx=thisMultiDetector->numberOfDetector[X]; - ny=thisMultiDetector->numberOfDetector[Y]; +void multiSlsDetector::getNumberOfDetectors(int &nx, int &ny) { + nx = thisMultiDetector->numberOfDetector[X]; + ny = thisMultiDetector->numberOfDetector[Y]; } - int multiSlsDetector::getTotalNumberOfChannels(int detPos) { - // single - if (detPos >= 0) { - return detectors[detPos]->getTotalNumberOfChannels(); - } + // single + if (detPos >= 0) { + return detectors[detPos]->getTotalNumberOfChannels(); + } - // multi - return thisMultiDetector->numberOfChannels; + // multi + return thisMultiDetector->numberOfChannels; } - int multiSlsDetector::getTotalNumberOfChannels(dimension d, int detPos) { - // single - if (detPos >= 0) { - return detectors[detPos]->getTotalNumberOfChannels(d); - } + // single + if (detPos >= 0) { + return detectors[detPos]->getTotalNumberOfChannels(d); + } - // multi - return thisMultiDetector->numberOfChannel[d]; + // multi + return thisMultiDetector->numberOfChannel[d]; } +int multiSlsDetector::getTotalNumberOfChannelsInclGapPixels(dimension d, + int detPos) { + // single + if (detPos >= 0) { + return detectors[detPos]->getTotalNumberOfChannelsInclGapPixels(d); + } -int multiSlsDetector::getTotalNumberOfChannelsInclGapPixels(dimension d, int detPos) { - // single - if (detPos >= 0) { - return detectors[detPos]->getTotalNumberOfChannelsInclGapPixels(d); - } - - // multi - return thisMultiDetector->numberOfChannelInclGapPixels[d]; + // multi + return thisMultiDetector->numberOfChannelInclGapPixels[d]; } - int multiSlsDetector::getMaxNumberOfChannelsPerDetector(dimension d) { - return thisMultiDetector->maxNumberOfChannelsPerDetector[d]; + return thisMultiDetector->maxNumberOfChannelsPerDetector[d]; } - -int multiSlsDetector::setMaxNumberOfChannelsPerDetector(dimension d,int i) { - thisMultiDetector->maxNumberOfChannelsPerDetector[d] = i; - return thisMultiDetector->maxNumberOfChannelsPerDetector[d]; +int multiSlsDetector::setMaxNumberOfChannelsPerDetector(dimension d, int i) { + thisMultiDetector->maxNumberOfChannelsPerDetector[d] = i; + return thisMultiDetector->maxNumberOfChannelsPerDetector[d]; } - int multiSlsDetector::getDetectorOffset(dimension d, int detPos) { - return detectors[detPos]->getDetectorOffset(d); + return detectors[detPos]->getDetectorOffset(d); } - void multiSlsDetector::setDetectorOffset(dimension d, int off, int detPos) { - detectors[detPos]->setDetectorOffset(d, off); + detectors[detPos]->setDetectorOffset(d, off); } - void multiSlsDetector::updateOffsets() { - //cannot paralllize due to slsdetector calling this via parentdet-> + // cannot paralllize due to slsdetector calling this via parentdet-> #ifdef VERBOSE - std::cout << std::endl - << "Updating Multi-Detector Offsets" << std::endl; + std::cout << std::endl << "Updating Multi-Detector Offsets" << std::endl; #endif - int offsetX = 0, offsetY = 0, numX = 0, numY = 0; - int maxChanX = thisMultiDetector->maxNumberOfChannelsPerDetector[X]; - int maxChanY = thisMultiDetector->maxNumberOfChannelsPerDetector[Y]; - int prevChanX = 0; - int prevChanY = 0; - bool firstTime = true; + int offsetX = 0, offsetY = 0, numX = 0, numY = 0; + int maxChanX = thisMultiDetector->maxNumberOfChannelsPerDetector[X]; + int maxChanY = thisMultiDetector->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; + thisMultiDetector->numberOfChannel[X] = 0; + thisMultiDetector->numberOfChannel[Y] = 0; + thisMultiDetector->numberOfDetector[X] = 0; + thisMultiDetector->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; + // 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; - - for (size_t idet = 0; idet < detectors.size(); ++idet) { + for (size_t idet = 0; idet < detectors.size(); ++idet) { #ifdef VERBOSE - std::cout << "offsetX:" << offsetX << " prevChanX:" << prevChanX << " " - "offsetY:" << offsetY << " prevChanY:" << prevChanY << std::endl; - std::cout << "offsetX_gp:" << offsetX_gp << " " - "prevChanX_gp:" << prevChanX_gp << " " - "offsetY_gp:" << offsetY_gp << " " - "prevChanY_gp:" << prevChanY_gp << std::endl; + std::cout << "offsetX:" << offsetX << " prevChanX:" << prevChanX + << " " + "offsetY:" + << offsetY << " prevChanY:" << prevChanY << std::endl; + std::cout << "offsetX_gp:" << offsetX_gp + << " " + "prevChanX_gp:" + << prevChanX_gp + << " " + "offsetY_gp:" + << offsetY_gp + << " " + "prevChanY_gp:" + << prevChanY_gp << std::endl; #endif - //std::cout<<" totalchan:"<< detectors[idet]->getTotalNumberOfChannels(Y) - //<<" maxChanY:"< 0) && ((offsetX + detectors[idet]->getTotalNumberOfChannels(X)) - > maxChanX)) - std::cout << "\nDetector[" << idet << "] exceeds maximum channels " - "allowed for complete detector set in X dimension!" << std::endl; - if ((maxChanY > 0) && ((offsetY + detectors[idet]->getTotalNumberOfChannels(Y)) - > maxChanY)) - std::cout << "\nDetector[" << idet << "] exceeds maximum channels " - "allowed for complete detector set in Y dimension!" << std::endl; - prevChanX = detectors[idet]->getTotalNumberOfChannels(X); - prevChanY = detectors[idet]->getTotalNumberOfChannels(Y); - prevChanX_gp = detectors[idet]->getTotalNumberOfChannelsInclGapPixels(X); - prevChanY_gp = detectors[idet]->getTotalNumberOfChannelsInclGapPixels(Y); - numX += detectors[idet]->getTotalNumberOfChannels(X); - numY += detectors[idet]->getTotalNumberOfChannels(Y); - numX_gp += detectors[idet]->getTotalNumberOfChannelsInclGapPixels(X); - numY_gp += detectors[idet]->getTotalNumberOfChannelsInclGapPixels(Y); - ++thisMultiDetector->numberOfDetector[X]; - ++thisMultiDetector->numberOfDetector[Y]; + // std::cout<<" totalchan:"<< + // detectors[idet]->getTotalNumberOfChannels(Y) + //<<" maxChanY:"< 0) && + ((offsetX + detectors[idet]->getTotalNumberOfChannels(X)) > + maxChanX)) + std::cout << "\nDetector[" << idet + << "] exceeds maximum channels " + "allowed for complete detector set in X dimension!" + << std::endl; + if ((maxChanY > 0) && + ((offsetY + detectors[idet]->getTotalNumberOfChannels(Y)) > + maxChanY)) + std::cout << "\nDetector[" << idet + << "] exceeds maximum channels " + "allowed for complete detector set in Y dimension!" + << std::endl; + prevChanX = detectors[idet]->getTotalNumberOfChannels(X); + prevChanY = detectors[idet]->getTotalNumberOfChannels(Y); + prevChanX_gp = + detectors[idet]->getTotalNumberOfChannelsInclGapPixels(X); + prevChanY_gp = + detectors[idet]->getTotalNumberOfChannelsInclGapPixels(Y); + numX += detectors[idet]->getTotalNumberOfChannels(X); + numY += detectors[idet]->getTotalNumberOfChannels(Y); + numX_gp += + detectors[idet]->getTotalNumberOfChannelsInclGapPixels(X); + numY_gp += + detectors[idet]->getTotalNumberOfChannelsInclGapPixels(Y); + ++thisMultiDetector->numberOfDetector[X]; + ++thisMultiDetector->numberOfDetector[Y]; #ifdef VERBOSE - std::cout << "incrementing in both direction" << std::endl; + std::cout << "incrementing in both direction" << std::endl; #endif - } + } - //incrementing in y direction - else if ((maxChanY == -1) || ((maxChanY > 0) && - ((offsetY + prevChanY + detectors[idet]->getTotalNumberOfChannels(Y)) - <= maxChanY))) { - offsetY += prevChanY; - offsetY_gp += prevChanY_gp; - prevChanY = detectors[idet]->getTotalNumberOfChannels(Y); - prevChanY_gp = detectors[idet]->getTotalNumberOfChannelsInclGapPixels(Y); - numY += detectors[idet]->getTotalNumberOfChannels(Y); - numY_gp += detectors[idet]->getTotalNumberOfChannelsInclGapPixels(Y); - ++thisMultiDetector->numberOfDetector[Y]; + // incrementing in y direction + else if ((maxChanY == -1) || + ((maxChanY > 0) && ((offsetY + prevChanY + + detectors[idet]->getTotalNumberOfChannels( + Y)) <= maxChanY))) { + offsetY += prevChanY; + offsetY_gp += prevChanY_gp; + prevChanY = detectors[idet]->getTotalNumberOfChannels(Y); + prevChanY_gp = + detectors[idet]->getTotalNumberOfChannelsInclGapPixels(Y); + numY += detectors[idet]->getTotalNumberOfChannels(Y); + numY_gp += + detectors[idet]->getTotalNumberOfChannelsInclGapPixels(Y); + ++thisMultiDetector->numberOfDetector[Y]; #ifdef VERBOSE - std::cout << "incrementing in y direction" << std::endl; + std::cout << "incrementing in y direction" << std::endl; #endif - } + } - //incrementing in x direction - else { - if ((maxChanX > 0) && - ((offsetX + prevChanX + detectors[idet]->getTotalNumberOfChannels(X)) - > maxChanX)) - std::cout << "\nDetector[" << idet << "] exceeds maximum channels " - "allowed for complete detector set in X dimension!" << std::endl; - offsetY = 0; - offsetY_gp = 0; - prevChanY = detectors[idet]->getTotalNumberOfChannels(Y); - prevChanY_gp = detectors[idet]->getTotalNumberOfChannelsInclGapPixels(Y); - numY = 0; //assuming symmetry with this statement. - //whats on 1st column should be on 2nd column - numY_gp = 0; - offsetX += prevChanX; - offsetX_gp += prevChanX_gp; - prevChanX = detectors[idet]->getTotalNumberOfChannels(X); - prevChanX_gp = detectors[idet]->getTotalNumberOfChannelsInclGapPixels(X); - numX += detectors[idet]->getTotalNumberOfChannels(X); - numX_gp += detectors[idet]->getTotalNumberOfChannelsInclGapPixels(X); - ++thisMultiDetector->numberOfDetector[X]; + // incrementing in x direction + else { + if ((maxChanX > 0) && + ((offsetX + prevChanX + + detectors[idet]->getTotalNumberOfChannels(X)) > maxChanX)) + std::cout << "\nDetector[" << idet + << "] exceeds maximum channels " + "allowed for complete detector set in X dimension!" + << std::endl; + offsetY = 0; + offsetY_gp = 0; + prevChanY = detectors[idet]->getTotalNumberOfChannels(Y); + prevChanY_gp = + detectors[idet]->getTotalNumberOfChannelsInclGapPixels(Y); + numY = 0; // assuming symmetry with this statement. + // whats on 1st column should be on 2nd column + numY_gp = 0; + offsetX += prevChanX; + offsetX_gp += prevChanX_gp; + prevChanX = detectors[idet]->getTotalNumberOfChannels(X); + prevChanX_gp = + detectors[idet]->getTotalNumberOfChannelsInclGapPixels(X); + numX += detectors[idet]->getTotalNumberOfChannels(X); + numX_gp += + detectors[idet]->getTotalNumberOfChannelsInclGapPixels(X); + ++thisMultiDetector->numberOfDetector[X]; #ifdef VERBOSE - std::cout << "incrementing in x direction" << std::endl; + std::cout << "incrementing in x direction" << std::endl; #endif - } + } - double bytesperchannel = (double)detectors[idet]->getDataBytes() / - (double)(detectors[idet]->getTotalNumberOfChannels(X) - * detectors[idet]->getTotalNumberOfChannels(Y)); - detectors[idet]->setDetectorOffset(X, (bytesperchannel >= 1.0) ? offsetX_gp : offsetX); - detectors[idet]->setDetectorOffset(Y, (bytesperchannel >= 1.0) ? offsetY_gp : offsetY); + double bytesperchannel = + (double)detectors[idet]->getDataBytes() / + (double)(detectors[idet]->getTotalNumberOfChannels(X) * + detectors[idet]->getTotalNumberOfChannels(Y)); + detectors[idet]->setDetectorOffset( + X, (bytesperchannel >= 1.0) ? offsetX_gp : offsetX); + detectors[idet]->setDetectorOffset( + Y, (bytesperchannel >= 1.0) ? offsetY_gp : offsetY); #ifdef VERBOSE - std::cout << "Detector[" << idet << "] has offsets (" << - detectors[idet]->getDetectorOffset(X) << ", " << - detectors[idet]->getDetectorOffset(Y) << ")" << std::endl; + std::cout << "Detector[" << idet << "] has offsets (" + << detectors[idet]->getDetectorOffset(X) << ", " + << detectors[idet]->getDetectorOffset(Y) << ")" << std::endl; #endif - //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 (numY > thisMultiDetector->numberOfChannel[Y]) - thisMultiDetector->numberOfChannel[Y] = numY; - if (numX_gp > thisMultiDetector->numberOfChannelInclGapPixels[X]) - thisMultiDetector->numberOfChannelInclGapPixels[X] = numX_gp; - if (numY_gp > thisMultiDetector->numberOfChannelInclGapPixels[Y]) - thisMultiDetector->numberOfChannelInclGapPixels[Y] = numY_gp; - } + // 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 (numY > thisMultiDetector->numberOfChannel[Y]) + thisMultiDetector->numberOfChannel[Y] = numY; + if (numX_gp > thisMultiDetector->numberOfChannelInclGapPixels[X]) + thisMultiDetector->numberOfChannelInclGapPixels[X] = numX_gp; + if (numY_gp > thisMultiDetector->numberOfChannelInclGapPixels[Y]) + thisMultiDetector->numberOfChannelInclGapPixels[Y] = numY_gp; + } #ifdef VERBOSE - std::cout << "Number of Channels in X direction:" << thisMultiDetector->numberOfChannel[X] << std::endl; - std::cout << "Number of Channels in Y direction:" << thisMultiDetector->numberOfChannel[Y] << std::endl - << std::endl; - std::cout << "Number of Channels in X direction with Gap Pixels:" << - thisMultiDetector->numberOfChannelInclGapPixels[X] << std::endl; - std::cout << "Number of Channels in Y direction with Gap Pixels:" << - thisMultiDetector->numberOfChannelInclGapPixels[Y] << std::endl - << std::endl; + std::cout << "Number of Channels in X direction:" + << thisMultiDetector->numberOfChannel[X] << std::endl; + std::cout << "Number of Channels in Y direction:" + << thisMultiDetector->numberOfChannel[Y] << std::endl + << std::endl; + std::cout << "Number of Channels in X direction with Gap Pixels:" + << thisMultiDetector->numberOfChannelInclGapPixels[X] + << std::endl; + std::cout << "Number of Channels in Y direction with Gap Pixels:" + << thisMultiDetector->numberOfChannelInclGapPixels[Y] << std::endl + << std::endl; #endif - thisMultiDetector->numberOfChannels = - thisMultiDetector->numberOfChannel[0] * - thisMultiDetector->numberOfChannel[1]; + thisMultiDetector->numberOfChannels = + thisMultiDetector->numberOfChannel[0] * + thisMultiDetector->numberOfChannel[1]; - for (auto& d : detectors) { - d->updateMultiSize(thisMultiDetector->numberOfDetector[0], - thisMultiDetector->numberOfDetector[1]); - } + for (auto &d : detectors) { + d->updateMultiSize(thisMultiDetector->numberOfDetector[0], + thisMultiDetector->numberOfDetector[1]); + } } - int multiSlsDetector::setOnline(int off, int detPos) { - // single - if (detPos >= 0) { - return detectors[detPos]->setOnline(off); - } + // single + if (detPos >= 0) { + return detectors[detPos]->setOnline(off); + } - // multi - if (off != GET_ONLINE_FLAG) { - auto r = parallelCall(&slsDetector::setOnline, off); - thisMultiDetector->onlineFlag = sls::minusOneIfDifferent(r); - } - return thisMultiDetector->onlineFlag; + // multi + if (off != GET_ONLINE_FLAG) { + auto r = parallelCall(&slsDetector::setOnline, off); + thisMultiDetector->onlineFlag = sls::minusOneIfDifferent(r); + } + return thisMultiDetector->onlineFlag; } - std::string multiSlsDetector::checkOnline(int detPos) { - if (detPos >= 0) - return detectors[detPos]->checkOnline(); + if (detPos >= 0) + return detectors[detPos]->checkOnline(); - auto r = parallelCall(&slsDetector::checkOnline); - return sls::concatenateNonEmptyStrings(r); + auto r = parallelCall(&slsDetector::checkOnline); + return sls::concatenateNonEmptyStrings(r); } - int multiSlsDetector::setPort(portType t, int num, int detPos) { - if (detPos >= 0) - return detectors[detPos]->setPort(t, num); - - auto r = serialCall(&slsDetector::setPort, t, num); - return sls::minusOneIfDifferent(r); -} + if (detPos >= 0) + return detectors[detPos]->setPort(t, num); + auto r = serialCall(&slsDetector::setPort, t, num); + return sls::minusOneIfDifferent(r); +} int multiSlsDetector::lockServer(int p, int detPos) { - // single - if (detPos >= 0) { - return detectors[detPos]->lockServer(p); - } + // single + if (detPos >= 0) { + return detectors[detPos]->lockServer(p); + } - // multi - auto r = parallelCall(&slsDetector::lockServer, p); - return sls::minusOneIfDifferent(r); + // multi + auto r = parallelCall(&slsDetector::lockServer, p); + return sls::minusOneIfDifferent(r); } - std::string multiSlsDetector::getLastClientIP(int detPos) { - // single - if (detPos >= 0) { - return detectors[detPos]->getLastClientIP(); - } + // single + if (detPos >= 0) { + return detectors[detPos]->getLastClientIP(); + } - // multi - auto r = parallelCall(&slsDetector::getLastClientIP); - return sls::concatenateIfDifferent(r); + // multi + auto r = parallelCall(&slsDetector::getLastClientIP); + return sls::concatenateIfDifferent(r); } - int multiSlsDetector::exitServer(int detPos) { - // single - if (detPos >= 0) { - return detectors[detPos]->exitServer(); - } + // single + if (detPos >= 0) { + return detectors[detPos]->exitServer(); + } - // multi - auto r = parallelCall(&slsDetector::exitServer); - return sls::allEqualTo(r, static_cast(OK)) ? OK : FAIL; + // multi + auto r = parallelCall(&slsDetector::exitServer); + return sls::allEqualTo(r, static_cast(OK)) ? OK : FAIL; } - int multiSlsDetector::execCommand(std::string cmd, int detPos) { - // single - if (detPos >= 0) { - return detectors[detPos]->execCommand(cmd); - } + // single + if (detPos >= 0) { + return detectors[detPos]->execCommand(cmd); + } - // multi - auto r = parallelCall(&slsDetector::execCommand, cmd); - return sls::allEqualTo(r, static_cast(OK)) ? OK : FAIL; + // multi + auto r = parallelCall(&slsDetector::execCommand, cmd); + return sls::allEqualTo(r, static_cast(OK)) ? OK : FAIL; } -int multiSlsDetector::readConfigurationFile(const std::string& fname) { - freeSharedMemory(); - setupMultiDetector(); +int multiSlsDetector::readConfigurationFile(const std::string &fname) { + freeSharedMemory(); + setupMultiDetector(); - char* args[100]; - char myargs[100][1000]; - std::cout << "Loading configuration file: " << fname << std::endl; + char *args[100]; + char myargs[100][1000]; + std::cout << "Loading configuration file: " << fname << std::endl; - std::ifstream input_file; - input_file.open(fname, std::ios_base::in); - if (input_file.is_open()) { - std::string current_line; - while (input_file.good()) { - getline(input_file, current_line); - if (current_line.find('#') != std::string::npos) - current_line.erase(current_line.find('#')); + std::ifstream input_file; + input_file.open(fname, std::ios_base::in); + if (input_file.is_open()) { + std::string current_line; + while (input_file.good()) { + getline(input_file, current_line); + if (current_line.find('#') != std::string::npos) + current_line.erase(current_line.find('#')); #ifdef VERBOSE - std::cout << "current_line after removing comments:" << current_line << std::endl; + std::cout << "current_line after removing comments:" << current_line + << std::endl; #endif - if (current_line.length() > 1) { - std::istringstream line_stream(current_line); - int n_arguments = 0; - std::string current_argument; - while (line_stream.good()) { - line_stream >> current_argument; - strcpy(myargs[n_arguments], current_argument.c_str()); - args[n_arguments] = myargs[n_arguments]; - ++n_arguments; - } - multiSlsDetectorClient(n_arguments, args, PUT_ACTION, this); - } - } - input_file.close(); - } else { - std::cout << "Error opening configuration file " << fname << " for reading" << std::endl; - setErrorMask(getErrorMask() | MULTI_CONFIG_FILE_ERROR); - return FAIL; - } + if (current_line.length() > 1) { + std::istringstream line_stream(current_line); + int n_arguments = 0; + std::string current_argument; + while (line_stream.good()) { + line_stream >> current_argument; + strcpy(myargs[n_arguments], current_argument.c_str()); + args[n_arguments] = myargs[n_arguments]; + ++n_arguments; + } + multiSlsDetectorClient(n_arguments, args, PUT_ACTION, this); + } + } + input_file.close(); + } else { + std::cout << "Error opening configuration file " << fname + << " for reading" << std::endl; + setErrorMask(getErrorMask() | MULTI_CONFIG_FILE_ERROR); + return FAIL; + } - if (getErrorMask()) { - int c; - cprintf(RED, "\n----------------\n Error Messages\n----------------\n%s\n", - getErrorMessage(c).c_str()); - return FAIL; - } - return OK; + if (getErrorMask()) { + int c; + cprintf(RED, + "\n----------------\n Error Messages\n----------------\n%s\n", + getErrorMessage(c).c_str()); + return FAIL; + } + return OK; } +int multiSlsDetector::writeConfigurationFile(const std::string &fname) { + const std::vector names = {"detsizechan", "hostname", "outdir", + "threaded"}; -int multiSlsDetector::writeConfigurationFile(const std::string& fname) { - const std::vector names = { - "detsizechan", - "hostname", - "outdir", - "threaded" - }; + char *args[100]; + for (int ia = 0; ia < 100; ++ia) { + args[ia] = new char[1000]; + } + int ret = OK, ret1 = OK; + std::ofstream outfile; + size_t iline = 0; - char* args[100]; - for (int ia = 0; ia < 100; ++ia) { - args[ia] = new char[1000]; - } - int ret = OK, ret1 = OK; - std::ofstream outfile; - size_t iline = 0; + outfile.open(fname.c_str(), std::ios_base::out); + if (outfile.is_open()) { + auto cmd = slsDetectorCommand(this); - outfile.open(fname.c_str(), std::ios_base::out); - if (outfile.is_open()) { - auto cmd = slsDetectorCommand(this); + // complete size of detector + std::cout << iline << " " << names[iline] << std::endl; + strcpy(args[0], names[iline].c_str()); + outfile << names[iline] << " " << cmd.executeLine(1, args, GET_ACTION) + << std::endl; + ++iline; - // complete size of detector - std::cout << iline << " " << names[iline] << std::endl; - strcpy(args[0], names[iline].c_str()); - outfile << names[iline] << " " << cmd.executeLine(1, args, GET_ACTION) << std::endl; - ++iline; + // hostname of the detectors + std::cout << iline << " " << names[iline] << std::endl; + strcpy(args[0], names[iline].c_str()); + outfile << names[iline] << " " << cmd.executeLine(1, args, GET_ACTION) + << std::endl; + ++iline; - // hostname of the detectors - std::cout << iline << " " << names[iline] << std::endl; - strcpy(args[0], names[iline].c_str()); - outfile << names[iline] << " " << cmd.executeLine(1, args, GET_ACTION) << std::endl; - ++iline; + // single detector configuration + for (size_t idet = 0; idet < detectors.size(); ++idet) { + outfile << std::endl; + ret1 = detectors[idet]->writeConfigurationFile(outfile, this); + if (detectors[idet]->getErrorMask()) + setErrorMask(getErrorMask() | (1 << idet)); + if (ret1 == FAIL) + ret = FAIL; + } - // single detector configuration - for (size_t idet = 0; idet < detectors.size(); ++idet) { - outfile << std::endl; - ret1 = detectors[idet]->writeConfigurationFile(outfile, this); - if (detectors[idet]->getErrorMask()) - setErrorMask(getErrorMask() | (1 << idet)); - if (ret1 == FAIL) - ret = FAIL; - } - - outfile << std::endl; - //other configurations - while (iline < names.size()) { - std::cout << iline << " " << names[iline] << std::endl; - strcpy(args[0], names[iline].c_str()); - outfile << names[iline] << " " << cmd.executeLine(1, args, GET_ACTION) << std::endl; - ++iline; - } - outfile.close(); + outfile << std::endl; + // other configurations + while (iline < names.size()) { + std::cout << iline << " " << names[iline] << std::endl; + strcpy(args[0], names[iline].c_str()); + outfile << names[iline] << " " + << cmd.executeLine(1, args, GET_ACTION) << std::endl; + ++iline; + } + outfile.close(); #ifdef VERBOSE - std::cout << "wrote " << iline << " lines to configuration file " << std::endl; + std::cout << "wrote " << iline << " lines to configuration file " + << std::endl; #endif - } else { - std::cout << "Error opening configuration file " << fname << " for writing" << std::endl; - setErrorMask(getErrorMask() | MULTI_CONFIG_FILE_ERROR); - ret = FAIL; - } + } else { + std::cout << "Error opening configuration file " << fname + << " for writing" << std::endl; + setErrorMask(getErrorMask() | MULTI_CONFIG_FILE_ERROR); + ret = FAIL; + } - for (int ia = 0; ia < 100; ++ia) { - delete[] args[ia]; - } + for (int ia = 0; ia < 100; ++ia) { + delete[] args[ia]; + } - return ret; + return ret; } - - std::string multiSlsDetector::getSettingsFile(int detPos) { - // single - if (detPos >= 0) { - return detectors[detPos]->getSettingsFile(); - } + // single + if (detPos >= 0) { + return detectors[detPos]->getSettingsFile(); + } - // multi - auto r = serialCall(&slsDetector::getSettingsFile); - return sls::concatenateIfDifferent(r); + // multi + auto r = serialCall(&slsDetector::getSettingsFile); + return sls::concatenateIfDifferent(r); } - slsDetectorDefs::detectorSettings multiSlsDetector::getSettings(int detPos) { - // single - if (detPos >= 0) { - return detectors[detPos]->getSettings(); - } + // single + if (detPos >= 0) { + return detectors[detPos]->getSettings(); + } - // multi - auto r = parallelCall(&slsDetector::getSettings); - return (detectorSettings)sls::minusOneIfDifferent(r); + // multi + auto r = parallelCall(&slsDetector::getSettings); + return (detectorSettings)sls::minusOneIfDifferent(r); } +slsDetectorDefs::detectorSettings +multiSlsDetector::setSettings(detectorSettings isettings, int detPos) { + // single + if (detPos >= 0) { + return detectors[detPos]->setSettings(isettings); + } - - -slsDetectorDefs::detectorSettings multiSlsDetector::setSettings(detectorSettings isettings, - int detPos) { - // single - if (detPos >= 0) { - return detectors[detPos]->setSettings(isettings); - } - - // multi - auto r = parallelCall(&slsDetector::setSettings, isettings); - return (detectorSettings)sls::minusOneIfDifferent(r); + // multi + auto r = parallelCall(&slsDetector::setSettings, isettings); + return (detectorSettings)sls::minusOneIfDifferent(r); } - - - int multiSlsDetector::getThresholdEnergy(int detPos) { - // single - if (detPos >= 0) { - return detectors[detPos]->getThresholdEnergy(); - } + // single + if (detPos >= 0) { + return detectors[detPos]->getThresholdEnergy(); + } - // multi - auto r = parallelCall(&slsDetector::getThresholdEnergy); - if (sls::allEqualWithTol(r, 200)) - return r.front(); - return -1; + // multi + auto r = parallelCall(&slsDetector::getThresholdEnergy); + if (sls::allEqualWithTol(r, 200)) + return r.front(); + return -1; } +int multiSlsDetector::setThresholdEnergy(int e_eV, detectorSettings isettings, + int tb, int detPos) { + // single + if (detPos >= 0) { + return detectors[detPos]->setThresholdEnergy(e_eV, isettings, tb); + } -int multiSlsDetector::setThresholdEnergy(int e_eV, detectorSettings isettings, int tb, int detPos) { - // single - if (detPos >= 0) { - return detectors[detPos]->setThresholdEnergy(e_eV, isettings, tb); - } - - // multi - auto r = parallelCall(&slsDetector::setThresholdEnergy, e_eV, isettings, tb); - if (sls::allEqualWithTol(r, 200)) - return r.front(); - return -1; + // multi + auto r = + parallelCall(&slsDetector::setThresholdEnergy, e_eV, isettings, tb); + if (sls::allEqualWithTol(r, 200)) + return r.front(); + return -1; } - std::string multiSlsDetector::getSettingsDir(int detPos) { - // single - if (detPos >= 0) { - return detectors[detPos]->getSettingsDir(); - } + // single + if (detPos >= 0) { + return detectors[detPos]->getSettingsDir(); + } - // multi - auto r = serialCall(&slsDetector::getSettingsDir); - return sls::concatenateIfDifferent(r); + // multi + auto r = serialCall(&slsDetector::getSettingsDir); + return sls::concatenateIfDifferent(r); } +std::string multiSlsDetector::setSettingsDir(std::string directory, + int detPos) { + if (detPos >= 0) + return detectors[detPos]->setSettingsDir(directory); -std::string multiSlsDetector::setSettingsDir(std::string directory, int detPos) { - if (detPos >= 0) - return detectors[detPos]->setSettingsDir(directory); - - auto r = parallelCall(&slsDetector::setSettingsDir, directory); - return sls::concatenateIfDifferent(r); + auto r = parallelCall(&slsDetector::setSettingsDir, directory); + return sls::concatenateIfDifferent(r); } - int multiSlsDetector::loadSettingsFile(std::string fname, int detPos) { - // single - if (detPos >= 0) { - return detectors[detPos]->loadSettingsFile(fname); - } + // single + if (detPos >= 0) { + return detectors[detPos]->loadSettingsFile(fname); + } - // multi - auto r = parallelCall(&slsDetector::loadSettingsFile, fname); - return sls::allEqualTo(r, static_cast(OK)) ? OK : FAIL; + // multi + auto r = parallelCall(&slsDetector::loadSettingsFile, fname); + return sls::allEqualTo(r, static_cast(OK)) ? OK : FAIL; } int multiSlsDetector::saveSettingsFile(std::string fname, int detPos) { - // single - if (detPos >= 0) { - return detectors[detPos]->saveSettingsFile(fname); - } + // single + if (detPos >= 0) { + return detectors[detPos]->saveSettingsFile(fname); + } - // multi - auto r = parallelCall(&slsDetector::saveSettingsFile, fname); - return sls::allEqualTo(r, static_cast(OK)) ? OK : FAIL; + // multi + auto r = parallelCall(&slsDetector::saveSettingsFile, fname); + return sls::allEqualTo(r, static_cast(OK)) ? OK : FAIL; } - slsDetectorDefs::runStatus multiSlsDetector::getRunStatus(int detPos) { - // single - if (detPos >= 0) { - return detectors[detPos]->getRunStatus(); - } + // single + if (detPos >= 0) { + return detectors[detPos]->getRunStatus(); + } - // multi - auto r = parallelCall(&slsDetector::getRunStatus); + // multi + auto r = parallelCall(&slsDetector::getRunStatus); if (sls::allEqual(r)) return r.front(); if (sls::anyEqualTo(r, ERROR)) return ERROR; - for (const auto& value : r) + for (const auto &value : r) if (value != IDLE) return value; - return IDLE; + return IDLE; } int multiSlsDetector::prepareAcquisition(int detPos) { - // single - if (detPos >= 0) { - return detectors[detPos]->prepareAcquisition(); - } + // single + if (detPos >= 0) { + return detectors[detPos]->prepareAcquisition(); + } - // multi - auto r = parallelCall(&slsDetector::prepareAcquisition); - return sls::allEqualTo(r, static_cast(OK)) ? OK : FAIL; + // multi + auto r = parallelCall(&slsDetector::prepareAcquisition); + return sls::allEqualTo(r, static_cast(OK)) ? OK : FAIL; } - int multiSlsDetector::startAcquisition(int detPos) { - // single - if (detPos >= 0) { - if (detectors[detPos]->getDetectorsType() == EIGER) { - if (detectors[detPos]->prepareAcquisition() == FAIL) - return FAIL; - } - return detectors[detPos]->startAcquisition(); - } + // single + if (detPos >= 0) { + if (detectors[detPos]->getDetectorsType() == EIGER) { + if (detectors[detPos]->prepareAcquisition() == FAIL) + return FAIL; + } + return detectors[detPos]->startAcquisition(); + } - // multi - if (getDetectorsType() == EIGER) { - if (prepareAcquisition() == FAIL) - return FAIL; - } + // multi + if (getDetectorsType() == EIGER) { + if (prepareAcquisition() == FAIL) + return FAIL; + } auto r = parallelCall(&slsDetector::startAcquisition); return sls::allEqualTo(r, static_cast(OK)) ? OK : FAIL; } - int multiSlsDetector::stopAcquisition(int detPos) { - // locks to synchronize using client->receiver simultaneously (processing thread) - std::lock_guard lock(mg); - if (detPos >= 0) { - // if only 1 detector, set flag to stop current acquisition - if (detectors.size() == 1) - thisMultiDetector->stoppedFlag = 1; + // locks to synchronize using client->receiver simultaneously (processing + // thread) + std::lock_guard lock(mg); + if (detPos >= 0) { + // if only 1 detector, set flag to stop current acquisition + if (detectors.size() == 1) + thisMultiDetector->stoppedFlag = 1; - return detectors[detPos]->stopAcquisition(); - } - else { - thisMultiDetector->stoppedFlag = 1; - auto r = parallelCall(&slsDetector::stopAcquisition); - return sls::allEqualTo(r, static_cast(OK)) ? OK : FAIL; - } + return detectors[detPos]->stopAcquisition(); + } else { + thisMultiDetector->stoppedFlag = 1; + auto r = parallelCall(&slsDetector::stopAcquisition); + return sls::allEqualTo(r, static_cast(OK)) ? OK : FAIL; + } } - - int multiSlsDetector::sendSoftwareTrigger(int detPos) { - // single - if (detPos >= 0) { - return detectors[detPos]->sendSoftwareTrigger(); - } + // single + if (detPos >= 0) { + return detectors[detPos]->sendSoftwareTrigger(); + } - // multi - auto r = parallelCall(&slsDetector::sendSoftwareTrigger); - return sls::allEqualTo(r, static_cast(OK)) ? OK : FAIL; + // multi + auto r = parallelCall(&slsDetector::sendSoftwareTrigger); + return sls::allEqualTo(r, static_cast(OK)) ? OK : FAIL; } - - int multiSlsDetector::startAndReadAll(int detPos) { - // single - if (detPos >= 0) { - if (detectors[detPos]->getDetectorsType() == EIGER) { - if (detectors[detPos]->prepareAcquisition() == FAIL) - return FAIL; - } - return detectors[detPos]->startAndReadAll(); - } + // single + if (detPos >= 0) { + if (detectors[detPos]->getDetectorsType() == EIGER) { + if (detectors[detPos]->prepareAcquisition() == FAIL) + return FAIL; + } + return detectors[detPos]->startAndReadAll(); + } - // multi - if (getDetectorsType() == EIGER) { - if (prepareAcquisition() == FAIL) - return FAIL; - } + // multi + if (getDetectorsType() == EIGER) { + if (prepareAcquisition() == FAIL) + return FAIL; + } auto r = parallelCall(&slsDetector::startAndReadAll); return sls::allEqualTo(r, static_cast(OK)) ? OK : FAIL; } - - - int multiSlsDetector::startReadOut(int detPos) { - // single - if (detPos >= 0) { - return detectors[detPos]->startReadOut(); - } + // single + if (detPos >= 0) { + return detectors[detPos]->startReadOut(); + } - // multi - auto r = parallelCall(&slsDetector::startReadOut); - return sls::allEqualTo(r, static_cast(OK)) ? OK : FAIL; + // multi + auto r = parallelCall(&slsDetector::startReadOut); + return sls::allEqualTo(r, static_cast(OK)) ? OK : FAIL; } - int multiSlsDetector::readAll(int detPos) { - // single - if (detPos >= 0) { - return detectors[detPos]->readAll(); - } + // single + if (detPos >= 0) { + return detectors[detPos]->readAll(); + } - // multi - auto r = parallelCall(&slsDetector::readAll); - return sls::allEqualTo(r, static_cast(OK)) ? OK : FAIL; + // multi + auto r = parallelCall(&slsDetector::readAll); + return sls::allEqualTo(r, static_cast(OK)) ? OK : FAIL; } - int multiSlsDetector::configureMAC(int detPos) { - // single - if (detPos >= 0) { - return detectors[detPos]->configureMAC(); - } + // single + if (detPos >= 0) { + return detectors[detPos]->configureMAC(); + } - // multi - auto r = parallelCall(&slsDetector::configureMAC); - return sls::allEqualTo(r, static_cast(OK)) ? OK : FAIL; + // multi + auto r = parallelCall(&slsDetector::configureMAC); + return sls::allEqualTo(r, static_cast(OK)) ? OK : FAIL; } - int64_t multiSlsDetector::setTimer(timerIndex index, int64_t t, int detPos) { - // single - if (detPos >= 0) { + // single + if (detPos >= 0) { - // error for setting values individually - // FIXME: what else? and error code - if (t!=-1){ - switch(index) { - case FRAME_NUMBER: - case CYCLES_NUMBER: - case STORAGE_CELL_NUMBER: - case MEASUREMENTS_NUMBER: - FILE_LOG(logERROR) << "Cannot set number of frames, cycles, " - "storage cells or measurements individually."; - setErrorMask(getErrorMask() | MUST_BE_MULTI_CMD); - return thisMultiDetector->timerValue[index]; - default: - break; - } - } + // error for setting values individually + // FIXME: what else? and error code + if (t != -1) { + switch (index) { + case FRAME_NUMBER: + case CYCLES_NUMBER: + case STORAGE_CELL_NUMBER: + case MEASUREMENTS_NUMBER: + FILE_LOG(logERROR) + << "Cannot set number of frames, cycles, " + "storage cells or measurements individually."; + setErrorMask(getErrorMask() | MUST_BE_MULTI_CMD); + return thisMultiDetector->timerValue[index]; + default: + break; + } + } - return detectors[detPos]->setTimer(index, t); - } + return detectors[detPos]->setTimer(index, t); + } - // multi - auto r = parallelCall(&slsDetector::setTimer, index, t); - int64_t ret = sls::minusOneIfDifferent(r); + // multi + auto r = parallelCall(&slsDetector::setTimer, index, t); + int64_t ret = sls::minusOneIfDifferent(r); - if (index == SAMPLES_JCTB) - setDynamicRange(); + if (index == SAMPLES_JCTB) + setDynamicRange(); - // set progress - if (t!=-1){ - switch(index) { - case FRAME_NUMBER: - case CYCLES_NUMBER: - case STORAGE_CELL_NUMBER: - case MEASUREMENTS_NUMBER: - setTotalProgress(); - break; - default: - break; - } - } + // set progress + if (t != -1) { + switch (index) { + case FRAME_NUMBER: + case CYCLES_NUMBER: + case STORAGE_CELL_NUMBER: + case MEASUREMENTS_NUMBER: + setTotalProgress(); + break; + default: + break; + } + } - thisMultiDetector->timerValue[index] = ret; - return ret; + thisMultiDetector->timerValue[index] = ret; + return ret; } +double multiSlsDetector::setExposureTime(double t, bool inseconds, int detPos) { + if (!inseconds) + return setTimer(ACQUISITION_TIME, (int64_t)t, detPos); -double multiSlsDetector::setExposureTime(double t, bool inseconds, int detPos){ - if(!inseconds) - return setTimer(ACQUISITION_TIME, (int64_t)t, detPos); - - // + 0.5 to round for precision lost from converting double to int64_t - int64_t tms = (int64_t)(t * (1E+9) + 0.5); - if (t < 0) tms = -1; - tms = setTimer(ACQUISITION_TIME, tms, detPos); - if (tms < 0) - return -1; - return ((1E-9) * (double)tms); + // + 0.5 to round for precision lost from converting double to int64_t + int64_t tms = (int64_t)(t * (1E+9) + 0.5); + if (t < 0) + tms = -1; + tms = setTimer(ACQUISITION_TIME, tms, detPos); + if (tms < 0) + return -1; + return ((1E-9) * (double)tms); } +double multiSlsDetector::setExposurePeriod(double t, bool inseconds, + int detPos) { + if (!inseconds) + return setTimer(FRAME_PERIOD, (int64_t)t, detPos); -double multiSlsDetector::setExposurePeriod(double t, bool inseconds, int detPos){ - if(!inseconds) - return setTimer(FRAME_PERIOD, (int64_t)t, detPos); - - // + 0.5 to round for precision lost from converting double to int64_t - int64_t tms = (int64_t)(t * (1E+9) + 0.5); - if (t < 0) tms = -1; - tms = setTimer(FRAME_PERIOD, tms, detPos); - if (tms < 0) - return -1; - return ((1E-9) * (double)tms); + // + 0.5 to round for precision lost from converting double to int64_t + int64_t tms = (int64_t)(t * (1E+9) + 0.5); + if (t < 0) + tms = -1; + tms = setTimer(FRAME_PERIOD, tms, detPos); + if (tms < 0) + return -1; + return ((1E-9) * (double)tms); } +double multiSlsDetector::setDelayAfterTrigger(double t, bool inseconds, + int detPos) { + if (!inseconds) + return setTimer(DELAY_AFTER_TRIGGER, (int64_t)t, detPos); -double multiSlsDetector::setDelayAfterTrigger(double t, bool inseconds, int detPos){ - if(!inseconds) - return setTimer(DELAY_AFTER_TRIGGER, (int64_t)t, detPos); - - // + 0.5 to round for precision lost from converting double to int64_t - int64_t tms = (int64_t)(t * (1E+9) + 0.5); - if (t < 0) tms = -1; - tms = setTimer(DELAY_AFTER_TRIGGER, tms, detPos); - if (tms < 0) - return -1; - return ((1E-9) * (double)tms); + // + 0.5 to round for precision lost from converting double to int64_t + int64_t tms = (int64_t)(t * (1E+9) + 0.5); + if (t < 0) + tms = -1; + tms = setTimer(DELAY_AFTER_TRIGGER, tms, detPos); + if (tms < 0) + return -1; + return ((1E-9) * (double)tms); } - -double multiSlsDetector::setSubFrameExposureTime(double t, bool inseconds, int detPos){ - if(!inseconds) - return setTimer(SUBFRAME_ACQUISITION_TIME, (int64_t)t, detPos); - else { - // + 0.5 to round for precision lost from converting double to int64_t - int64_t tms = (int64_t)(t * (1E+9) + 0.5); - if (t < 0) tms = -1; - tms = setTimer(SUBFRAME_ACQUISITION_TIME, tms, detPos); - if (tms < 0) - return -1; - return ((1E-9) * (double)tms); - } +double multiSlsDetector::setSubFrameExposureTime(double t, bool inseconds, + int detPos) { + if (!inseconds) + return setTimer(SUBFRAME_ACQUISITION_TIME, (int64_t)t, detPos); + else { + // + 0.5 to round for precision lost from converting double to int64_t + int64_t tms = (int64_t)(t * (1E+9) + 0.5); + if (t < 0) + tms = -1; + tms = setTimer(SUBFRAME_ACQUISITION_TIME, tms, detPos); + if (tms < 0) + return -1; + return ((1E-9) * (double)tms); + } } - -double multiSlsDetector::setSubFrameExposureDeadTime(double t, bool inseconds, int detPos){ - if(!inseconds) - return setTimer(SUBFRAME_DEADTIME, (int64_t)t, detPos); - else { - // + 0.5 to round for precision lost from converting double to int64_t - int64_t tms = (int64_t)(t * (1E+9) + 0.5); - if (t < 0) tms = -1; - tms = setTimer(SUBFRAME_DEADTIME, tms, detPos); - if (tms < 0) - return -1; - return ((1E-9) * (double)tms); - } +double multiSlsDetector::setSubFrameExposureDeadTime(double t, bool inseconds, + int detPos) { + if (!inseconds) + return setTimer(SUBFRAME_DEADTIME, (int64_t)t, detPos); + else { + // + 0.5 to round for precision lost from converting double to int64_t + int64_t tms = (int64_t)(t * (1E+9) + 0.5); + if (t < 0) + tms = -1; + tms = setTimer(SUBFRAME_DEADTIME, tms, detPos); + if (tms < 0) + return -1; + return ((1E-9) * (double)tms); + } } - -int64_t multiSlsDetector::setNumberOfFrames(int64_t t, int detPos){ - return setTimer(FRAME_NUMBER, t, detPos); +int64_t multiSlsDetector::setNumberOfFrames(int64_t t, int detPos) { + return setTimer(FRAME_NUMBER, t, detPos); } -int64_t multiSlsDetector::setNumberOfCycles(int64_t t, int detPos){ - return setTimer(CYCLES_NUMBER, t, detPos); +int64_t multiSlsDetector::setNumberOfCycles(int64_t t, int detPos) { + return setTimer(CYCLES_NUMBER, t, detPos); } -int64_t multiSlsDetector::setNumberOfGates(int64_t t, int detPos){ - return setTimer(GATES_NUMBER, t, detPos); +int64_t multiSlsDetector::setNumberOfGates(int64_t t, int detPos) { + return setTimer(GATES_NUMBER, t, detPos); } int64_t multiSlsDetector::setNumberOfStorageCells(int64_t t, int detPos) { - return setTimer(STORAGE_CELL_NUMBER, t, detPos); + return setTimer(STORAGE_CELL_NUMBER, t, detPos); } - -double multiSlsDetector::getMeasuredPeriod(bool inseconds, int detPos){ - if(!inseconds) - return getTimeLeft(MEASURED_PERIOD, detPos); - else { - int64_t tms = getTimeLeft(MEASURED_PERIOD, detPos); - if (tms < 0) - return -1; - return ((1E-9) * (double)tms); - } +double multiSlsDetector::getMeasuredPeriod(bool inseconds, int detPos) { + if (!inseconds) + return getTimeLeft(MEASURED_PERIOD, detPos); + else { + int64_t tms = getTimeLeft(MEASURED_PERIOD, detPos); + if (tms < 0) + return -1; + return ((1E-9) * (double)tms); + } } - -double multiSlsDetector::getMeasuredSubFramePeriod(bool inseconds, int detPos){ - if(!inseconds) - return getTimeLeft(MEASURED_SUBPERIOD, detPos); - else { - int64_t tms = getTimeLeft(MEASURED_SUBPERIOD, detPos); - if (tms < 0) - return -1; - return ((1E-9) * (double)tms); - } +double multiSlsDetector::getMeasuredSubFramePeriod(bool inseconds, int detPos) { + if (!inseconds) + return getTimeLeft(MEASURED_SUBPERIOD, detPos); + else { + int64_t tms = getTimeLeft(MEASURED_SUBPERIOD, detPos); + if (tms < 0) + return -1; + return ((1E-9) * (double)tms); + } } - int64_t multiSlsDetector::getTimeLeft(timerIndex index, int detPos) { - // single - if (detPos >= 0) { - return detectors[detPos]->getTimeLeft(index); - } + // single + if (detPos >= 0) { + return detectors[detPos]->getTimeLeft(index); + } - // multi - auto r = parallelCall(&slsDetector::getTimeLeft, index); - return sls::minusOneIfDifferent(r); + // multi + auto r = parallelCall(&slsDetector::getTimeLeft, index); + return sls::minusOneIfDifferent(r); } int multiSlsDetector::setSpeed(speedVariable index, int value, int detPos) { - // single - if (detPos >= 0) { - return detectors[detPos]->setSpeed(index, value); - } + // single + if (detPos >= 0) { + return detectors[detPos]->setSpeed(index, value); + } - // multi + // multi auto r = parallelCall(&slsDetector::setSpeed, index, value); return (sls::allEqualTo(r, static_cast(OK)) ? OK : FAIL); } int multiSlsDetector::setDynamicRange(int p, int detPos) { - // single - if (detPos >= 0) { - FILE_LOG(logERROR) << "Dynamic Range cannot be set individually"; - setErrorMask(getErrorMask() | MUST_BE_MULTI_CMD); - return -1; - } + // single + if (detPos >= 0) { + FILE_LOG(logERROR) << "Dynamic Range cannot be set individually"; + setErrorMask(getErrorMask() | MUST_BE_MULTI_CMD); + return -1; + } - // multi - auto r = parallelCall(&slsDetector::setDynamicRange, p); - int ret = sls::minusOneIfDifferent(r); + // multi + auto r = parallelCall(&slsDetector::setDynamicRange, p); + int ret = sls::minusOneIfDifferent(r); - //update shm - int prevValue = thisMultiDetector->dataBytes; - int prevGValue = thisMultiDetector->dataBytesInclGapPixels; - thisMultiDetector->dataBytes = 0; - thisMultiDetector->dataBytesInclGapPixels = 0; - thisMultiDetector->numberOfChannels = 0; - for (auto& d : detectors) { - thisMultiDetector->dataBytes += d->getDataBytes(); - thisMultiDetector->dataBytesInclGapPixels += d->getDataBytesInclGapPixels(); - thisMultiDetector->numberOfChannels += d->getTotalNumberOfChannels(); - } + // update shm + int prevValue = thisMultiDetector->dataBytes; + int prevGValue = thisMultiDetector->dataBytesInclGapPixels; + thisMultiDetector->dataBytes = 0; + thisMultiDetector->dataBytesInclGapPixels = 0; + thisMultiDetector->numberOfChannels = 0; + for (auto &d : detectors) { + thisMultiDetector->dataBytes += d->getDataBytes(); + thisMultiDetector->dataBytesInclGapPixels += + d->getDataBytesInclGapPixels(); + thisMultiDetector->numberOfChannels += d->getTotalNumberOfChannels(); + } + // for usability + if (getDetectorsType() == EIGER) { + switch (p) { + case 32: + FILE_LOG(logINFO) << "Setting Clock to Quarter Speed to cope with " + "Dynamic Range of 32"; + setSpeed(CLOCK_DIVIDER, 2); + break; + case 16: + FILE_LOG(logINFO) + << "Setting Clock to Half Speed for Dynamic Range of 16"; + setSpeed(CLOCK_DIVIDER, 1); + break; + default: + break; + } + } - //for usability - if (getDetectorsType() == EIGER) { - switch(p){ - case 32: - FILE_LOG(logINFO) << "Setting Clock to Quarter Speed to cope with Dynamic Range of 32"; - setSpeed(CLOCK_DIVIDER, 2); - break; - case 16: - FILE_LOG(logINFO) << "Setting Clock to Half Speed for Dynamic Range of 16"; - setSpeed(CLOCK_DIVIDER, 1); - break; - default: - break; - } - } + // update offsets if there was a change FIXME:add dr to sls shm and check + // that instead + if ((prevValue != thisMultiDetector->dataBytes) || + (prevGValue != thisMultiDetector->dataBytesInclGapPixels)) + updateOffsets(); - // update offsets if there was a change FIXME:add dr to sls shm and check that instead - if ((prevValue != thisMultiDetector->dataBytes) || - (prevGValue != thisMultiDetector->dataBytesInclGapPixels)) - updateOffsets(); - - return ret; + return ret; } - int multiSlsDetector::getDataBytes(int detPos) { - // single - if (detPos >= 0) { - return detectors[detPos]->getDataBytes(); - } + // single + if (detPos >= 0) { + return detectors[detPos]->getDataBytes(); + } - // multi + // multi auto r = parallelCall(&slsDetector::getDataBytes); return sls::sum(r); } - int multiSlsDetector::setDAC(int val, dacIndex idac, int mV, int detPos) { - // single - if (detPos >= 0) { - return detectors[detPos]->setDAC(val, idac, mV); - } + // single + if (detPos >= 0) { + return detectors[detPos]->setDAC(val, idac, mV); + } - // multi - auto r = parallelCall(&slsDetector::setDAC, val, idac, mV); - if (idac != HV_NEW) - return sls::minusOneIfDifferent(r); + // multi + auto r = parallelCall(&slsDetector::setDAC, val, idac, mV); + if (idac != HV_NEW) + return sls::minusOneIfDifferent(r); - // ignore slave values for hv (-999) - int firstValue = r.front(); - for (const auto& value : r) { - if ((value != -999) && (value != firstValue)) - return -1; - } + // ignore slave values for hv (-999) + int firstValue = r.front(); + for (const auto &value : r) { + if ((value != -999) && (value != firstValue)) + return -1; + } - return firstValue; + return firstValue; } - int multiSlsDetector::getADC(dacIndex idac, int detPos) { - // single - if (detPos >= 0) { - return detectors[detPos]->getADC(idac); - } + // single + if (detPos >= 0) { + return detectors[detPos]->getADC(idac); + } - // multi - auto r = parallelCall(&slsDetector::getADC, idac); - return sls::minusOneIfDifferent(r); + // multi + auto r = parallelCall(&slsDetector::getADC, idac); + return sls::minusOneIfDifferent(r); } +slsDetectorDefs::externalCommunicationMode +multiSlsDetector::setExternalCommunicationMode(externalCommunicationMode pol, + int detPos) { + // single + if (detPos >= 0) { + return detectors[detPos]->setExternalCommunicationMode(pol); + } -slsDetectorDefs::externalCommunicationMode multiSlsDetector::setExternalCommunicationMode( - externalCommunicationMode pol, int detPos) { - // single - if (detPos >= 0) { - return detectors[detPos]->setExternalCommunicationMode(pol); - } - - // multi - auto r = parallelCall(&slsDetector::setExternalCommunicationMode, pol); - return sls::minusOneIfDifferent(r); + // multi + auto r = parallelCall(&slsDetector::setExternalCommunicationMode, pol); + return sls::minusOneIfDifferent(r); } +slsDetectorDefs::externalSignalFlag +multiSlsDetector::setExternalSignalFlags(externalSignalFlag pol, + int signalindex, int detPos) { + // single + if (detPos >= 0) { + return detectors[detPos]->setExternalSignalFlags(pol, signalindex); + } -slsDetectorDefs::externalSignalFlag multiSlsDetector::setExternalSignalFlags( - externalSignalFlag pol, int signalindex, int detPos) { - // single - if (detPos >= 0) { - return detectors[detPos]->setExternalSignalFlags(pol, signalindex); - } - - // multi - auto r = parallelCall(&slsDetector::setExternalSignalFlags, pol, signalindex); - return sls::minusOneIfDifferent(r); + // multi + auto r = + parallelCall(&slsDetector::setExternalSignalFlags, pol, signalindex); + return sls::minusOneIfDifferent(r); } - int multiSlsDetector::setReadOutFlags(readOutFlags flag, int detPos) { - // single - if (detPos >= 0) { - return detectors[detPos]->setReadOutFlags(flag); - } + // single + if (detPos >= 0) { + return detectors[detPos]->setReadOutFlags(flag); + } - // multi - auto r = parallelCall(&slsDetector::setReadOutFlags, flag); - return sls::minusOneIfDifferent(r); + // multi + auto r = parallelCall(&slsDetector::setReadOutFlags, flag); + return sls::minusOneIfDifferent(r); } +uint32_t multiSlsDetector::writeRegister(uint32_t addr, uint32_t val, + int detPos) { + // single + if (detPos >= 0) { + return detectors[detPos]->writeRegister(addr, val); + } -uint32_t multiSlsDetector::writeRegister(uint32_t addr, uint32_t val, int detPos) { - // single - if (detPos >= 0) { - return detectors[detPos]->writeRegister(addr, val); - } + // multi + auto r = parallelCall(&slsDetector::writeRegister, addr, val); + if (sls::allEqual(r)) + return r.front(); - // multi - auto r = parallelCall(&slsDetector::writeRegister, addr, val); - if (sls::allEqual(r)) - return r.front(); - - // can't have different values - FILE_LOG(logERROR) << "Error: Different Values for function writeRegister " - "(write 0x" << std::hex << val << " to addr 0x" << std::hex << addr << std::dec << ")"; - setErrorMask(getErrorMask() | MULTI_HAVE_DIFFERENT_VALUES); - return -1; + // can't have different values + FILE_LOG(logERROR) << "Error: Different Values for function writeRegister " + "(write 0x" + << std::hex << val << " to addr 0x" << std::hex << addr + << std::dec << ")"; + setErrorMask(getErrorMask() | MULTI_HAVE_DIFFERENT_VALUES); + return -1; } - uint32_t multiSlsDetector::readRegister(uint32_t addr, int detPos) { - // single - if (detPos >= 0) { - return detectors[detPos]->readRegister(addr); - } + // single + if (detPos >= 0) { + return detectors[detPos]->readRegister(addr); + } - // multi - auto r = parallelCall(&slsDetector::readRegister, addr); - if (sls::allEqual(r)) - return r.front(); + // multi + auto r = parallelCall(&slsDetector::readRegister, addr); + if (sls::allEqual(r)) + return r.front(); - // can't have different values - FILE_LOG(logERROR) << "Error: Different Values for function readRegister " - "(read from 0x" << std::hex << addr << std::dec << ")"; - setErrorMask(getErrorMask() | MULTI_HAVE_DIFFERENT_VALUES); - return -1; + // can't have different values + FILE_LOG(logERROR) << "Error: Different Values for function readRegister " + "(read from 0x" + << std::hex << addr << std::dec << ")"; + setErrorMask(getErrorMask() | MULTI_HAVE_DIFFERENT_VALUES); + return -1; } - uint32_t multiSlsDetector::setBit(uint32_t addr, int n, int detPos) { - // single - if (detPos >= 0) { - return detectors[detPos]->setBit(addr, n); - } + // single + if (detPos >= 0) { + return detectors[detPos]->setBit(addr, n); + } - // multi - auto r = parallelCall(&slsDetector::setBit, addr, n); - if (sls::allEqual(r)) - return r.front(); + // multi + auto r = parallelCall(&slsDetector::setBit, addr, n); + if (sls::allEqual(r)) + return r.front(); - // can't have different values - FILE_LOG(logERROR) << "Error: Different Values for function setBit " - "(set bit " << n << " to addr 0x" << std::hex << addr << std::dec << ")"; - setErrorMask(getErrorMask() | MULTI_HAVE_DIFFERENT_VALUES); - return -1; + // can't have different values + FILE_LOG(logERROR) << "Error: Different Values for function setBit " + "(set bit " + << n << " to addr 0x" << std::hex << addr << std::dec + << ")"; + setErrorMask(getErrorMask() | MULTI_HAVE_DIFFERENT_VALUES); + return -1; } - uint32_t multiSlsDetector::clearBit(uint32_t addr, int n, int detPos) { - // single - if (detPos >= 0) { - return detectors[detPos]->clearBit(addr, n); - } + // single + if (detPos >= 0) { + return detectors[detPos]->clearBit(addr, n); + } - // multi - auto r = parallelCall(&slsDetector::clearBit, addr, n); - if (sls::allEqual(r)) - return r.front(); + // multi + auto r = parallelCall(&slsDetector::clearBit, addr, n); + if (sls::allEqual(r)) + return r.front(); - // can't have different values - FILE_LOG(logERROR) << "Error: Different Values for function clearBit " - "(clear bit " << n << " to addr 0x" << std::hex << addr << std::dec << ")"; - setErrorMask(getErrorMask() | MULTI_HAVE_DIFFERENT_VALUES); - return -1; + // can't have different values + FILE_LOG(logERROR) << "Error: Different Values for function clearBit " + "(clear bit " + << n << " to addr 0x" << std::hex << addr << std::dec + << ")"; + setErrorMask(getErrorMask() | MULTI_HAVE_DIFFERENT_VALUES); + return -1; } +std::string multiSlsDetector::setNetworkParameter(networkParameter parameter, + std::string value, + int detPos) { + // single + if (detPos >= 0) + return detectors[detPos]->setNetworkParameter(parameter, value); + // multi + if (parameter != RECEIVER_STREAMING_PORT && + parameter != CLIENT_STREAMING_PORT) { + auto r = + parallelCall(&slsDetector::setNetworkParameter, parameter, value); + return sls::concatenateIfDifferent(r); + } -std::string multiSlsDetector::setNetworkParameter(networkParameter parameter, std::string value, int detPos) { - // single - if (detPos >= 0) - return detectors[detPos]->setNetworkParameter(parameter, value); + // calculate ports individually + int firstPort = stoi(value); + int numSockets = (getDetectorsType() == EIGER) ? 2 : 1; - // multi - if (parameter != RECEIVER_STREAMING_PORT && parameter != CLIENT_STREAMING_PORT){ - auto r = parallelCall(&slsDetector::setNetworkParameter, parameter, value); - return sls::concatenateIfDifferent(r); - } - - // calculate ports individually - int firstPort = stoi(value); - int numSockets = (getDetectorsType() == EIGER) ? 2 : 1; - - std::vector r; - for (size_t idet = 0; idet < detectors.size(); ++idet) { - auto port = std::to_string(firstPort + (idet * numSockets)); - r.push_back(detectors[idet]->setNetworkParameter(parameter, port)); - } - return sls::concatenateIfDifferent(r); + std::vector r; + for (size_t idet = 0; idet < detectors.size(); ++idet) { + auto port = std::to_string(firstPort + (idet * numSockets)); + r.push_back(detectors[idet]->setNetworkParameter(parameter, port)); + } + return sls::concatenateIfDifferent(r); } +std::string multiSlsDetector::getNetworkParameter(networkParameter p, + int detPos) { + // single + if (detPos >= 0) { + return detectors[detPos]->getNetworkParameter(p); + } -std::string multiSlsDetector::getNetworkParameter(networkParameter p, int detPos) { - // single - if (detPos >= 0) { - return detectors[detPos]->getNetworkParameter(p); - } - - // multi + // multi auto r = serialCall(&slsDetector::getNetworkParameter, p); return sls::concatenateIfDifferent(r); } - int multiSlsDetector::setReceiverDataStreamingOutPort(int i, int detPos) { - if (i >= 0) { - std::string s = std::to_string(i); - int prev_streaming = enableDataStreamingFromReceiver(-1, detPos); - setNetworkParameter(RECEIVER_STREAMING_PORT, s, detPos); - if (prev_streaming) { - enableDataStreamingFromReceiver(0, detPos); - enableDataStreamingFromReceiver(1, detPos); - } - } - return stoi(getNetworkParameter(RECEIVER_STREAMING_PORT, detPos)); + if (i >= 0) { + std::string s = std::to_string(i); + int prev_streaming = enableDataStreamingFromReceiver(-1, detPos); + setNetworkParameter(RECEIVER_STREAMING_PORT, s, detPos); + if (prev_streaming) { + enableDataStreamingFromReceiver(0, detPos); + enableDataStreamingFromReceiver(1, detPos); + } + } + return stoi(getNetworkParameter(RECEIVER_STREAMING_PORT, detPos)); } - int multiSlsDetector::setClientDataStreamingInPort(int i, int detPos) { - if (i >= 0) { - std::string s = std::to_string(i); - int prev_streaming = enableDataStreamingToClient(); - setNetworkParameter(CLIENT_STREAMING_PORT, s, detPos); - if (prev_streaming) { - enableDataStreamingToClient(0); - enableDataStreamingToClient(1); - } - } - return stoi(getNetworkParameter(CLIENT_STREAMING_PORT, detPos)); + if (i >= 0) { + std::string s = std::to_string(i); + int prev_streaming = enableDataStreamingToClient(); + setNetworkParameter(CLIENT_STREAMING_PORT, s, detPos); + if (prev_streaming) { + enableDataStreamingToClient(0); + enableDataStreamingToClient(1); + } + } + return stoi(getNetworkParameter(CLIENT_STREAMING_PORT, detPos)); } - -std::string multiSlsDetector::setReceiverDataStreamingOutIP(std::string ip, int detPos) { - if (ip.length()) { - int prev_streaming = enableDataStreamingFromReceiver(-1, detPos); - setNetworkParameter(RECEIVER_STREAMING_SRC_IP, ip, detPos); - if (prev_streaming) { - enableDataStreamingFromReceiver(0, detPos); - enableDataStreamingFromReceiver(1, detPos); - } - } - return getNetworkParameter(RECEIVER_STREAMING_SRC_IP, detPos); +std::string multiSlsDetector::setReceiverDataStreamingOutIP(std::string ip, + int detPos) { + if (ip.length()) { + int prev_streaming = enableDataStreamingFromReceiver(-1, detPos); + setNetworkParameter(RECEIVER_STREAMING_SRC_IP, ip, detPos); + if (prev_streaming) { + enableDataStreamingFromReceiver(0, detPos); + enableDataStreamingFromReceiver(1, detPos); + } + } + return getNetworkParameter(RECEIVER_STREAMING_SRC_IP, detPos); } - -std::string multiSlsDetector::setClientDataStreamingInIP(std::string ip, int detPos) { - if (ip.length()) { - int prev_streaming = enableDataStreamingToClient(-1); - setNetworkParameter(CLIENT_STREAMING_SRC_IP, ip, detPos); - if (prev_streaming) { - enableDataStreamingToClient(0); - enableDataStreamingToClient(1); - } - } - return getNetworkParameter(CLIENT_STREAMING_SRC_IP, detPos); +std::string multiSlsDetector::setClientDataStreamingInIP(std::string ip, + int detPos) { + if (ip.length()) { + int prev_streaming = enableDataStreamingToClient(-1); + setNetworkParameter(CLIENT_STREAMING_SRC_IP, ip, detPos); + if (prev_streaming) { + enableDataStreamingToClient(0); + enableDataStreamingToClient(1); + } + } + return getNetworkParameter(CLIENT_STREAMING_SRC_IP, detPos); } - int multiSlsDetector::setFlowControl10G(int enable, int detPos) { - std::string s; - if (enable != -1) { - s = std::to_string((enable >= 1) ? 1 : 0); - s = setNetworkParameter(FLOW_CONTROL_10G, s); - } else - s = getNetworkParameter(FLOW_CONTROL_10G); - return stoi(s); + std::string s; + if (enable != -1) { + s = std::to_string((enable >= 1) ? 1 : 0); + s = setNetworkParameter(FLOW_CONTROL_10G, s); + } else + s = getNetworkParameter(FLOW_CONTROL_10G); + return stoi(s); } - int multiSlsDetector::digitalTest(digitalTestMode mode, int ival, int detPos) { - // single - if (detPos >= 0) { - return detectors[detPos]->digitalTest(mode, ival); - } + // single + if (detPos >= 0) { + return detectors[detPos]->digitalTest(mode, ival); + } - // multi + // multi auto r = parallelCall(&slsDetector::digitalTest, mode, ival); return sls::minusOneIfDifferent(r); } +int multiSlsDetector::loadImageToDetector(imageType index, + const std::string &fname, + int detPos) { + // single + if (detPos >= 0) { + return detectors[detPos]->loadImageToDetector(index, fname); + } -int multiSlsDetector::loadImageToDetector(imageType index, const std::string& fname, int detPos) { - // single - if (detPos >= 0) { - return detectors[detPos]->loadImageToDetector(index, fname); - } + // multi - // multi + // read image for all + int nch = thisMultiDetector->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 " + "to load image to detector."; + setErrorMask(getErrorMask() | MULTI_OTHER_ERROR); + return -1; + } - //read image for all - int nch = thisMultiDetector->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 " - "to load image to detector."; - setErrorMask(getErrorMask() | MULTI_OTHER_ERROR); - return -1; - } - - // send image to all - std::vector r; - for (size_t idet = 0; idet < detectors.size(); ++idet) { - r.push_back(detectors[idet]->sendImageToDetector(index, - imageVals + idet * detectors[idet]->getTotalNumberOfChannels())); - } - return sls::allEqualTo(r, static_cast(OK)) ? OK : FAIL; + // send image to all + std::vector r; + for (size_t idet = 0; idet < detectors.size(); ++idet) { + r.push_back(detectors[idet]->sendImageToDetector( + index, + imageVals + idet * detectors[idet]->getTotalNumberOfChannels())); + } + return sls::allEqualTo(r, static_cast(OK)) ? OK : FAIL; } +int multiSlsDetector::writeCounterBlockFile(const std::string &fname, + int startACQ, int detPos) { + // single + if (detPos >= 0) { + return detectors[detPos]->writeCounterBlockFile(fname, startACQ); + } -int multiSlsDetector::writeCounterBlockFile(const std::string& fname, int startACQ, int detPos) { - // single - if (detPos >= 0) { - return detectors[detPos]->writeCounterBlockFile(fname, startACQ); - } + // multi - // multi + // get image from all + int nch = thisMultiDetector->numberOfChannels; + short int imageVals[nch]; + std::vector r; + for (size_t idet = 0; idet < detectors.size(); ++idet) { + r.push_back(detectors[idet]->getCounterBlock( + imageVals + idet * detectors[idet]->getTotalNumberOfChannels(), + startACQ)); + } - //get image from all - int nch = thisMultiDetector->numberOfChannels; - short int imageVals[nch]; - std::vector r; - for (size_t idet = 0; idet < detectors.size(); ++idet) { - r.push_back(detectors[idet]->getCounterBlock( - imageVals+ idet * detectors[idet]->getTotalNumberOfChannels(), - startACQ)); - } - - // write image if all ok - if (sls::allEqualTo(r, static_cast(OK))) { - if (writeDataFile(fname, nch, imageVals) < nch * (int)sizeof(short int)) { - FILE_LOG(logERROR) << "Could not open file to write or did not write enough data in file " - "to wrte counter block file from detector."; - setErrorMask(getErrorMask() | MULTI_OTHER_ERROR); - return -1; - } - return OK; - } - return FAIL; + // write image if all ok + if (sls::allEqualTo(r, static_cast(OK))) { + if (writeDataFile(fname, nch, imageVals) < + nch * (int)sizeof(short int)) { + FILE_LOG(logERROR) << "Could not open file to write or did not " + "write enough data in file " + "to wrte counter block file from detector."; + setErrorMask(getErrorMask() | MULTI_OTHER_ERROR); + return -1; + } + return OK; + } + return FAIL; } - int multiSlsDetector::resetCounterBlock(int startACQ, int detPos) { - // single - if (detPos >= 0) { - return detectors[detPos]->resetCounterBlock(startACQ); - } + // single + if (detPos >= 0) { + return detectors[detPos]->resetCounterBlock(startACQ); + } - // multi + // multi auto r = parallelCall(&slsDetector::resetCounterBlock, startACQ); - return sls::allEqualTo(r, static_cast(OK)) ? OK : FAIL; + return sls::allEqualTo(r, static_cast(OK)) ? OK : FAIL; } - int multiSlsDetector::setCounterBit(int i, int detPos) { - // single - if (detPos >= 0) { - return detectors[detPos]->setCounterBit(i); - } + // single + if (detPos >= 0) { + return detectors[detPos]->setCounterBit(i); + } - // multi + // multi auto r = parallelCall(&slsDetector::setCounterBit, i); return sls::minusOneIfDifferent(r); } - void multiSlsDetector::verifyMinMaxROI(int n, ROI r[]) { - int temp; - for (int i = 0; i < n; ++i) { - if ((r[i].xmax) < (r[i].xmin)) { - temp = r[i].xmax; - r[i].xmax = r[i].xmin; - r[i].xmin = temp; - } - if ((r[i].ymax) < (r[i].ymin)) { - temp = r[i].ymax; - r[i].ymax = r[i].ymin; - r[i].ymin = temp; - } - } + int temp; + for (int i = 0; i < n; ++i) { + if ((r[i].xmax) < (r[i].xmin)) { + temp = r[i].xmax; + r[i].xmax = r[i].xmin; + r[i].xmin = temp; + } + if ((r[i].ymax) < (r[i].ymin)) { + temp = r[i].ymax; + r[i].ymax = r[i].ymin; + r[i].ymin = temp; + } + } } int multiSlsDetector::setROI(int n, ROI roiLimits[], int detPos) { - // single - if (detPos >= 0) { - return detectors[detPos]->setROI(n, roiLimits); - } + // single + if (detPos >= 0) { + return detectors[detPos]->setROI(n, roiLimits); + } - // multi - int i, xmin, xmax, ymin, ymax, channelX, channelY, idet, lastChannelX, - lastChannelY, index, offsetX, offsetY; + // multi + int i, xmin, xmax, ymin, ymax, channelX, channelY, idet, lastChannelX, + lastChannelY, index, offsetX, offsetY; - bool invalidroi = false; - int ndet = detectors.size(); - ROI allroi[ndet][n]; - int nroi[ndet]; - for (i = 0; i < ndet; ++i) - nroi[i] = 0; + bool invalidroi = false; + int ndet = detectors.size(); + ROI allroi[ndet][n]; + int nroi[ndet]; + for (i = 0; i < ndet; ++i) + nroi[i] = 0; - if ((n < 0) || (roiLimits == NULL)) - return FAIL; + if ((n < 0) || (roiLimits == NULL)) + return FAIL; - //ensures min < max - verifyMinMaxROI(n, roiLimits); + // ensures min < max + verifyMinMaxROI(n, roiLimits); #ifdef VERBOSE - std::cout << "Setting ROI for " << n << "rois:" << std::endl; - for (i = 0; i < n; ++i) - std::cout << i << ":" << roiLimits[i].xmin << "\t" << roiLimits[i].xmax - << "\t" << roiLimits[i].ymin << "\t" << roiLimits[i].ymax << std::endl; + std::cout << "Setting ROI for " << n << "rois:" << std::endl; + for (i = 0; i < n; ++i) + std::cout << i << ":" << roiLimits[i].xmin << "\t" << roiLimits[i].xmax + << "\t" << roiLimits[i].ymin << "\t" << roiLimits[i].ymax + << std::endl; #endif - //for each roi - for (i = 0; i < n; ++i) { - xmin = roiLimits[i].xmin; - xmax = roiLimits[i].xmax; - ymin = roiLimits[i].ymin; - ymax = roiLimits[i].ymax; + // for each roi + for (i = 0; i < n; ++i) { + xmin = roiLimits[i].xmin; + xmax = roiLimits[i].xmax; + ymin = roiLimits[i].ymin; + ymax = roiLimits[i].ymax; - //check roi max values - idet = decodeNChannel(xmax, ymax, channelX, channelY); + // check roi max values + idet = decodeNChannel(xmax, ymax, channelX, channelY); #ifdef VERBOSE - std::cout << "Decoded Channel max vals: " << std::endl; - std::cout << "det:" << idet << "\t" << xmax << "\t" << ymax << "\t" - << channelX << "\t" << channelY << std::endl; + std::cout << "Decoded Channel max vals: " << std::endl; + std::cout << "det:" << idet << "\t" << xmax << "\t" << ymax << "\t" + << channelX << "\t" << channelY << std::endl; #endif - if (idet == -1) { - std::cout << "invalid roi" << std::endl; - continue; - } + if (idet == -1) { + std::cout << "invalid roi" << std::endl; + continue; + } - //split in x dir - while (xmin <= xmax) { - invalidroi = false; - ymin = roiLimits[i].ymin; - //split in y dir - while (ymin <= ymax) { - //get offset for each detector - idet = decodeNChannel(xmin, ymin, channelX, channelY); + // split in x dir + while (xmin <= xmax) { + invalidroi = false; + ymin = roiLimits[i].ymin; + // split in y dir + while (ymin <= ymax) { + // get offset for each detector + idet = decodeNChannel(xmin, ymin, channelX, channelY); #ifdef VERBOSE - std::cout << "Decoded Channel min vals: " << std::endl; - std::cout << "det:" << idet << "\t" << xmin << "\t" << ymin - << "\t" << channelX << "\t" << channelY << std::endl; + std::cout << "Decoded Channel min vals: " << std::endl; + std::cout << "det:" << idet << "\t" << xmin << "\t" << ymin + << "\t" << channelX << "\t" << channelY << std::endl; #endif - if (idet < 0 || idet >= (int)detectors.size()) { - std::cout << "invalid roi" << std::endl; - invalidroi = true; - break; - } - //get last channel for each det in x and y dir - lastChannelX = (detectors[idet]->getTotalNumberOfChannelsInclGapPixels(X)) - 1; - lastChannelY = (detectors[idet]->getTotalNumberOfChannelsInclGapPixels(Y)) - 1; + if (idet < 0 || idet >= (int)detectors.size()) { + std::cout << "invalid roi" << std::endl; + invalidroi = true; + break; + } + // get last channel for each det in x and y dir + lastChannelX = + (detectors[idet]->getTotalNumberOfChannelsInclGapPixels( + X)) - + 1; + lastChannelY = + (detectors[idet]->getTotalNumberOfChannelsInclGapPixels( + Y)) - + 1; - offsetX = detectors[idet]->getDetectorOffset(X); - offsetY = detectors[idet]->getDetectorOffset(Y); - //at the end in x dir - if ((offsetX + lastChannelX) >= xmax) - lastChannelX = xmax - offsetX; - //at the end in y dir - if ((offsetY + lastChannelY) >= ymax) - lastChannelY = ymax - offsetY; + offsetX = detectors[idet]->getDetectorOffset(X); + offsetY = detectors[idet]->getDetectorOffset(Y); + // at the end in x dir + if ((offsetX + lastChannelX) >= xmax) + lastChannelX = xmax - offsetX; + // at the end in y dir + if ((offsetY + lastChannelY) >= ymax) + lastChannelY = ymax - offsetY; #ifdef VERBOSE - std::cout << "lastChannelX:" << lastChannelX << "\t" - << "lastChannelY:" << lastChannelY << std::endl; + std::cout << "lastChannelX:" << lastChannelX << "\t" + << "lastChannelY:" << lastChannelY << std::endl; #endif - //creating the list of roi for corresponding detector - index = nroi[idet]; - allroi[idet][index].xmin = channelX; - allroi[idet][index].xmax = lastChannelX; - allroi[idet][index].ymin = channelY; - allroi[idet][index].ymax = lastChannelY; - nroi[idet] = nroi[idet] + 1; + // creating the list of roi for corresponding detector + index = nroi[idet]; + allroi[idet][index].xmin = channelX; + allroi[idet][index].xmax = lastChannelX; + allroi[idet][index].ymin = channelY; + allroi[idet][index].ymax = lastChannelY; + nroi[idet] = nroi[idet] + 1; - ymin = lastChannelY + offsetY + 1; - if ((lastChannelY + offsetY) == ymax) - ymin = ymax + 1; + ymin = lastChannelY + offsetY + 1; + if ((lastChannelY + offsetY) == ymax) + ymin = ymax + 1; #ifdef VERBOSE - std::cout << "nroi[idet]:" << nroi[idet] << "\tymin:" << ymin << std::endl; + std::cout << "nroi[idet]:" << nroi[idet] << "\tymin:" << ymin + << std::endl; #endif + } + if (invalidroi) + break; - } - if (invalidroi) - break; - - xmin = lastChannelX + offsetX + 1; - if ((lastChannelX + offsetX) == xmax) - xmin = xmax + 1; - } - } + xmin = lastChannelX + offsetX + 1; + if ((lastChannelX + offsetX) == xmax) + xmin = xmax + 1; + } + } #ifdef VERBOSE - std::cout << "Setting ROI :" << std::endl; - for (i = 0; i < detectors.size(); ++i) { - std::cout << "detector " << i << std::endl; - for (int j = 0; j < nroi[i]; ++j) { - std::cout << allroi[i][j].xmin << "\t" << allroi[i][j].xmax << "\t" - << allroi[i][j].ymin << "\t" << allroi[i][j].ymax << std::endl; - } - } + std::cout << "Setting ROI :" << std::endl; + for (i = 0; i < detectors.size(); ++i) { + std::cout << "detector " << i << std::endl; + for (int j = 0; j < nroi[i]; ++j) { + std::cout << allroi[i][j].xmin << "\t" << allroi[i][j].xmax << "\t" + << allroi[i][j].ymin << "\t" << allroi[i][j].ymax + << std::endl; + } + } #endif - //settings the rois for each detector - std::vector r; - for (size_t idet = 0; idet < detectors.size(); ++idet) { - r.push_back(detectors[idet]->setROI(nroi[i], allroi[i])); - - } - return sls::allEqualTo(r, static_cast(OK)) ? OK : FAIL; + // settings the rois for each detector + std::vector r; + for (size_t idet = 0; idet < detectors.size(); ++idet) { + r.push_back(detectors[idet]->setROI(nroi[i], allroi[i])); + } + return sls::allEqualTo(r, static_cast(OK)) ? OK : FAIL; } +slsDetectorDefs::ROI *multiSlsDetector::getROI(int &n, int detPos) { + // single + if (detPos >= 0) { + return detectors[detPos]->getROI(n); + } -slsDetectorDefs::ROI* multiSlsDetector::getROI(int& n, int detPos) { - // single - if (detPos >= 0) { - return detectors[detPos]->getROI(n); - } + // multi + n = 0; + int num = 0, i, j; + int ndet = detectors.size(); + int maxroi = ndet * MAX_ROIS; + ROI temproi; + ROI roiLimits[maxroi]; + ROI *retval = new ROI[maxroi]; + ROI *temp = 0; + int index = 0; - // multi - n = 0; - int num = 0, i, j; - int ndet = detectors.size(); - int maxroi = ndet * MAX_ROIS; - ROI temproi; - ROI roiLimits[maxroi]; - ROI* retval = new ROI[maxroi]; - ROI* temp = 0; - int index = 0; + // get each detector's roi array + for (size_t idet = 0; idet < detectors.size(); ++idet) { + temp = detectors[idet]->getROI(index); + if (temp) { + //#ifdef VERBOSE + if (index) + std::cout << "detector " << idet << ":" << std::endl; + //#endif + for (j = 0; j < index; ++j) { + //#ifdef VERBOSE + std::cout << temp[j].xmin << "\t" << temp[j].xmax << "\t" + << temp[j].ymin << "\t" << temp[j].ymax << std::endl; + //#endif + int x = detectors[idet]->getDetectorOffset(X); + int y = detectors[idet]->getDetectorOffset(Y); + roiLimits[n].xmin = temp[j].xmin + x; + roiLimits[n].xmax = temp[j].xmax + x; + roiLimits[n].ymin = temp[j].ymin + y; + roiLimits[n].ymax = temp[j].ymin + y; + ++n; + } + } + } - //get each detector's roi array - for (size_t idet = 0; idet < detectors.size(); ++idet) { - temp = detectors[idet]->getROI(index); - if (temp) { - //#ifdef VERBOSE - if (index) - std::cout << "detector " << idet << ":" << std::endl; - //#endif - for (j = 0; j < index; ++j) { - //#ifdef VERBOSE - std::cout << temp[j].xmin << "\t" << temp[j].xmax << "\t" - << temp[j].ymin << "\t" << temp[j].ymax << std::endl; - //#endif - int x = detectors[idet]->getDetectorOffset(X); - int y = detectors[idet]->getDetectorOffset(Y); - roiLimits[n].xmin = temp[j].xmin + x; - roiLimits[n].xmax = temp[j].xmax + x; - roiLimits[n].ymin = temp[j].ymin + y; - roiLimits[n].ymax = temp[j].ymin + y; - ++n; - } - } - } - - //empty roi - if (!n) - return NULL; + // empty roi + if (!n) + return NULL; #ifdef VERBOSE - std::cout << "ROI :" << std::endl; - for (int j = 0; j < n; ++j) { - std::cout << roiLimits[j].xmin << "\t" << roiLimits[j].xmax << "\t" - << roiLimits[j].ymin << "\t" << roiLimits[j].ymax << std::endl; - } + std::cout << "ROI :" << std::endl; + for (int j = 0; j < n; ++j) { + std::cout << roiLimits[j].xmin << "\t" << roiLimits[j].xmax << "\t" + << roiLimits[j].ymin << "\t" << roiLimits[j].ymax + << std::endl; + } #endif - //combine all the adjacent rois in x direction - for (i = 0; i < n; ++i) { - //since the ones combined are replaced by -1 - if ((roiLimits[i].xmin) == -1) - continue; - for (j = i + 1; j < n; ++j) { - //since the ones combined are replaced by -1 - if ((roiLimits[j].xmin) == -1) - continue; - //if y values are same - if (((roiLimits[i].ymin) == (roiLimits[j].ymin)) && - ((roiLimits[i].ymax) == (roiLimits[j].ymax))) { - //if adjacent, increase [i] range and replace all [j] with -1 - if ((roiLimits[i].xmax) + 1 == roiLimits[j].xmin) { - roiLimits[i].xmax = roiLimits[j].xmax; - roiLimits[j].xmin = -1; - roiLimits[j].xmax = -1; - roiLimits[j].ymin = -1; - roiLimits[j].ymax = -1; - } - //if adjacent, increase [i] range and replace all [j] with -1 - else if ((roiLimits[i].xmin) - 1 == roiLimits[j].xmax) { - roiLimits[i].xmin = roiLimits[j].xmin; - roiLimits[j].xmin = -1; - roiLimits[j].xmax = -1; - roiLimits[j].ymin = -1; - roiLimits[j].ymax = -1; - } - } - } - } + // combine all the adjacent rois in x direction + for (i = 0; i < n; ++i) { + // since the ones combined are replaced by -1 + if ((roiLimits[i].xmin) == -1) + continue; + for (j = i + 1; j < n; ++j) { + // since the ones combined are replaced by -1 + if ((roiLimits[j].xmin) == -1) + continue; + // if y values are same + if (((roiLimits[i].ymin) == (roiLimits[j].ymin)) && + ((roiLimits[i].ymax) == (roiLimits[j].ymax))) { + // if adjacent, increase [i] range and replace all [j] with -1 + if ((roiLimits[i].xmax) + 1 == roiLimits[j].xmin) { + roiLimits[i].xmax = roiLimits[j].xmax; + roiLimits[j].xmin = -1; + roiLimits[j].xmax = -1; + roiLimits[j].ymin = -1; + roiLimits[j].ymax = -1; + } + // if adjacent, increase [i] range and replace all [j] with -1 + else if ((roiLimits[i].xmin) - 1 == roiLimits[j].xmax) { + roiLimits[i].xmin = roiLimits[j].xmin; + roiLimits[j].xmin = -1; + roiLimits[j].xmax = -1; + roiLimits[j].ymin = -1; + roiLimits[j].ymax = -1; + } + } + } + } #ifdef VERBOSE - std::cout << "Combined along x axis Getting ROI :" << std::endl; - std::cout << "detector " << i << std::endl; - for (int j = 0; j < n; ++j) { - std::cout << roiLimits[j].xmin << "\t" << roiLimits[j].xmax << "\t" - << roiLimits[j].ymin << "\t" << roiLimits[j].ymax << std::endl; - } + std::cout << "Combined along x axis Getting ROI :" << std::endl; + std::cout << "detector " << i << std::endl; + for (int j = 0; j < n; ++j) { + std::cout << roiLimits[j].xmin << "\t" << roiLimits[j].xmax << "\t" + << roiLimits[j].ymin << "\t" << roiLimits[j].ymax + << std::endl; + } #endif - //combine all the adjacent rois in y direction - for (i = 0; i < n; ++i) { - //since the ones combined are replaced by -1 - if ((roiLimits[i].ymin) == -1) - continue; - for (j = i + 1; j < n; ++j) { - //since the ones combined are replaced by -1 - if ((roiLimits[j].ymin) == -1) - continue; - //if x values are same - if (((roiLimits[i].xmin) == (roiLimits[j].xmin)) && - ((roiLimits[i].xmax) == (roiLimits[j].xmax))) { - //if adjacent, increase [i] range and replace all [j] with -1 - if ((roiLimits[i].ymax) + 1 == roiLimits[j].ymin) { - roiLimits[i].ymax = roiLimits[j].ymax; - roiLimits[j].xmin = -1; - roiLimits[j].xmax = -1; - roiLimits[j].ymin = -1; - roiLimits[j].ymax = -1; - } - //if adjacent, increase [i] range and replace all [j] with -1 - else if ((roiLimits[i].ymin) - 1 == roiLimits[j].ymax) { - roiLimits[i].ymin = roiLimits[j].ymin; - roiLimits[j].xmin = -1; - roiLimits[j].xmax = -1; - roiLimits[j].ymin = -1; - roiLimits[j].ymax = -1; - } - } - } - } + // combine all the adjacent rois in y direction + for (i = 0; i < n; ++i) { + // since the ones combined are replaced by -1 + if ((roiLimits[i].ymin) == -1) + continue; + for (j = i + 1; j < n; ++j) { + // since the ones combined are replaced by -1 + if ((roiLimits[j].ymin) == -1) + continue; + // if x values are same + if (((roiLimits[i].xmin) == (roiLimits[j].xmin)) && + ((roiLimits[i].xmax) == (roiLimits[j].xmax))) { + // if adjacent, increase [i] range and replace all [j] with -1 + if ((roiLimits[i].ymax) + 1 == roiLimits[j].ymin) { + roiLimits[i].ymax = roiLimits[j].ymax; + roiLimits[j].xmin = -1; + roiLimits[j].xmax = -1; + roiLimits[j].ymin = -1; + roiLimits[j].ymax = -1; + } + // if adjacent, increase [i] range and replace all [j] with -1 + else if ((roiLimits[i].ymin) - 1 == roiLimits[j].ymax) { + roiLimits[i].ymin = roiLimits[j].ymin; + roiLimits[j].xmin = -1; + roiLimits[j].xmax = -1; + roiLimits[j].ymin = -1; + roiLimits[j].ymax = -1; + } + } + } + } - // get rid of -1s - for (i = 0; i < n; ++i) { - if ((roiLimits[i].xmin) != -1) { - retval[num] = roiLimits[i]; - ++num; - } - } - //sort final roi - for (i = 0; i < num; ++i) { - for (j = i + 1; j < num; ++j) { - if (retval[j].xmin < retval[i].xmin) { - temproi = retval[i]; - retval[i] = retval[j]; - retval[j] = temproi; - } - } - } - n = num; + // get rid of -1s + for (i = 0; i < n; ++i) { + if ((roiLimits[i].xmin) != -1) { + retval[num] = roiLimits[i]; + ++num; + } + } + // sort final roi + for (i = 0; i < num; ++i) { + for (j = i + 1; j < num; ++j) { + if (retval[j].xmin < retval[i].xmin) { + temproi = retval[i]; + retval[i] = retval[j]; + retval[j] = temproi; + } + } + } + n = num; - std::cout << "\nxmin\txmax\tymin\tymax" << std::endl; - for (i = 0; i < n; ++i) - std::cout << retval[i].xmin << "\t" << retval[i].xmax << "\t" - << retval[i].ymin << "\t" << retval[i].ymax << std::endl; - return retval; + std::cout << "\nxmin\txmax\tymin\tymax" << std::endl; + for (i = 0; i < n; ++i) + std::cout << retval[i].xmin << "\t" << retval[i].xmax << "\t" + << retval[i].ymin << "\t" << retval[i].ymax << std::endl; + return retval; } - int multiSlsDetector::writeAdcRegister(int addr, int val, int detPos) { - // single - if (detPos >= 0) { - return detectors[detPos]->writeAdcRegister(addr, val); - } + // single + if (detPos >= 0) { + return detectors[detPos]->writeAdcRegister(addr, val); + } - // multi - auto r = parallelCall(&slsDetector::writeAdcRegister, addr, val); - if (sls::allEqual(r)) - return r.front(); + // multi + auto r = parallelCall(&slsDetector::writeAdcRegister, addr, val); + if (sls::allEqual(r)) + return r.front(); - // can't have different values - FILE_LOG(logERROR) << "Error: Different Values for function writeAdcRegister " - "(write 0x" << std::hex << val << " to addr 0x" << std::hex << addr << std::dec << ")"; - setErrorMask(getErrorMask() | MULTI_HAVE_DIFFERENT_VALUES); - return -1; + // can't have different values + FILE_LOG(logERROR) + << "Error: Different Values for function writeAdcRegister " + "(write 0x" + << std::hex << val << " to addr 0x" << std::hex << addr << std::dec + << ")"; + setErrorMask(getErrorMask() | MULTI_HAVE_DIFFERENT_VALUES); + return -1; } - int multiSlsDetector::activate(int const enable, int detPos) { - // single - if (detPos >= 0) { - return detectors[detPos]->activate(enable); - } + // single + if (detPos >= 0) { + return detectors[detPos]->activate(enable); + } - // multi - auto r = parallelCall(&slsDetector::activate, enable); - return sls::minusOneIfDifferent(r); + // multi + auto r = parallelCall(&slsDetector::activate, enable); + return sls::minusOneIfDifferent(r); } - int multiSlsDetector::setDeactivatedRxrPaddingMode(int padding, int detPos) { - // single - if (detPos >= 0) { - return detectors[detPos]->setDeactivatedRxrPaddingMode(padding); - } + // single + if (detPos >= 0) { + return detectors[detPos]->setDeactivatedRxrPaddingMode(padding); + } - // multi - auto r = parallelCall(&slsDetector::setDeactivatedRxrPaddingMode, padding); - return sls::minusOneIfDifferent(r); + // multi + auto r = parallelCall(&slsDetector::setDeactivatedRxrPaddingMode, padding); + return sls::minusOneIfDifferent(r); } - int multiSlsDetector::getFlippedData(dimension d, int detPos) { - // single - if (detPos >= 0) { - return detectors[detPos]->getFlippedData(d); - } + // single + if (detPos >= 0) { + return detectors[detPos]->getFlippedData(d); + } - // multi - auto r = serialCall(&slsDetector::getFlippedData, d); - return sls::minusOneIfDifferent(r); + // multi + auto r = serialCall(&slsDetector::getFlippedData, d); + return sls::minusOneIfDifferent(r); } - int multiSlsDetector::setFlippedData(dimension d, int value, int detPos) { - // single - if (detPos >= 0) { - return detectors[detPos]->setFlippedData(d, value); - } + // single + if (detPos >= 0) { + return detectors[detPos]->setFlippedData(d, value); + } - // multi - auto r = parallelCall(&slsDetector::setFlippedData, d, value); - return sls::minusOneIfDifferent(r); + // multi + auto r = parallelCall(&slsDetector::setFlippedData, d, value); + return sls::minusOneIfDifferent(r); } - int multiSlsDetector::setAllTrimbits(int val, int detPos) { - // single - if (detPos >= 0) { - return detectors[detPos]->setAllTrimbits(val); - } + // single + if (detPos >= 0) { + return detectors[detPos]->setAllTrimbits(val); + } - // multi - auto r = parallelCall(&slsDetector::setAllTrimbits, val); - return sls::minusOneIfDifferent(r); + // multi + auto r = parallelCall(&slsDetector::setAllTrimbits, val); + return sls::minusOneIfDifferent(r); } - int multiSlsDetector::enableGapPixels(int val, int detPos) { - if (getDetectorsType() != EIGER) { - if (val >= 0) { - FILE_LOG(logERROR) << "Function (enableGapPixels) not implemented for this detector"; - setErrorMask(getErrorMask() | MULTI_OTHER_ERROR); - } - return 0; - } + if (getDetectorsType() != EIGER) { + if (val >= 0) { + FILE_LOG(logERROR) << "Function (enableGapPixels) not implemented " + "for this detector"; + setErrorMask(getErrorMask() | MULTI_OTHER_ERROR); + } + return 0; + } - // single - if (detPos >= 0) { - if (val >= 0) { - FILE_LOG(logERROR) << "Function (enableGapPixels) must be called from a multi detector level."; - setErrorMask(getErrorMask() | MUST_BE_MULTI_CMD); - return -1; - } - return detectors[detPos]->enableGapPixels(val); - } + // single + if (detPos >= 0) { + if (val >= 0) { + FILE_LOG(logERROR) << "Function (enableGapPixels) must be called " + "from a multi detector level."; + setErrorMask(getErrorMask() | MUST_BE_MULTI_CMD); + return -1; + } + return detectors[detPos]->enableGapPixels(val); + } - // multi - auto r = parallelCall(&slsDetector::enableGapPixels, val); - int ret = sls::minusOneIfDifferent(r); + // multi + auto r = parallelCall(&slsDetector::enableGapPixels, val); + int ret = sls::minusOneIfDifferent(r); - // update data bytes incl gap pixels - if (val != -1) { - auto r = serialCall(&slsDetector::getDataBytesInclGapPixels); - thisMultiDetector->dataBytesInclGapPixels = sls::sum(r); + // update data bytes incl gap pixels + if (val != -1) { + auto r = serialCall(&slsDetector::getDataBytesInclGapPixels); + thisMultiDetector->dataBytesInclGapPixels = sls::sum(r); - // update - updateOffsets(); - } - return ret; + // update + updateOffsets(); + } + return ret; } +int multiSlsDetector::setTrimEn(int ne, int *ene, int detPos) { + // single + if (detPos >= 0) { + return detectors[detPos]->setTrimEn(ne, ene); + } -int multiSlsDetector::setTrimEn(int ne, int* ene, int detPos) { - // single - if (detPos >= 0) { - return detectors[detPos]->setTrimEn(ne, ene); - } - - // multi - auto r = serialCall(&slsDetector::setTrimEn, ne, ene); - return sls::minusOneIfDifferent(r); + // multi + auto r = serialCall(&slsDetector::setTrimEn, ne, ene); + return sls::minusOneIfDifferent(r); } +int multiSlsDetector::getTrimEn(int *ene, int detPos) { + // single + if (detPos >= 0) { + return detectors[detPos]->getTrimEn(ene); + } -int multiSlsDetector::getTrimEn(int* ene, int detPos) { - // single - if (detPos >= 0) { - return detectors[detPos]->getTrimEn(ene); - } - - // multi - auto r = serialCall(&slsDetector::getTrimEn, ene); - return sls::minusOneIfDifferent(r); + // multi + auto r = serialCall(&slsDetector::getTrimEn, ene); + return sls::minusOneIfDifferent(r); } - int multiSlsDetector::pulsePixel(int n, int x, int y, int detPos) { - // single - if (detPos >= 0) { - return detectors[detPos]->pulsePixel(n, x, y); - } + // single + if (detPos >= 0) { + return detectors[detPos]->pulsePixel(n, x, y); + } - // multi - auto r = parallelCall(&slsDetector::pulsePixel, n, x, y); - return sls::allEqualTo(r, static_cast(OK)) ? OK : FAIL; + // multi + auto r = parallelCall(&slsDetector::pulsePixel, n, x, y); + return sls::allEqualTo(r, static_cast(OK)) ? OK : FAIL; } - int multiSlsDetector::pulsePixelNMove(int n, int x, int y, int detPos) { - // single - if (detPos >= 0) { - return detectors[detPos]->pulsePixelNMove(n, x, y); - } + // single + if (detPos >= 0) { + return detectors[detPos]->pulsePixelNMove(n, x, y); + } - // multi - auto r = parallelCall(&slsDetector::pulsePixelNMove, n, x, y); - return sls::allEqualTo(r, static_cast(OK)) ? OK : FAIL; + // multi + auto r = parallelCall(&slsDetector::pulsePixelNMove, n, x, y); + return sls::allEqualTo(r, static_cast(OK)) ? OK : FAIL; } - int multiSlsDetector::pulseChip(int n, int detPos) { - // single - if (detPos >= 0) { - return detectors[detPos]->pulseChip(n); - } + // single + if (detPos >= 0) { + return detectors[detPos]->pulseChip(n); + } - // multi - auto r = parallelCall(&slsDetector::pulseChip, n); - return sls::allEqualTo(r, static_cast(OK)) ? OK : FAIL; + // multi + auto r = parallelCall(&slsDetector::pulseChip, n); + return sls::allEqualTo(r, static_cast(OK)) ? OK : FAIL; } - int multiSlsDetector::setThresholdTemperature(int val, int detPos) { - // single - if (detPos >= 0) { - return detectors[detPos]->setThresholdTemperature(val); - } + // single + if (detPos >= 0) { + return detectors[detPos]->setThresholdTemperature(val); + } - // multi - auto r = parallelCall(&slsDetector::setThresholdTemperature, val); - return sls::minusOneIfDifferent(r); + // multi + auto r = parallelCall(&slsDetector::setThresholdTemperature, val); + return sls::minusOneIfDifferent(r); } - int multiSlsDetector::setTemperatureControl(int val, int detPos) { - // single - if (detPos >= 0) { - return detectors[detPos]->setTemperatureControl(val); - } + // single + if (detPos >= 0) { + return detectors[detPos]->setTemperatureControl(val); + } - // multi - auto r = parallelCall(&slsDetector::setTemperatureControl, val); - return sls::minusOneIfDifferent(r); + // multi + auto r = parallelCall(&slsDetector::setTemperatureControl, val); + return sls::minusOneIfDifferent(r); } - int multiSlsDetector::setTemperatureEvent(int val, int detPos) { - // single - if (detPos >= 0) { - return detectors[detPos]->setTemperatureEvent(val); - } + // single + if (detPos >= 0) { + return detectors[detPos]->setTemperatureEvent(val); + } - // multi - auto r = parallelCall(&slsDetector::setTemperatureEvent, val); - return sls::minusOneIfDifferent(r); + // multi + auto r = parallelCall(&slsDetector::setTemperatureEvent, val); + return sls::minusOneIfDifferent(r); } - int multiSlsDetector::setStoragecellStart(int pos, int detPos) { - // single - if (detPos >= 0) { - return detectors[detPos]->setStoragecellStart(pos); - } + // single + if (detPos >= 0) { + return detectors[detPos]->setStoragecellStart(pos); + } - // multi - auto r = parallelCall(&slsDetector::setStoragecellStart, pos); - return sls::minusOneIfDifferent(r); + // multi + auto r = parallelCall(&slsDetector::setStoragecellStart, pos); + return sls::minusOneIfDifferent(r); } - int multiSlsDetector::programFPGA(std::string fname, int detPos) { - // single - if (detPos >= 0) { - return detectors[detPos]->programFPGA(fname); - } + // single + if (detPos >= 0) { + return detectors[detPos]->programFPGA(fname); + } - // multi - auto r = serialCall(&slsDetector::programFPGA, fname); - return sls::allEqualTo(r, static_cast(OK)) ? OK : FAIL; + // multi + auto r = serialCall(&slsDetector::programFPGA, fname); + return sls::allEqualTo(r, static_cast(OK)) ? OK : FAIL; } - int multiSlsDetector::resetFPGA(int detPos) { - // single - if (detPos >= 0) { - return detectors[detPos]->resetFPGA(); - } + // single + if (detPos >= 0) { + return detectors[detPos]->resetFPGA(); + } - // multi - auto r = parallelCall(&slsDetector::resetFPGA); - return sls::allEqualTo(r, static_cast(OK)) ? OK : FAIL; + // multi + auto r = parallelCall(&slsDetector::resetFPGA); + return sls::allEqualTo(r, static_cast(OK)) ? OK : FAIL; } - int multiSlsDetector::powerChip(int ival, int detPos) { - // single - if (detPos >= 0) { - return detectors[detPos]->powerChip(ival); - } + // single + if (detPos >= 0) { + return detectors[detPos]->powerChip(ival); + } - // multi - auto r = parallelCall(&slsDetector::powerChip, ival); - return sls::minusOneIfDifferent(r); + // multi + auto r = parallelCall(&slsDetector::powerChip, ival); + return sls::minusOneIfDifferent(r); } - int multiSlsDetector::setAutoComparatorDisableMode(int ival, int detPos) { - // single - if (detPos >= 0) { - return detectors[detPos]->setAutoComparatorDisableMode(ival); - } + // single + if (detPos >= 0) { + return detectors[detPos]->setAutoComparatorDisableMode(ival); + } - // multi - auto r = parallelCall(&slsDetector::setAutoComparatorDisableMode, ival); - return sls::minusOneIfDifferent(r); + // multi + auto r = parallelCall(&slsDetector::setAutoComparatorDisableMode, ival); + return sls::minusOneIfDifferent(r); } +int multiSlsDetector::getChanRegs(double *retval, bool fromDetector, + int detPos) { -int multiSlsDetector::getChanRegs(double* retval, bool fromDetector, int detPos) { - - int offset = 0; - std::vector r; - for (auto& d : detectors) { - int nch = d->getTotalNumberOfChannels(); - double result[nch]; - r.push_back(d->getChanRegs(result, fromDetector)); - memcpy(retval + offset, result, nch * sizeof(double)); - } - return sls::minusOneIfDifferent(r); + int offset = 0; + std::vector r; + for (auto &d : detectors) { + int nch = d->getTotalNumberOfChannels(); + double result[nch]; + r.push_back(d->getChanRegs(result, fromDetector)); + memcpy(retval + offset, result, nch * sizeof(double)); + } + return sls::minusOneIfDifferent(r); } - int multiSlsDetector::calibratePedestal(int frames, int detPos) { - // single - if (detPos >= 0) { - return detectors[detPos]->calibratePedestal(frames); - } + // single + if (detPos >= 0) { + return detectors[detPos]->calibratePedestal(frames); + } - // multi - auto r = parallelCall(&slsDetector::calibratePedestal, frames); - return sls::minusOneIfDifferent(r); + // multi + auto r = parallelCall(&slsDetector::calibratePedestal, frames); + return sls::minusOneIfDifferent(r); } - int multiSlsDetector::setRateCorrection(int t, int detPos) { - // single - if (detPos >= 0) { - return detectors[detPos]->setRateCorrection(t); - } + // single + if (detPos >= 0) { + return detectors[detPos]->setRateCorrection(t); + } - // multi - auto r = parallelCall(&slsDetector::setRateCorrection, t); - return sls::allEqualTo(r, static_cast(OK)) ? OK : FAIL; + // multi + auto r = parallelCall(&slsDetector::setRateCorrection, t); + return sls::allEqualTo(r, static_cast(OK)) ? OK : FAIL; } - int multiSlsDetector::getRateCorrection(int detPos) { - // single - if (detPos >= 0) { - return detectors[detPos]->getRateCorrection(); - } + // single + if (detPos >= 0) { + return detectors[detPos]->getRateCorrection(); + } - // multi - auto r = parallelCall(&slsDetector::getRateCorrection); - return sls::minusOneIfDifferent(r); + // multi + auto r = parallelCall(&slsDetector::getRateCorrection); + return sls::minusOneIfDifferent(r); } - int multiSlsDetector::printReceiverConfiguration(int detPos) { - // single - if (detPos >= 0) { - return detectors[detPos]->printReceiverConfiguration(); - } + // single + if (detPos >= 0) { + return detectors[detPos]->printReceiverConfiguration(); + } - // multi - auto r = parallelCall(&slsDetector::printReceiverConfiguration); - return sls::allEqualTo(r, static_cast(OK)) ? OK : FAIL; + // multi + auto r = parallelCall(&slsDetector::printReceiverConfiguration); + return sls::allEqualTo(r, static_cast(OK)) ? OK : FAIL; } - int multiSlsDetector::setReceiverOnline(int off, int detPos) { - // single - if (detPos >= 0) { - return detectors[detPos]->setReceiverOnline(off); - } + // single + if (detPos >= 0) { + return detectors[detPos]->setReceiverOnline(off); + } - // multi - if (off != GET_ONLINE_FLAG) { - auto r = parallelCall(&slsDetector::setReceiverOnline, off); - thisMultiDetector->receiverOnlineFlag = sls::minusOneIfDifferent(r); - } - return thisMultiDetector->receiverOnlineFlag; + // multi + if (off != GET_ONLINE_FLAG) { + auto r = parallelCall(&slsDetector::setReceiverOnline, off); + thisMultiDetector->receiverOnlineFlag = sls::minusOneIfDifferent(r); + } + return thisMultiDetector->receiverOnlineFlag; } - std::string multiSlsDetector::checkReceiverOnline(int detPos) { - // single - if (detPos >= 0) { - return detectors[detPos]->checkReceiverOnline(); - } + // single + if (detPos >= 0) { + return detectors[detPos]->checkReceiverOnline(); + } - // multi - auto r = parallelCall(&slsDetector::checkReceiverOnline); - return sls::concatenateNonEmptyStrings(r); + // multi + auto r = parallelCall(&slsDetector::checkReceiverOnline); + return sls::concatenateNonEmptyStrings(r); } - int multiSlsDetector::lockReceiver(int lock, int detPos) { - // single - if (detPos >= 0) { - return detectors[detPos]->lockReceiver(lock); - } + // single + if (detPos >= 0) { + return detectors[detPos]->lockReceiver(lock); + } - // multi - auto r = parallelCall(&slsDetector::lockReceiver, lock); - return sls::minusOneIfDifferent(r); + // multi + auto r = parallelCall(&slsDetector::lockReceiver, lock); + return sls::minusOneIfDifferent(r); } - std::string multiSlsDetector::getReceiverLastClientIP(int detPos) { - // single - if (detPos >= 0) { - return detectors[detPos]->getReceiverLastClientIP(); - } + // single + if (detPos >= 0) { + return detectors[detPos]->getReceiverLastClientIP(); + } - // multi - auto r = parallelCall(&slsDetector::getReceiverLastClientIP); - return sls::concatenateIfDifferent(r); + // multi + auto r = parallelCall(&slsDetector::getReceiverLastClientIP); + return sls::concatenateIfDifferent(r); } - int multiSlsDetector::exitReceiver(int detPos) { - // single - if (detPos >= 0) { - return detectors[detPos]->exitReceiver(); - } + // single + if (detPos >= 0) { + return detectors[detPos]->exitReceiver(); + } - // multi - auto r = parallelCall(&slsDetector::exitReceiver); - return sls::allEqualTo(r, static_cast(OK)) ? OK : FAIL; + // multi + auto r = parallelCall(&slsDetector::exitReceiver); + return sls::allEqualTo(r, static_cast(OK)) ? OK : FAIL; } - int multiSlsDetector::execReceiverCommand(std::string cmd, int detPos) { - // single - if (detPos >= 0) { - return detectors[detPos]->execReceiverCommand(cmd); - } + // single + if (detPos >= 0) { + return detectors[detPos]->execReceiverCommand(cmd); + } - // multi - auto r = parallelCall(&slsDetector::execReceiverCommand, cmd); - return sls::allEqualTo(r, static_cast(OK)) ? OK : FAIL; + // multi + auto r = parallelCall(&slsDetector::execReceiverCommand, cmd); + return sls::allEqualTo(r, static_cast(OK)) ? OK : FAIL; } - std::string multiSlsDetector::getFilePath(int detPos) { - // single - if (detPos >= 0) { - return detectors[detPos]->getFilePath(); - } + // single + if (detPos >= 0) { + return detectors[detPos]->getFilePath(); + } - // multi - auto r = serialCall(&slsDetector::getFilePath); - return sls::concatenateIfDifferent(r); + // multi + auto r = serialCall(&slsDetector::getFilePath); + return sls::concatenateIfDifferent(r); } - std::string multiSlsDetector::setFilePath(std::string s, int detPos) { - if (s.empty()) - return getFilePath(detPos); + if (s.empty()) + return getFilePath(detPos); - // single - if (detPos >= 0) { - return detectors[detPos]->setFilePath(s); - } + // single + if (detPos >= 0) { + return detectors[detPos]->setFilePath(s); + } - // multi - auto r = parallelCall(&slsDetector::setFilePath, s); - return sls::concatenateIfDifferent(r); + // multi + auto r = parallelCall(&slsDetector::setFilePath, s); + return sls::concatenateIfDifferent(r); } - std::string multiSlsDetector::getFileName(int detPos) { - // single - if (detPos >= 0) { - return detectors[detPos]->getFileName(); - } + // single + if (detPos >= 0) { + return detectors[detPos]->getFileName(); + } - // multi - auto r = serialCall(&slsDetector::getFileName); - return sls::concatenateIfDifferent(r); + // multi + auto r = serialCall(&slsDetector::getFileName); + return sls::concatenateIfDifferent(r); } - std::string multiSlsDetector::setFileName(std::string s, int detPos) { - if (s.empty()) - return getFileName(detPos); + if (s.empty()) + return getFileName(detPos); - // single - if (detPos >= 0) { - return detectors[detPos]->setFileName(s); - } + // single + if (detPos >= 0) { + return detectors[detPos]->setFileName(s); + } - // multi - auto r = parallelCall(&slsDetector::setFileName, s); - return sls::concatenateIfDifferent(r); + // multi + auto r = parallelCall(&slsDetector::setFileName, s); + return sls::concatenateIfDifferent(r); } - int multiSlsDetector::setReceiverFramesPerFile(int f, int detPos) { - // single - if (detPos >= 0) { - return detectors[detPos]->setReceiverFramesPerFile(f); - } + // single + if (detPos >= 0) { + return detectors[detPos]->setReceiverFramesPerFile(f); + } - // multi - auto r = parallelCall(&slsDetector::setReceiverFramesPerFile, f); - return sls::minusOneIfDifferent(r); + // multi + auto r = parallelCall(&slsDetector::setReceiverFramesPerFile, f); + return sls::minusOneIfDifferent(r); } +slsDetectorDefs::frameDiscardPolicy +multiSlsDetector::setReceiverFramesDiscardPolicy(frameDiscardPolicy f, + int detPos) { + // single + if (detPos >= 0) { + return detectors[detPos]->setReceiverFramesDiscardPolicy(f); + } -slsDetectorDefs::frameDiscardPolicy multiSlsDetector::setReceiverFramesDiscardPolicy( - frameDiscardPolicy f, int detPos) { - // single - if (detPos >= 0) { - return detectors[detPos]->setReceiverFramesDiscardPolicy(f); - } - - // multi - auto r = parallelCall(&slsDetector::setReceiverFramesDiscardPolicy, f); - return sls::minusOneIfDifferent(r); + // multi + auto r = parallelCall(&slsDetector::setReceiverFramesDiscardPolicy, f); + return sls::minusOneIfDifferent(r); } - int multiSlsDetector::setReceiverPartialFramesPadding(int f, int detPos) { - // single - if (detPos >= 0) { - return detectors[detPos]->setReceiverPartialFramesPadding(f); - } + // single + if (detPos >= 0) { + return detectors[detPos]->setReceiverPartialFramesPadding(f); + } - // multi - auto r = parallelCall(&slsDetector::setReceiverPartialFramesPadding, f); - return sls::minusOneIfDifferent(r); + // multi + auto r = parallelCall(&slsDetector::setReceiverPartialFramesPadding, f); + return sls::minusOneIfDifferent(r); } - slsDetectorDefs::fileFormat multiSlsDetector::getFileFormat(int detPos) { - // single - if (detPos >= 0) { - return detectors[detPos]->getFileFormat(); - } + // single + if (detPos >= 0) { + return detectors[detPos]->getFileFormat(); + } - // multi - auto r = serialCall(&slsDetector::getFileFormat); - return sls::minusOneIfDifferent(r); + // multi + auto r = serialCall(&slsDetector::getFileFormat); + return sls::minusOneIfDifferent(r); } +slsDetectorDefs::fileFormat multiSlsDetector::setFileFormat(fileFormat f, + int detPos) { + // single + if (detPos >= 0) { + return detectors[detPos]->setFileFormat(f); + } -slsDetectorDefs::fileFormat multiSlsDetector::setFileFormat(fileFormat f, int detPos) { - // single - if (detPos >= 0) { - return detectors[detPos]->setFileFormat(f); - } - - // multi - auto r = parallelCall(&slsDetector::setFileFormat, f); - return sls::minusOneIfDifferent(r); + // multi + auto r = parallelCall(&slsDetector::setFileFormat, f); + return sls::minusOneIfDifferent(r); } - int multiSlsDetector::getFileIndex(int detPos) { - // single - if (detPos >= 0) { - return detectors[detPos]->getFileIndex(); - } + // single + if (detPos >= 0) { + return detectors[detPos]->getFileIndex(); + } - // multi - auto r = serialCall(&slsDetector::getFileIndex); - return sls::minusOneIfDifferent(r); + // multi + auto r = serialCall(&slsDetector::getFileIndex); + return sls::minusOneIfDifferent(r); } - int multiSlsDetector::incrementFileIndex(int detPos) { - // single - if (detPos >= 0) { - return detectors[detPos]->incrementFileIndex(); - } + // single + if (detPos >= 0) { + return detectors[detPos]->incrementFileIndex(); + } - // multi - auto r = parallelCall(&slsDetector::incrementFileIndex); - return sls::minusOneIfDifferent(r); + // multi + auto r = parallelCall(&slsDetector::incrementFileIndex); + return sls::minusOneIfDifferent(r); } - int multiSlsDetector::setFileIndex(int i, int detPos) { - // single - if (detPos >= 0) { - return detectors[detPos]->setFileIndex(i); - } + // single + if (detPos >= 0) { + return detectors[detPos]->setFileIndex(i); + } - // multi - auto r = parallelCall(&slsDetector::setFileIndex, i); - return sls::minusOneIfDifferent(r); + // multi + auto r = parallelCall(&slsDetector::setFileIndex, i); + return sls::minusOneIfDifferent(r); } - int multiSlsDetector::startReceiver(int detPos) { - // single - if (detPos >= 0) { - return detectors[detPos]->startReceiver(); - } + // single + if (detPos >= 0) { + return detectors[detPos]->startReceiver(); + } - // multi - auto r = parallelCall(&slsDetector::startReceiver); - return sls::allEqualTo(r, static_cast(OK)) ? OK : FAIL; + // multi + auto r = parallelCall(&slsDetector::startReceiver); + return sls::allEqualTo(r, static_cast(OK)) ? OK : FAIL; } - int multiSlsDetector::stopReceiver(int detPos) { - // single - if (detPos >= 0) { - return detectors[detPos]->stopReceiver(); - } + // single + if (detPos >= 0) { + return detectors[detPos]->stopReceiver(); + } - // multi - auto r = parallelCall(&slsDetector::stopReceiver); - return sls::allEqualTo(r, static_cast(OK)) ? OK : FAIL; + // multi + auto r = parallelCall(&slsDetector::stopReceiver); + return sls::allEqualTo(r, static_cast(OK)) ? OK : FAIL; } - slsDetectorDefs::runStatus multiSlsDetector::getReceiverStatus(int detPos) { - // single - if (detPos >= 0) { - return detectors[detPos]->getReceiverStatus(); - } + // single + if (detPos >= 0) { + return detectors[detPos]->getReceiverStatus(); + } - // multi - auto r = parallelCall(&slsDetector::getReceiverStatus); - if (sls::allEqual(r)) - return r.front(); - if (sls::anyEqualTo(r, ERROR)) - return ERROR; - for (const auto& value : r) - if (value != IDLE) - return value; - return IDLE; + // multi + auto r = parallelCall(&slsDetector::getReceiverStatus); + if (sls::allEqual(r)) + return r.front(); + if (sls::anyEqualTo(r, ERROR)) + return ERROR; + for (const auto &value : r) + if (value != IDLE) + return value; + return IDLE; } - int multiSlsDetector::getFramesCaughtByReceiver(int detPos) { - // single - if (detPos >= 0) { - return detectors[detPos]->getFramesCaughtByReceiver(); - } + // single + if (detPos >= 0) { + return detectors[detPos]->getFramesCaughtByReceiver(); + } - // multi - auto r = parallelCall(&slsDetector::getFramesCaughtByReceiver); + // multi + auto r = parallelCall(&slsDetector::getFramesCaughtByReceiver); - // prevent divide by all or do not take avg when -1 for "did not connect" - if ((!detectors.size()) || (sls::anyEqualTo(r, -1))) - return -1; + // prevent divide by all or do not take avg when -1 for "did not connect" + if ((!detectors.size()) || (sls::anyEqualTo(r, -1))) + return -1; - // return average - return ((sls::sum(r))/(int)detectors.size()); + // return average + return ((sls::sum(r)) / (int)detectors.size()); } - int multiSlsDetector::getReceiverCurrentFrameIndex(int detPos) { - // single - if (detPos >= 0) { - return detectors[detPos]->getReceiverCurrentFrameIndex(); - } + // single + if (detPos >= 0) { + return detectors[detPos]->getReceiverCurrentFrameIndex(); + } - // multi - auto r = parallelCall(&slsDetector::getReceiverCurrentFrameIndex); + // multi + auto r = parallelCall(&slsDetector::getReceiverCurrentFrameIndex); - // prevent divide by all or do not take avg when -1 for "did not connect" - if ((!detectors.size()) || (sls::anyEqualTo(r, -1))) - return -1; + // prevent divide by all or do not take avg when -1 for "did not connect" + if ((!detectors.size()) || (sls::anyEqualTo(r, -1))) + return -1; - // return average - return ((sls::sum(r))/(int)detectors.size()); + // return average + return ((sls::sum(r)) / (int)detectors.size()); } - int multiSlsDetector::resetFramesCaught(int detPos) { - // single - if (detPos >= 0) { - return detectors[detPos]->resetFramesCaught(); - } + // single + if (detPos >= 0) { + return detectors[detPos]->resetFramesCaught(); + } - // multi - auto r = parallelCall(&slsDetector::resetFramesCaught); - return sls::allEqualTo(r, static_cast(OK)) ? OK : FAIL; + // multi + auto r = parallelCall(&slsDetector::resetFramesCaught); + return sls::allEqualTo(r, static_cast(OK)) ? OK : FAIL; } - int multiSlsDetector::createReceivingDataSockets(const bool destroy) { - if (destroy) { - cprintf(MAGENTA, "Going to destroy data sockets\n"); - //close socket - zmqSocket.clear(); + if (destroy) { + cprintf(MAGENTA, "Going to destroy data sockets\n"); + // close socket + zmqSocket.clear(); - client_downstream = false; - FILE_LOG(logINFO) << "Destroyed Receiving Data Socket(s)"; - return OK; - } + client_downstream = false; + FILE_LOG(logINFO) << "Destroyed Receiving Data Socket(s)"; + return OK; + } - cprintf(MAGENTA, "Going to create data sockets\n"); + cprintf(MAGENTA, "Going to create data sockets\n"); - size_t numSockets = detectors.size(); - size_t numSocketsPerDetector = 1; - if (getDetectorsType() == EIGER) { - numSocketsPerDetector = 2; - } - numSockets *= numSocketsPerDetector; + size_t numSockets = detectors.size(); + size_t numSocketsPerDetector = 1; + if (getDetectorsType() == EIGER) { + numSocketsPerDetector = 2; + } + numSockets *= numSocketsPerDetector; - for (size_t iSocket = 0; iSocket < numSockets; ++iSocket) { - uint32_t portnum = stoi(detectors[iSocket / numSocketsPerDetector]->getClientStreamingPort()); - portnum += (iSocket % numSocketsPerDetector); - try { - zmqSocket.push_back(sls::make_unique(detectors[iSocket / numSocketsPerDetector]->getClientStreamingIP().c_str(), - portnum)); - printf("Zmq Client[%lu] at %s\n", iSocket, zmqSocket.back()->GetZmqServerAddress()); - } catch (...) { - cprintf(RED, "Error: Could not create Zmq socket on port %d\n", portnum); - createReceivingDataSockets(true); - return FAIL; - } - } + for (size_t iSocket = 0; iSocket < numSockets; ++iSocket) { + uint32_t portnum = stoi(detectors[iSocket / numSocketsPerDetector] + ->getClientStreamingPort()); + portnum += (iSocket % numSocketsPerDetector); + try { + zmqSocket.push_back(sls::make_unique( + detectors[iSocket / numSocketsPerDetector] + ->getClientStreamingIP() + .c_str(), + portnum)); + printf("Zmq Client[%lu] at %s\n", iSocket, + zmqSocket.back()->GetZmqServerAddress()); + } catch (...) { + cprintf(RED, "Error: Could not create Zmq socket on port %d\n", + portnum); + createReceivingDataSockets(true); + return FAIL; + } + } - client_downstream = true; - FILE_LOG(logINFO) << "Receiving Data Socket(s) created"; - return OK; + client_downstream = true; + FILE_LOG(logINFO) << "Receiving Data Socket(s) created"; + return OK; } - void multiSlsDetector::readFrameFromReceiver() { - int nX = thisMultiDetector->numberOfDetector[X]; // to copy data in multi module - int nY = thisMultiDetector->numberOfDetector[Y]; // for eiger, to reverse the data - bool gappixelsenable = false; - bool eiger = false; - if (getDetectorsType() == EIGER) { - eiger = true; - nX *= 2; - gappixelsenable = detectors[0]->enableGapPixels(-1) >= 1 ? true : false; - } + int nX = + thisMultiDetector->numberOfDetector[X]; // to copy data in multi module + int nY = thisMultiDetector + ->numberOfDetector[Y]; // for eiger, to reverse the data + bool gappixelsenable = false; + bool eiger = false; + if (getDetectorsType() == EIGER) { + eiger = true; + nX *= 2; + gappixelsenable = detectors[0]->enableGapPixels(-1) >= 1 ? true : false; + } - bool runningList[zmqSocket.size()], connectList[zmqSocket.size()]; - int numRunning = 0; - for (size_t i = 0; i < zmqSocket.size(); ++i) { - if (!zmqSocket[i]->Connect()) { - connectList[i] = true; - runningList[i] = true; - ++numRunning; - } else { - // to remember the list it connected to, to disconnect later - connectList[i] = false; - cprintf(RED, "Error: Could not connect to socket %s\n", - zmqSocket[i]->GetZmqServerAddress()); - runningList[i] = false; - } - } - int numConnected = numRunning; - bool data = false; - char* image = NULL; - char* multiframe = NULL; - char* multigappixels = NULL; - int multisize = 0; - // only first message header - uint32_t size = 0, nPixelsX = 0, nPixelsY = 0, dynamicRange = 0; - float bytesPerPixel = 0; - // header info every header - std::string currentFileName = ""; - uint64_t currentAcquisitionIndex = -1, currentFrameIndex = -1, currentFileIndex = -1; - uint32_t currentSubFrameIndex = -1, coordX = -1, coordY = -1, flippedDataX = -1; + bool runningList[zmqSocket.size()], connectList[zmqSocket.size()]; + int numRunning = 0; + for (size_t i = 0; i < zmqSocket.size(); ++i) { + if (!zmqSocket[i]->Connect()) { + connectList[i] = true; + runningList[i] = true; + ++numRunning; + } else { + // to remember the list it connected to, to disconnect later + connectList[i] = false; + cprintf(RED, "Error: Could not connect to socket %s\n", + zmqSocket[i]->GetZmqServerAddress()); + runningList[i] = false; + } + } + int numConnected = numRunning; + bool data = false; + char *image = NULL; + char *multiframe = NULL; + char *multigappixels = NULL; + int multisize = 0; + // only first message header + uint32_t size = 0, nPixelsX = 0, nPixelsY = 0, dynamicRange = 0; + float bytesPerPixel = 0; + // header info every header + std::string currentFileName = ""; + uint64_t currentAcquisitionIndex = -1, currentFrameIndex = -1, + currentFileIndex = -1; + uint32_t currentSubFrameIndex = -1, coordX = -1, coordY = -1, + flippedDataX = -1; - //wait for real time acquisition to start - bool running = true; - sem_wait(&sem_newRTAcquisition); - if (getJoinThreadFlag()) - running = false; + // wait for real time acquisition to start + bool running = true; + sem_wait(&sem_newRTAcquisition); + if (getJoinThreadFlag()) + running = false; + while (running) { + // reset data + data = false; + if (multiframe != NULL) + memset(multiframe, 0xFF, multisize); - while (running) { - // reset data - data = false; - if (multiframe != NULL) - memset(multiframe, 0xFF, multisize); + // get each frame + for (unsigned int isocket = 0; isocket < zmqSocket.size(); ++isocket) { - //get each frame - for (unsigned int isocket = 0; isocket < zmqSocket.size(); ++isocket) { + // if running + if (runningList[isocket]) { - //if running - if (runningList[isocket]) { + // HEADER + { + rapidjson::Document doc; + if (!zmqSocket[isocket]->ReceiveHeader( + isocket, doc, SLS_DETECTOR_JSON_HEADER_VERSION)) { + // parse error, version error or end of acquisition for + // socket + runningList[isocket] = false; + --numRunning; + continue; + } - // HEADER - { - rapidjson::Document doc; - if (!zmqSocket[isocket]->ReceiveHeader(isocket, doc, - SLS_DETECTOR_JSON_HEADER_VERSION)) { - // parse error, version error or end of acquisition for socket - runningList[isocket] = false; - --numRunning; - continue; - } - - // if first message, allocate (all one time stuff) - if (image == NULL) { - // allocate - size = doc["size"].GetUint(); - multisize = size * zmqSocket.size(); - image = new char[size]; - multiframe = new char[multisize]; - memset(multiframe, 0xFF, multisize); - // dynamic range - dynamicRange = doc["bitmode"].GetUint(); - bytesPerPixel = (float)dynamicRange / 8; - // shape - nPixelsX = doc["shape"][0].GetUint(); - nPixelsY = doc["shape"][1].GetUint(); + // if first message, allocate (all one time stuff) + if (image == NULL) { + // allocate + size = doc["size"].GetUint(); + multisize = size * zmqSocket.size(); + image = new char[size]; + multiframe = new char[multisize]; + memset(multiframe, 0xFF, multisize); + // dynamic range + dynamicRange = doc["bitmode"].GetUint(); + bytesPerPixel = (float)dynamicRange / 8; + // shape + nPixelsX = doc["shape"][0].GetUint(); + nPixelsY = doc["shape"][1].GetUint(); #ifdef VERBOSE - cprintf(BLUE, "(Debug) One Time Header Info:\n" - "size: %u\n" - "multisize: %u\n" - "dynamicRange: %u\n" - "bytesPerPixel: %f\n" - "nPixelsX: %u\n" - "nPixelsY: %u\n", - size, multisize, dynamicRange, bytesPerPixel, - nPixelsX, nPixelsY); + cprintf(BLUE, + "(Debug) One Time Header Info:\n" + "size: %u\n" + "multisize: %u\n" + "dynamicRange: %u\n" + "bytesPerPixel: %f\n" + "nPixelsX: %u\n" + "nPixelsY: %u\n", + size, multisize, dynamicRange, bytesPerPixel, + nPixelsX, nPixelsY); #endif - } - // each time, parse rest of header - currentFileName = doc["fname"].GetString(); - currentAcquisitionIndex = doc["acqIndex"].GetUint64(); - currentFrameIndex = doc["fIndex"].GetUint64(); - currentFileIndex = doc["fileIndex"].GetUint64(); - currentSubFrameIndex = doc["expLength"].GetUint(); - coordY = doc["row"].GetUint(); - coordX = doc["column"].GetUint(); - if (eiger) - coordY = (nY - 1) - coordY; - //std::cout << "X:" << doc["row"].GetUint() <<" Y:"<ReceiveData(isocket, image, size); + // DATA + data = true; + zmqSocket[isocket]->ReceiveData(isocket, image, size); - // creating multi image - { - uint32_t xoffset = coordX * nPixelsX * bytesPerPixel; - uint32_t yoffset = coordY * nPixelsY; - uint32_t singledetrowoffset = nPixelsX * bytesPerPixel; - uint32_t rowoffset = nX * singledetrowoffset; + // creating multi image + { + uint32_t xoffset = coordX * nPixelsX * bytesPerPixel; + uint32_t yoffset = coordY * nPixelsY; + uint32_t singledetrowoffset = nPixelsX * bytesPerPixel; + uint32_t rowoffset = nX * singledetrowoffset; #ifdef VERBOSE - cprintf(BLUE, "(Debug) Multi Image Info:\n" - "xoffset: %u\n" - "yoffset: %u\n" - "singledetrowoffset: %u\n" - "rowoffset: %u\n", - xoffset, yoffset, singledetrowoffset, rowoffset); + cprintf(BLUE, + "(Debug) Multi Image Info:\n" + "xoffset: %u\n" + "yoffset: %u\n" + "singledetrowoffset: %u\n" + "rowoffset: %u\n", + xoffset, yoffset, singledetrowoffset, rowoffset); #endif - if (eiger && flippedDataX) { - for (uint32_t i = 0; i < nPixelsY; ++i) { - memcpy(((char*)multiframe) + - ((yoffset + (nPixelsY - 1 - i)) * rowoffset) + xoffset, - (char*)image + (i * singledetrowoffset), - singledetrowoffset); - } - } else { - for (uint32_t i = 0; i < nPixelsY; ++i) { - memcpy(((char*)multiframe) + - ((yoffset + i) * rowoffset) + xoffset, - (char*)image + (i * singledetrowoffset), - singledetrowoffset); - } - } - } - } - } + if (eiger && flippedDataX) { + for (uint32_t i = 0; i < nPixelsY; ++i) { + memcpy(((char *)multiframe) + + ((yoffset + (nPixelsY - 1 - i)) * + rowoffset) + + xoffset, + (char *)image + (i * singledetrowoffset), + singledetrowoffset); + } + } else { + for (uint32_t i = 0; i < nPixelsY; ++i) { + memcpy(((char *)multiframe) + + ((yoffset + i) * rowoffset) + xoffset, + (char *)image + (i * singledetrowoffset), + singledetrowoffset); + } + } + } + } + } - //send data to callback - if (data) { - // 4bit gap pixels - if (dynamicRange == 4 && gappixelsenable) { - int n = processImageWithGapPixels(multiframe, multigappixels); - nPixelsX = thisMultiDetector->numberOfChannelInclGapPixels[X]; - nPixelsY = thisMultiDetector->numberOfChannelInclGapPixels[Y]; - thisData = new detectorData(getCurrentProgress(), - currentFileName.c_str(), nPixelsX, nPixelsY, - multigappixels, n, dynamicRange, currentFileIndex); - } - // normal pixels - else { - thisData = new detectorData(getCurrentProgress(), - currentFileName.c_str(), nPixelsX, nPixelsY, - multiframe, multisize, dynamicRange, currentFileIndex); - } - dataReady(thisData, currentFrameIndex, - ((dynamicRange == 32) ? currentSubFrameIndex : -1), - pCallbackArg); - delete thisData; - setCurrentProgress(currentAcquisitionIndex + 1); - } + // send data to callback + if (data) { + // 4bit gap pixels + if (dynamicRange == 4 && gappixelsenable) { + int n = processImageWithGapPixels(multiframe, multigappixels); + nPixelsX = thisMultiDetector->numberOfChannelInclGapPixels[X]; + nPixelsY = thisMultiDetector->numberOfChannelInclGapPixels[Y]; + thisData = new detectorData(getCurrentProgress(), + currentFileName.c_str(), nPixelsX, + nPixelsY, multigappixels, n, + dynamicRange, currentFileIndex); + } + // normal pixels + else { + thisData = new detectorData(getCurrentProgress(), + currentFileName.c_str(), nPixelsX, + nPixelsY, multiframe, multisize, + dynamicRange, currentFileIndex); + } + dataReady(thisData, currentFrameIndex, + ((dynamicRange == 32) ? currentSubFrameIndex : -1), + pCallbackArg); + delete thisData; + setCurrentProgress(currentAcquisitionIndex + 1); + } - //all done - if (!numRunning) { - // let main thread know that all dummy packets have been received - //(also from external process), - // main thread can now proceed to measurement finished call back - sem_post(&sem_endRTAcquisition); - // wait for next scan/measurement, else join thread - sem_wait(&sem_newRTAcquisition); - //done with complete acquisition - if (getJoinThreadFlag()) - running = false; - else { - //starting a new scan/measurement (got dummy data) - for (size_t i = 0; i < zmqSocket.size(); ++i) - runningList[i] = connectList[i]; - numRunning = numConnected; - } - } - } + // all done + if (!numRunning) { + // let main thread know that all dummy packets have been received + //(also from external process), + // main thread can now proceed to measurement finished call back + sem_post(&sem_endRTAcquisition); + // wait for next scan/measurement, else join thread + sem_wait(&sem_newRTAcquisition); + // done with complete acquisition + if (getJoinThreadFlag()) + running = false; + else { + // starting a new scan/measurement (got dummy data) + for (size_t i = 0; i < zmqSocket.size(); ++i) + runningList[i] = connectList[i]; + numRunning = numConnected; + } + } + } - // Disconnect resources - for (size_t i= 0; i < zmqSocket.size(); ++i) - if (connectList[i]) - zmqSocket[i]->Disconnect(); + // Disconnect resources + for (size_t i = 0; i < zmqSocket.size(); ++i) + if (connectList[i]) + zmqSocket[i]->Disconnect(); - //free resources - if (image != NULL) - delete[] image; - if (multiframe != NULL) - delete[] multiframe; - if (multigappixels != NULL) - delete[] multigappixels; + // free resources + if (image != NULL) + delete[] image; + if (multiframe != NULL) + delete[] multiframe; + if (multigappixels != NULL) + delete[] multigappixels; } +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 gapdatabytes = nxb * nyb; -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 gapdatabytes = nxb * nyb; + int nxchip = thisMultiDetector->numberOfDetector[X] * 4; + int nychip = thisMultiDetector->numberOfDetector[Y] * 1; - int nxchip = thisMultiDetector->numberOfDetector[X] * 4; - int nychip = thisMultiDetector->numberOfDetector[Y] * 1; + // allocate + if (gpImage == NULL) + gpImage = new char[gapdatabytes]; + // fill value + memset(gpImage, 0xFF, gapdatabytes); - // allocate - if (gpImage == NULL) - gpImage = new char[gapdatabytes]; - // fill value - memset(gpImage, 0xFF, gapdatabytes); + const int b1chipx = 128; + const int b1chipy = 256; + char *src = 0; + char *dst = 0; - const int b1chipx = 128; - const int b1chipy = 256; - char* src = 0; - char* dst = 0; + // copying line by line + src = image; + dst = gpImage; + for (int row = 0; row < nychip; ++row) { // for each chip in a row + for (int ichipy = 0; ichipy < b1chipy; + ++ichipy) { // for each row in a chip + for (int col = 0; col < nxchip; ++col) { + memcpy(dst, src, b1chipx); + src += b1chipx; + dst += b1chipx; + if ((col + 1) % 4) + ++dst; + } + } - // copying line by line - src = image; - dst = gpImage; - for (int row = 0; row < nychip; ++row) { // for each chip in a row - for (int ichipy = 0; ichipy < b1chipy; ++ichipy) { //for each row in a chip - for (int col = 0; col < nxchip; ++col) { - memcpy(dst, src, b1chipx); - src += b1chipx; - dst += b1chipx; - if ((col + 1) % 4) - ++dst; - } - } + dst += (2 * nxb); + } - dst += (2 * nxb); - } + // vertical filling of values + { + uint8_t temp, g1, g2; + int mod; + dst = gpImage; + for (int row = 0; row < nychip; ++row) { // for each chip in a row + for (int ichipy = 0; ichipy < b1chipy; + ++ichipy) { // for each row in a chip + for (int col = 0; col < nxchip; ++col) { + dst += b1chipx; + mod = (col + 1) % 4; + // copy gap pixel(chip 0, 1, 2) + if (mod) { + // neighbouring gap pixels to left + temp = (*((uint8_t *)(dst - 1))); + g1 = ((temp & 0xF) / 2); + (*((uint8_t *)(dst - 1))) = (temp & 0xF0) + g1; - // vertical filling of values - { - uint8_t temp, g1, g2; - int mod; - dst = gpImage; - for (int row = 0; row < nychip; ++row) { // for each chip in a row - for (int ichipy = 0; ichipy < b1chipy; ++ichipy) { //for each row in a chip - for (int col = 0; col < nxchip; ++col) { - dst += b1chipx; - mod = (col + 1) % 4; - // copy gap pixel(chip 0, 1, 2) - if (mod) { - // neighbouring gap pixels to left - temp = (*((uint8_t*)(dst - 1))); - g1 = ((temp & 0xF) / 2); - (*((uint8_t*)(dst - 1))) = (temp & 0xF0) + g1; + // neighbouring gap pixels to right + temp = (*((uint8_t *)(dst + 1))); + g2 = ((temp >> 4) / 2); + (*((uint8_t *)(dst + 1))) = (g2 << 4) + (temp & 0x0F); - // neighbouring gap pixels to right - temp = (*((uint8_t*)(dst + 1))); - g2 = ((temp >> 4) / 2); - (*((uint8_t*)(dst + 1))) = (g2 << 4) + (temp & 0x0F); + // gap pixels + (*((uint8_t *)dst)) = (g1 << 4) + g2; - // gap pixels - (*((uint8_t*)dst)) = (g1 << 4) + g2; + // increment to point to proper chip destination + ++dst; + } + } + } - // increment to point to proper chip destination - ++dst; - } - } - } + dst += (2 * nxb); + } + } - dst += (2 * nxb); - } - } + // return gapdatabytes; + // horizontal filling + { + uint8_t temp, g1, g2; + char *dst_prevline = 0; + dst = gpImage; + for (int row = 0; row < nychip; ++row) { // for each chip in a row + dst += (b1chipy * nxb); + // horizontal copying of gap pixels from neighboring past line + // (bottom parts) + if (row < nychip - 1) { + dst_prevline = dst - nxb; + for (int gapline = 0; gapline < nxb; ++gapline) { + temp = (*((uint8_t *)dst_prevline)); + g1 = ((temp >> 4) / 2); + g2 = ((temp & 0xF) / 2); + (*((uint8_t *)dst_prevline)) = (g1 << 4) + g2; + (*((uint8_t *)dst)) = (*((uint8_t *)dst_prevline)); + ++dst; + ++dst_prevline; + } + } - //return gapdatabytes; - // horizontal filling - { - uint8_t temp, g1, g2; - char* dst_prevline = 0; - dst = gpImage; - for (int row = 0; row < nychip; ++row) { // for each chip in a row - dst += (b1chipy * nxb); - // horizontal copying of gap pixels from neighboring past line (bottom parts) - if (row < nychip - 1) { - dst_prevline = dst - nxb; - for (int gapline = 0; gapline < nxb; ++gapline) { - temp = (*((uint8_t*)dst_prevline)); - g1 = ((temp >> 4) / 2); - g2 = ((temp & 0xF) / 2); - (*((uint8_t*)dst_prevline)) = (g1 << 4) + g2; - (*((uint8_t*)dst)) = (*((uint8_t*)dst_prevline)); - ++dst; - ++dst_prevline; - } - } + // horizontal copying of gap pixels from neihboring future line (top + // part) + if (row > 0) { + dst -= ((b1chipy + 1) * nxb); + dst_prevline = dst + nxb; + for (int gapline = 0; gapline < nxb; ++gapline) { + temp = (*((uint8_t *)dst_prevline)); + g1 = ((temp >> 4) / 2); + g2 = ((temp & 0xF) / 2); + temp = (g1 << 4) + g2; + (*((uint8_t *)dst_prevline)) = temp; + (*((uint8_t *)dst)) = temp; + ++dst; + ++dst_prevline; + } + dst += ((b1chipy + 1) * nxb); + } - // horizontal copying of gap pixels from neihboring future line (top part) - if (row > 0) { - dst -= ((b1chipy + 1) * nxb); - dst_prevline = dst + nxb; - for (int gapline = 0; gapline < nxb; ++gapline) { - temp = (*((uint8_t*)dst_prevline)); - g1 = ((temp >> 4) / 2); - g2 = ((temp & 0xF) / 2); - temp = (g1 << 4) + g2; - (*((uint8_t*)dst_prevline)) = temp; - (*((uint8_t*)dst)) = temp; - ++dst; - ++dst_prevline; - } - dst += ((b1chipy + 1) * nxb); - } + dst += nxb; + } + } - dst += nxb; - } - } - - return gapdatabytes; + return gapdatabytes; } - int multiSlsDetector::enableWriteToFile(int enable, int detPos) { - // single - if (detPos >= 0) { - return detectors[detPos]->enableWriteToFile(enable); - } + // single + if (detPos >= 0) { + return detectors[detPos]->enableWriteToFile(enable); + } - // multi - auto r = parallelCall(&slsDetector::enableWriteToFile, enable); - return sls::minusOneIfDifferent(r); + // multi + auto r = parallelCall(&slsDetector::enableWriteToFile, enable); + return sls::minusOneIfDifferent(r); } int multiSlsDetector::overwriteFile(int enable, int detPos) { - // single - if (detPos >= 0) { - return detectors[detPos]->overwriteFile(enable); - } + // single + if (detPos >= 0) { + return detectors[detPos]->overwriteFile(enable); + } - // multi - auto r = parallelCall(&slsDetector::overwriteFile, enable); - return sls::minusOneIfDifferent(r); + // multi + auto r = parallelCall(&slsDetector::overwriteFile, enable); + return sls::minusOneIfDifferent(r); } - int multiSlsDetector::setReceiverStreamingFrequency(int freq, int detPos) { - // single - if (detPos >= 0) { - return detectors[detPos]->setReceiverStreamingFrequency(freq); - } + // single + if (detPos >= 0) { + return detectors[detPos]->setReceiverStreamingFrequency(freq); + } - // multi - auto r = parallelCall(&slsDetector::setReceiverStreamingFrequency, freq); - return sls::minusOneIfDifferent(r); + // multi + auto r = parallelCall(&slsDetector::setReceiverStreamingFrequency, freq); + return sls::minusOneIfDifferent(r); } - int multiSlsDetector::setReceiverStreamingTimer(int time_in_ms, int detPos) { - // single - if (detPos >= 0) { - return detectors[detPos]->setReceiverStreamingTimer(time_in_ms); - } + // single + if (detPos >= 0) { + return detectors[detPos]->setReceiverStreamingTimer(time_in_ms); + } - // multi - auto r = parallelCall(&slsDetector::setReceiverStreamingTimer, time_in_ms); - return sls::minusOneIfDifferent(r); + // multi + auto r = parallelCall(&slsDetector::setReceiverStreamingTimer, time_in_ms); + return sls::minusOneIfDifferent(r); } - int multiSlsDetector::enableDataStreamingToClient(int enable) { - if (enable >= 0) { - //destroy data threads - if (!enable) - createReceivingDataSockets(true); - //create data threads - else { - if (createReceivingDataSockets() == FAIL) { - FILE_LOG(logERROR) << "Could not create data threads in client."; - detectors[0]->setErrorMask((detectors[0]->getErrorMask()) | - (DATA_STREAMING)); - //only for the first det as theres no general one - setErrorMask(getErrorMask() | (1 << 0)); - } - } - } - return client_downstream; + if (enable >= 0) { + // destroy data threads + if (!enable) + createReceivingDataSockets(true); + // create data threads + else { + if (createReceivingDataSockets() == FAIL) { + FILE_LOG(logERROR) + << "Could not create data threads in client."; + detectors[0]->setErrorMask((detectors[0]->getErrorMask()) | + (DATA_STREAMING)); + // only for the first det as theres no general one + setErrorMask(getErrorMask() | (1 << 0)); + } + } + } + return client_downstream; } - int multiSlsDetector::enableDataStreamingFromReceiver(int enable, int detPos) { - // single - if (detPos >= 0) { - return detectors[detPos]->enableDataStreamingFromReceiver(enable); - } + // single + if (detPos >= 0) { + return detectors[detPos]->enableDataStreamingFromReceiver(enable); + } - // multi - auto r = parallelCall(&slsDetector::enableDataStreamingFromReceiver, enable); - return sls::minusOneIfDifferent(r); + // multi + auto r = + parallelCall(&slsDetector::enableDataStreamingFromReceiver, enable); + return sls::minusOneIfDifferent(r); } - int multiSlsDetector::enableTenGigabitEthernet(int i, int detPos) { - // single - if (detPos >= 0) { - return detectors[detPos]->enableTenGigabitEthernet(i); - } + // single + if (detPos >= 0) { + return detectors[detPos]->enableTenGigabitEthernet(i); + } - // multi - auto r = parallelCall(&slsDetector::enableTenGigabitEthernet, i); - return sls::minusOneIfDifferent(r); + // multi + auto r = parallelCall(&slsDetector::enableTenGigabitEthernet, i); + return sls::minusOneIfDifferent(r); } - int multiSlsDetector::setReceiverFifoDepth(int i, int detPos) { - // single - if (detPos >= 0) { - return detectors[detPos]->setReceiverFifoDepth(i); - } + // single + if (detPos >= 0) { + return detectors[detPos]->setReceiverFifoDepth(i); + } - // multi - auto r = parallelCall(&slsDetector::setReceiverFifoDepth, i); - return sls::minusOneIfDifferent(r); + // multi + auto r = parallelCall(&slsDetector::setReceiverFifoDepth, i); + return sls::minusOneIfDifferent(r); } - int multiSlsDetector::setReceiverSilentMode(int i, int detPos) { - // single - if (detPos >= 0) { - return detectors[detPos]->setReceiverSilentMode(i); - } + // single + if (detPos >= 0) { + return detectors[detPos]->setReceiverSilentMode(i); + } - // multi - auto r = parallelCall(&slsDetector::setReceiverSilentMode, i); - return sls::minusOneIfDifferent(r); + // multi + auto r = parallelCall(&slsDetector::setReceiverSilentMode, i); + return sls::minusOneIfDifferent(r); } - int multiSlsDetector::setCTBPattern(std::string fname, int detPos) { - // single - if (detPos >= 0) { - return detectors[detPos]->setCTBPattern(fname); - } + // single + if (detPos >= 0) { + return detectors[detPos]->setCTBPattern(fname); + } - // multi - int addr = 0; + // multi + int addr = 0; - FILE* fd = fopen(fname.c_str(), "r"); - if (fd <= 0) { - FILE_LOG(logERROR) << "Could not open file"; - setErrorMask(getErrorMask() | MULTI_OTHER_ERROR); - return -1; - } + FILE *fd = fopen(fname.c_str(), "r"); + if (fd <= 0) { + FILE_LOG(logERROR) << "Could not open file"; + setErrorMask(getErrorMask() | MULTI_OTHER_ERROR); + return -1; + } + uint64_t word; + while (fread(&word, sizeof(word), 1, fd)) { + serialCall(&slsDetector::setCTBWord, addr, word); + ++addr; + } - uint64_t word; - while (fread(&word, sizeof(word), 1, fd)) { - serialCall(&slsDetector::setCTBWord, addr, word); - ++addr; - } - - fclose(fd); - return addr; + fclose(fd); + return addr; } - uint64_t multiSlsDetector::setCTBWord(int addr, uint64_t word, int detPos) { - // single - if (detPos >= 0) { - return detectors[detPos]->setCTBWord(addr, word); - } + // single + if (detPos >= 0) { + return detectors[detPos]->setCTBWord(addr, word); + } - // multi - auto r = parallelCall(&slsDetector::setCTBWord, addr, word); - return sls::minusOneIfDifferent(r); + // multi + auto r = parallelCall(&slsDetector::setCTBWord, addr, word); + return sls::minusOneIfDifferent(r); } +int multiSlsDetector::setCTBPatLoops(int level, int &start, int &stop, int &n, + int detPos) { + // single + if (detPos >= 0) { + return detectors[detPos]->setCTBPatLoops(level, start, stop, n); + } -int multiSlsDetector::setCTBPatLoops(int level, int& start, int& stop, int& n, int detPos) { - // single - if (detPos >= 0) { - return detectors[detPos]->setCTBPatLoops(level, start, stop, n); - } - - // multi - std::vector r; - for (auto& d : detectors) { - r.push_back(d->setCTBPatLoops(level, start, stop, n)); - } - return sls::allEqualTo(r, static_cast(OK)) ? OK : FAIL; + // multi + std::vector r; + for (auto &d : detectors) { + r.push_back(d->setCTBPatLoops(level, start, stop, n)); + } + return sls::allEqualTo(r, static_cast(OK)) ? OK : FAIL; } - int multiSlsDetector::setCTBPatWaitAddr(int level, int addr, int detPos) { - // single - if (detPos >= 0) { - return detectors[detPos]->setCTBPatWaitAddr(level, addr); - } + // single + if (detPos >= 0) { + return detectors[detPos]->setCTBPatWaitAddr(level, addr); + } - // multi - auto r = parallelCall(&slsDetector::setCTBPatWaitAddr, level, addr); - return sls::minusOneIfDifferent(r); + // multi + auto r = parallelCall(&slsDetector::setCTBPatWaitAddr, level, addr); + return sls::minusOneIfDifferent(r); } - int multiSlsDetector::setCTBPatWaitTime(int level, uint64_t t, int detPos) { - // single - if (detPos >= 0) { - return detectors[detPos]->setCTBPatWaitTime(level, t); - } + // single + if (detPos >= 0) { + return detectors[detPos]->setCTBPatWaitTime(level, t); + } - // multi - auto r = parallelCall(&slsDetector::setCTBPatWaitTime, level, t); - return sls::minusOneIfDifferent(r); + // multi + auto r = parallelCall(&slsDetector::setCTBPatWaitTime, level, t); + return sls::minusOneIfDifferent(r); } +int multiSlsDetector::retrieveDetectorSetup(const std::string &fname1, + int level) { -int multiSlsDetector::retrieveDetectorSetup(const std::string& fname1, int level){ + int skip = 0; + std::string fname; + std::string str; + std::ifstream infile; + int iargval; + int interrupt = 0; + char *args[10]; - int skip=0; - std::string fname; - std::string str; - std::ifstream infile; - int iargval; - int interrupt=0; - char *args[10]; + char myargs[10][1000]; + ; - char myargs[10][1000]; - ; + std::string sargname, sargval; + int iline = 0; - std::string sargname, sargval; - int iline=0; - - if (level==2) { + if (level == 2) { #ifdef VERBOSE - std::cout << "config file read" << std::endl; + std::cout << "config file read" << std::endl; #endif - fname=fname1+std::string(".det"); - } else - fname=fname1; + fname = fname1 + std::string(".det"); + } else + fname = fname1; - infile.open(fname.c_str(), std::ios_base::in); - if (infile.is_open()) { - auto cmd = slsDetectorCommand(this); - while (infile.good() and interrupt==0) { - sargname="none"; - sargval="0"; - getline(infile,str); - iline++; + infile.open(fname.c_str(), std::ios_base::in); + if (infile.is_open()) { + auto cmd = slsDetectorCommand(this); + while (infile.good() and interrupt == 0) { + sargname = "none"; + sargval = "0"; + getline(infile, str); + iline++; #ifdef VERBOSE - std::cout<< str << std::endl; + std::cout << str << std::endl; #endif - if (str.find('#')!=std::string::npos) { + if (str.find('#') != std::string::npos) { #ifdef VERBOSE - std::cout<< "Line is a comment " << std::endl; - std::cout<< str << std::endl; + std::cout << "Line is a comment " << std::endl; + std::cout << str << std::endl; #endif - continue; - } else { - std::istringstream ssstr(str); - iargval=0; - while (ssstr.good()) { - ssstr >> sargname; - // if (ssstr.good()) { - strcpy(myargs[iargval],sargname.c_str()); - args[iargval]=myargs[iargval]; + continue; + } else { + std::istringstream ssstr(str); + iargval = 0; + while (ssstr.good()) { + ssstr >> sargname; + // if (ssstr.good()) { + strcpy(myargs[iargval], sargname.c_str()); + args[iargval] = myargs[iargval]; #ifdef VERBOSE - std::cout<< args[iargval] << std::endl; + std::cout << args[iargval] << std::endl; #endif - iargval++; - // } - skip=0; - } + iargval++; + // } + skip = 0; + } - if (level!=2) { - if (std::string(args[0])==std::string("trimbits")) - skip=1; - } - if (skip==0) - cmd.executeLine(iargval,args,PUT_ACTION); - } - iline++; - } - infile.close(); + if (level != 2) { + if (std::string(args[0]) == std::string("trimbits")) + skip = 1; + } + if (skip == 0) + cmd.executeLine(iargval, args, PUT_ACTION); + } + iline++; + } + infile.close(); - } else { - std::cout<< "Error opening " << fname << " for reading" << std::endl; - return FAIL; - } + } else { + std::cout << "Error opening " << fname << " for reading" << std::endl; + return FAIL; + } #ifdef VERBOSE - std::cout<< "Read " << iline << " lines" << std::endl; + std::cout << "Read " << iline << " lines" << std::endl; #endif - if (getErrorMask()) - return FAIL; + if (getErrorMask()) + return FAIL; - return OK; + return OK; } +int multiSlsDetector::dumpDetectorSetup(const std::string &fname, int level) { + detectorType type = getDetectorsType(); + std::string names[100]; + int nvar = 0; -int multiSlsDetector::dumpDetectorSetup(const std::string& fname, int level){ - detectorType type = getDetectorsType(); - std::string names[100]; - int nvar=0; + // common config + names[nvar++] = "fname"; + names[nvar++] = "index"; + names[nvar++] = "enablefwrite"; + names[nvar++] = "overwrite"; + names[nvar++] = "dr"; + names[nvar++] = "settings"; + names[nvar++] = "exptime"; + names[nvar++] = "period"; + names[nvar++] = "frames"; + names[nvar++] = "cycles"; + names[nvar++] = "measurements"; + names[nvar++] = "timing"; - // common config - names[nvar++]="fname"; - names[nvar++]="index"; - names[nvar++]="enablefwrite"; - names[nvar++]="overwrite"; - names[nvar++]="dr"; - names[nvar++]="settings"; - names[nvar++]="exptime"; - names[nvar++]="period"; - names[nvar++]="frames"; - names[nvar++]="cycles"; - names[nvar++]="measurements"; - names[nvar++]="timing"; + switch (type) { + case EIGER: + names[nvar++] = "flags"; + names[nvar++] = "clkdivider"; + names[nvar++] = "threshold"; + names[nvar++] = "ratecorr"; + names[nvar++] = "trimbits"; + break; + case GOTTHARD: + names[nvar++] = "delay"; + break; + case JUNGFRAU: + names[nvar++] = "delay"; + names[nvar++] = "clkdivider"; + break; + case JUNGFRAUCTB: + names[nvar++] = "dac:0"; + names[nvar++] = "dac:1"; + names[nvar++] = "dac:2"; + names[nvar++] = "dac:3"; + names[nvar++] = "dac:4"; + names[nvar++] = "dac:5"; + names[nvar++] = "dac:6"; + names[nvar++] = "dac:7"; + names[nvar++] = "dac:8"; + names[nvar++] = "dac:9"; + names[nvar++] = "dac:10"; + names[nvar++] = "dac:11"; + names[nvar++] = "dac:12"; + names[nvar++] = "dac:13"; + names[nvar++] = "dac:14"; + names[nvar++] = "dac:15"; + names[nvar++] = "adcvpp"; - switch (type) { - case EIGER: - names[nvar++]="flags"; - names[nvar++]="clkdivider"; - names[nvar++]="threshold"; - names[nvar++]="ratecorr"; - names[nvar++]="trimbits"; - break; - case GOTTHARD: - names[nvar++]="delay"; - break; - case JUNGFRAU: - names[nvar++]="delay"; - names[nvar++]="clkdivider"; - break; - case JUNGFRAUCTB: - names[nvar++]="dac:0"; - names[nvar++]="dac:1"; - names[nvar++]="dac:2"; - names[nvar++]="dac:3"; - names[nvar++]="dac:4"; - names[nvar++]="dac:5"; - names[nvar++]="dac:6"; - names[nvar++]="dac:7"; - names[nvar++]="dac:8"; - names[nvar++]="dac:9"; - names[nvar++]="dac:10"; - names[nvar++]="dac:11"; - names[nvar++]="dac:12"; - names[nvar++]="dac:13"; - names[nvar++]="dac:14"; - names[nvar++]="dac:15"; - names[nvar++]="adcvpp"; + names[nvar++] = "adcclk"; + names[nvar++] = "clkdivider"; + names[nvar++] = "adcphase"; + names[nvar++] = "adcpipeline"; + names[nvar++] = "adcinvert"; // + names[nvar++] = "adcdisable"; + names[nvar++] = "patioctrl"; + names[nvar++] = "patclkctrl"; + names[nvar++] = "patlimits"; + names[nvar++] = "patloop0"; + names[nvar++] = "patnloop0"; + names[nvar++] = "patwait0"; + names[nvar++] = "patwaittime0"; + names[nvar++] = "patloop1"; + names[nvar++] = "patnloop1"; + names[nvar++] = "patwait1"; + names[nvar++] = "patwaittime1"; + names[nvar++] = "patloop2"; + names[nvar++] = "patnloop2"; + names[nvar++] = "patwait2"; + names[nvar++] = "patwaittime2"; + break; + default: + break; + } + int iv = 0; + std::string fname1; + std::ofstream outfile; + char *args[4]; + for (int ia = 0; ia < 4; ia++) { + args[ia] = new char[1000]; + } + if (level == 2) { + fname1 = fname + std::string(".config"); + writeConfigurationFile(fname1); + fname1 = fname + std::string(".det"); + } else + fname1 = fname; - names[nvar++]="adcclk"; - names[nvar++]="clkdivider"; - names[nvar++]="adcphase"; - names[nvar++]="adcpipeline"; - names[nvar++]="adcinvert"; // - names[nvar++]="adcdisable"; - names[nvar++]="patioctrl"; - names[nvar++]="patclkctrl"; - names[nvar++]="patlimits"; - names[nvar++]="patloop0"; - names[nvar++]="patnloop0"; - names[nvar++]="patwait0"; - names[nvar++]="patwaittime0"; - names[nvar++]="patloop1"; - names[nvar++]="patnloop1"; - names[nvar++]="patwait1"; - names[nvar++]="patwaittime1"; - names[nvar++]="patloop2"; - names[nvar++]="patnloop2"; - names[nvar++]="patwait2"; - names[nvar++]="patwaittime2"; - break; - default: - break; - } - - - int iv=0; - std::string fname1; - std::ofstream outfile; - char *args[4]; - for (int ia=0; ia<4; ia++) { - args[ia]=new char[1000]; - } - - - if (level==2) { - fname1=fname+std::string(".config"); - writeConfigurationFile(fname1); - fname1=fname+std::string(".det"); - } else - fname1=fname; - - - - outfile.open(fname1.c_str(),std::ios_base::out); - if (outfile.is_open()) { - auto cmd = slsDetectorCommand(this); - for (iv=0; ivtimerValue[FRAME_NUMBER]) - nf=thisMultiDetector->timerValue[FRAME_NUMBER]; + if (thisMultiDetector->timerValue[FRAME_NUMBER]) + nf = thisMultiDetector->timerValue[FRAME_NUMBER]; - if (thisMultiDetector->timerValue[CYCLES_NUMBER]>0) - nc=thisMultiDetector->timerValue[CYCLES_NUMBER]; + if (thisMultiDetector->timerValue[CYCLES_NUMBER] > 0) + nc = thisMultiDetector->timerValue[CYCLES_NUMBER]; - if (thisMultiDetector->timerValue[STORAGE_CELL_NUMBER]>0) - ns=thisMultiDetector->timerValue[STORAGE_CELL_NUMBER]+1; + if (thisMultiDetector->timerValue[STORAGE_CELL_NUMBER] > 0) + ns = thisMultiDetector->timerValue[STORAGE_CELL_NUMBER] + 1; - if (thisMultiDetector->timerValue[MEASUREMENTS_NUMBER]>0) - nm=thisMultiDetector->timerValue[MEASUREMENTS_NUMBER]; + if (thisMultiDetector->timerValue[MEASUREMENTS_NUMBER] > 0) + nm = thisMultiDetector->timerValue[MEASUREMENTS_NUMBER]; - totalProgress=nm*nf*nc*ns; + totalProgress = nm * nf * nc * ns; #ifdef VERBOSE - std::cout << "nm " << nm << std::endl; - std::cout << "nf " << nf << std::endl; - std::cout << "nc " << nc << std::endl; - std::cout << "ns " << ns << std::endl; - std::cout << "Set total progress " << totalProgress << std::endl; + std::cout << "nm " << nm << std::endl; + std::cout << "nf " << nf << std::endl; + std::cout << "nc " << nc << std::endl; + std::cout << "ns " << ns << std::endl; + std::cout << "Set total progress " << totalProgress << std::endl; #endif - return totalProgress; + return totalProgress; } - double multiSlsDetector::getCurrentProgress() { - std::lock_guard lock(mp); - return 100.*((double)progressIndex)/((double)totalProgress); + std::lock_guard lock(mp); + return 100. * ((double)progressIndex) / ((double)totalProgress); } - -void multiSlsDetector::incrementProgress() { - std::lock_guard lock(mp); - progressIndex++; - std::cout << std::fixed << std::setprecision(2) << std::setw (6) - << 100.*((double)progressIndex)/((double)totalProgress) << " \%"; - std::cout << '\r' << std::flush; +void multiSlsDetector::incrementProgress() { + std::lock_guard lock(mp); + progressIndex++; + std::cout << std::fixed << std::setprecision(2) << std::setw(6) + << 100. * ((double)progressIndex) / ((double)totalProgress) + << " \%"; + std::cout << '\r' << std::flush; } - -void multiSlsDetector::setCurrentProgress(int i){ - std::lock_guard lock(mp); - progressIndex=i; - std::cout << std::fixed << std::setprecision(2) << std::setw (6) - << 100.*((double)progressIndex)/((double)totalProgress) << " \%"; - std::cout << '\r' << std::flush; +void multiSlsDetector::setCurrentProgress(int i) { + std::lock_guard lock(mp); + progressIndex = i; + std::cout << std::fixed << std::setprecision(2) << std::setw(6) + << 100. * ((double)progressIndex) / ((double)totalProgress) + << " \%"; + std::cout << '\r' << std::flush; } - -int multiSlsDetector::acquire(){ - //ensure acquire isnt started multiple times by same client - if (isAcquireReady() == FAIL) - return FAIL; +int multiSlsDetector::acquire() { + // ensure acquire isnt started multiple times by same client + if (isAcquireReady() == FAIL) + return FAIL; #ifdef VERBOSE - struct timespec begin,end; - clock_gettime(CLOCK_REALTIME, &begin); + struct timespec begin, end; + clock_gettime(CLOCK_REALTIME, &begin); #endif - //in the real time acquisition loop, processing thread will wait for a post each time - sem_init(&sem_newRTAcquisition,1,0); - //in the real time acquistion loop, main thread will wait for processing thread to be done each time (which in turn waits for receiver/ext process) - sem_init(&sem_endRTAcquisition,1,0); + // in the real time acquisition loop, processing thread will wait for a post + // each time + sem_init(&sem_newRTAcquisition, 1, 0); + // in the real time acquistion loop, main thread will wait for processing + // thread to be done each time (which in turn waits for receiver/ext + // process) + sem_init(&sem_endRTAcquisition, 1, 0); - bool receiver = (setReceiverOnline()==ONLINE_FLAG); - progressIndex=0; - thisMultiDetector->stoppedFlag=0; - setJoinThreadFlag(false); + bool receiver = (setReceiverOnline() == ONLINE_FLAG); + progressIndex = 0; + thisMultiDetector->stoppedFlag = 0; + setJoinThreadFlag(false); - int nm=thisMultiDetector->timerValue[MEASUREMENTS_NUMBER]; - if (nm<1) - nm=1; + int nm = thisMultiDetector->timerValue[MEASUREMENTS_NUMBER]; + if (nm < 1) + nm = 1; - // verify receiver is idle - if(receiver){ - std::lock_guard lock(mg); - if(getReceiverStatus()!=IDLE) - if(stopReceiver() == FAIL) - thisMultiDetector->stoppedFlag=1; - } + // verify receiver is idle + if (receiver) { + std::lock_guard lock(mg); + if (getReceiverStatus() != IDLE) + if (stopReceiver() == FAIL) + thisMultiDetector->stoppedFlag = 1; + } - startProcessingThread(); + startProcessingThread(); - //resets frames caught in receiver - if(receiver){ - std::lock_guard lock(mg); - if (resetFramesCaught() == FAIL) - thisMultiDetector->stoppedFlag=1; - } + // resets frames caught in receiver + if (receiver) { + std::lock_guard lock(mg); + if (resetFramesCaught() == FAIL) + thisMultiDetector->stoppedFlag = 1; + } - // loop through measurements - for(int im=0;imstoppedFlag) - break; + // loop through measurements + for (int im = 0; im < nm; ++im) { + if (thisMultiDetector->stoppedFlag) + break; - // start receiver - if(receiver){ - std::lock_guard lock(mg); - if(startReceiver() == FAIL) { - std::cout << "Start receiver failed " << std::endl; - stopReceiver(); - thisMultiDetector->stoppedFlag=1; - break; - } - //let processing thread listen to these packets - sem_post(&sem_newRTAcquisition); - } + // start receiver + if (receiver) { + std::lock_guard lock(mg); + if (startReceiver() == FAIL) { + std::cout << "Start receiver failed " << std::endl; + stopReceiver(); + thisMultiDetector->stoppedFlag = 1; + break; + } + // let processing thread listen to these packets + sem_post(&sem_newRTAcquisition); + } - startAndReadAll(); + startAndReadAll(); - // stop receiver - std::lock_guard lock(mg); - if(receiver){ - if (stopReceiver() == FAIL) { - thisMultiDetector->stoppedFlag = 1; - } else { - if (dataReady) - sem_wait(&sem_endRTAcquisition); // waits for receiver's external process to be done sending data to gui - } - } - int findex = 0; - findex = incrementFileIndex(); + // stop receiver + std::lock_guard lock(mg); + if (receiver) { + if (stopReceiver() == FAIL) { + thisMultiDetector->stoppedFlag = 1; + } else { + if (dataReady) + sem_wait(&sem_endRTAcquisition); // waits for receiver's + // external process to be + // done sending data to gui + } + } + int findex = 0; + findex = incrementFileIndex(); - if (measurement_finished){ - measurement_finished(im,findex,measFinished_p); - } - if (thisMultiDetector->stoppedFlag) { - break; - } + if (measurement_finished) { + measurement_finished(im, findex, measFinished_p); + } + if (thisMultiDetector->stoppedFlag) { + break; + } - }//end measurements loop im + } // end measurements loop im - // waiting for the data processing thread to finish! - setJoinThreadFlag(true); - sem_post(&sem_newRTAcquisition); - dataProcessingThread.join(); + // waiting for the data processing thread to finish! + setJoinThreadFlag(true); + sem_post(&sem_newRTAcquisition); + dataProcessingThread.join(); + if (progress_call) + progress_call(getCurrentProgress(), pProgressCallArg); - if(progress_call) - progress_call(getCurrentProgress(),pProgressCallArg); + if (acquisition_finished) + acquisition_finished(getCurrentProgress(), getRunStatus(), + acqFinished_p); - if (acquisition_finished) - acquisition_finished(getCurrentProgress(),getRunStatus(),acqFinished_p); - - sem_destroy(&sem_newRTAcquisition); - sem_destroy(&sem_endRTAcquisition); + sem_destroy(&sem_newRTAcquisition); + sem_destroy(&sem_endRTAcquisition); #ifdef VERBOSE - clock_gettime(CLOCK_REALTIME, &end); - std::cout << "Elapsed time for acquisition:" << (( end.tv_sec - begin.tv_sec ) + ( end.tv_nsec - begin.tv_nsec ) / 1000000000.0) << " seconds" << std::endl; + clock_gettime(CLOCK_REALTIME, &end); + std::cout << "Elapsed time for acquisition:" + << ((end.tv_sec - begin.tv_sec) + + (end.tv_nsec - begin.tv_nsec) / 1000000000.0) + << " seconds" << std::endl; #endif - setAcquiringFlag(false); - - return OK; - + setAcquiringFlag(false); + return OK; } - - void multiSlsDetector::startProcessingThread() { - setTotalProgress(); - dataProcessingThread = std::thread(&multiSlsDetector::processData, this); + setTotalProgress(); + dataProcessingThread = std::thread(&multiSlsDetector::processData, this); } - // void* multiSlsDetector::startProcessData(void *n) { // ((multiSlsDetector*)n)->processData(); // return n; // } - void multiSlsDetector::processData() { - if(setReceiverOnline()==OFFLINE_FLAG){ - return; - } - else{ - if(dataReady) { - readFrameFromReceiver(); - } - //only update progress - else{ - int caught = -1; - while(true){ - // to exit acquire by typing q - if (kbhit()!=0){ - if (fgetc(stdin) == 'q') { - std::cout<<"Caught the command to stop acquisition"< lock(mg); - caught = getFramesCaughtByReceiver(0); - } - //updating progress - if(caught!= -1){ - setCurrentProgress(caught); - } - // exiting loop - if (getJoinThreadFlag()){ - break; - } - usleep(100 * 1000); //20ms need this else connecting error to receiver (too fast) - } - } - } - return; + if (setReceiverOnline() == OFFLINE_FLAG) { + return; + } else { + if (dataReady) { + readFrameFromReceiver(); + } + // only update progress + else { + int caught = -1; + while (true) { + // to exit acquire by typing q + if (kbhit() != 0) { + if (fgetc(stdin) == 'q') { + std::cout << "Caught the command to stop acquisition" + << std::endl; + stopAcquisition(); + } + } + // get progress + if (setReceiverOnline() == ONLINE_FLAG) { + std::lock_guard lock(mg); + caught = getFramesCaughtByReceiver(0); + } + // updating progress + if (caught != -1) { + setCurrentProgress(caught); + } + // exiting loop + if (getJoinThreadFlag()) { + break; + } + usleep(100 * 1000); // 20ms need this else connecting error to + // receiver (too fast) + } + } + } + return; } - bool multiSlsDetector::getJoinThreadFlag() const { - std::lock_guard lock(mp); - return jointhread; + std::lock_guard lock(mp); + return jointhread; } -void multiSlsDetector::setJoinThreadFlag( bool value) { - std::lock_guard lock(mp); - jointhread=value; +void multiSlsDetector::setJoinThreadFlag(bool value) { + std::lock_guard lock(mp); + jointhread = value; } int multiSlsDetector::kbhit() { - struct timeval tv; - fd_set fds; - tv.tv_sec = 0; - tv.tv_usec = 0; - FD_ZERO(&fds); - FD_SET(STDIN_FILENO, &fds); //STDIN_FILENO is 0 - select(STDIN_FILENO+1, &fds, NULL, NULL, &tv); - return FD_ISSET(STDIN_FILENO, &fds); + struct timeval tv; + fd_set fds; + tv.tv_sec = 0; + tv.tv_usec = 0; + FD_ZERO(&fds); + FD_SET(STDIN_FILENO, &fds); // STDIN_FILENO is 0 + select(STDIN_FILENO + 1, &fds, NULL, NULL, &tv); + return FD_ISSET(STDIN_FILENO, &fds); } bool multiSlsDetector::isDetectorIndexOutOfBounds(int detPos) { - // position exceeds multi list size - if (detPos >= (int)detectors.size()) { - FILE_LOG(logERROR) << "Position " << detPos << " is out of bounds with " - "a detector list of " << detectors.size(); - setErrorMask(getErrorMask() | MULTI_POS_EXCEEDS_LIST); - return true; - } - return false; + // position exceeds multi list size + if (detPos >= (int)detectors.size()) { + FILE_LOG(logERROR) << "Position " << detPos + << " is out of bounds with " + "a detector list of " + << detectors.size(); + setErrorMask(getErrorMask() | MULTI_POS_EXCEEDS_LIST); + return true; + } + return false; } \ No newline at end of file diff --git a/slsDetectorSoftware/multiSlsDetector/multiSlsDetector.h b/slsDetectorSoftware/multiSlsDetector/multiSlsDetector.h index 4054390f7..b382be525 100644 --- a/slsDetectorSoftware/multiSlsDetector/multiSlsDetector.h +++ b/slsDetectorSoftware/multiSlsDetector/multiSlsDetector.h @@ -2,13 +2,14 @@ #define MULTI_SLS_DETECTOR_H /** - @libdoc The multiSlsDetector class is used to operate several slsDetectors in parallel. + @libdoc The multiSlsDetector class is used to operate several slsDetectors in + parallel. * @short This is the base class for multi detector system functionalities * @author Anna Bergamaschi */ -#include "sls_detector_defs.h" #include "error_defs.h" +#include "sls_detector_defs.h" class slsDetector; class SharedMemory; @@ -16,1743 +17,1785 @@ class ZmqSocket; class detectorData; #include -#include -#include -#include #include #include +#include +#include +#include +#define MULTI_SHMVERSION 0x181002 +#define SHORT_STRING_LENGTH 50 +#define DATE_LENGTH 30 -#define MULTI_SHMVERSION 0x181002 -#define SHORT_STRING_LENGTH 50 -#define DATE_LENGTH 30 +class multiSlsDetector : public virtual slsDetectorDefs, + public virtual errorDefs { -class multiSlsDetector : public virtual slsDetectorDefs, public virtual errorDefs { + private: + /** + * @short structure allocated in shared memory to store detector settings + * for IPC and cache + */ + typedef struct sharedMultiSlsDetector { -private: + /* FIXED PATTERN FOR STATIC FUNCTIONS. DO NOT CHANGE, ONLY APPEND + * ------*/ - /** - * @short structure allocated in shared memory to store detector settings for IPC and cache - */ - typedef struct sharedMultiSlsDetector { + /** shared memory version */ + int shmversion; + /** last process id accessing the shared memory */ + pid_t lastPID; - /* FIXED PATTERN FOR STATIC FUNCTIONS. DO NOT CHANGE, ONLY APPEND ------*/ + /** last user name accessing the shared memory */ + char lastUser[SHORT_STRING_LENGTH]; - /** shared memory version */ - int shmversion; + /** last time stamp when accessing the shared memory */ + char lastDate[SHORT_STRING_LENGTH]; - /** last process id accessing the shared memory */ - pid_t lastPID; + /** number of sls detectors in shared memory */ + int numberOfDetectors; - /** last user name accessing the shared memory */ - char lastUser[SHORT_STRING_LENGTH]; + /** END OF FIXED PATTERN + * -----------------------------------------------*/ - /** last time stamp when accessing the shared memory */ - char lastDate[SHORT_STRING_LENGTH]; + /** Number of detectors operated at once */ + int numberOfDetector[2]; - /** number of sls detectors in shared memory */ - int numberOfDetectors; + /** online flag - is set if the detector is connected, unset if socket + * connection is not possible */ + int onlineFlag; - /** END OF FIXED PATTERN -----------------------------------------------*/ + /** 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; + /** size of the data that are transfered from all detectors */ + int dataBytes; + /** data bytes including gap pixels transferred from all detectors */ + int dataBytesInclGapPixels; + /** total number of channels for all detectors */ + int numberOfChannels; - /** Number of detectors operated at once */ - int numberOfDetector[2]; + /** total number of channels for all detectors in one dimension*/ + int numberOfChannel[2]; - /** online flag - is set if the detector is connected, unset if socket - * connection is not possible */ - int onlineFlag; + /** total number of channels including gap pixels in one dimension */ + int numberOfChannelInclGapPixels[2]; - /** 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; + /** total number of channels for all detectors */ + int maxNumberOfChannels; - /** size of the data that are transfered from all detectors */ - int dataBytes; + /** max number of channels for all detectors in one dimension*/ + int maxNumberOfChannel[2]; - /** data bytes including gap pixels transferred from all detectors */ - int dataBytesInclGapPixels; + /** max number of channels including gap pixels for all detectors in + * one dimension*/ + int maxNumberOfChannelInclGapPixels[2]; - /** total number of channels for all detectors */ - int numberOfChannels; + /** max number of channels allowed for the complete set of detectors in + * one dimension */ + int maxNumberOfChannelsPerDetector[2]; - /** total number of channels for all detectors in one dimension*/ - int numberOfChannel[2]; + /** timer values */ + int64_t timerValue[MAX_TIMERS]; - /** total number of channels including gap pixels in one dimension */ - int numberOfChannelInclGapPixels[2]; + /** flag for acquiring */ + bool acquiringFlag; - /** total number of channels for all detectors */ - int maxNumberOfChannels; + /** receiver online flag - is set if the receiver is connected, + * unset if socket connection is not possible */ + int receiverOnlineFlag; - /** max number of channels for all detectors in one dimension*/ - int maxNumberOfChannel[2]; + /** data streaming (up stream) enable in receiver */ + bool receiver_upstream; - /** max number of channels including gap pixels for all detectors in - * one dimension*/ - int maxNumberOfChannelInclGapPixels[2]; + } sharedMultiSlsDetector; - /** max number of channels allowed for the complete set of detectors in - * one dimension */ - int maxNumberOfChannelsPerDetector[2]; + public: + /** + * Constructor + * @param id multi detector id + * @param verify true to verify if shared memory version matches existing + * one + * @param update true to update last user pid, date etc + */ + multiSlsDetector(int id = 0, bool verify = true, bool update = true); - /** timer values */ - int64_t timerValue[MAX_TIMERS]; + /** + * Destructor + */ + virtual ~multiSlsDetector(); + /** + * Creates/open shared memory, initializes detector structure and members + * Called by constructor/ set hostname / read config file + * @param verify true to verify if shared memory version matches existing + * one + * @param update true to update last user pid, date etc + */ + void setupMultiDetector(bool verify = true, bool update = true); - /** flag for acquiring */ - bool acquiringFlag; - - /** receiver online flag - is set if the receiver is connected, - * unset if socket connection is not possible */ - int receiverOnlineFlag; - - /** data streaming (up stream) enable in receiver */ - bool receiver_upstream; - - } sharedMultiSlsDetector; - - - - -public: - - - /** - * Constructor - * @param id multi detector id - * @param verify true to verify if shared memory version matches existing one - * @param update true to update last user pid, date etc - */ - multiSlsDetector(int id = 0, bool verify = true, bool update = true); - - /** - * Destructor - */ - virtual ~multiSlsDetector(); - - /** - * Creates/open shared memory, initializes detector structure and members - * Called by constructor/ set hostname / read config file - * @param verify true to verify if shared memory version matches existing one - * @param update true to update last user pid, date etc - */ - void setupMultiDetector(bool verify = true, bool update = true); - - /** - * Loop through the detectors serially - * and return a vector of results - */ + /** + * Loop through the detectors serially + * and return a vector of results + */ template std::vector serialCall(RT (slsDetector::*somefunc)(CT...), CT... Args); - /** - * Loop through the detectors in parallel threads - * and return a vector of results - */ + /** + * Loop through the detectors in parallel threads + * and return a vector of results + */ template - std::vector parallelCall(RT (slsDetector::*somefunc)(CT...), CT... Args); + std::vector parallelCall(RT (slsDetector::*somefunc)(CT...), + CT... Args); - /** - * If specific position, then provide result with that detector at position pos - * else concatenate the result of all detectors - * @param somefunc function pointer - * @param pos positin of detector in array (-1 is for all) - * @returns result for detector at that position or concatenated string of all detectors - */ - // std::string concatResultOrPos(std::string (slsDetector::*somefunc)(int), int pos); + /** + * If specific position, then provide result with that detector at position + * pos else concatenate the result of all detectors + * @param somefunc function pointer + * @param pos positin of detector in array (-1 is for all) + * @returns result for detector at that position or concatenated string of + * all detectors + */ + // std::string concatResultOrPos(std::string (slsDetector::*somefunc)(int), + // int pos); - /** - * Decodes which detector and the corresponding channel numbers for it - * Mainly useful in a multi detector setROI (Gotthard, Mythen?) - * @param offsetX channel number or total channel offset in x direction - * @param offsetY channel number or total channel offset in y direction - * @param channelX channel number from detector offset in x direction - * @param channelY channel number from detector offset in x direction - * @returns detector id or -1 if channel number out of range - */ - int decodeNChannel(int offsetX, int offsetY, int &channelX, int &channelY); + /** + * Decodes which detector and the corresponding channel numbers for it + * Mainly useful in a multi detector setROI (Gotthard, Mythen?) + * @param offsetX channel number or total channel offset in x direction + * @param offsetY channel number or total channel offset in y direction + * @param channelX channel number from detector offset in x direction + * @param channelY channel number from detector offset in x direction + * @returns detector id or -1 if channel number out of range + */ + int decodeNChannel(int offsetX, int offsetY, int &channelX, int &channelY); - /** - * Checks error mask and returns error message and its severity if it exists - * @param critical is 1 if any of the messages is critical - * @param detPos -1 for all detectors in list or specific detector position - * @returns error message else an empty std::string - */ - std::string getErrorMessage(int &critical, int detPos = -1); + /** + * Checks error mask and returns error message and its severity if it exists + * @param critical is 1 if any of the messages is critical + * @param detPos -1 for all detectors in list or specific detector position + * @returns error message else an empty std::string + */ + std::string getErrorMessage(int &critical, int detPos = -1); - /** - * Clears error mask of both multi and sls - * @param detPos -1 for all detectors in list or specific detector position - * @returns error mask - */ - int64_t clearAllErrorMask(int detPos = -1); + /** + * Clears error mask of both multi and sls + * @param detPos -1 for all detectors in list or specific detector position + * @returns error mask + */ + int64_t clearAllErrorMask(int detPos = -1); - /** - * Set Error Mask from all detectors - * if each had errors in the mask already - */ - void setErrorMaskFromAllDetectors(); + /** + * Set Error Mask from all detectors + * if each had errors in the mask already + */ + void setErrorMaskFromAllDetectors(); - /** - * Set acquiring flag in shared memory - * @param b acquiring flag - */ - void setAcquiringFlag(bool b=false); + /** + * Set acquiring flag in shared memory + * @param b acquiring flag + */ + void setAcquiringFlag(bool b = false); - /** - * Get acquiring flag from shared memory - * @returns acquiring flag - */ - bool getAcquiringFlag() const; + /** + * Get acquiring flag from shared memory + * @returns acquiring flag + */ + bool getAcquiringFlag() const; - /** - * Check if acquiring flag is set, set error if set - * @returns FAIL if not ready, OK if ready - */ - bool isAcquireReady(); + /** + * Check if acquiring flag is set, set error if set + * @returns FAIL if not ready, OK if ready + */ + bool isAcquireReady(); - /** - * Check version compatibility with detector/receiver software - * (if hostname/rx_hostname has been set/ sockets created) - * @param p port type control port or receiver port - * @param detPos -1 for all detectors in list or specific detector position - * @returns FAIL for incompatibility, OK for compatibility - */ - int checkVersionCompatibility(portType t, int detPos = -1); + /** + * Check version compatibility with detector/receiver software + * (if hostname/rx_hostname has been set/ sockets created) + * @param p port type control port or receiver port + * @param detPos -1 for all detectors in list or specific detector position + * @returns FAIL for incompatibility, OK for compatibility + */ + int checkVersionCompatibility(portType t, int detPos = -1); - /** - * Get ID or version numbers - * @param mode version type - * @param detPos -1 for all detectors in list or specific detector position - * @returns Id or version number of that type - */ - int64_t getId(idMode mode, int detPos = -1); + /** + * Get ID or version numbers + * @param mode version type + * @param detPos -1 for all detectors in list or specific detector position + * @returns Id or version number of that type + */ + int64_t getId(idMode mode, int detPos = -1); - /** - * Get sls detector object from position in detectors array - * @param detPos -1 for all detectors in list or specific detector position - * @returns pointer to sls detector object - */ - // slsDetector* getSlsDetector(int detPos = -1); + /** + * Get sls detector object from position in detectors array + * @param detPos -1 for all detectors in list or specific detector position + * @returns pointer to sls detector object + */ + // slsDetector* getSlsDetector(int detPos = -1); - /** - * Accessing the sls detector from the multi list using position - * @param detPos -1 for all detectors in list or specific detector position - * @returns slsDetector object - */ - // slsDetector *operator()(int detPos = -1) const; + /** + * Accessing the sls detector from the multi list using position + * @param detPos -1 for all detectors in list or specific detector position + * @returns slsDetector object + */ + // slsDetector *operator()(int detPos = -1) const; // slsDetector* operator[](int detPos) const; - /** - * Free shared memory from the command line - * avoiding creating the constructor classes and mapping - * @param multiId multi detector Id - * @param detPos -1 for all detectors in list or specific detector position - */ - static void freeSharedMemory(int multiId, int detPos = -1); - - /** - * Free shared memory and delete shared memory structure - * occupied by the sharedMultiSlsDetector structure - * Clears all the vectors and bring - * object back to state before object creation amap - * @param detPos -1 for all detectors in list or specific detector position - */ - void freeSharedMemory(int detPos = -1); - - /** - * Get user details of shared memory - * @returns string with user details - */ - std::string getUserDetails(); - - /** - * Sets the hostname of all sls detectors in shared memory - * Connects to them to set up online flag - * @param name concatenated hostname of all the sls detectors - * @param detPos -1 for all detectors in list or specific detector position - */ - void setHostname(const char* name, int detPos = -1); - - /** - * Gets the hostname of detector at particular position - * or concatenated hostnames of all the sls detectors - * @param detPos -1 for all detectors in list or specific detector position - * @returns concatenated hostnames of all detectors or hostname of specific one - */ - std::string getHostname(int detPos = -1); - - /** - * Appends detectors to the end of the list in shared memory - * Connects to them to set up online flag - * @param name concatenated hostname of the sls detectors to be appended to the list - */ - void addMultipleDetectors(const char* name); - - - using slsDetectorDefs::getDetectorType; - /** - * Get Detector type for a particular sls detector or get the first one - * @param detPos -1 for all detectors in list or specific detector position - * @returns detector type of sls detector in position pos, if -1, returns the first det type - */ - detectorType getDetectorsType(int detPos = -1); - - /** - * Concatenates string types of all sls detectors or - * returns the detector type of the first sls detector - * @param detPos -1 for all detectors in list or specific detector position - * @returns detector type of sls detector in position pos, if -1, concatenates - */ - std::string sgetDetectorsType(int detPos = -1); - - /** - * Gets Detector type (concatenates if different) - * @param detPos -1 for all detectors in list or specific detector position - * @returns detector type of sls detector in position pos, if -1, concatenates - */ - std::string getDetectorType(int detPos = -1); - - /** - * Returns the number of detectors in the multidetector structure - * @returns number of detectors - */ - int getNumberOfDetectors(); - - /** - * Returns number of detectors in dimension d - * @param d dimension d - * @returns number of detectors in dimension d - */ - int getNumberOfDetectors(dimension d); - - /** - * Returns the number of detectors in each direction - @param nx number of detectors in x direction - @param ny number of detectors in y direction - */ - void getNumberOfDetectors(int& nx, int& ny); - - /** - * Returns the total number of channels of all sls detectors from shared memory - * @param detPos -1 for all detectors in list or specific detector position - * @returns the total number of channels of all sls detectors - */ - int getTotalNumberOfChannels(int detPos = -1); - - /** - * Returns the total number of channels of all sls detectors in dimension d - * from shared memory - * @param d dimension d - * @param detPos -1 for all detectors in list or specific detector position - * @returns the total number of channels of all sls detectors in dimension d - */ - int getTotalNumberOfChannels(dimension d, int detPos = -1); - - /** - * Returns the total number of channels of all sls detectors in dimension d - * including gap pixels from shared memory - * @param d dimension d - * @param detPos -1 for all detectors in list or specific detector position - * @returns the total number of channels of all sls detectors in dimension d - * including gap pixels - */ - int getTotalNumberOfChannelsInclGapPixels(dimension d, int detPos = -1); - - /** - * Returns the maximum number of channels of all sls detectors in each dimension d - * from shared memory. multi detector shared memory variable to calculate - * offsets for each sls detector - * @param d dimension d - * @returns the maximum number of channels of all sls detectors in dimension d - */ - int getMaxNumberOfChannelsPerDetector(dimension d); - - /** - * Sets the maximum number of channels of all sls detectors in each dimension d - * from shared memory, multi detector shared memory variable to calculate - * offsets for each sls detector - * @param d dimension d - * @param i maximum number of channels for multi structure in dimension d - * @returns the maximum number of channels of all sls detectors in dimension d - */ - int setMaxNumberOfChannelsPerDetector(dimension d,int i); - - /** - * Get Detector offset from shared memory in dimension d - * @param d dimension d - * @param detPos -1 for all detectors in list or specific detector position - * @returns offset in dimension d, -1 if pos is not an actual position in list - */ - int getDetectorOffset(dimension d, int detPos = -1); - - /** - * Set Detector offset in shared memory in dimension d - * @param d dimension d - * @param off offset for detector - * @param detPos -1 for all detectors in list or specific detector position - */ - void setDetectorOffset(dimension d, int off, int detPos = -1); - - /** - * Updates the channel offsets in X and Y dimension for all the sls detectors - * It is required for decodeNMod and setting ROI - */ - void updateOffsets(); - - /** - * Checks if the multi detectors are 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 - * if OFFLINE_FLAG, (i.e. no communication to the detector - using only local structure - no data acquisition possible!); - * if ONLINE_FLAG, detector in online state (i.e. communication to the detector updating the local structure) - * @param detPos -1 for all detectors in list or specific detector position - * @returns online/offline status - */ - int setOnline(int const online=GET_ONLINE_FLAG, int detPos = -1); - - /** - * Checks if each of the detectors are online/offline - * @param detPos -1 for all detectors in list or specific detector position - * @returns empty string if they are all online, - * else returns concatenation of strings of all detectors that are offline - */ - std::string checkOnline(int detPos = -1); - - /** - * Set/Gets TCP Port of detector or receiver - * @param t port type - * @param num port number (-1 gets) - * @param detPos -1 for all detectors in list or specific detector position - * @returns port number - */ - int setPort(portType t, int num=-1, int detPos = -1); - - /** - * Lock server for this client IP - * @param p 0 to unlock, 1 to lock - * @param detPos -1 for all detectors in list or specific detector position - * @returns 1 for locked or 0 for unlocked - */ - int lockServer(int p=-1, int detPos = -1); - - /** - * Get last client IP saved on detector server - * @param detPos -1 for all detectors in list or specific detector position - * @returns last client IP saved on detector server - */ - std::string getLastClientIP(int detPos = -1); - - /** - * Exit detector server - * @param detPos -1 for all detectors in list or specific detector position - * @returns OK or FAIL - */ - int exitServer(int detPos = -1); - - /** - * Execute a command on the detector server - * @param cmd command - * @param detPos -1 for all detectors in list or specific detector position - * @returns OK or FAIL - */ - int execCommand(std::string cmd, int detPos); - - /** - * Load configuration from a configuration File - * @param fname configuration file name - * @return OK or FAIL - */ - int readConfigurationFile(const std::string& fname); - - /** - * Write current configuration to a file - * @param fname configuration file name - * @returns OK or FAIL - */ - int writeConfigurationFile(const std::string& fname); - - /** - * Returns the trimfile or settings file name (Useless??) - * @param detPos -1 for all detectors in list or specific detector position - * @returns the trimfile or settings file name - */ - std::string getSettingsFile(int detPos = -1); - - /** - * Get detector settings - * @param detPos -1 for all detectors in list or specific detector position - * @returns current settings - */ - detectorSettings getSettings(int detPos = -1); - - /** - * 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 - * @param isettings settings - * @param detPos -1 for all detectors in list or specific detector position - * @returns current settings - */ - detectorSettings setSettings(detectorSettings isettings, int detPos = -1); - - /** - * Get threshold energy (Eiger) - * @param detPos -1 for all detectors in list or specific detector position - * @returns current threshold value for imod in ev (-1 failed) - */ - int getThresholdEnergy(int detPos = -1); - - /** - * Set threshold energy (Eiger) - * @param e_eV threshold in eV - * @param isettings ev. change settings - * @param tb 1 to include trimbits, 0 to exclude - * @param detPos -1 for all detectors in list or specific detector position - * @returns current threshold value for imod in ev (-1 failed) - */ - int setThresholdEnergy(int e_eV, detectorSettings isettings=GET_SETTINGS,int tb=1, int detPos = -1); - - /** - * Returns the detector trimbit/settings directory \sa sharedSlsDetector - * @param detPos -1 for all detectors in list or specific detector position - * @returns the trimbit/settings directory - */ - std::string getSettingsDir(int detPos = -1); - - /** - * Sets the detector trimbit/settings directory \sa sharedSlsDetector - * @param s trimbits/settings directory - * @param detPos -1 for all detectors in list or specific detector position - * @returns the trimbit/settings directory - */ - std::string setSettingsDir(std::string directory, int detPos = -1); - - /** - * Loads the modules settings/trimbits reading from a specific file - * file name extension is automatically generated. - * @param fname specific settings/trimbits file - * @param detPos -1 for all detectors in list or specific detector position - * returns OK or FAIL - */ - int loadSettingsFile(std::string fname, int detPos = -1); - - /** - * Saves the modules settings/trimbits to a specific file - * file name extension is automatically generated. - * @param fname specific settings/trimbits file - * @param detPos -1 for all detectors in list or specific detector position - * returns OK or FAIL - */ - int saveSettingsFile(std::string fname, int detPos = -1); - - /** - * Get Detector run status - * @param detPos -1 for all detectors in list or specific detector position - * @returns status - */ - runStatus getRunStatus(int detPos = -1); - - /** - * Prepares detector for acquisition (Eiger) - * @param detPos -1 for all detectors in list or specific detector position - * @returns OK if all detectors are ready for acquisition, FAIL otherwise - */ - int prepareAcquisition(int detPos = -1); - - /** - * Start detector acquisition (Non blocking) - * @param detPos -1 for all detectors in list or specific detector position - * @returns OK or FAIL if even one does not start properly - */ - int startAcquisition(int detPos = -1); - - /** - * Stop detector acquisition - * @param detPos -1 for all detectors in list or specific detector position - * @returns OK or FAIL - */ - int stopAcquisition(int detPos = -1); - - /** - * Give an internal software trigger to the detector (Eiger only) - * @param detPos -1 for all detectors in list or specific detector position - * @return OK or FAIL - */ - int sendSoftwareTrigger(int detPos = -1); - - /** - * Start detector acquisition and read all data (Blocking until end of acquisition) - * @param detPos -1 for all detectors in list or specific detector position - * @returns OK or FAIL - */ - int startAndReadAll(int detPos = -1); - - /** - * Start readout (without exposure or interrupting exposure) (Eiger store in ram) - * @param detPos -1 for all detectors in list or specific detector position - * @returns OK or FAIL - */ - int startReadOut(int detPos = -1); - - /** - * Requests and receives all data from the detector (Eiger store in ram) - * @param detPos -1 for all detectors in list or specific detector position - * @returns OK or FAIL - */ - int readAll(int detPos = -1); - - /** - * Configures in detector the destination for UDP packets - * @param detPos -1 for all detectors in list or specific detector position - * @returns OK or FAIL - */ - int configureMAC(int detPos = -1); - - /** - * 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) - * @param detPos -1 for all detectors in list or specific detector position - * @returns timer set value in ns or number of...(e.g. frames, gates, probes) - */ - int64_t setTimer(timerIndex index, int64_t t=-1, int detPos = -1); - - /** - * Set/get exposure time - * @param t time (-1 gets) - * @param inseconds true if the value is in s, else ns - * @param detPos -1 for all detectors in list or specific detector position - * @returns exposure time in ns, or s if specified - */ - double setExposureTime(double t = -1, bool inseconds = false, int detPos = -1); - - /** - * Set/get exposure period - * @param t time (-1 gets) - * @param inseconds true if the value is in s, else ns - * @param detPos -1 for all detectors in list or specific detector position - * @returns exposure period in ns, or s if specified - */ - double setExposurePeriod(double t = -1, bool inseconds = false, int detPos = -1); - - /** - * Set/get delay after trigger (Gotthard, Jungfrau(not for this release)) - * @param t time (-1 gets) - * @param inseconds true if the value is in s, else ns - * @param detPos -1 for all detectors in list or specific detector position - * @returns delay after trigger in ns, or s if specified - */ - double setDelayAfterTrigger(double t = -1, bool inseconds = false, int detPos = -1); - - /** - * (Advanced users) - * Set/get sub frame exposure time (Eiger in 32 bit mode) - * @param t time (-1 gets) - * @param inseconds true if the value is in s, else ns - * @param detPos -1 for all detectors in list or specific detector position - * @returns sub frame exposure time in ns, or s if specified - */ - double setSubFrameExposureTime(double t = -1, bool inseconds = false, int detPos = -1); - - /** - * (Advanced users) - * Set/get sub frame dead time (Eiger in 32 bit mode) - * @param t time (-1 gets) - * @param inseconds true if the value is in s, else ns - * @param detPos -1 for all detectors in list or specific detector position - * @returns sub frame dead time in ns, or s if specified - */ - double setSubFrameExposureDeadTime(double t = -1, bool inseconds = false, int detPos = -1); - - /** - * Set/get number of frames - * @param t number of frames (-1 gets) - * @param detPos -1 for all detectors in list or specific detector position - * @returns number of frames - */ - int64_t setNumberOfFrames(int64_t t = -1, int detPos = -1); - - /** - * Set/get number of cycles - * @param t number of cycles (-1 gets) - * @param detPos -1 for all detectors in list or specific detector position - * @returns number of cycles - */ - int64_t setNumberOfCycles(int64_t t = -1, int detPos = -1); - - /** - * Set/get number of gates (none of the detectors at the moment) - * @param t number of gates (-1 gets) - * @param detPos -1 for all detectors in list or specific detector position - * @returns number of gates - */ - int64_t setNumberOfGates(int64_t t = -1, int detPos = -1); - - /** - * Set/get number of additional storage cells (Jungfrau) - * @param t number of additional storage cells. Default is 0. (-1 gets) - * @param detPos -1 for all detectors in list or specific detector position - * @returns number of additional storage cells - */ - int64_t setNumberOfStorageCells(int64_t t = -1, int detPos = -1); - - /** - * Get measured period between previous two frames (EIGER) - * @param t time (-1 gets) - * @param inseconds true if the value is in s, else ns - * @param detPos -1 for all detectors in list or specific detector position - * @returns sub frame dead time in ns, or s if specified - */ - double getMeasuredPeriod(bool inseconds = false, int detPos = -1); - - /** - * Get sub period between previous two sub frames in 32 bit mode (EIGER) - * @param t time (-1 gets) - * @param inseconds true if the value is in s, else ns - * @param detPos -1 for all detectors in list or specific detector position - * @returns sub frame dead time in ns, or s if specified - */ - double getMeasuredSubFramePeriod(bool inseconds = false, int detPos = -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) - * @param detPos -1 for all detectors in list or specific detector position - * @returns timer set value in ns or number of...(e.g. frames, gates, probes) - */ - int64_t getTimeLeft(timerIndex index, int detPos = -1); - - /** - * 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 - * @param detPos -1 for all detectors in list or specific detector position - * @returns value of speed set - */ - int setSpeed(speedVariable sp, int value=-1, int detPos = -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) - * @param detPos -1 for all detectors in list or specific detector position - * @returns current dynamic range - * \sa sharedSlsDetector - */ - int setDynamicRange(int i=-1, int detPos = -1); - - /** - * Recalculated number of data bytes for multi detector - * @param detPos -1 for all detectors in list or specific detector position - * @returns tota number of data bytes for multi detector - */ - int getDataBytes(int detPos = -1); - - /** - * Set/get dacs value - * @param val value (in V) - * @param index DAC index - * @param mV 0 in dac units or 1 in mV - * @param detPos -1 for all detectors in list or specific detector position - * @returns current DAC value - */ - int setDAC(int val, dacIndex index , int mV, int detPos = -1); - - /** - * Get adc value - * @param index adc(DAC) index - * @param detPos -1 for all detectors in list or specific detector position - * @returns current adc value (temperature for eiger and jungfrau in millidegrees) - */ - int getADC(dacIndex index, int detPos = -1); - - /** - * Set/get timing mode - * @param pol timing mode (-1 gets) - * @param detPos -1 for all detectors in list or specific detector position - * @returns current timing mode - */ - externalCommunicationMode setExternalCommunicationMode(externalCommunicationMode pol=GET_EXTERNAL_COMMUNICATION_MODE, int detPos = -1); - - /** - * 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) - * @param detPos -1 for all detectors in list or specific detector position - * @returns current timing mode - */ - externalSignalFlag setExternalSignalFlags(externalSignalFlag pol=GET_EXTERNAL_SIGNAL_FLAG , int signalindex=0, int detPos = -1); - - /** - * Set/get readout flags (Eiger, Mythen) - * @param flag readout flag (Eiger options: parallel, nonparallel, safe etc.) (-1 gets) - * @param detPos -1 for all detectors in list or specific detector position - * @returns readout flag - */ - int setReadOutFlags(readOutFlags flag=GET_READOUT_FLAGS, int detPos = -1); - - /** - * Write in a register. For Advanced users - * @param addr address of register - * @param val value to write into register - * @param detPos -1 for all detectors in list or specific detector position - * @returns value read after writing - */ - uint32_t writeRegister(uint32_t addr, uint32_t val, int detPos = -1); - - /** - * Read from a register. For Advanced users - * @param addr address of register - * @param detPos -1 for all detectors in list or specific detector position - * @returns value read from register - */ - uint32_t readRegister(uint32_t addr, int detPos = -1); - - /** - * Set bit in a register. For Advanced users - * @param addr address of register - * @param n nth bit - * @param detPos -1 for all detectors in list or specific detector position - * @returns value read from register - */ - uint32_t setBit(uint32_t addr, int n, int detPos = -1); - - /** - * Clear bit in a register. For Advanced users - * @param addr address of register - * @param n nth bit - * @param detPos -1 for all detectors in list or specific detector position - * @returns value read from register - */ - uint32_t clearBit(uint32_t addr, int n, int detPos = -1); - - /** - * Set up Receiver and update it from shm - * @param s hostname - * @param detPos -1 for all detectors in list or specific detector position - * @returns hostname - */ - std::string setReceiverHostname(std::string s, int detPos = -1); - - /** - * Get receiver hostname - * @param detPos -1 for all detectors in list or specific detector position - * @returns hostname - */ - std::string getReceiverHostname(int detPos = -1); - - /** - * Set network parameter - * @param p network parameter type - * @param s network parameter value - * @param detPos -1 for all detectors in list or specific detector position - * @returns network parameter value set (from getNetworkParameter) - */ - std::string setNetworkParameter(networkParameter parameter, std::string value, int detPos = -1); - - /** - * Get network parameter - * @param p network parameter type - * @param detPos -1 for all detectors in list or specific detector position - * @returns network parameter value set (from getNetworkParameter) - */ - std::string getNetworkParameter(networkParameter p, int detPos = -1); - - /** - * (advanced users) - * Set/Get receiver streaming out ZMQ port and restarts receiver sockets - * @param i sets, -1 gets - * If detPos is -1(multi module), port calculated (increments) for all the individual detectors using i - * @param detPos -1 for all detectors in list or specific detector position - * @returns receiver streaming out ZMQ port (if multiple, of first receiver socket) - */ - int setReceiverDataStreamingOutPort(int i = -1, int detPos = -1); - - /** - * (advanced users) - * Set/Get client streaming in ZMQ port and restarts client sockets - * @param i sets, -1 gets - * If detPos is -1(multi module), port calculated (increments) for all the individual detectors using i - * @param detPos -1 for all detectors in list or specific detector position - * @returns receiver streaming out ZMQ port (if multiple, of first receiver socket) - */ - int setClientDataStreamingInPort(int i = -1, int detPos = -1); - - /** - * (advanced users) - * Set/Get receiver streaming out ZMQ IP and restarts receiver sockets - * @param i sets, empty string gets - * By default, it is the IP of receiver hostname - * @param detPos -1 for all detectors in list or specific detector position - * @returns receiver streaming out ZMQ IP - */ - std::string setReceiverDataStreamingOutIP(std::string ip="", int detPos = -1); - - /** - * (advanced users) - * Set/Get client streaming in ZMQ IP and restarts client sockets - * @param i sets, empty string gets - * By default, it is the IP of receiver hostname - * @param detPos -1 for all detectors in list or specific detector position - * @returns client streaming in ZMQ IP - */ - std::string setClientDataStreamingInIP(std::string ip="", int detPos = -1); - - /** - * Set 10GbE Flow Control (Eiger) - * @param enable 1 to set, 0 to unset, -1 gets - * @param detPos -1 for all detectors in list or specific detector position - * @returns 10GbE flow Control - */ - int setFlowControl10G(int enable = -1, int detPos = -1); - - /** - * Execute a digital test (Gotthard) - * @param mode testmode type - * @param value 1 to set or 0 to clear the digital test bit - * @param detPos -1 for all detectors in list or specific detector position - * @returns result of test - */ - int digitalTest(digitalTestMode mode, int ival=-1, int detPos = -1); - - /** - * Load dark or gain image to detector (Gotthard) - * @param index image type - * @param fname file name from which to load image - * @param detPos -1 for all detectors in list or specific detector position - * @returns OK or FAIL - */ - int loadImageToDetector(imageType index, const std::string& fname, int detPos = -1); - - /** - * 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 - * @param detPos -1 for all detectors in list or specific detector position - * @returns OK or FAIL - */ - int writeCounterBlockFile(const std::string& fname,int startACQ=0, int detPos = -1); - - /** - * Resets counter in detector (Gotthard) - * @param startACQ is 1 to start acquisition after resetting counter - * @param detPos -1 for all detectors in list or specific detector position - * @returns OK or FAIL - */ - int resetCounterBlock(int startACQ=0, int detPos = -1); - - /** - * 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 - * @param detPos -1 for all detectors in list or specific detector position - * @returns the counter bit in detector - */ - int setCounterBit(int i = -1, int detPos = -1); - - /** - * Ensures that min is less than max in both dimensions (Gotthard) - * @param n number of rois - * @param r array of rois - */ - void verifyMinMaxROI(int n, ROI r[]); - - /** - * Set ROI (Gotthard) - * At the moment only one set allowed - * @param n number of rois - * @param roiLimits array of roi - * @param detPos -1 for all detectors in list or specific detector position - * @returns OK or FAIL - */ - int setROI(int n=-1,ROI roiLimits[]=NULL, int detPos = -1); - - /** - * Get ROI from each detector and convert it to the multi detector scale (Gotthard) - * @param n number of rois - * @param detPos -1 for all detectors in list or specific detector position - * @returns OK or FAIL - */ - ROI* getROI(int &n, int detPos = -1); - - /** - * Write to ADC register (Gotthard, Jungfrau, ChipTestBoard). For expert users - * @param addr address of adc register - * @param val value - * @param detPos -1 for all detectors in list or specific detector position - * @returns return value (mostly -1 as it can't read adc register) - */ - int writeAdcRegister(int addr, int val, int detPos = -1); - - /** - * Activates/Deactivates the detector (Eiger only) - * @param enable active (1) or inactive (0), -1 gets - * @param detPos -1 for all detectors in list or specific detector position - * @returns 0 (inactive) or 1 (active)for activate mode - */ - int activate(int const enable=-1, int detPos = -1); - - /** - * Set deactivated Receiver padding mode (Eiger only) - * @param padding padding option for deactivated receiver. Can be 1 (padding), 0 (no padding), -1 (gets) - * @param detPos -1 for all detectors in list or specific detector position - * @returns 1 (padding), 0 (no padding), -1 (inconsistent values) for padding option - */ - int setDeactivatedRxrPaddingMode(int padding=-1, int detPos = -1); - - /** - * Returns the enable if data will be flipped across x or y axis (Eiger) - * @param d axis across which data is flipped - * @param detPos -1 for all detectors in list or specific detector position - * @returns 1 for flipped, else 0 - */ - int getFlippedData(dimension d=X, int detPos = -1); - - /** - * 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 - * @param detPos -1 for all detectors in list or specific detector position - * @returns enable flipped data across x or y axis - */ - int setFlippedData(dimension d=X, int value=-1, int detPos = -1); - - /** - * Sets all the trimbits to a particular value (Eiger) - * @param val trimbit value - * @param detPos -1 for all detectors in list or specific detector position - * @returns OK or FAIL - */ - int setAllTrimbits(int val, int detPos = -1); - - /** - * 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 detPos = -1); - - /** - * Sets the number of trim energies and their value (Eiger) - * \sa sharedSlsDetector - * @param nen number of energies - * @param en array of energies - * @param detPos -1 for all detectors in list or specific detector position - * @returns number of trim energies - */ - int setTrimEn(int nen, int *en=NULL, int detPos = -1); - - /** - * Returns the number of trim energies and their value (Eiger) - * \sa sharedSlsDetector - * @param en array of energies - * @param detPos -1 for all detectors in list or specific detector position - * @returns number of trim energies - */ - int getTrimEn(int *en=NULL, int detPos = -1); - - /** - * Pulse Pixel (Eiger) - * @param n is number of times to pulse - * @param x is x coordinate - * @param y is y coordinate - * @param detPos -1 for all detectors in list or specific detector position - * @returns OK or FAIL - */ - int pulsePixel(int n=0,int x=0,int y=0, int detPos = -1); - - /** - * 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 - * @param detPos -1 for all detectors in list or specific detector position - * @returns OK or FAIL - */ - int pulsePixelNMove(int n=0,int x=0,int y=0, int detPos = -1); - - /** - * Pulse Chip (Eiger) - * @param n is number of times to pulse - * @param detPos -1 for all detectors in list or specific detector position - * @returns OK or FAIL - */ - int pulseChip(int n=0, int detPos = -1); - - /** - * Set/gets threshold temperature (Jungfrau) - * @param val value in millidegrees, -1 gets - * @param detPos -1 for all detectors in list or specific detector position - * @returns threshold temperature in millidegrees - */ - int setThresholdTemperature(int val=-1, int detPos = -1); - - /** - * Enables/disables temperature control (Jungfrau) - * @param val value, -1 gets - * @param detPos -1 for all detectors in list or specific detector position - * @returns temperature control enable - */ - int setTemperatureControl(int val=-1, int detPos = -1); - - /** - * Resets/ gets over-temperature event (Jungfrau) - * @param val value, -1 gets - * @param detPos -1 for all detectors in list or specific detector position - * @returns over-temperature event - */ - int setTemperatureEvent(int val=-1, int detPos = -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) - * @param detPos -1 for all detectors in list or specific detector position - * @returns the storage cell that stores the first acquisition of the series - */ - int setStoragecellStart(int pos=-1, int detPos = -1); - - /** - * Programs FPGA with pof file (Jungfrau) - * @param fname file name - * @param detPos -1 for all detectors in list or specific detector position - * @returns OK or FAIL - */ - int programFPGA(std::string fname, int detPos = -1); - - /** - * Resets FPGA (Jungfrau) - * @param detPos -1 for all detectors in list or specific detector position - * @returns OK or FAIL - */ - int resetFPGA(int detPos = -1); - - /** - * Power on/off Chip (Jungfrau) - * @param ival on is 1, off is 0, -1 to get - * @param detPos -1 for all detectors in list or specific detector position - * @returns OK or FAIL - */ - int powerChip(int ival= -1, int detPos = -1); - - /** - * Automatic comparator disable (Jungfrau) - * @param ival on is 1, off is 0, -1 to get - * @param detPos -1 for all detectors in list or specific detector position - * @returns OK or FAIL - */ - int setAutoComparatorDisableMode(int ival= -1, int detPos = -1); - - /** - * Returns the trimbits from the detector's shared memmory (Mythen, Eiger) - * @param retval is the array with the trimbits - * @param fromDetector is true if the trimbits shared memory have to be - * uploaded from detector - * @param detPos -1 for all detectors in list or specific detector position - * @returns total number of channels for the detector - */ - int getChanRegs(double* retval,bool fromDetector, int detPos = -1); - - /** - * Calibrate Pedestal (ChipTestBoard) - * Starts acquisition, calibrates pedestal and writes to fpga - * @param frames number of frames - * @param detPos -1 for all detectors in list or specific detector position - * @returns number of frames - */ - int calibratePedestal(int frames = 0, int detPos = -1); - - /** - * Set Rate correction ( 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 - * @param detPos -1 for all detectors in list or specific detector position - * @returns 0 if rate correction disabled, >0 otherwise - */ - int setRateCorrection(int t=0, int detPos = -1); - - /** - * Get rate correction ( Eiger) - * @param detPos -1 for all detectors in list or specific detector position - * @returns 0 if rate correction disabled, > 0 otherwise (ns) - */ - int getRateCorrection(int detPos = -1); - - /** - * Prints receiver configuration - * @param detPos -1 for all detectors in list or specific detector position - * @returns OK or FAIL - */ - int printReceiverConfiguration(int detPos = -1); - - /** - * Sets up receiver socket if online and sets the flag - * @param online online/offline flag (-1 gets) - * @param detPos -1 for all detectors in list or specific detector position - * @returns online/offline flag - */ - int setReceiverOnline(int const online=GET_ONLINE_FLAG, int detPos = -1); - - /** - * Checks if the receiver is really online - * @param detPos -1 for all detectors in list or specific detector position - * @returns empty string if all online, else concatenates hostnames of all - * detectors that are offline - */ - std::string checkReceiverOnline(int detPos = -1); - - /** - * Locks/Unlocks the connection to the receiver - * @param lock sets (1), usets (0), gets (-1) the lock - * @param detPos -1 for all detectors in list or specific detector position - * @returns lock status of the receiver - */ - int lockReceiver(int lock=-1, int detPos = -1); - - /** - * Returns the IP of the last client connecting to the receiver - * @param detPos -1 for all detectors in list or specific detector position - * @returns IP of last client connecting to receiver - */ - std::string getReceiverLastClientIP(int detPos = -1); - - /** - * Turns off the receiver server! - * @param detPos -1 for all detectors in list or specific detector position - * @returns OK or FAIL - */ - int exitReceiver(int detPos = -1); - - /** - * 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 - * @param detPos -1 for all detectors in list or specific detector position - * @returns OK or FAIL - */ - int execReceiverCommand(std::string cmd, int detPos = -1); - - /** - * Returns output file directory - * @param detPos -1 for all detectors in list or specific detector position - * @returns output file directory - */ - std::string getFilePath(int detPos = -1); - - /** - * Sets up the file directory - * @param detPos -1 for all detectors in list or specific detector position - * @param s file directory - * @returns file dir - */ - std::string setFilePath(std::string s, int detPos = -1); - - /** - * Returns file name prefix - * @param detPos -1 for all detectors in list or specific detector position - * @returns file name prefix - */ - std::string getFileName(int detPos = -1); - - /** - * Sets up the file name prefix - * @param detPos -1 for all detectors in list or specific detector position - * @param s file name prefix - * @returns file name prefix - */ - std::string setFileName(std::string s, int detPos = -1); - - /** - * Sets the max frames per file in receiver - * @param f max frames per file - * @param detPos -1 for all detectors in list or specific detector position - * @returns max frames per file in receiver - */ - int setReceiverFramesPerFile(int f = -1, int detPos = -1); - - /** - * Sets the frames discard policy in receiver - * @param f frames discard policy - * @param detPos -1 for all detectors in list or specific detector position - * @returns frames discard policy set in receiver - */ - frameDiscardPolicy setReceiverFramesDiscardPolicy(frameDiscardPolicy f = GET_FRAME_DISCARD_POLICY, int detPos = -1); - - /** - * Sets the partial frames padding enable in receiver - * @param f partial frames padding enable - * @param detPos -1 for all detectors in list or specific detector position - * @returns partial frames padding enable in receiver - */ - int setReceiverPartialFramesPadding(int f = -1, int detPos = -1); - - /** - * Returns file format - * @param detPos -1 for all detectors in list or specific detector position - * @returns file name - */ - fileFormat getFileFormat(int detPos = -1); - - /** - * Sets up the file format - * @param f file format - * @param detPos -1 for all detectors in list or specific detector position - * @returns file format - */ - fileFormat setFileFormat(fileFormat f, int detPos = -1); - - /** - * Returns file index - * @param detPos -1 for all detectors in list or specific detector position - * @returns file index - */ - int getFileIndex(int detPos = -1); - - /** - * Sets up the file index - * @param i file index - * @param detPos -1 for all detectors in list or specific detector position - * @returns file index - */ - int setFileIndex(int i, int detPos = -1); - - /** - * increments file index - * @param detPos -1 for all detectors in list or specific detector position - * @returns the file index - */ - int incrementFileIndex(int detPos = -1); - - /** - * Receiver starts listening to packets - * @param detPos -1 for all detectors in list or specific detector position - * @returns OK or FAIL - */ - int startReceiver(int detPos = -1); - - /** - * Stops the listening mode of receiver - * @param detPos -1 for all detectors in list or specific detector position - * @returns OK or FAIL - */ - int stopReceiver(int detPos = -1); - - /** - * Gets the status of the listening mode of receiver - * @param detPos -1 for all detectors in list or specific detector position - * @returns status - */ - runStatus getReceiverStatus(int detPos = -1); - - /** - * Gets the number of frames caught by receiver - * @param detPos -1 for all detectors in list or specific detector position - * @returns number of frames caught by receiver - */ - int getFramesCaughtByReceiver(int detPos = -1); - - /** - * Gets the current frame index of receiver - * @param detPos -1 for all detectors in list or specific detector position - * @returns current frame index of receiver - */ - int getReceiverCurrentFrameIndex(int detPos = -1); - - /** - * Resets framescaught in receiver - * Use this when using startAcquisition instead of acquire - * @param detPos -1 for all detectors in list or specific detector position - * @returns OK or FAIL - */ - int resetFramesCaught(int detPos = -1); - - /** - * Create Receiving Data Sockets - * @param destroy is true to destroy all the sockets - * @returns OK or FAIL - */ - int createReceivingDataSockets(const bool destroy = false); - - /** - * Reads frames from receiver through a constant socket - * Called during acquire() when call back registered or when using gui - */ - void readFrameFromReceiver(); - - /** - * Sets/Gets receiver file write enable - * @param enable 1 or 0 to set/reset file write enable - * @param detPos -1 for all detectors in list or specific detector position - * @returns file write enable - */ - int enableWriteToFile(int enable=-1, int detPos = -1); - - /** - * Sets/Gets file overwrite enable - * @param enable 1 or 0 to set/reset file overwrite enable - * @param detPos -1 for all detectors in list or specific detector position - * @returns file overwrite enable - */ - int overwriteFile(int enable=-1, int detPos = -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 detPos = -1); - - /** - * (previously setReceiverReadTimer) - * Sets the receiver streaming timer - * If receiver streaming frequency is 0, then this timer between each - * data stream is set. Default is 200 ms. - * @param time_in_ms timer between frames - * @param detPos -1 for all detectors in list or specific detector position - * @returns receiver streaming timer in ms - */ - int setReceiverStreamingTimer(int time_in_ms=500, int detPos = -1); - - /** - * Enable data streaming to client - * @param enable 0 to disable, 1 to enable, -1 to get the value - * @returns data streaming to client enable - */ - int enableDataStreamingToClient(int enable=-1); - - /** - * Enable or disable streaming data from receiver to client - * @param enable 0 to disable 1 to enable -1 to only get the value - * @param detPos -1 for all detectors in list or specific detector position - * @returns data streaming from receiver enable - */ - int enableDataStreamingFromReceiver(int enable=-1, int detPos = -1); - - /** - * Enable/disable or 10Gbe - * @param i is -1 to get, 0 to disable and 1 to enable - * @param detPos -1 for all detectors in list or specific detector position - * @returns if 10Gbe is enabled - */ - int enableTenGigabitEthernet(int i = -1, int detPos = -1); - - /** - * Set/get receiver fifo depth - * @param i is -1 to get, any other value to set the fifo deph - * @param detPos -1 for all detectors in list or specific detector position - * @returns the receiver fifo depth - */ - int setReceiverFifoDepth(int i = -1, int detPos = -1); - - /** - * Set/get receiver silent mode - * @param i is -1 to get, 0 unsets silent mode, 1 sets silent mode - * @param detPos -1 for all detectors in list or specific detector position - * @returns the receiver silent mode enable - */ - int setReceiverSilentMode(int i = -1, int detPos = -1); - - /** - * Opens pattern file and sends pattern to CTB - * @param fname pattern file to open - * @param detPos -1 for all detectors in list or specific detector position - * @returns OK/FAIL - */ - int setCTBPattern(std::string fname, int detPos = -1); - - /** - * 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 - * @param detPos -1 for all detectors in list or specific detector position - * @returns actual value - */ - uint64_t setCTBWord(int addr,uint64_t word=-1, int detPos = -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 - * @param stop stop address if >=0 - * @param n number of loops (if level >=0) - * @param detPos -1 for all detectors in list or specific detector position - * @returns OK/FAIL - */ - int setCTBPatLoops(int level,int &start, int &stop, int &n, int detPos = -1); - - /** - * Sets the wait address in the CTB - * @param level 0,1,2, wait level - * @param addr wait address, -1 gets - * @param detPos -1 for all detectors in list or specific detector position - * @returns actual value - */ - int setCTBPatWaitAddr(int level, int addr=-1, int detPos = -1); - - /** - * Sets the wait time in the CTB - * @param level 0,1,2, wait level - * @param t wait time, -1 gets - * @param detPos -1 for all detectors in list or specific detector position - * @returns actual value - */ - int setCTBPatWaitTime(int level, uint64_t t=-1, int detPos = -1); - - /** - * Loads the detector setup from file - * @param fname file to read from - * @param level if 2 reads also reads trimbits, angular conversion coefficients etc. - * from files with default extensions as generated by dumpDetectorSetup - * @returns OK or FAIL - */ - int retrieveDetectorSetup(const std::string& fname, int level=0); - - /** - * Saves the detector setup to file - * @param fname file to write to - * @param level if 2 reads also trimbits, flat field, angular correction etc. - * and writes them to files with automatically added extension - * @returns OK or FAIL - */ - int dumpDetectorSetup(const std::string& fname, int level=0); - - /** - * register callback for accessing acquisition final data - * @param func function to be called at the end of the acquisition. - * gets detector status and progress index as arguments - * @param pArg argument - */ - void registerAcquisitionFinishedCallback(int( *func)(double,int, void*), void *pArg); - - /** - * register callback for accessing measurement final data - * @param func function to be called at the end of the acquisition. - * gets detector status and progress index as arguments - * @param pArg argument - */ - void registerMeasurementFinishedCallback(int( *func)(int,int, void*), void *pArg); - - /** - * register callback for accessing detector progress - * @param func function to be called at the end of the acquisition. - * gets detector status and progress index as arguments - * @param pArg argument - */ - void registerProgressCallback(int( *func)(double,void*), void *pArg); - - /** - * register calbback for accessing detector final data, - * also enables data streaming in client and receiver - * @param userCallback function for plotting/analyzing the data. - * Its arguments are - * the data structure d and the frame number f, - * s is for subframe number for eiger for 32 bit mode - * @param pArg argument - */ - void registerDataCallback(int( *userCallback)(detectorData*, int, int, void*), void *pArg); - - /** - * Performs a complete acquisition - * resets frames caught in receiver, starts receiver, starts detector, - * blocks till detector finished acquisition, stop receiver, increments file index, - * loops for measurements, calls required call backs. - * @returns OK or FAIL depending on if it already started - */ - int acquire(); - - - - /** - * Returns true if detector position is out of bounds - */ - bool isDetectorIndexOutOfBounds(int detPos); - - /** - * Combines data from all readouts and gives it to the gui - * or just gives progress of acquisition by polling receivers - */ - void processData(); - -private: - /** - * Initialize (open/create) shared memory for the sharedMultiDetector structure - * @param verify true to verify if shm size matches existing one - * @param update true to update last user pid, date etc - * @returns true if shared memory was created in this call, else false - */ - void initSharedMemory(bool verify = true); - - /** - * Initialize detector structure for the shared memory just created - */ - void initializeDetectorStructure(); - - /** - * Initialize class members (and from parent classes) - * @param verify true to verify if shm size matches existing one - */ - void initializeMembers(bool verify = true); - - /** - * Update user details in detector structure - */ - void updateUserdetails(); - - /** - * Execute in command line and return result - * @param cmd command - * @returns result - */ - std::string exec(const char* cmd); - - /** - * Add sls detector - * @param s hostname of the single detector - */ - void addSlsDetector (std::string s); - - /** - * add gap pixels to the image (only for Eiger in 4 bit mode) - * @param image pointer to image without gap pixels - * @param gpImage poiner to image with gap pixels, if NULL, allocated inside function - * @returns number of data bytes of image with gap pixels - */ - int processImageWithGapPixels(char* image, char*& gpImage); - - /** - * Set total progress (total number of frames/images in an acquisition) - * @returns total progress - */ - int setTotalProgress(); - - /** - * Get progress in current acquisition - * @returns current progress - */ - double getCurrentProgress(); - - /** - * Increment progress by one - */ - void incrementProgress(); - - /** - * Set current progress to argument - * @param i current progress - */ - void setCurrentProgress(int i=0); + /** + * Free shared memory from the command line + * avoiding creating the constructor classes and mapping + * @param multiId multi detector Id + * @param detPos -1 for all detectors in list or specific detector position + */ + static void freeSharedMemory(int multiId, int detPos = -1); + + /** + * Free shared memory and delete shared memory structure + * occupied by the sharedMultiSlsDetector structure + * Clears all the vectors and bring + * object back to state before object creation amap + * @param detPos -1 for all detectors in list or specific detector position + */ + void freeSharedMemory(int detPos = -1); + + /** + * Get user details of shared memory + * @returns string with user details + */ + std::string getUserDetails(); + + /** + * Sets the hostname of all sls detectors in shared memory + * Connects to them to set up online flag + * @param name concatenated hostname of all the sls detectors + * @param detPos -1 for all detectors in list or specific detector position + */ + void setHostname(const char *name, int detPos = -1); + + /** + * Gets the hostname of detector at particular position + * or concatenated hostnames of all the sls detectors + * @param detPos -1 for all detectors in list or specific detector position + * @returns concatenated hostnames of all detectors or hostname of specific + * one + */ + std::string getHostname(int detPos = -1); + + /** + * Appends detectors to the end of the list in shared memory + * Connects to them to set up online flag + * @param name concatenated hostname of the sls detectors to be appended to + * the list + */ + void addMultipleDetectors(const char *name); + + using slsDetectorDefs::getDetectorType; + /** + * Get Detector type for a particular sls detector or get the first one + * @param detPos -1 for all detectors in list or specific detector position + * @returns detector type of sls detector in position pos, if -1, returns + * the first det type + */ + detectorType getDetectorsType(int detPos = -1); + + /** + * Concatenates string types of all sls detectors or + * returns the detector type of the first sls detector + * @param detPos -1 for all detectors in list or specific detector position + * @returns detector type of sls detector in position pos, if -1, + * concatenates + */ + std::string sgetDetectorsType(int detPos = -1); + + /** + * Gets Detector type (concatenates if different) + * @param detPos -1 for all detectors in list or specific detector position + * @returns detector type of sls detector in position pos, if -1, + * concatenates + */ + std::string getDetectorType(int detPos = -1); + + /** + * Returns the number of detectors in the multidetector structure + * @returns number of detectors + */ + int getNumberOfDetectors(); + + /** + * Returns number of detectors in dimension d + * @param d dimension d + * @returns number of detectors in dimension d + */ + int getNumberOfDetectors(dimension d); + + /** + * Returns the number of detectors in each direction + @param nx number of detectors in x direction + @param ny number of detectors in y direction + */ + void getNumberOfDetectors(int &nx, int &ny); + + /** + * Returns the total number of channels of all sls detectors from shared + * memory + * @param detPos -1 for all detectors in list or specific detector position + * @returns the total number of channels of all sls detectors + */ + int getTotalNumberOfChannels(int detPos = -1); + + /** + * Returns the total number of channels of all sls detectors in dimension d + * from shared memory + * @param d dimension d + * @param detPos -1 for all detectors in list or specific detector position + * @returns the total number of channels of all sls detectors in dimension d + */ + int getTotalNumberOfChannels(dimension d, int detPos = -1); + + /** + * Returns the total number of channels of all sls detectors in dimension d + * including gap pixels from shared memory + * @param d dimension d + * @param detPos -1 for all detectors in list or specific detector position + * @returns the total number of channels of all sls detectors in dimension d + * including gap pixels + */ + int getTotalNumberOfChannelsInclGapPixels(dimension d, int detPos = -1); + + /** + * Returns the maximum number of channels of all sls detectors in each + * dimension d from shared memory. multi detector shared memory variable to + * calculate offsets for each sls detector + * @param d dimension d + * @returns the maximum number of channels of all sls detectors in dimension + * d + */ + int getMaxNumberOfChannelsPerDetector(dimension d); + + /** + * Sets the maximum number of channels of all sls detectors in each + * dimension d from shared memory, multi detector shared memory variable to + * calculate offsets for each sls detector + * @param d dimension d + * @param i maximum number of channels for multi structure in dimension d + * @returns the maximum number of channels of all sls detectors in dimension + * d + */ + int setMaxNumberOfChannelsPerDetector(dimension d, int i); + + /** + * Get Detector offset from shared memory in dimension d + * @param d dimension d + * @param detPos -1 for all detectors in list or specific detector position + * @returns offset in dimension d, -1 if pos is not an actual position in + * list + */ + int getDetectorOffset(dimension d, int detPos = -1); + + /** + * Set Detector offset in shared memory in dimension d + * @param d dimension d + * @param off offset for detector + * @param detPos -1 for all detectors in list or specific detector position + */ + void setDetectorOffset(dimension d, int off, int detPos = -1); + + /** + * Updates the channel offsets in X and Y dimension for all the sls + * detectors It is required for decodeNMod and setting ROI + */ + void updateOffsets(); + + /** + * Checks if the multi detectors are 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 + * if OFFLINE_FLAG, (i.e. no communication to the detector - using only + * local structure - no data acquisition possible!); if ONLINE_FLAG, + * detector in online state (i.e. communication to the detector updating the + * local structure) + * @param detPos -1 for all detectors in list or specific detector position + * @returns online/offline status + */ + int setOnline(int const online = GET_ONLINE_FLAG, int detPos = -1); + + /** + * Checks if each of the detectors are online/offline + * @param detPos -1 for all detectors in list or specific detector position + * @returns empty string if they are all online, + * else returns concatenation of strings of all detectors that are offline + */ + std::string checkOnline(int detPos = -1); + + /** + * Set/Gets TCP Port of detector or receiver + * @param t port type + * @param num port number (-1 gets) + * @param detPos -1 for all detectors in list or specific detector position + * @returns port number + */ + int setPort(portType t, int num = -1, int detPos = -1); + + /** + * Lock server for this client IP + * @param p 0 to unlock, 1 to lock + * @param detPos -1 for all detectors in list or specific detector position + * @returns 1 for locked or 0 for unlocked + */ + int lockServer(int p = -1, int detPos = -1); + + /** + * Get last client IP saved on detector server + * @param detPos -1 for all detectors in list or specific detector position + * @returns last client IP saved on detector server + */ + std::string getLastClientIP(int detPos = -1); + + /** + * Exit detector server + * @param detPos -1 for all detectors in list or specific detector position + * @returns OK or FAIL + */ + int exitServer(int detPos = -1); + + /** + * Execute a command on the detector server + * @param cmd command + * @param detPos -1 for all detectors in list or specific detector position + * @returns OK or FAIL + */ + int execCommand(std::string cmd, int detPos); + + /** + * Load configuration from a configuration File + * @param fname configuration file name + * @return OK or FAIL + */ + int readConfigurationFile(const std::string &fname); + + /** + * Write current configuration to a file + * @param fname configuration file name + * @returns OK or FAIL + */ + int writeConfigurationFile(const std::string &fname); + + /** + * Returns the trimfile or settings file name (Useless??) + * @param detPos -1 for all detectors in list or specific detector position + * @returns the trimfile or settings file name + */ + std::string getSettingsFile(int detPos = -1); + + /** + * Get detector settings + * @param detPos -1 for all detectors in list or specific detector position + * @returns current settings + */ + detectorSettings getSettings(int detPos = -1); + + /** + * 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 + * @param isettings settings + * @param detPos -1 for all detectors in list or specific detector position + * @returns current settings + */ + detectorSettings setSettings(detectorSettings isettings, int detPos = -1); + + /** + * Get threshold energy (Eiger) + * @param detPos -1 for all detectors in list or specific detector position + * @returns current threshold value for imod in ev (-1 failed) + */ + int getThresholdEnergy(int detPos = -1); + + /** + * Set threshold energy (Eiger) + * @param e_eV threshold in eV + * @param isettings ev. change settings + * @param tb 1 to include trimbits, 0 to exclude + * @param detPos -1 for all detectors in list or specific detector position + * @returns current threshold value for imod in ev (-1 failed) + */ + int setThresholdEnergy(int e_eV, detectorSettings isettings = GET_SETTINGS, + int tb = 1, int detPos = -1); + + /** + * Returns the detector trimbit/settings directory \sa sharedSlsDetector + * @param detPos -1 for all detectors in list or specific detector position + * @returns the trimbit/settings directory + */ + std::string getSettingsDir(int detPos = -1); + + /** + * Sets the detector trimbit/settings directory \sa sharedSlsDetector + * @param s trimbits/settings directory + * @param detPos -1 for all detectors in list or specific detector position + * @returns the trimbit/settings directory + */ + std::string setSettingsDir(std::string directory, int detPos = -1); + + /** + * Loads the modules settings/trimbits reading from a specific file + * file name extension is automatically generated. + * @param fname specific settings/trimbits file + * @param detPos -1 for all detectors in list or specific detector position + * returns OK or FAIL + */ + int loadSettingsFile(std::string fname, int detPos = -1); + + /** + * Saves the modules settings/trimbits to a specific file + * file name extension is automatically generated. + * @param fname specific settings/trimbits file + * @param detPos -1 for all detectors in list or specific detector position + * returns OK or FAIL + */ + int saveSettingsFile(std::string fname, int detPos = -1); + + /** + * Get Detector run status + * @param detPos -1 for all detectors in list or specific detector position + * @returns status + */ + runStatus getRunStatus(int detPos = -1); + + /** + * Prepares detector for acquisition (Eiger) + * @param detPos -1 for all detectors in list or specific detector position + * @returns OK if all detectors are ready for acquisition, FAIL otherwise + */ + int prepareAcquisition(int detPos = -1); + + /** + * Start detector acquisition (Non blocking) + * @param detPos -1 for all detectors in list or specific detector position + * @returns OK or FAIL if even one does not start properly + */ + int startAcquisition(int detPos = -1); + + /** + * Stop detector acquisition + * @param detPos -1 for all detectors in list or specific detector position + * @returns OK or FAIL + */ + int stopAcquisition(int detPos = -1); + + /** + * Give an internal software trigger to the detector (Eiger only) + * @param detPos -1 for all detectors in list or specific detector position + * @return OK or FAIL + */ + int sendSoftwareTrigger(int detPos = -1); + + /** + * Start detector acquisition and read all data (Blocking until end of + * acquisition) + * @param detPos -1 for all detectors in list or specific detector position + * @returns OK or FAIL + */ + int startAndReadAll(int detPos = -1); + + /** + * Start readout (without exposure or interrupting exposure) (Eiger store in + * ram) + * @param detPos -1 for all detectors in list or specific detector position + * @returns OK or FAIL + */ + int startReadOut(int detPos = -1); + + /** + * Requests and receives all data from the detector (Eiger store in ram) + * @param detPos -1 for all detectors in list or specific detector position + * @returns OK or FAIL + */ + int readAll(int detPos = -1); + + /** + * Configures in detector the destination for UDP packets + * @param detPos -1 for all detectors in list or specific detector position + * @returns OK or FAIL + */ + int configureMAC(int detPos = -1); + + /** + * 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) + * @param detPos -1 for all detectors in list or specific detector position + * @returns timer set value in ns or number of...(e.g. frames, gates, + * probes) + */ + int64_t setTimer(timerIndex index, int64_t t = -1, int detPos = -1); + + /** + * Set/get exposure time + * @param t time (-1 gets) + * @param inseconds true if the value is in s, else ns + * @param detPos -1 for all detectors in list or specific detector position + * @returns exposure time in ns, or s if specified + */ + double setExposureTime(double t = -1, bool inseconds = false, + int detPos = -1); + + /** + * Set/get exposure period + * @param t time (-1 gets) + * @param inseconds true if the value is in s, else ns + * @param detPos -1 for all detectors in list or specific detector position + * @returns exposure period in ns, or s if specified + */ + double setExposurePeriod(double t = -1, bool inseconds = false, + int detPos = -1); + + /** + * Set/get delay after trigger (Gotthard, Jungfrau(not for this release)) + * @param t time (-1 gets) + * @param inseconds true if the value is in s, else ns + * @param detPos -1 for all detectors in list or specific detector position + * @returns delay after trigger in ns, or s if specified + */ + double setDelayAfterTrigger(double t = -1, bool inseconds = false, + int detPos = -1); + + /** + * (Advanced users) + * Set/get sub frame exposure time (Eiger in 32 bit mode) + * @param t time (-1 gets) + * @param inseconds true if the value is in s, else ns + * @param detPos -1 for all detectors in list or specific detector position + * @returns sub frame exposure time in ns, or s if specified + */ + double setSubFrameExposureTime(double t = -1, bool inseconds = false, + int detPos = -1); + + /** + * (Advanced users) + * Set/get sub frame dead time (Eiger in 32 bit mode) + * @param t time (-1 gets) + * @param inseconds true if the value is in s, else ns + * @param detPos -1 for all detectors in list or specific detector position + * @returns sub frame dead time in ns, or s if specified + */ + double setSubFrameExposureDeadTime(double t = -1, bool inseconds = false, + int detPos = -1); + + /** + * Set/get number of frames + * @param t number of frames (-1 gets) + * @param detPos -1 for all detectors in list or specific detector position + * @returns number of frames + */ + int64_t setNumberOfFrames(int64_t t = -1, int detPos = -1); + + /** + * Set/get number of cycles + * @param t number of cycles (-1 gets) + * @param detPos -1 for all detectors in list or specific detector position + * @returns number of cycles + */ + int64_t setNumberOfCycles(int64_t t = -1, int detPos = -1); + + /** + * Set/get number of gates (none of the detectors at the moment) + * @param t number of gates (-1 gets) + * @param detPos -1 for all detectors in list or specific detector position + * @returns number of gates + */ + int64_t setNumberOfGates(int64_t t = -1, int detPos = -1); + + /** + * Set/get number of additional storage cells (Jungfrau) + * @param t number of additional storage cells. Default is 0. (-1 gets) + * @param detPos -1 for all detectors in list or specific detector position + * @returns number of additional storage cells + */ + int64_t setNumberOfStorageCells(int64_t t = -1, int detPos = -1); + + /** + * Get measured period between previous two frames (EIGER) + * @param t time (-1 gets) + * @param inseconds true if the value is in s, else ns + * @param detPos -1 for all detectors in list or specific detector position + * @returns sub frame dead time in ns, or s if specified + */ + double getMeasuredPeriod(bool inseconds = false, int detPos = -1); + + /** + * Get sub period between previous two sub frames in 32 bit mode (EIGER) + * @param t time (-1 gets) + * @param inseconds true if the value is in s, else ns + * @param detPos -1 for all detectors in list or specific detector position + * @returns sub frame dead time in ns, or s if specified + */ + double getMeasuredSubFramePeriod(bool inseconds = false, int detPos = -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) + * @param detPos -1 for all detectors in list or specific detector position + * @returns timer set value in ns or number of...(e.g. frames, gates, + * probes) + */ + int64_t getTimeLeft(timerIndex index, int detPos = -1); + + /** + * 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 + * @param detPos -1 for all detectors in list or specific detector position + * @returns value of speed set + */ + int setSpeed(speedVariable sp, int value = -1, int detPos = -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) + * @param detPos -1 for all detectors in list or specific detector position + * @returns current dynamic range + * \sa sharedSlsDetector + */ + int setDynamicRange(int i = -1, int detPos = -1); + + /** + * Recalculated number of data bytes for multi detector + * @param detPos -1 for all detectors in list or specific detector position + * @returns tota number of data bytes for multi detector + */ + int getDataBytes(int detPos = -1); + + /** + * Set/get dacs value + * @param val value (in V) + * @param index DAC index + * @param mV 0 in dac units or 1 in mV + * @param detPos -1 for all detectors in list or specific detector position + * @returns current DAC value + */ + int setDAC(int val, dacIndex index, int mV, int detPos = -1); + + /** + * Get adc value + * @param index adc(DAC) index + * @param detPos -1 for all detectors in list or specific detector position + * @returns current adc value (temperature for eiger and jungfrau in + * millidegrees) + */ + int getADC(dacIndex index, int detPos = -1); + + /** + * Set/get timing mode + * @param pol timing mode (-1 gets) + * @param detPos -1 for all detectors in list or specific detector position + * @returns current timing mode + */ + externalCommunicationMode setExternalCommunicationMode( + externalCommunicationMode pol = GET_EXTERNAL_COMMUNICATION_MODE, + int detPos = -1); + + /** + * 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) + * @param detPos -1 for all detectors in list or specific detector position + * @returns current timing mode + */ + externalSignalFlag + setExternalSignalFlags(externalSignalFlag pol = GET_EXTERNAL_SIGNAL_FLAG, + int signalindex = 0, int detPos = -1); + + /** + * Set/get readout flags (Eiger, Mythen) + * @param flag readout flag (Eiger options: parallel, nonparallel, safe + * etc.) (-1 gets) + * @param detPos -1 for all detectors in list or specific detector position + * @returns readout flag + */ + int setReadOutFlags(readOutFlags flag = GET_READOUT_FLAGS, int detPos = -1); + + /** + * Write in a register. For Advanced users + * @param addr address of register + * @param val value to write into register + * @param detPos -1 for all detectors in list or specific detector position + * @returns value read after writing + */ + uint32_t writeRegister(uint32_t addr, uint32_t val, int detPos = -1); + + /** + * Read from a register. For Advanced users + * @param addr address of register + * @param detPos -1 for all detectors in list or specific detector position + * @returns value read from register + */ + uint32_t readRegister(uint32_t addr, int detPos = -1); + + /** + * Set bit in a register. For Advanced users + * @param addr address of register + * @param n nth bit + * @param detPos -1 for all detectors in list or specific detector position + * @returns value read from register + */ + uint32_t setBit(uint32_t addr, int n, int detPos = -1); + + /** + * Clear bit in a register. For Advanced users + * @param addr address of register + * @param n nth bit + * @param detPos -1 for all detectors in list or specific detector position + * @returns value read from register + */ + uint32_t clearBit(uint32_t addr, int n, int detPos = -1); + + /** + * Set up Receiver and update it from shm + * @param s hostname + * @param detPos -1 for all detectors in list or specific detector position + * @returns hostname + */ + std::string setReceiverHostname(std::string s, int detPos = -1); + + /** + * Get receiver hostname + * @param detPos -1 for all detectors in list or specific detector position + * @returns hostname + */ + std::string getReceiverHostname(int detPos = -1); + + /** + * Set network parameter + * @param p network parameter type + * @param s network parameter value + * @param detPos -1 for all detectors in list or specific detector position + * @returns network parameter value set (from getNetworkParameter) + */ + std::string setNetworkParameter(networkParameter parameter, + std::string value, int detPos = -1); + + /** + * Get network parameter + * @param p network parameter type + * @param detPos -1 for all detectors in list or specific detector position + * @returns network parameter value set (from getNetworkParameter) + */ + std::string getNetworkParameter(networkParameter p, int detPos = -1); + + /** + * (advanced users) + * Set/Get receiver streaming out ZMQ port and restarts receiver sockets + * @param i sets, -1 gets + * If detPos is -1(multi module), port calculated (increments) for all the + * individual detectors using i + * @param detPos -1 for all detectors in list or specific detector position + * @returns receiver streaming out ZMQ port (if multiple, of first receiver + * socket) + */ + int setReceiverDataStreamingOutPort(int i = -1, int detPos = -1); + + /** + * (advanced users) + * Set/Get client streaming in ZMQ port and restarts client sockets + * @param i sets, -1 gets + * If detPos is -1(multi module), port calculated (increments) for all the + * individual detectors using i + * @param detPos -1 for all detectors in list or specific detector position + * @returns receiver streaming out ZMQ port (if multiple, of first receiver + * socket) + */ + int setClientDataStreamingInPort(int i = -1, int detPos = -1); + + /** + * (advanced users) + * Set/Get receiver streaming out ZMQ IP and restarts receiver sockets + * @param i sets, empty string gets + * By default, it is the IP of receiver hostname + * @param detPos -1 for all detectors in list or specific detector position + * @returns receiver streaming out ZMQ IP + */ + std::string setReceiverDataStreamingOutIP(std::string ip = "", + int detPos = -1); + + /** + * (advanced users) + * Set/Get client streaming in ZMQ IP and restarts client sockets + * @param i sets, empty string gets + * By default, it is the IP of receiver hostname + * @param detPos -1 for all detectors in list or specific detector position + * @returns client streaming in ZMQ IP + */ + std::string setClientDataStreamingInIP(std::string ip = "", + int detPos = -1); + + /** + * Set 10GbE Flow Control (Eiger) + * @param enable 1 to set, 0 to unset, -1 gets + * @param detPos -1 for all detectors in list or specific detector position + * @returns 10GbE flow Control + */ + int setFlowControl10G(int enable = -1, int detPos = -1); + + /** + * Execute a digital test (Gotthard) + * @param mode testmode type + * @param value 1 to set or 0 to clear the digital test bit + * @param detPos -1 for all detectors in list or specific detector position + * @returns result of test + */ + int digitalTest(digitalTestMode mode, int ival = -1, int detPos = -1); + + /** + * Load dark or gain image to detector (Gotthard) + * @param index image type + * @param fname file name from which to load image + * @param detPos -1 for all detectors in list or specific detector position + * @returns OK or FAIL + */ + int loadImageToDetector(imageType index, const std::string &fname, + int detPos = -1); + + /** + * 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 + * @param detPos -1 for all detectors in list or specific detector position + * @returns OK or FAIL + */ + int writeCounterBlockFile(const std::string &fname, int startACQ = 0, + int detPos = -1); + + /** + * Resets counter in detector (Gotthard) + * @param startACQ is 1 to start acquisition after resetting counter + * @param detPos -1 for all detectors in list or specific detector position + * @returns OK or FAIL + */ + int resetCounterBlock(int startACQ = 0, int detPos = -1); + + /** + * 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 + * @param detPos -1 for all detectors in list or specific detector position + * @returns the counter bit in detector + */ + int setCounterBit(int i = -1, int detPos = -1); + + /** + * Ensures that min is less than max in both dimensions (Gotthard) + * @param n number of rois + * @param r array of rois + */ + void verifyMinMaxROI(int n, ROI r[]); + + /** + * Set ROI (Gotthard) + * At the moment only one set allowed + * @param n number of rois + * @param roiLimits array of roi + * @param detPos -1 for all detectors in list or specific detector position + * @returns OK or FAIL + */ + int setROI(int n = -1, ROI roiLimits[] = NULL, int detPos = -1); + + /** + * Get ROI from each detector and convert it to the multi detector scale + * (Gotthard) + * @param n number of rois + * @param detPos -1 for all detectors in list or specific detector position + * @returns OK or FAIL + */ + ROI *getROI(int &n, int detPos = -1); + + /** + * Write to ADC register (Gotthard, Jungfrau, ChipTestBoard). For expert + * users + * @param addr address of adc register + * @param val value + * @param detPos -1 for all detectors in list or specific detector position + * @returns return value (mostly -1 as it can't read adc register) + */ + int writeAdcRegister(int addr, int val, int detPos = -1); + + /** + * Activates/Deactivates the detector (Eiger only) + * @param enable active (1) or inactive (0), -1 gets + * @param detPos -1 for all detectors in list or specific detector position + * @returns 0 (inactive) or 1 (active)for activate mode + */ + int activate(int const enable = -1, int detPos = -1); + + /** + * Set deactivated Receiver padding mode (Eiger only) + * @param padding padding option for deactivated receiver. Can be 1 + * (padding), 0 (no padding), -1 (gets) + * @param detPos -1 for all detectors in list or specific detector position + * @returns 1 (padding), 0 (no padding), -1 (inconsistent values) for + * padding option + */ + int setDeactivatedRxrPaddingMode(int padding = -1, int detPos = -1); + + /** + * Returns the enable if data will be flipped across x or y axis (Eiger) + * @param d axis across which data is flipped + * @param detPos -1 for all detectors in list or specific detector position + * @returns 1 for flipped, else 0 + */ + int getFlippedData(dimension d = X, int detPos = -1); + + /** + * 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 + * @param detPos -1 for all detectors in list or specific detector position + * @returns enable flipped data across x or y axis + */ + int setFlippedData(dimension d = X, int value = -1, int detPos = -1); + + /** + * Sets all the trimbits to a particular value (Eiger) + * @param val trimbit value + * @param detPos -1 for all detectors in list or specific detector position + * @returns OK or FAIL + */ + int setAllTrimbits(int val, int detPos = -1); + + /** + * 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 detPos = -1); + + /** + * Sets the number of trim energies and their value (Eiger) + * \sa sharedSlsDetector + * @param nen number of energies + * @param en array of energies + * @param detPos -1 for all detectors in list or specific detector position + * @returns number of trim energies + */ + int setTrimEn(int nen, int *en = NULL, int detPos = -1); + + /** + * Returns the number of trim energies and their value (Eiger) + * \sa sharedSlsDetector + * @param en array of energies + * @param detPos -1 for all detectors in list or specific detector position + * @returns number of trim energies + */ + int getTrimEn(int *en = NULL, int detPos = -1); + + /** + * Pulse Pixel (Eiger) + * @param n is number of times to pulse + * @param x is x coordinate + * @param y is y coordinate + * @param detPos -1 for all detectors in list or specific detector position + * @returns OK or FAIL + */ + int pulsePixel(int n = 0, int x = 0, int y = 0, int detPos = -1); + + /** + * 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 + * @param detPos -1 for all detectors in list or specific detector position + * @returns OK or FAIL + */ + int pulsePixelNMove(int n = 0, int x = 0, int y = 0, int detPos = -1); + + /** + * Pulse Chip (Eiger) + * @param n is number of times to pulse + * @param detPos -1 for all detectors in list or specific detector position + * @returns OK or FAIL + */ + int pulseChip(int n = 0, int detPos = -1); + + /** + * Set/gets threshold temperature (Jungfrau) + * @param val value in millidegrees, -1 gets + * @param detPos -1 for all detectors in list or specific detector position + * @returns threshold temperature in millidegrees + */ + int setThresholdTemperature(int val = -1, int detPos = -1); + + /** + * Enables/disables temperature control (Jungfrau) + * @param val value, -1 gets + * @param detPos -1 for all detectors in list or specific detector position + * @returns temperature control enable + */ + int setTemperatureControl(int val = -1, int detPos = -1); + + /** + * Resets/ gets over-temperature event (Jungfrau) + * @param val value, -1 gets + * @param detPos -1 for all detectors in list or specific detector position + * @returns over-temperature event + */ + int setTemperatureEvent(int val = -1, int detPos = -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) + * @param detPos -1 for all detectors in list or specific detector position + * @returns the storage cell that stores the first acquisition of the series + */ + int setStoragecellStart(int pos = -1, int detPos = -1); + + /** + * Programs FPGA with pof file (Jungfrau) + * @param fname file name + * @param detPos -1 for all detectors in list or specific detector position + * @returns OK or FAIL + */ + int programFPGA(std::string fname, int detPos = -1); + + /** + * Resets FPGA (Jungfrau) + * @param detPos -1 for all detectors in list or specific detector position + * @returns OK or FAIL + */ + int resetFPGA(int detPos = -1); + + /** + * Power on/off Chip (Jungfrau) + * @param ival on is 1, off is 0, -1 to get + * @param detPos -1 for all detectors in list or specific detector position + * @returns OK or FAIL + */ + int powerChip(int ival = -1, int detPos = -1); + + /** + * Automatic comparator disable (Jungfrau) + * @param ival on is 1, off is 0, -1 to get + * @param detPos -1 for all detectors in list or specific detector position + * @returns OK or FAIL + */ + int setAutoComparatorDisableMode(int ival = -1, int detPos = -1); + + /** + * Returns the trimbits from the detector's shared memmory (Mythen, Eiger) + * @param retval is the array with the trimbits + * @param fromDetector is true if the trimbits shared memory have to be + * uploaded from detector + * @param detPos -1 for all detectors in list or specific detector position + * @returns total number of channels for the detector + */ + int getChanRegs(double *retval, bool fromDetector, int detPos = -1); + + /** + * Calibrate Pedestal (ChipTestBoard) + * Starts acquisition, calibrates pedestal and writes to fpga + * @param frames number of frames + * @param detPos -1 for all detectors in list or specific detector position + * @returns number of frames + */ + int calibratePedestal(int frames = 0, int detPos = -1); + + /** + * Set Rate correction ( 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 + * @param detPos -1 for all detectors in list or specific detector position + * @returns 0 if rate correction disabled, >0 otherwise + */ + int setRateCorrection(int t = 0, int detPos = -1); + + /** + * Get rate correction ( Eiger) + * @param detPos -1 for all detectors in list or specific detector position + * @returns 0 if rate correction disabled, > 0 otherwise (ns) + */ + int getRateCorrection(int detPos = -1); + + /** + * Prints receiver configuration + * @param detPos -1 for all detectors in list or specific detector position + * @returns OK or FAIL + */ + int printReceiverConfiguration(int detPos = -1); + + /** + * Sets up receiver socket if online and sets the flag + * @param online online/offline flag (-1 gets) + * @param detPos -1 for all detectors in list or specific detector position + * @returns online/offline flag + */ + int setReceiverOnline(int const online = GET_ONLINE_FLAG, int detPos = -1); + + /** + * Checks if the receiver is really online + * @param detPos -1 for all detectors in list or specific detector position + * @returns empty string if all online, else concatenates hostnames of all + * detectors that are offline + */ + std::string checkReceiverOnline(int detPos = -1); + + /** + * Locks/Unlocks the connection to the receiver + * @param lock sets (1), usets (0), gets (-1) the lock + * @param detPos -1 for all detectors in list or specific detector position + * @returns lock status of the receiver + */ + int lockReceiver(int lock = -1, int detPos = -1); + + /** + * Returns the IP of the last client connecting to the receiver + * @param detPos -1 for all detectors in list or specific detector position + * @returns IP of last client connecting to receiver + */ + std::string getReceiverLastClientIP(int detPos = -1); + + /** + * Turns off the receiver server! + * @param detPos -1 for all detectors in list or specific detector position + * @returns OK or FAIL + */ + int exitReceiver(int detPos = -1); + + /** + * 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 + * @param detPos -1 for all detectors in list or specific detector position + * @returns OK or FAIL + */ + int execReceiverCommand(std::string cmd, int detPos = -1); + + /** + * Returns output file directory + * @param detPos -1 for all detectors in list or specific detector position + * @returns output file directory + */ + std::string getFilePath(int detPos = -1); + + /** + * Sets up the file directory + * @param detPos -1 for all detectors in list or specific detector position + * @param s file directory + * @returns file dir + */ + std::string setFilePath(std::string s, int detPos = -1); + + /** + * Returns file name prefix + * @param detPos -1 for all detectors in list or specific detector position + * @returns file name prefix + */ + std::string getFileName(int detPos = -1); + + /** + * Sets up the file name prefix + * @param detPos -1 for all detectors in list or specific detector position + * @param s file name prefix + * @returns file name prefix + */ + std::string setFileName(std::string s, int detPos = -1); + + /** + * Sets the max frames per file in receiver + * @param f max frames per file + * @param detPos -1 for all detectors in list or specific detector position + * @returns max frames per file in receiver + */ + int setReceiverFramesPerFile(int f = -1, int detPos = -1); + + /** + * Sets the frames discard policy in receiver + * @param f frames discard policy + * @param detPos -1 for all detectors in list or specific detector position + * @returns frames discard policy set in receiver + */ + frameDiscardPolicy setReceiverFramesDiscardPolicy( + frameDiscardPolicy f = GET_FRAME_DISCARD_POLICY, int detPos = -1); + + /** + * Sets the partial frames padding enable in receiver + * @param f partial frames padding enable + * @param detPos -1 for all detectors in list or specific detector position + * @returns partial frames padding enable in receiver + */ + int setReceiverPartialFramesPadding(int f = -1, int detPos = -1); + + /** + * Returns file format + * @param detPos -1 for all detectors in list or specific detector position + * @returns file name + */ + fileFormat getFileFormat(int detPos = -1); + + /** + * Sets up the file format + * @param f file format + * @param detPos -1 for all detectors in list or specific detector position + * @returns file format + */ + fileFormat setFileFormat(fileFormat f, int detPos = -1); + + /** + * Returns file index + * @param detPos -1 for all detectors in list or specific detector position + * @returns file index + */ + int getFileIndex(int detPos = -1); + + /** + * Sets up the file index + * @param i file index + * @param detPos -1 for all detectors in list or specific detector position + * @returns file index + */ + int setFileIndex(int i, int detPos = -1); + + /** + * increments file index + * @param detPos -1 for all detectors in list or specific detector position + * @returns the file index + */ + int incrementFileIndex(int detPos = -1); + + /** + * Receiver starts listening to packets + * @param detPos -1 for all detectors in list or specific detector position + * @returns OK or FAIL + */ + int startReceiver(int detPos = -1); + + /** + * Stops the listening mode of receiver + * @param detPos -1 for all detectors in list or specific detector position + * @returns OK or FAIL + */ + int stopReceiver(int detPos = -1); + + /** + * Gets the status of the listening mode of receiver + * @param detPos -1 for all detectors in list or specific detector position + * @returns status + */ + runStatus getReceiverStatus(int detPos = -1); + + /** + * Gets the number of frames caught by receiver + * @param detPos -1 for all detectors in list or specific detector position + * @returns number of frames caught by receiver + */ + int getFramesCaughtByReceiver(int detPos = -1); + + /** + * Gets the current frame index of receiver + * @param detPos -1 for all detectors in list or specific detector position + * @returns current frame index of receiver + */ + int getReceiverCurrentFrameIndex(int detPos = -1); + + /** + * Resets framescaught in receiver + * Use this when using startAcquisition instead of acquire + * @param detPos -1 for all detectors in list or specific detector position + * @returns OK or FAIL + */ + int resetFramesCaught(int detPos = -1); + + /** + * Create Receiving Data Sockets + * @param destroy is true to destroy all the sockets + * @returns OK or FAIL + */ + int createReceivingDataSockets(const bool destroy = false); + + /** + * Reads frames from receiver through a constant socket + * Called during acquire() when call back registered or when using gui + */ + void readFrameFromReceiver(); + + /** + * Sets/Gets receiver file write enable + * @param enable 1 or 0 to set/reset file write enable + * @param detPos -1 for all detectors in list or specific detector position + * @returns file write enable + */ + int enableWriteToFile(int enable = -1, int detPos = -1); + + /** + * Sets/Gets file overwrite enable + * @param enable 1 or 0 to set/reset file overwrite enable + * @param detPos -1 for all detectors in list or specific detector position + * @returns file overwrite enable + */ + int overwriteFile(int enable = -1, int detPos = -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 detPos = -1); + + /** + * (previously setReceiverReadTimer) + * Sets the receiver streaming timer + * If receiver streaming frequency is 0, then this timer between each + * data stream is set. Default is 200 ms. + * @param time_in_ms timer between frames + * @param detPos -1 for all detectors in list or specific detector position + * @returns receiver streaming timer in ms + */ + int setReceiverStreamingTimer(int time_in_ms = 500, int detPos = -1); + + /** + * Enable data streaming to client + * @param enable 0 to disable, 1 to enable, -1 to get the value + * @returns data streaming to client enable + */ + int enableDataStreamingToClient(int enable = -1); + + /** + * Enable or disable streaming data from receiver to client + * @param enable 0 to disable 1 to enable -1 to only get the value + * @param detPos -1 for all detectors in list or specific detector position + * @returns data streaming from receiver enable + */ + int enableDataStreamingFromReceiver(int enable = -1, int detPos = -1); + + /** + * Enable/disable or 10Gbe + * @param i is -1 to get, 0 to disable and 1 to enable + * @param detPos -1 for all detectors in list or specific detector position + * @returns if 10Gbe is enabled + */ + int enableTenGigabitEthernet(int i = -1, int detPos = -1); + + /** + * Set/get receiver fifo depth + * @param i is -1 to get, any other value to set the fifo deph + * @param detPos -1 for all detectors in list or specific detector position + * @returns the receiver fifo depth + */ + int setReceiverFifoDepth(int i = -1, int detPos = -1); + + /** + * Set/get receiver silent mode + * @param i is -1 to get, 0 unsets silent mode, 1 sets silent mode + * @param detPos -1 for all detectors in list or specific detector position + * @returns the receiver silent mode enable + */ + int setReceiverSilentMode(int i = -1, int detPos = -1); + + /** + * Opens pattern file and sends pattern to CTB + * @param fname pattern file to open + * @param detPos -1 for all detectors in list or specific detector position + * @returns OK/FAIL + */ + int setCTBPattern(std::string fname, int detPos = -1); + + /** + * 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 + * @param detPos -1 for all detectors in list or specific detector position + * @returns actual value + */ + uint64_t setCTBWord(int addr, uint64_t word = -1, int detPos = -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 + * @param stop stop address if >=0 + * @param n number of loops (if level >=0) + * @param detPos -1 for all detectors in list or specific detector position + * @returns OK/FAIL + */ + int setCTBPatLoops(int level, int &start, int &stop, int &n, + int detPos = -1); + + /** + * Sets the wait address in the CTB + * @param level 0,1,2, wait level + * @param addr wait address, -1 gets + * @param detPos -1 for all detectors in list or specific detector position + * @returns actual value + */ + int setCTBPatWaitAddr(int level, int addr = -1, int detPos = -1); + + /** + * Sets the wait time in the CTB + * @param level 0,1,2, wait level + * @param t wait time, -1 gets + * @param detPos -1 for all detectors in list or specific detector position + * @returns actual value + */ + int setCTBPatWaitTime(int level, uint64_t t = -1, int detPos = -1); + + /** + * Loads the detector setup from file + * @param fname file to read from + * @param level if 2 reads also reads trimbits, angular conversion + * coefficients etc. from files with default extensions as generated by + * dumpDetectorSetup + * @returns OK or FAIL + */ + int retrieveDetectorSetup(const std::string &fname, int level = 0); + + /** + * Saves the detector setup to file + * @param fname file to write to + * @param level if 2 reads also trimbits, flat field, angular correction + * etc. and writes them to files with automatically added extension + * @returns OK or FAIL + */ + int dumpDetectorSetup(const std::string &fname, int level = 0); + + /** + * register callback for accessing acquisition final data + * @param func function to be called at the end of the acquisition. + * gets detector status and progress index as arguments + * @param pArg argument + */ + void registerAcquisitionFinishedCallback(int (*func)(double, int, void *), + void *pArg); + + /** + * register callback for accessing measurement final data + * @param func function to be called at the end of the acquisition. + * gets detector status and progress index as arguments + * @param pArg argument + */ + void registerMeasurementFinishedCallback(int (*func)(int, int, void *), + void *pArg); + + /** + * register callback for accessing detector progress + * @param func function to be called at the end of the acquisition. + * gets detector status and progress index as arguments + * @param pArg argument + */ + void registerProgressCallback(int (*func)(double, void *), void *pArg); + + /** + * register calbback for accessing detector final data, + * also enables data streaming in client and receiver + * @param userCallback function for plotting/analyzing the data. + * Its arguments are + * the data structure d and the frame number f, + * s is for subframe number for eiger for 32 bit mode + * @param pArg argument + */ + void registerDataCallback(int (*userCallback)(detectorData *, int, int, + void *), + void *pArg); + + /** + * Performs a complete acquisition + * resets frames caught in receiver, starts receiver, starts detector, + * blocks till detector finished acquisition, stop receiver, increments file + * index, loops for measurements, calls required call backs. + * @returns OK or FAIL depending on if it already started + */ + int acquire(); + + /** + * Returns true if detector position is out of bounds + */ + bool isDetectorIndexOutOfBounds(int detPos); + + /** + * Combines data from all readouts and gives it to the gui + * or just gives progress of acquisition by polling receivers + */ + void processData(); + + private: + /** + * Initialize (open/create) shared memory for the sharedMultiDetector + * structure + * @param verify true to verify if shm size matches existing one + * @param update true to update last user pid, date etc + * @returns true if shared memory was created in this call, else false + */ + void initSharedMemory(bool verify = true); + + /** + * Initialize detector structure for the shared memory just created + */ + void initializeDetectorStructure(); + + /** + * Initialize class members (and from parent classes) + * @param verify true to verify if shm size matches existing one + */ + void initializeMembers(bool verify = true); + + /** + * Update user details in detector structure + */ + void updateUserdetails(); + + /** + * Execute in command line and return result + * @param cmd command + * @returns result + */ + std::string exec(const char *cmd); + + /** + * Add sls detector + * @param s hostname of the single detector + */ + void addSlsDetector(std::string s); + + /** + * add gap pixels to the image (only for Eiger in 4 bit mode) + * @param image pointer to image without gap pixels + * @param gpImage poiner to image with gap pixels, if NULL, allocated inside + * function + * @returns number of data bytes of image with gap pixels + */ + int processImageWithGapPixels(char *image, char *&gpImage); + + /** + * Set total progress (total number of frames/images in an acquisition) + * @returns total progress + */ + int setTotalProgress(); + + /** + * Get progress in current acquisition + * @returns current progress + */ + double getCurrentProgress(); + + /** + * Increment progress by one + */ + void incrementProgress(); + + /** + * Set current progress to argument + * @param i current progress + */ + void setCurrentProgress(int i = 0); + + /** + * Start data processing thread + */ + void startProcessingThread(); + + // /** + // * Static function to call processing thread + // */ + // static void* startProcessData(void *n); + + /** + * Check if processing thread is ready to join main thread + * @returns true if ready, else false + */ + bool getJoinThreadFlag() const; + + /** + * Main thread sets if the processing thread should join it + * @param v true if it should join, else false + */ + void setJoinThreadFlag(bool value); + + /** + * Listen to key event to stop acquiring + * when using acquire command + */ + int kbhit(void); + + /** Multi detector Id */ + int detId; + + /** Shared Memory object */ + SharedMemory *sharedMemory; + + /** Shared memory structure */ + sharedMultiSlsDetector *thisMultiDetector; + + /** pointers to the slsDetector structures */ + std::vector> detectors; + + /** data streaming (down stream) enabled in client (zmq sckets created) */ + bool client_downstream; + + /** ZMQ Socket - Receiver to Client */ + std::vector> zmqSocket; + + /** semaphore to let postprocessing thread continue for next + * scan/measurement */ + sem_t sem_newRTAcquisition; + + /** semaphore to let main thread know it got all the dummy packets (also + * from ext. process) */ + sem_t sem_endRTAcquisition; + + /** Total number of frames/images for next acquisition */ + int totalProgress; + + /** Current progress or frames/images processed in current acquisition */ + int progressIndex; + + /** mutex to synchronize main and data processing threads */ + mutable std::mutex mp; + + /** mutex to synchronizedata processing and plotting threads */ + mutable std::mutex mg; + + /** sets when the acquisition is finished */ + bool jointhread; + + /** set when detector finishes acquiring */ + int acquiringDone; - /** - * Start data processing thread - */ - void startProcessingThread(); - - // /** - // * Static function to call processing thread - // */ - // static void* startProcessData(void *n); - - /** - * Check if processing thread is ready to join main thread - * @returns true if ready, else false - */ - bool getJoinThreadFlag() const; - - /** - * Main thread sets if the processing thread should join it - * @param v true if it should join, else false - */ - void setJoinThreadFlag(bool value); - - /** - * Listen to key event to stop acquiring - * when using acquire command - */ - int kbhit(void); - - - /** Multi detector Id */ - int detId; - - /** Shared Memory object */ - SharedMemory* sharedMemory; - - /** Shared memory structure */ - sharedMultiSlsDetector *thisMultiDetector; - - /** pointers to the slsDetector structures */ - std::vector > detectors; - - /** data streaming (down stream) enabled in client (zmq sckets created) */ - bool client_downstream; - - /** ZMQ Socket - Receiver to Client */ - std::vector > zmqSocket; - - - /** semaphore to let postprocessing thread continue for next scan/measurement */ - sem_t sem_newRTAcquisition; - - /** semaphore to let main thread know it got all the dummy packets (also from ext. process) */ - sem_t sem_endRTAcquisition; - - /** Total number of frames/images for next acquisition */ - int totalProgress; - - /** Current progress or frames/images processed in current acquisition */ - int progressIndex; - - /** mutex to synchronize main and data processing threads */ - mutable std::mutex mp; - - /** mutex to synchronizedata processing and plotting threads */ - mutable std::mutex mg; - - /** sets when the acquisition is finished */ - bool jointhread; - - /** set when detector finishes acquiring */ - int acquiringDone; - - /** the data processing thread */ - // pthread_t dataProcessingThread; - std::thread dataProcessingThread; - - /** gui data */ - double *fdata; - - /** detector data packed for the gui */ - detectorData *thisData; - - int (*acquisition_finished)(double,int,void*); - void *acqFinished_p; - - int (*measurement_finished)(int,int,void*); - void *measFinished_p; - - int (*progress_call)(double,void*); - void *pProgressCallArg; - - int (*dataReady)(detectorData*,int, int, void*); - void *pCallbackArg; + /** the data processing thread */ + // pthread_t dataProcessingThread; + std::thread dataProcessingThread; + /** gui data */ + double *fdata; + /** detector data packed for the gui */ + detectorData *thisData; + int (*acquisition_finished)(double, int, void *); + void *acqFinished_p; + int (*measurement_finished)(int, int, void *); + void *measFinished_p; + int (*progress_call)(double, void *); + void *pProgressCallArg; + int (*dataReady)(detectorData *, int, int, void *); + void *pCallbackArg; }; - - #endif From 5671f1c87b0bc605ae2ba0f9fceda65af9d04d9e Mon Sep 17 00:00:00 2001 From: Erik Frojdh Date: Fri, 19 Oct 2018 10:30:31 +0200 Subject: [PATCH 17/18] using split in add multiple detectors --- .../multiSlsDetector/multiSlsDetector.cpp | 18 ++---------------- 1 file changed, 2 insertions(+), 16 deletions(-) diff --git a/slsDetectorSoftware/multiSlsDetector/multiSlsDetector.cpp b/slsDetectorSoftware/multiSlsDetector/multiSlsDetector.cpp index 21e60e3ad..82d79f1d5 100644 --- a/slsDetectorSoftware/multiSlsDetector/multiSlsDetector.cpp +++ b/slsDetectorSoftware/multiSlsDetector/multiSlsDetector.cpp @@ -462,23 +462,9 @@ std::string multiSlsDetector::getHostname(int detPos) { } void multiSlsDetector::addMultipleDetectors(const char *name) { - size_t p1 = 0; - std::string temp = std::string(name); - size_t p2 = temp.find('+', p1); - // single - if (p2 == std::string::npos) { - addSlsDetector(temp); - } - // multi - else { - while (p2 != std::string::npos) { - addSlsDetector(temp.substr(p1, p2 - p1)); - temp = temp.substr(p2 + 1); - p2 = temp.find('+'); - } - } + for (const auto &hostname : sls::split(name, '+')) + addSlsDetector(hostname); - // a get to update shared memory online flag setOnline(); updateOffsets(); } From ab2eb607c869b69e83f27bd15a5d9275075e8fdd Mon Sep 17 00:00:00 2001 From: Erik Frojdh Date: Fri, 19 Oct 2018 15:47:36 +0200 Subject: [PATCH 18/18] replced usleep with chrono and thread --- slsDetectorSoftware/multiSlsDetector/multiSlsDetector.cpp | 5 +++-- 1 file changed, 3 insertions(+), 2 deletions(-) diff --git a/slsDetectorSoftware/multiSlsDetector/multiSlsDetector.cpp b/slsDetectorSoftware/multiSlsDetector/multiSlsDetector.cpp index 82d79f1d5..98eee7127 100644 --- a/slsDetectorSoftware/multiSlsDetector/multiSlsDetector.cpp +++ b/slsDetectorSoftware/multiSlsDetector/multiSlsDetector.cpp @@ -22,6 +22,7 @@ #include "container_utils.h" #include #include +#include multiSlsDetector::multiSlsDetector(int id, bool verify, bool update) : detId(id), sharedMemory(0), thisMultiDetector(0), @@ -3726,8 +3727,8 @@ void multiSlsDetector::processData() { if (getJoinThreadFlag()) { break; } - usleep(100 * 1000); // 20ms need this else connecting error to - // receiver (too fast) + //otherwise error when connecting to the receiver too fast + std::this_thread::sleep_for(std::chrono::milliseconds(100)); } } }