Merge branch 'developer' of github.com:slsdetectorgroup/slsDetectorPackage into developer

This commit is contained in:
Erik Frojdh 2019-12-03 10:12:58 +01:00
commit 9bc60518d8
24 changed files with 645 additions and 1050 deletions

View File

@ -462,7 +462,6 @@ class multiSlsDetector : public virtual slsDetectorDefs {
bool jointhread{false}; bool jointhread{false};
/** the data processing thread */ /** the data processing thread */
// pthread_t dataProcessingThread;
std::thread dataProcessingThread; std::thread dataProcessingThread;
/** detector data packed for the gui */ /** detector data packed for the gui */

View File

@ -51,17 +51,15 @@ class BinaryFile : private virtual slsDetectorDefs, public File, public BinaryFi
/** /**
* Create file * Create file
* @returns OK or FAIL
*/ */
int CreateFile() override; void CreateFile() override;
/** /**
* Create master file * Create master file
* @param mfwenable master file write enable * @param mfwenable master file write enable
* @param attr master file attributes * @param attr master file attributes
* @returns OK or FAIL
*/ */
int CreateMasterFile(bool mfwenable, masterAttributes& attr) override; void CreateMasterFile(bool mfwenable, masterAttributes& attr) override;
/** /**
* Close Current File * Close Current File
@ -79,9 +77,8 @@ class BinaryFile : private virtual slsDetectorDefs, public File, public BinaryFi
* @param buffersize size of buffer * @param buffersize size of buffer
* @param fnum current image number * @param fnum current image number
* @param nump number of packets caught * @param nump number of packets caught
* @returns OK or FAIL
*/ */
int WriteToFile(char* buffer, int buffersize, uint64_t fnum, uint32_t nump) override; void WriteToFile(char* buffer, int buffersize, uint64_t fnum, uint32_t nump) override;

View File

@ -98,23 +98,20 @@ class BinaryFileStatic {
* @param fname master file name * @param fname master file name
* @param owenable overwrite enable * @param owenable overwrite enable
* @param attr master file attributes * @param attr master file attributes
* @returns 0 for success and 1 for fail
*/ */
static int CreateMasterDataFile(FILE*& fd, std::string fname, bool owenable, static void CreateMasterDataFile(FILE*& fd, std::string fname, bool owenable,
masterAttributes& attr) masterAttributes& attr)
{ {
if(!owenable){ if(!owenable){
if (NULL == (fd = fopen((const char *) fname.c_str(), "wx"))){ if (NULL == (fd = fopen((const char *) fname.c_str(), "wx"))){
FILE_LOG(logERROR) << "Could not create binary master file "
"(without overwrite enable) " << fname;
fd = 0; fd = 0;
return 1; throw sls::RuntimeError("Could not create binary master file "
"(without overwrite enable) " + fname);
} }
}else if (NULL == (fd = fopen((const char *) fname.c_str(), "w"))){ }else if (NULL == (fd = fopen((const char *) fname.c_str(), "w"))){
FILE_LOG(logERROR) << "Could not create binary master file "
"(with overwrite enable) " << fname;
fd = 0; fd = 0;
return 1; throw sls::RuntimeError("Could not create binary master file "
"(with overwrite enable) " + fname);
} }
time_t t = time(0); time_t t = time(0);
char message[MAX_MASTER_FILE_LENGTH]; char message[MAX_MASTER_FILE_LENGTH];
@ -182,16 +179,15 @@ class BinaryFileStatic {
attr.roiXmax, attr.roiXmax,
ctime(&t)); ctime(&t));
if (strlen(message) > MAX_MASTER_FILE_LENGTH) { if (strlen(message) > MAX_MASTER_FILE_LENGTH) {
FILE_LOG(logERROR) << "Master File Size " << strlen(message) << throw sls::RuntimeError("Master File Size " + std::to_string(strlen(message)) +
" is greater than max str size " << MAX_MASTER_FILE_LENGTH; " is greater than max str size " + std::to_string(MAX_MASTER_FILE_LENGTH));
return 1;
} }
if (fwrite((void*)message, 1, strlen(message), fd) != strlen(message)) if (fwrite((void*)message, 1, strlen(message), fd) != strlen(message)) {
return 1; throw sls::RuntimeError("Master binary file incorrect number of bytes written to file");
}
BinaryFileStatic::CloseDataFile(fd); BinaryFileStatic::CloseDataFile(fd);
return 0;
} }
@ -203,22 +199,19 @@ class BinaryFileStatic {
* @param filebuffersize file buffer size * @param filebuffersize file buffer size
* @returns 0 for success and 1 for fail * @returns 0 for success and 1 for fail
*/ */
static int CreateDataFile(FILE*& fd, bool owenable, std::string fname, size_t filebuffersize) static void CreateDataFile(FILE*& fd, bool owenable, std::string fname, size_t filebuffersize)
{ {
if(!owenable){ if(!owenable){
if (NULL == (fd = fopen((const char *) fname.c_str(), "wx"))){ if (NULL == (fd = fopen((const char *) fname.c_str(), "wx"))){
FILE_LOG(logERROR) << "Could not create/overwrite file" << fname;
fd = 0; fd = 0;
return 1; throw sls::RuntimeError("Could not create/overwrite file " + fname);
} }
} else if (NULL == (fd = fopen((const char *) fname.c_str(), "w"))){ } else if (NULL == (fd = fopen((const char *) fname.c_str(), "w"))){
FILE_LOG(logERROR) << "Could not create file" << fname;
fd = 0; fd = 0;
return 1; throw sls::RuntimeError("Could not create file " + fname);
} }
//setting file buffer size to 16mb //setting file buffer size to 16mb
setvbuf(fd,NULL,_IOFBF,filebuffersize); setvbuf(fd,NULL,_IOFBF,filebuffersize);
return 0;
} }
}; };

View File

@ -6,7 +6,8 @@
class MySocketTCP; class MySocketTCP;
class ServerInterface; class ServerInterface;
#include <atomic>
#include <future>
class ClientInterface : private virtual slsDetectorDefs { class ClientInterface : private virtual slsDetectorDefs {
private: private:
@ -38,17 +39,16 @@ class ClientInterface : private virtual slsDetectorDefs {
void *arg); void *arg);
private: private:
void startTCPSocket();
void stopTCPSocket();
static void *startTCPServerThread(void *this_pointer);
void startTCPServer(); void startTCPServer();
int functionTable();
int function_table(); int decodeFunction(sls::ServerInterface2 &socket);
int decode_function(sls::ServerInterface2 &socket);
void functionNotImplemented(); void functionNotImplemented();
void modeNotImplemented(const std::string& modename, int mode); void modeNotImplemented(const std::string& modename, int mode);
template <typename T> template <typename T>
void validate(T arg, T retval, std::string modename, numberMode hex); void validate(T arg, T retval, std::string modename, numberMode hex);
void verifyLock();
void verifyIdle(sls::ServerInterface2 &socket);
int exec_command(sls::ServerInterface2 &socket); int exec_command(sls::ServerInterface2 &socket);
int exit_server(sls::ServerInterface2 &socket); int exit_server(sls::ServerInterface2 &socket);
@ -120,20 +120,27 @@ class ClientInterface : private virtual slsDetectorDefs {
int set_num_interfaces(sls::ServerInterface2 &socket); int set_num_interfaces(sls::ServerInterface2 &socket);
int set_adc_mask_10g(sls::ServerInterface2 &socket); int set_adc_mask_10g(sls::ServerInterface2 &socket);
Implementation *impl() {
if (receiver != nullptr) {
return receiver.get();
} else {
throw sls::SocketError(
"Receiver not set up. Please use rx_hostname first.\n");
}
}
detectorType myDetectorType; detectorType myDetectorType;
std::unique_ptr<Implementation> receiver{nullptr}; std::unique_ptr<Implementation> receiver{nullptr};
int (ClientInterface::*flist[NUM_REC_FUNCTIONS])( int (ClientInterface::*flist[NUM_REC_FUNCTIONS])(
sls::ServerInterface2 &socket); sls::ServerInterface2 &socket);
int ret{OK}; int ret{OK};
int fnum{-1}; int fnum{-1};
/** Lock Status if server locked to a client */ int lockedByClient{0};
int lockStatus{0}; int portNumber{0};
std::atomic<bool> killTcpThread{false};
std::unique_ptr<std::thread> tcpThread;
int killTCPServerThread{0};
pthread_t TCPServer_thread;
bool tcpThreadCreated{false};
int portNumber;
//***callback parameters*** //***callback parameters***
@ -149,17 +156,4 @@ class ClientInterface : private virtual slsDetectorDefs {
protected: protected:
std::unique_ptr<sls::ServerSocket> server{nullptr}; std::unique_ptr<sls::ServerSocket> server{nullptr};
private:
void VerifyLock();
void VerifyIdle(sls::ServerInterface2 &socket);
Implementation *impl() {
if (receiver != nullptr) {
return receiver.get();
} else {
throw sls::SocketError(
"Receiver not set up. Please use rx_hostname first.\n");
}
}
}; };

View File

@ -118,13 +118,6 @@ class DataProcessor : private virtual slsDetectorDefs, public ThreadObject {
*/ */
void SetGeneralData(GeneralData* g); void SetGeneralData(GeneralData* g);
/**
* Set thread priority
* @priority priority
* @returns OK or FAIL
*/
int SetThreadPriority(int priority);
/** /**
* Set File Format * Set File Format
* @param f file format * @param f file format
@ -155,9 +148,8 @@ class DataProcessor : private virtual slsDetectorDefs, public ThreadObject {
/** /**
* Create New File * Create New File
* @param attr master file attributes * @param attr master file attributes
* @returns OK or FAIL
*/ */
int CreateNewFile(masterAttributes& attr); void CreateNewFile(masterAttributes& attr);
/** /**
* Closes files * Closes files
@ -201,24 +193,12 @@ class DataProcessor : private virtual slsDetectorDefs, public ThreadObject {
private: private:
/**
* Get Type
* @return type
*/
std::string GetType() override;
/** /**
* Record First Index * Record First Index
* @param fnum frame index to record * @param fnum frame index to record
*/ */
void RecordFirstIndex(uint64_t fnum); void RecordFirstIndex(uint64_t fnum);
/**
* Destroy file writer object
* @return OK or FAIL
*/
void DestroyFileWriter();
/** /**
* Thread Exeution for DataProcessor Class * Thread Exeution for DataProcessor Class
* Pop bound addresses, process them, * Pop bound addresses, process them,

View File

@ -79,13 +79,6 @@ class DataStreamer : private virtual slsDetectorDefs, public ThreadObject {
*/ */
void SetGeneralData(GeneralData* g); void SetGeneralData(GeneralData* g);
/**
* Set thread priority
* @priority priority
* @returns OK or FAIL
*/
int SetThreadPriority(int priority);
/** /**
* Set number of detectors * Set number of detectors
* @param number of detectors in both dimensions * @param number of detectors in both dimensions
@ -114,19 +107,12 @@ class DataStreamer : private virtual slsDetectorDefs, public ThreadObject {
/** /**
* Restream stop dummy packet * Restream stop dummy packet
* @return OK or FAIL
*/ */
int RestreamStop(); void RestreamStop();
private: private:
/**
* Get Type
* @return type
*/
std::string GetType();
/** /**
* Record First Index * Record First Index
* @param fnum frame index to record * @param fnum frame index to record

View File

@ -78,9 +78,8 @@ class Fifo : private virtual slsDetectorDefs {
/** /**
* Create Fifos, allocate memory & push addresses into fifo * Create Fifos, allocate memory & push addresses into fifo
* @param fifoItemSize size of each fifo item * @param fifoItemSize size of each fifo item
* @return OK if successful, else FAIL
*/ */
int CreateFifos(uint32_t fifoItemSize); void CreateFifos(uint32_t fifoItemSize);
/** /**
* Destroy Fifos and deallocate memory * Destroy Fifos and deallocate memory

View File

@ -84,9 +84,8 @@ class File : private virtual slsDetectorDefs {
/** /**
* Create file * Create file
* @returns OK or FAIL
*/ */
virtual int CreateFile() = 0; virtual void CreateFile() = 0;
/** /**
* Close Current File * Close Current File
@ -103,17 +102,15 @@ class File : private virtual slsDetectorDefs {
* @param buffer buffer to write from * @param buffer buffer to write from
* @param fnum current image number * @param fnum current image number
* @param nump number of packets caught * @param nump number of packets caught
* @param OK or FAIL
*/ */
virtual int WriteToFile(char* buffer, int buffersize, uint64_t fnum, uint32_t nump) = 0; virtual void WriteToFile(char* buffer, int buffersize, uint64_t fnum, uint32_t nump) = 0;
/** /**
* Create master file * Create master file
* @param mfwenable master file write enable * @param mfwenable master file write enable
* @param attr master file attributes * @param attr master file attributes
* @returns OK or FAIL
*/ */
virtual int CreateMasterFile(bool mfwenable, masterAttributes& attr) = 0; virtual void CreateMasterFile(bool mfwenable, masterAttributes& attr) = 0;
// HDf5 specific // HDf5 specific
/** /**

View File

@ -17,6 +17,7 @@
#ifndef H5_NO_NAMESPACE #ifndef H5_NO_NAMESPACE
using namespace H5; using namespace H5;
#endif #endif
#include <mutex>
class HDF5File : private virtual slsDetectorDefs, public File, public HDF5FileStatic { class HDF5File : private virtual slsDetectorDefs, public File, public HDF5FileStatic {
@ -67,9 +68,8 @@ class HDF5File : private virtual slsDetectorDefs, public File, public HDF5FileSt
/** /**
* Create file * Create file
* @param fnum current frame index to include in file name * @param fnum current frame index to include in file name
* @returns OK or FAIL
*/ */
int CreateFile(); void CreateFile();
/** /**
* Close Current File * Close Current File
@ -87,17 +87,15 @@ class HDF5File : private virtual slsDetectorDefs, public File, public HDF5FileSt
* @param bsize size of buffer (not used) * @param bsize size of buffer (not used)
* @param fnum current image number * @param fnum current image number
* @param nump number of packets caught * @param nump number of packets caught
* @returns OK or FAIL
*/ */
int WriteToFile(char* buffer, int bsize, uint64_t fnum, uint32_t nump); void WriteToFile(char* buffer, int bsize, uint64_t fnum, uint32_t nump);
/** /**
* Create master file * Create master file
* @param mfwenable master file write enable * @param mfwenable master file write enable
* @param attr master file attributes * @param attr master file attributes
* @returns OK or FAIL
*/ */
int CreateMasterFile(bool mfwenable, masterAttributes& attr); void CreateMasterFile(bool mfwenable, masterAttributes& attr);
/** /**
* End of Acquisition * End of Acquisition
@ -112,16 +110,14 @@ class HDF5File : private virtual slsDetectorDefs, public File, public HDF5FileSt
/** /**
* Create Virtual File * Create Virtual File
* @param numf number of images caught * @param numf number of images caught
* @returns OK or FAIL
*/ */
int CreateVirtualFile(uint64_t numf); void CreateVirtualFile(uint64_t numf);
/** /**
* Link virtual file in master file * Link virtual file in master file
* Only for Jungfrau at the moment for 1 module and 1 data file * Only for Jungfrau at the moment for 1 module and 1 data file
* @returns OK or FAIL
*/ */
int LinkVirtualFileinMasterFile(); void LinkVirtualFileinMasterFile();
/** /**
* Get Type * Get Type
@ -135,9 +131,8 @@ class HDF5File : private virtual slsDetectorDefs, public File, public HDF5FileSt
void UpdateDataType(); void UpdateDataType();
/** mutex to update static items among objects (threads)*/ /** mutex to update static items among objects (threads)*/
static pthread_mutex_t Mutex; static mutable std::mutex mutex;
/** Master File handle */ /** Master File handle */
static H5File* masterfd; static H5File* masterfd;

View File

@ -156,9 +156,8 @@ public:
* @param dspace dataspace pointer * @param dspace dataspace pointer
* @param dset dataset pointer * @param dset dataset pointer
* @param dtype datatype * @param dtype datatype
* @returns 0 for success and 1 for fail
*/ */
static int WriteDataFile(int ind, char* buf, static void WriteDataFile(int ind, char* buf,
uint64_t nDimx, uint32_t nDimy, uint32_t nDimz, uint64_t nDimx, uint32_t nDimy, uint32_t nDimz,
DataSpace* dspace, DataSet* dset, DataType dtype) DataSpace* dspace, DataSet* dset, DataType dtype)
{ {
@ -176,9 +175,8 @@ public:
catch(const Exception& error){ catch(const Exception& error){
FILE_LOG(logERROR) << "Could not write to file in object " << ind; FILE_LOG(logERROR) << "Could not write to file in object " << ind;
error.printErrorStack(); error.printErrorStack();
return 1; throw RuntimeError("Could not write to file in object " + std::to_string(ind));
} }
return 0;
} }
@ -192,7 +190,7 @@ public:
* @param rheader sls_receiver_header pointer * @param rheader sls_receiver_header pointer
* @param parameterDataTypes parameter datatypes * @param parameterDataTypes parameter datatypes
*/ */
static int WriteParameterDatasets(int ind, DataSpace* dspace_para, uint64_t fnum, static void WriteParameterDatasets(int ind, DataSpace* dspace_para, uint64_t fnum,
std::vector <DataSet*> dset_para,sls_receiver_header* rheader, std::vector <DataSet*> dset_para,sls_receiver_header* rheader,
std::vector <DataType> parameterDataTypes) std::vector <DataType> parameterDataTypes)
{ {
@ -236,11 +234,9 @@ public:
}i=14; }i=14;
} }
catch(const Exception& error){ catch(const Exception& error){
FILE_LOG(logERROR) << "Could not write parameters (index:" << i << ") to file in object " << ind;
error.printErrorStack(); error.printErrorStack();
return 1; throw RuntimeError("Could not write parameters (index:" + std::to_string(i) + ") to file in object " + std::to_string(ind));
} }
return 0;
} }
@ -253,9 +249,8 @@ public:
* @param dspace_para parameter dataspace address pointer * @param dspace_para parameter dataspace address pointer
* @param dset dataset parameter pointer * @param dset dataset parameter pointer
* @param initialNumImages initial number of images * @param initialNumImages initial number of images
* @returns 0 for success and 1 for fail
*/ */
static int ExtendDataset(int ind, DataSpace*& dspace, DataSet* dset, static void ExtendDataset(int ind, DataSpace*& dspace, DataSet* dset,
DataSpace*& dspace_para, std::vector <DataSet*> dset_para, DataSpace*& dspace_para, std::vector <DataSet*> dset_para,
uint64_t initialNumImages) { uint64_t initialNumImages) {
try{ try{
@ -279,11 +274,9 @@ public:
} }
catch(const Exception& error){ catch(const Exception& error){
FILE_LOG(logERROR) << "Could not extend dataset in object " << ind;
error.printErrorStack(); error.printErrorStack();
return 1; throw RuntimeError("Could not extend dataset in object " + std::to_string(ind));
} }
return 0;
} }
@ -292,9 +285,8 @@ public:
* @param fname master file name * @param fname master file name
* @param owenable overwrite enable * @param owenable overwrite enable
* @param attr master file attributes * @param attr master file attributes
* @returns 0 for success and 1 for fail
*/ */
static int CreateMasterDataFile(H5File*& fd, std::string fname, bool owenable, static void CreateMasterDataFile(H5File*& fd, std::string fname, bool owenable,
masterAttributes& attr) masterAttributes& attr)
{ {
try { try {
@ -443,12 +435,10 @@ public:
fd->close(); fd->close();
} catch(const Exception& error) { } catch(const Exception& error) {
FILE_LOG(logERROR) << "Could not create master HDF5 handles";
error.printErrorStack(); error.printErrorStack();
if (fd) fd->close(); if (fd) fd->close();
return 1; throw RuntimeError("Could not create master HDF5 handles");
} }
return 0;
} }
@ -473,9 +463,8 @@ public:
* @param dset_para vector of datasets of parameters * @param dset_para vector of datasets of parameters
* @param parameterNames parameter names * @param parameterNames parameter names
* @param parameterDataTypes parameter datatypes * @param parameterDataTypes parameter datatypes
* @returns 0 for success and 1 for fail
*/ */
static int CreateDataFile(int ind, bool owenable, std::string fname, bool frindexenable, static void CreateDataFile(int ind, bool owenable, std::string fname, bool frindexenable,
uint64_t fnum, uint64_t nDimx, uint32_t nDimy, uint32_t nDimz, uint64_t fnum, uint64_t nDimx, uint32_t nDimy, uint32_t nDimz,
DataType dtype, H5File*& fd, DataSpace*& dspace, DataSet*& dset, DataType dtype, H5File*& fd, DataSpace*& dspace, DataSet*& dset,
double version, uint64_t maxchunkedimages, double version, uint64_t maxchunkedimages,
@ -547,12 +536,10 @@ public:
} }
} }
catch(const Exception& error){ catch(const Exception& error){
FILE_LOG(logERROR) << "Could not create HDF5 handles in object " << ind;
error.printErrorStack(); error.printErrorStack();
if (fd) fd->close(); if (fd) fd->close();
return 1; throw RuntimeError("Could not create HDF5 handles in object " + ind);
} }
return 0;
} }
@ -579,9 +566,8 @@ public:
* @param version version of software for hdf5 writing * @param version version of software for hdf5 writing
* @param parameterNames parameter names * @param parameterNames parameter names
* @param parameterDataTypes parameter datatypes * @param parameterDataTypes parameter datatypes
* @returns 0 for success and 1 for fail
*/ */
static int CreateVirtualDataFile( static void CreateVirtualDataFile(
std::string virtualFileName, std::string virtualFileName,
hid_t& fd, std::string masterFileName, hid_t& fd, std::string masterFileName,
std::string fpath, std::string fnameprefix, uint64_t findex, bool frindexenable, std::string fpath, std::string fnameprefix, uint64_t findex, bool frindexenable,
@ -593,86 +579,61 @@ public:
std::vector <const char*> parameterNames, std::vector <const char*> parameterNames,
std::vector <DataType> parameterDataTypes) std::vector <DataType> parameterDataTypes)
{ {
try {
//file //file
hid_t dfal = H5Pcreate (H5P_FILE_ACCESS); hid_t dfal = H5Pcreate (H5P_FILE_ACCESS);
if (dfal < 0) if (dfal < 0)
return CloseFileOnError(fd, throw RuntimeError("Could not create file access property for virtual file " + virtualFileName);
std::string("Could not create file access property for virtual file ")
+ virtualFileName + std::string("\n"));
if (H5Pset_fclose_degree (dfal, H5F_CLOSE_STRONG) < 0) if (H5Pset_fclose_degree (dfal, H5F_CLOSE_STRONG) < 0)
return CloseFileOnError(fd, throw RuntimeError("Could not set strong file close degree for virtual file " + virtualFileName);
std::string("Could not set strong file close degree for virtual file ")
+ virtualFileName + std::string("\n"));
fd = H5Fcreate( virtualFileName.c_str(), H5F_ACC_TRUNC, H5P_DEFAULT, dfal); fd = H5Fcreate( virtualFileName.c_str(), H5F_ACC_TRUNC, H5P_DEFAULT, dfal);
if (fd < 0) if (fd < 0)
return CloseFileOnError(fd, throw RuntimeError("Could not create virtual file " + virtualFileName);
std::string("Could not create virtual file ") + virtualFileName + std::string("\n"));
//attributes - version //attributes - version
hid_t dataspace_attr = H5Screate (H5S_SCALAR); hid_t dataspace_attr = H5Screate (H5S_SCALAR);
if (dataspace_attr < 0) if (dataspace_attr < 0)
return CloseFileOnError(fd, throw RuntimeError("Could not create dataspace for attribute in virtual file " + virtualFileName);
std::string("Could not create dataspace for attribute in virtual file ")
+ virtualFileName + std::string("\n"));
hid_t attrid = H5Acreate2 (fd, "version", H5T_NATIVE_DOUBLE, dataspace_attr, H5P_DEFAULT, H5P_DEFAULT); hid_t attrid = H5Acreate2 (fd, "version", H5T_NATIVE_DOUBLE, dataspace_attr, H5P_DEFAULT, H5P_DEFAULT);
if (attrid < 0) if (attrid < 0)
return CloseFileOnError(fd, throw RuntimeError("Could not create attribute in virtual file " + virtualFileName);
std::string("Could not create attribute in virtual file ")
+ virtualFileName + std::string("\n"));
double attr_data = version; double attr_data = version;
if (H5Awrite (attrid, H5T_NATIVE_DOUBLE, &attr_data) < 0) if (H5Awrite (attrid, H5T_NATIVE_DOUBLE, &attr_data) < 0)
return CloseFileOnError(fd, throw RuntimeError("Could not write attribute in virtual file " + virtualFileName);
std::string("Could not write attribute in virtual file ")
+ virtualFileName + std::string("\n"));
if (H5Aclose (attrid) < 0) if (H5Aclose (attrid) < 0)
return CloseFileOnError(fd, throw RuntimeError("Could not close attribute in virtual file " + virtualFileName);
std::string("Could not close attribute in virtual file ")
+ virtualFileName + std::string("\n"));
//virtual dataspace //virtual dataspace
hsize_t vdsdims[3] = {numf, numDety * nDimy, numDetz * nDimz}; hsize_t vdsdims[3] = {numf, numDety * nDimy, numDetz * nDimz};
hid_t vdsDataspace = H5Screate_simple(3, vdsdims ,NULL); hid_t vdsDataspace = H5Screate_simple(3, vdsdims ,NULL);
if (vdsDataspace < 0) if (vdsDataspace < 0)
return CloseFileOnError(fd, throw RuntimeError("Could not create virtual dataspace in virtual file " + virtualFileName);
std::string("Could not create virtual dataspace in virtual file ")
+ virtualFileName + std::string("\n"));
hsize_t vdsdims_para[2] = {numf, (unsigned int) numDety * numDetz}; hsize_t vdsdims_para[2] = {numf, (unsigned int) numDety * numDetz};
hid_t vdsDataspace_para = H5Screate_simple(2, vdsdims_para, NULL); hid_t vdsDataspace_para = H5Screate_simple(2, vdsdims_para, NULL);
if (vdsDataspace_para < 0) if (vdsDataspace_para < 0)
return CloseFileOnError(fd, throw RuntimeError("Could not create virtual dataspace (parameters) in virtual file " + virtualFileName);
std::string("Could not create virtual dataspace (parameters) in virtual file ")
+ virtualFileName + std::string("\n"));
//fill values //fill values
hid_t dcpl = H5Pcreate (H5P_DATASET_CREATE); hid_t dcpl = H5Pcreate (H5P_DATASET_CREATE);
if (dcpl < 0) if (dcpl < 0)
return CloseFileOnError(fd, throw RuntimeError("Could not create file creation properties in virtual file " + virtualFileName);
std::string("Could not create file creation properties in virtual file ")
+ virtualFileName + std::string("\n"));
int fill_value = -1; int fill_value = -1;
if (H5Pset_fill_value (dcpl, GetDataTypeinC(dataType), &fill_value) < 0) if (H5Pset_fill_value (dcpl, GetDataTypeinC(dataType), &fill_value) < 0)
return CloseFileOnError(fd, throw RuntimeError("Could not create fill value in virtual file " + virtualFileName);
std::string("Could not create fill value in virtual file ")
+ virtualFileName + std::string("\n"));
hid_t dcpl_para[parameterNames.size()]; hid_t dcpl_para[parameterNames.size()];
for (unsigned int i = 0; i < parameterNames.size(); ++i) { for (unsigned int i = 0; i < parameterNames.size(); ++i) {
dcpl_para[i] = H5Pcreate (H5P_DATASET_CREATE); dcpl_para[i] = H5Pcreate (H5P_DATASET_CREATE);
if (dcpl_para[i] < 0) if (dcpl_para[i] < 0)
return CloseFileOnError(fd, throw RuntimeError("Could not create file creation properties (parameters) in virtual file " + virtualFileName);
std::string("Could not create file creation properties (parameters) in virtual file ")
+ virtualFileName + std::string("\n"));
if (H5Pset_fill_value (dcpl_para[i], GetDataTypeinC(parameterDataTypes[i]), &fill_value) < 0) if (H5Pset_fill_value (dcpl_para[i], GetDataTypeinC(parameterDataTypes[i]), &fill_value) < 0)
return CloseFileOnError(fd, throw RuntimeError("Could not create fill value (parameters) in virtual file " + virtualFileName);
std::string("Could not create fill value (parameters) in virtual file ")
+ virtualFileName + std::string("\n"));
} }
//hyperslab //hyperslab
int numMajorHyperslab = numf/maxFramesPerFile; int numMajorHyperslab = numf/maxFramesPerFile;
if (numf%maxFramesPerFile) numMajorHyperslab++; if (numf%maxFramesPerFile) numMajorHyperslab++;
bool error = false;
uint64_t framesSaved = 0; uint64_t framesSaved = 0;
for (int j = 0; j < numMajorHyperslab; j++) { for (int j = 0; j < numMajorHyperslab; j++) {
@ -687,15 +648,11 @@ public:
//setect hyperslabs //setect hyperslabs
if (H5Sselect_hyperslab (vdsDataspace, H5S_SELECT_SET, offset, NULL, count, NULL) < 0) { if (H5Sselect_hyperslab (vdsDataspace, H5S_SELECT_SET, offset, NULL, count, NULL) < 0) {
FILE_LOG(logERROR) << "Could not select hyperslab"; throw RuntimeError("Could not select hyperslab");
error = true;
break;
} }
if (H5Sselect_hyperslab (vdsDataspace_para, H5S_SELECT_SET, if (H5Sselect_hyperslab (vdsDataspace_para, H5S_SELECT_SET,
offset_para, NULL, count_para, NULL) < 0) { offset_para, NULL, count_para, NULL) < 0) {
FILE_LOG(logERROR) << "Could not select hyperslab for parameters"; throw RuntimeError("Could not select hyperslab for parameters");
error = true;
break;
} }
//source file name //source file name
@ -722,31 +679,23 @@ public:
hsize_t srcdimsmax[3] = {H5S_UNLIMITED, nDimy, nDimz}; hsize_t srcdimsmax[3] = {H5S_UNLIMITED, nDimy, nDimz};
hid_t srcDataspace = H5Screate_simple(3, srcdims, srcdimsmax); hid_t srcDataspace = H5Screate_simple(3, srcdims, srcdimsmax);
if (srcDataspace < 0) if (srcDataspace < 0)
return CloseFileOnError(fd, throw RuntimeError("Could not create source dataspace in virtual file " + virtualFileName);
std::string("Could not create source dataspace in virtual file ")
+ virtualFileName + std::string("\n"));
hsize_t srcdims_para[1] = {nDimx}; hsize_t srcdims_para[1] = {nDimx};
hsize_t srcdimsmax_para[1] = {H5S_UNLIMITED}; hsize_t srcdimsmax_para[1] = {H5S_UNLIMITED};
hid_t srcDataspace_para = H5Screate_simple(1, srcdims_para, srcdimsmax_para); hid_t srcDataspace_para = H5Screate_simple(1, srcdims_para, srcdimsmax_para);
if (srcDataspace_para < 0) if (srcDataspace_para < 0)
return CloseFileOnError(fd, throw RuntimeError("Could not create source dataspace (parameters) in virtual file " + virtualFileName);
std::string("Could not create source dataspace (parameters) in virtual file ")
+ virtualFileName + std::string("\n"));
//mapping //mapping
if (H5Pset_virtual(dcpl, vdsDataspace, relative_srcFileName.c_str(), if (H5Pset_virtual(dcpl, vdsDataspace, relative_srcFileName.c_str(),
srcDatasetName.c_str(), srcDataspace) < 0) { srcDatasetName.c_str(), srcDataspace) < 0) {
FILE_LOG(logERROR) << "Could not set mapping for paramter 1"; throw RuntimeError("Could not set mapping for paramter 1");
error = true;
break;
} }
for (unsigned int k = 0; k < parameterNames.size(); ++k) { for (unsigned int k = 0; k < parameterNames.size(); ++k) {
if (H5Pset_virtual(dcpl_para[k], vdsDataspace_para, relative_srcFileName.c_str(), if (H5Pset_virtual(dcpl_para[k], vdsDataspace_para, relative_srcFileName.c_str(),
parameterNames[k], srcDataspace_para) < 0) { parameterNames[k], srcDataspace_para) < 0) {
FILE_LOG(logERROR) << "Could not set mapping for paramter " << k; throw RuntimeError("Could not set mapping for paramter " + std::to_string(k));
error = true;
break;
} }
} }
@ -761,19 +710,13 @@ public:
} }
framesSaved += nDimx; framesSaved += nDimx;
} }
if (error)
return CloseFileOnError(fd,
std::string("Could not map files in virtual file ")
+ virtualFileName + std::string("\n"));
//dataset //dataset
std::string virtualDatasetName = srcDataseName; std::string virtualDatasetName = srcDataseName;
hid_t vdsdataset = H5Dcreate2 (fd, virtualDatasetName.c_str(), hid_t vdsdataset = H5Dcreate2 (fd, virtualDatasetName.c_str(),
GetDataTypeinC(dataType), vdsDataspace, H5P_DEFAULT, dcpl, H5P_DEFAULT); GetDataTypeinC(dataType), vdsDataspace, H5P_DEFAULT, dcpl, H5P_DEFAULT);
if (vdsdataset < 0) if (vdsdataset < 0)
return CloseFileOnError(fd, throw RuntimeError("Could not create virutal dataset in virtual file " + virtualFileName);
std::string("Could not create virutal dataset in virtual file ")
+ virtualFileName + std::string("\n"));
//virtual parameter dataset //virtual parameter dataset
@ -783,16 +726,20 @@ public:
GetDataTypeinC(parameterDataTypes[i]), vdsDataspace_para, GetDataTypeinC(parameterDataTypes[i]), vdsDataspace_para,
H5P_DEFAULT, dcpl_para[i], H5P_DEFAULT); H5P_DEFAULT, dcpl_para[i], H5P_DEFAULT);
if (vdsdataset_para < 0) if (vdsdataset_para < 0)
return CloseFileOnError(fd, throw RuntimeError("Could not create virutal dataset (parameters) in virtual file " + virtualFileName);
std::string("Could not create virutal dataset (parameters) in virtual file ")
+ virtualFileName + std::string("\n"));
} }
//close //close
H5Fclose(fd); fd = 0; H5Fclose(fd);
fd = 0;
//link //link
return LinkVirtualInMaster(masterFileName, virtualFileName, virtualDatasetName, parameterNames); LinkVirtualInMaster(masterFileName, virtualFileName, virtualDatasetName, parameterNames);
} catch (const RuntimeError &e) {
if (fd > 0)
H5Fclose(fd);
fd = 0;
}
} }
@ -809,10 +756,9 @@ public:
* @param nDimx Number of objects in x dimension * @param nDimx Number of objects in x dimension
* @param nDimy Number of objects in y dimension * @param nDimy Number of objects in y dimension
* @param nDimz Number of objects in z dimension * @param nDimz Number of objects in z dimension
* @returns 0 for success and 1 for fail
*/ */
template <typename T> template <typename T>
static int CopyVirtualFile(T datatype, bool owenable, std::string oldFileName, std::string oldDatasetName, static void CopyVirtualFile(T datatype, bool owenable, std::string oldFileName, std::string oldDatasetName,
std::string newFileName, std::string newDatasetName, int rank, std::string newFileName, std::string newDatasetName, int rank,
uint64_t nDimx, uint32_t nDimy, uint32_t nDimz=0) uint64_t nDimx, uint32_t nDimy, uint32_t nDimz=0)
{ {
@ -825,8 +771,7 @@ public:
data_out = (T*)malloc(sizeof(T)*(nDimx*nDimy*nDimz)); data_out = (T*)malloc(sizeof(T)*(nDimx*nDimy*nDimz));
break; break;
default: default:
FILE_LOG(logERROR) << "Invalid rank. Options: 2 or 3"; throw RuntimeError("Invalid rank. Options: 2 or 3");
return 0;
} }
if (datatype == PredType::STD_U16LE) { if (datatype == PredType::STD_U16LE) {
FILE_LOG(logINFO) << "datatype:16"; FILE_LOG(logINFO) << "datatype:16";
@ -837,8 +782,7 @@ public:
} else if (datatype == PredType::STD_U8LE) { } else if (datatype == PredType::STD_U8LE) {
FILE_LOG(logINFO) << "datatype:8"; FILE_LOG(logINFO) << "datatype:8";
} else { } else {
FILE_LOG(logERROR) << "Unknown datatype: " << datatype; throw RuntimeError("Unknown datatype:" + std::to_string(datatype));
return 1;
} }
FILE_LOG(logINFO) << "owenable:" << (owenable?1:0) << std::endl FILE_LOG(logINFO) << "owenable:" << (owenable?1:0) << std::endl
<< "oldFileName:" << oldFileName << std::endl << "oldFileName:" << oldFileName << std::endl
@ -888,15 +832,13 @@ public:
newfd->close(); newfd->close();
oldfd->close(); oldfd->close();
} catch(const Exception& error){ } catch(const Exception& error){
FILE_LOG(logERROR) << "Could not copy virtual files";
error.printErrorStack(); error.printErrorStack();
free(data_out); free(data_out);
oldfd->close(); oldfd->close();
newfd->close(); newfd->close();
return 1; throw RuntimeError("Could not copy virtual files");
} }
free(data_out); free(data_out);
return 0;
} }
@ -908,29 +850,29 @@ public:
* @param virtualfname virtual file name * @param virtualfname virtual file name
* @param virtualDatasetname virtual dataset name * @param virtualDatasetname virtual dataset name
* @param parameterNames parameter names * @param parameterNames parameter names
* @returns 0 for success and 1 for fail
*/ */
static int LinkVirtualInMaster(std::string masterFileName, std::string virtualfname, static void LinkVirtualInMaster(std::string masterFileName, std::string virtualfname,
std::string virtualDatasetname, std::vector <const char*> parameterNames) { std::string virtualDatasetname, std::vector <const char*> parameterNames) {
char linkname[100]; char linkname[100];
hid_t vfd = 0; hid_t vfd = 0;
try {
hid_t dfal = H5Pcreate (H5P_FILE_ACCESS); hid_t dfal = H5Pcreate (H5P_FILE_ACCESS);
if (dfal < 0) if (dfal < 0)
return CloseFileOnError( vfd, std::string("Could not create file access property for link\n")); throw RuntimeError("Could not create file access property for link");
if (H5Pset_fclose_degree (dfal, H5F_CLOSE_STRONG) < 0) if (H5Pset_fclose_degree (dfal, H5F_CLOSE_STRONG) < 0)
return CloseFileOnError( vfd, std::string("Could not set strong file close degree for link\n")); throw RuntimeError("Could not set strong file close degree for link");
//open master file //open master file
hid_t mfd = H5Fopen( masterFileName.c_str(), H5F_ACC_RDWR, dfal); hid_t mfd = H5Fopen( masterFileName.c_str(), H5F_ACC_RDWR, dfal);
if (mfd < 0) if (mfd < 0)
return CloseFileOnError( vfd, std::string("Could not open master file\n")); throw RuntimeError("Could not open master file");
//open virtual file //open virtual file
vfd = H5Fopen( virtualfname.c_str(), H5F_ACC_RDWR, dfal); vfd = H5Fopen( virtualfname.c_str(), H5F_ACC_RDWR, dfal);
if (vfd < 0) { if (vfd < 0) {
H5Fclose(mfd); mfd = 0; H5Fclose(mfd); mfd = 0;
return CloseFileOnError( vfd, std::string("Could not open virtual file\n")); throw RuntimeError("Could not open virtual file");
} }
// find relative path // find relative path
@ -945,13 +887,13 @@ public:
hid_t vdset = H5Dopen2( vfd, virtualDatasetname.c_str(), H5P_DEFAULT); hid_t vdset = H5Dopen2( vfd, virtualDatasetname.c_str(), H5P_DEFAULT);
if (vdset < 0) { if (vdset < 0) {
H5Fclose(mfd); H5Fclose(mfd);
return CloseFileOnError( vfd, std::string("Could not open virtual data dataset\n")); throw RuntimeError("Could not open virtual data dataset");
} }
sprintf(linkname, "/entry/data/%s",virtualDatasetname.c_str()); sprintf(linkname, "/entry/data/%s",virtualDatasetname.c_str());
if(H5Lcreate_external( relative_virtualfname.c_str(), virtualDatasetname.c_str(), if(H5Lcreate_external( relative_virtualfname.c_str(), virtualDatasetname.c_str(),
mfd, linkname, H5P_DEFAULT, H5P_DEFAULT) < 0) { mfd, linkname, H5P_DEFAULT, H5P_DEFAULT) < 0) {
H5Fclose(mfd); mfd = 0; H5Fclose(mfd); mfd = 0;
return CloseFileOnError( vfd, std::string("Could not create link to data dataset\n")); throw RuntimeError("Could not create link to data dataset");
} }
H5Dclose(vdset); H5Dclose(vdset);
@ -960,37 +902,28 @@ public:
hid_t vdset_para = H5Dopen2( vfd, (std::string (parameterNames[i])).c_str(), H5P_DEFAULT); hid_t vdset_para = H5Dopen2( vfd, (std::string (parameterNames[i])).c_str(), H5P_DEFAULT);
if (vdset_para < 0) { if (vdset_para < 0) {
H5Fclose(mfd); mfd = 0; H5Fclose(mfd); mfd = 0;
return CloseFileOnError( vfd, std::string("Could not open virtual parameter dataset to create link\n")); throw RuntimeError("Could not open virtual parameter dataset to create link");
} }
sprintf(linkname, "/entry/data/%s",(std::string (parameterNames[i])).c_str()); sprintf(linkname, "/entry/data/%s",(std::string (parameterNames[i])).c_str());
if(H5Lcreate_external( relative_virtualfname.c_str(), (std::string (parameterNames[i])).c_str(), if(H5Lcreate_external( relative_virtualfname.c_str(), (std::string (parameterNames[i])).c_str(),
mfd, linkname, H5P_DEFAULT, H5P_DEFAULT) < 0) { mfd, linkname, H5P_DEFAULT, H5P_DEFAULT) < 0) {
H5Fclose(mfd); mfd = 0; H5Fclose(mfd); mfd = 0;
return CloseFileOnError( vfd, std::string("Could not create link to virtual parameter dataset\n")); throw RuntimeError("Could not create link to virtual parameter dataset");
} }
} }
H5Fclose(mfd); mfd = 0; H5Fclose(mfd); mfd = 0;
H5Fclose(vfd); vfd = 0; H5Fclose(vfd); vfd = 0;
return 0; } catch () {
if(vfd > 0)
H5Fclose(vfd);
vfd = 0;
}
} }
/**
* Print Error msg and Close File and called on error
* @returns 1 for fail
*/
static int CloseFileOnError(hid_t& fd, const std::string msg) {
FILE_LOG(logERROR) << msg;
if(fd > 0)
H5Fclose(fd);
fd = 0;
return 1;
}
/** /**
* Get Data type in C * Get Data type in C
* @param dtype datatype in C++ * @param dtype datatype in C++

View File

@ -17,22 +17,16 @@ class slsDetectorDefs;
class Implementation : private virtual slsDetectorDefs { class Implementation : private virtual slsDetectorDefs {
public: public:
Implementation(); Implementation(const detectorType d);
virtual ~Implementation(); virtual ~Implementation();
/************************************************** /**************************************************
* * * *
* Configuration Parameters * * Configuration Parameters *
* * * *
* ************************************************/ * ************************************************/
/**
* Set receiver type. It is the first function called by the client when void setDetectorType(const detectorType d);
* connecting to receiver
* @param d detector type
* @return OK or FAIL
*/
int setDetectorType(const detectorType d);
int *getMultiDetectorSize() const; int *getMultiDetectorSize() const;
void setMultiDetectorSize(const int *size); void setMultiDetectorSize(const int *size);
int getDetectorPositionId() const; int getDetectorPositionId() const;
@ -42,7 +36,7 @@ class Implementation : private virtual slsDetectorDefs {
bool getSilentMode() const; bool getSilentMode() const;
void setSilentMode(const bool i); void setSilentMode(const bool i);
uint32_t getFifoDepth() const; uint32_t getFifoDepth() const;
int setFifoDepth(const uint32_t i); void setFifoDepth(const uint32_t i);
frameDiscardPolicy getFrameDiscardPolicy() const; frameDiscardPolicy getFrameDiscardPolicy() const;
void setFrameDiscardPolicy(const frameDiscardPolicy i); void setFrameDiscardPolicy(const frameDiscardPolicy i);
bool getFramePaddingEnable() const; bool getFramePaddingEnable() const;
@ -81,13 +75,13 @@ class Implementation : private virtual slsDetectorDefs {
uint64_t getFramesCaught() const; uint64_t getFramesCaught() const;
uint64_t getAcquisitionIndex() const; uint64_t getAcquisitionIndex() const;
std::vector<uint64_t> getNumMissingPackets() const; std::vector<uint64_t> getNumMissingPackets() const;
int startReceiver(std::string& err); void startReceiver();
void setStoppedFlag(bool stopped); void setStoppedFlag(bool stopped);
void stopReceiver(); void stopReceiver();
void startReadout(); void startReadout();
void shutDownUDPSockets(); void shutDownUDPSockets();
void closeFiles(); void closeFiles();
int restreamStop(); void restreamStop();
/************************************************** /**************************************************
@ -97,7 +91,7 @@ class Implementation : private virtual slsDetectorDefs {
* ************************************************/ * ************************************************/
int getNumberofUDPInterfaces() const; int getNumberofUDPInterfaces() const;
/* [Jungfrau] */ /* [Jungfrau] */
int setNumberofUDPInterfaces(const int n); void setNumberofUDPInterfaces(const int n);
std::string getEthernetInterface() const; std::string getEthernetInterface() const;
void setEthernetInterface(const std::string &c); void setEthernetInterface(const std::string &c);
std::string getEthernetInterface2() const; std::string getEthernetInterface2() const;
@ -109,7 +103,7 @@ class Implementation : private virtual slsDetectorDefs {
/* [Eiger][Jungfrau] */ /* [Eiger][Jungfrau] */
void setUDPPortNumber2(const uint32_t i); void setUDPPortNumber2(const uint32_t i);
int64_t getUDPSocketBufferSize() const; int64_t getUDPSocketBufferSize() const;
int setUDPSocketBufferSize(const int64_t s); void setUDPSocketBufferSize(const int64_t s);
int64_t getActualUDPSocketBufferSize() const; int64_t getActualUDPSocketBufferSize() const;
@ -119,10 +113,10 @@ class Implementation : private virtual slsDetectorDefs {
* * * *
* ************************************************/ * ************************************************/
bool getDataStreamEnable() const; bool getDataStreamEnable() const;
int setDataStreamEnable(const bool enable); void setDataStreamEnable(const bool enable);
uint32_t getStreamingFrequency() const; uint32_t getStreamingFrequency() const;
/* 0 for timer */ /* 0 for timer */
int setStreamingFrequency(const uint32_t freq); void setStreamingFrequency(const uint32_t freq);
uint32_t getStreamingTimer() const; uint32_t getStreamingTimer() const;
void setStreamingTimer(const uint32_t time_in_ms); void setStreamingTimer(const uint32_t time_in_ms);
uint32_t getStreamingPort() const; uint32_t getStreamingPort() const;
@ -151,26 +145,26 @@ class Implementation : private virtual slsDetectorDefs {
void setSubPeriod(const uint64_t i); void setSubPeriod(const uint64_t i);
uint32_t getNumberofAnalogSamples() const; uint32_t getNumberofAnalogSamples() const;
/**[Ctb][Moench] */ /**[Ctb][Moench] */
int setNumberofAnalogSamples(const uint32_t i); void setNumberofAnalogSamples(const uint32_t i);
uint32_t getNumberofDigitalSamples() const; uint32_t getNumberofDigitalSamples() const;
/**[Ctb] */ /**[Ctb] */
int setNumberofDigitalSamples(const uint32_t i); void setNumberofDigitalSamples(const uint32_t i);
uint32_t getDynamicRange() const; uint32_t getDynamicRange() const;
int setDynamicRange(const uint32_t i); void setDynamicRange(const uint32_t i);
ROI getROI() const; ROI getROI() const;
/* [Gotthard] */ /* [Gotthard] */
int setROI(ROI arg); void setROI(ROI arg);
bool getTenGigaEnable() const; bool getTenGigaEnable() const;
/* [Eiger][Ctb] */ /* [Eiger][Ctb] */
int setTenGigaEnable(const bool b); void setTenGigaEnable(const bool b);
int getFlippedDataX() const; int getFlippedDataX() const;
void setFlippedDataX(int enable = -1); void setFlippedDataX(int enable = -1);
bool getGapPixelsEnable() const; bool getGapPixelsEnable() const;
/* [Eiger] */ /* [Eiger] */
int setGapPixelsEnable(const bool b); void setGapPixelsEnable(const bool b);
bool getQuad() const; bool getQuad() const;
/* [Eiger] */ /* [Eiger] */
int setQuad(const bool b); void setQuad(const bool b);
bool getActivate() const; bool getActivate() const;
/** [Eiger] If deactivated, receiver will create dummy data if deactivated padding is enabled (as it will receive nothing from detector) */ /** [Eiger] If deactivated, receiver will create dummy data if deactivated padding is enabled (as it will receive nothing from detector) */
bool setActivate(const bool enable); bool setActivate(const bool enable);
@ -182,13 +176,13 @@ class Implementation : private virtual slsDetectorDefs {
void setReadNLines(const int value); void setReadNLines(const int value);
readoutMode getReadoutMode() const; readoutMode getReadoutMode() const;
/* [Ctb] */ /* [Ctb] */
int setReadoutMode(const readoutMode f); void setReadoutMode(const readoutMode f);
uint32_t getADCEnableMask() const; uint32_t getADCEnableMask() const;
/* [Ctb][Moench] */ /* [Ctb][Moench] */
int setADCEnableMask(const uint32_t mask); void setADCEnableMask(const uint32_t mask);
uint32_t getTenGigaADCEnableMask() const; uint32_t getTenGigaADCEnableMask() const;
/* [Ctb][Moench] */ /* [Ctb][Moench] */
int setTenGigaADCEnableMask(const uint32_t mask); void setTenGigaADCEnableMask(const uint32_t mask);
std::vector<int> getDbitList() const; std::vector<int> getDbitList() const;
/* [Ctb] */ /* [Ctb] */
void setDbitList(const std::vector<int> v); void setDbitList(const std::vector<int> v);
@ -215,11 +209,11 @@ class Implementation : private virtual slsDetectorDefs {
void InitializeMembers(); void InitializeMembers();
void SetLocalNetworkParameters(); void SetLocalNetworkParameters();
void SetThreadPriorities(); void SetThreadPriorities();
int SetupFifoStructure(); void SetupFifoStructure();
void ResetParametersforNewAcquisition(); void ResetParametersforNewAcquisition();
int CreateUDPSockets(); void CreateUDPSockets();
int SetupWriter(); void SetupWriter();
void StartRunning(); void StartRunning();

View File

@ -102,18 +102,10 @@ class Listener : private virtual slsDetectorDefs, public ThreadObject {
*/ */
void SetGeneralData(GeneralData* g); void SetGeneralData(GeneralData* g);
/**
* Set thread priority
* @priority priority
* @returns OK or FAIL
*/
int SetThreadPriority(int priority);
/** /**
* Creates UDP Sockets * Creates UDP Sockets
* @return OK or FAIL
*/ */
int CreateUDPSockets(); void CreateUDPSockets();
/** /**
* Shuts down and deletes UDP Sockets * Shuts down and deletes UDP Sockets
@ -124,9 +116,8 @@ class Listener : private virtual slsDetectorDefs, public ThreadObject {
* Create & closes a dummy UDP socket * Create & closes a dummy UDP socket
* to set & get actual buffer size * to set & get actual buffer size
* @param s UDP socket buffer size to be set * @param s UDP socket buffer size to be set
* @return OK or FAIL of dummy socket creation
*/ */
int CreateDummySocketForUDPSocketBufferSize(int64_t s); void CreateDummySocketForUDPSocketBufferSize(int64_t s);
/** /**
* Set hard coded (calculated but not from detector) row and column * Set hard coded (calculated but not from detector) row and column
@ -139,12 +130,6 @@ class Listener : private virtual slsDetectorDefs, public ThreadObject {
private: private:
/**
* Get Type
* @return type
*/
std::string GetType() override;
/** /**
* Record First Acquisition Index * Record First Acquisition Index
* @param fnum frame index to record * @param fnum frame index to record

View File

@ -10,77 +10,27 @@
#include "sls_detector_defs.h" #include "sls_detector_defs.h"
#include "logger.h" #include "logger.h"
#include <pthread.h>
#include <semaphore.h> #include <semaphore.h>
#include <string> #include <string>
#include <atomic>
#include <future>
class ThreadObject : private virtual slsDetectorDefs { class ThreadObject : private virtual slsDetectorDefs {
public: public:
/** ThreadObject(int threadIndex, std::string threadType);
* Constructor
* @param ind self index
*/
ThreadObject(int ind);
/**
* Destructor
* if alive, destroys thread
*/
virtual ~ThreadObject(); virtual ~ThreadObject();
/**
* Print all member values
*/
void PrintMembers();
/**
* Get Type
* @return type
*/
virtual std::string GetType() = 0;
/**
* Returns if the thread is currently running
* @returns true if thread is running, else false
*/
virtual bool IsRunning() = 0; virtual bool IsRunning() = 0;
/**
* What is really being executed in the thread
*/
virtual void ThreadExecution() = 0;
/**
* Post semaphore so thread can continue & start an acquisition
*/
void Continue(); void Continue();
void SetThreadPriority(int priority);
protected: protected:
virtual void ThreadExecution() = 0;
/**
* Destroy thread, semaphore and resets alive and killThread
*/
void DestroyThread();
/**
* Create Thread, sets semaphore, alive and killThread
* @return OK if successful, else FAIL
*/
int CreateThread();
private: private:
/** /**
* Static function using pointer from argument to call RunningThread() * Thread called: An infinite while loop in which,
* @param thisPointer pointer to an object of ThreadObject
*/
static void* StartThread(void *thisPointer);
/**
* Actual Thread called: An infinite while loop in which,
* semaphore starts executing its contents as long RunningMask is satisfied * semaphore starts executing its contents as long RunningMask is satisfied
* Then it exits the thread on its own if killThread is true * Then it exits the thread on its own if killThread is true
*/ */
@ -88,22 +38,10 @@ class ThreadObject : private virtual slsDetectorDefs {
protected: protected:
/** Self Index */ int index{0};
int index; std::string type;
std::atomic<bool> killThread{false};
/** Thread is alive/dead */ std::unique_ptr<std::thread> threadObject;
volatile bool alive;
/** Variable monitored by thread to kills itself */
volatile bool killThread;
/** Thread variable */
pthread_t thread;
/** Semaphore to synchonize starting of each run */
sem_t semaphore; sem_t semaphore;
}; };

View File

@ -42,20 +42,18 @@ slsDetectorDefs::fileFormat BinaryFile::GetFileType() {
} }
int BinaryFile::CreateFile() { void BinaryFile::CreateFile() {
numFramesInFile = 0; numFramesInFile = 0;
numActualPacketsInFile = 0; numActualPacketsInFile = 0;
currentFileName = BinaryFileStatic::CreateFileName(*filePath, *fileNamePrefix, *fileIndex, currentFileName = BinaryFileStatic::CreateFileName(*filePath, *fileNamePrefix, *fileIndex,
subFileIndex, *detIndex, *numUnitsPerDetector, index); subFileIndex, *detIndex, *numUnitsPerDetector, index);
if (BinaryFileStatic::CreateDataFile(filefd, *overWriteEnable, currentFileName, FILE_BUFFER_SIZE) == FAIL) BinaryFileStatic::CreateDataFile(filefd, *overWriteEnable, currentFileName, FILE_BUFFER_SIZE);
return FAIL;
if(!(*silentMode)) { if(!(*silentMode)) {
FILE_LOG(logINFO) << "[" << *udpPortNumber << "]: Binary File created: " << currentFileName; FILE_LOG(logINFO) << "[" << *udpPortNumber << "]: Binary File created: " << currentFileName;
} }
return OK;
} }
void BinaryFile::CloseCurrentFile() { void BinaryFile::CloseCurrentFile() {
@ -68,7 +66,7 @@ void BinaryFile::CloseAllFiles() {
BinaryFileStatic::CloseDataFile(masterfd); BinaryFileStatic::CloseDataFile(masterfd);
} }
int BinaryFile::WriteToFile(char* buffer, int buffersize, uint64_t fnum, uint32_t nump) { void BinaryFile::WriteToFile(char* buffer, int buffersize, uint64_t fnum, uint32_t nump) {
// check if maxframesperfile = 0 for infinite // check if maxframesperfile = 0 for infinite
if ((*maxFramesPerFile) && (numFramesInFile >= (*maxFramesPerFile))) { if ((*maxFramesPerFile) && (numFramesInFile >= (*maxFramesPerFile))) {
CloseCurrentFile(); CloseCurrentFile();
@ -107,14 +105,12 @@ int BinaryFile::WriteToFile(char* buffer, int buffersize, uint64_t fnum, uint32_
// if write error // if write error
if (ret != buffersize) { if (ret != buffersize) {
FILE_LOG(logERROR) << index << " Error: Write to file failed for image number " << fnum; throw sls::RuntimeError(std::to_string(index) + " : Write to file failed for image number " + std::to_string(fnum));
return FAIL;
} }
return OK;
} }
int BinaryFile::CreateMasterFile(bool mfwenable, masterAttributes& attr) { void BinaryFile::CreateMasterFile(bool mfwenable, masterAttributes& attr) {
//beginning of every acquisition //beginning of every acquisition
numFramesInFile = 0; numFramesInFile = 0;
numActualPacketsInFile = 0; numActualPacketsInFile = 0;
@ -126,10 +122,9 @@ int BinaryFile::CreateMasterFile(bool mfwenable, masterAttributes& attr) {
FILE_LOG(logINFO) << "Master File: " << masterFileName; FILE_LOG(logINFO) << "Master File: " << masterFileName;
} }
attr.version = BINARY_WRITER_VERSION; attr.version = BINARY_WRITER_VERSION;
return BinaryFileStatic::CreateMasterDataFile(masterfd, masterFileName, BinaryFileStatic::CreateMasterDataFile(masterfd, masterFileName,
*overWriteEnable, attr); *overWriteEnable, attr);
} }
return OK;
} }

View File

@ -20,38 +20,24 @@ using sls::RuntimeError;
using sls::SocketError; using sls::SocketError;
using Interface = sls::ServerInterface2; using Interface = sls::ServerInterface2;
ClientInterface::~ClientInterface() { stopTCPSocket(); } ClientInterface::~ClientInterface() {
killTcpThread = true;
ClientInterface::ClientInterface(int portNumber) // shut down tcp sockets
: myDetectorType(GOTTHARD), portNumber(portNumber > 0 ? portNumber : DEFAULT_PORTNO + 2) { if (server.get() != nullptr) {
function_table();
startTCPSocket();
}
void ClientInterface::startTCPSocket() {
FILE_LOG(logDEBUG) << "Creating TCP Server Thread";
killTCPServerThread = 0;
if (pthread_create(&TCPServer_thread, nullptr, startTCPServerThread,
(void *)this)) {
throw RuntimeError("Could not create TCP Server thread");
}
tcpThreadCreated = true;
FILE_LOG(logDEBUG) << "TCP Server thread created successfully.";
}
void ClientInterface::stopTCPSocket() {
if (tcpThreadCreated) {
FILE_LOG(logINFO) << "Shutting down TCP Socket on port " << portNumber; FILE_LOG(logINFO) << "Shutting down TCP Socket on port " << portNumber;
killTCPServerThread = 1;
if (server)
server->shutDownSocket(); server->shutDownSocket();
FILE_LOG(logDEBUG) << "TCP Socket closed on port " << portNumber; FILE_LOG(logDEBUG) << "TCP Socket closed on port " << portNumber;
pthread_join(TCPServer_thread, nullptr);
tcpThreadCreated = false;
killTCPServerThread = 0;
FILE_LOG(logDEBUG) << "Exiting TCP Server Thread on port "
<< portNumber;
} }
// shut down tcp thread
tcpThread->join();
}
ClientInterface::ClientInterface(int portNumber)
: myDetectorType(GOTTHARD),
portNumber(portNumber > 0 ? portNumber : DEFAULT_PORTNO + 2) {
functionTable();
// start up tcp thread
tcpThread = sls::make_unique<std::thread>(&ClientInterface::startTCPServer, this);
} }
int64_t ClientInterface::getReceiverVersion() { return APIRECEIVER; } int64_t ClientInterface::getReceiverVersion() { return APIRECEIVER; }
@ -81,14 +67,8 @@ void ClientInterface::registerCallBackRawDataModifyReady(
pRawDataReady = arg; pRawDataReady = arg;
} }
void *ClientInterface::startTCPServerThread(void *this_pointer) {
((ClientInterface *)this_pointer)->startTCPServer();
return this_pointer;
}
void ClientInterface::startTCPServer() { void ClientInterface::startTCPServer() {
FILE_LOG(logINFOBLUE) << "Created [ TCP server Tid: " << syscall(SYS_gettid) FILE_LOG(logINFOBLUE) << "Created [ TCP server Tid: " << syscall(SYS_gettid) << "]";
<< "]";
FILE_LOG(logINFO) << "SLS Receiver starting TCP Server on port " FILE_LOG(logINFO) << "SLS Receiver starting TCP Server on port "
<< portNumber << '\n'; << portNumber << '\n';
server = sls::make_unique<sls::ServerSocket>(portNumber); server = sls::make_unique<sls::ServerSocket>(portNumber);
@ -97,8 +77,8 @@ void ClientInterface::startTCPServer() {
try { try {
auto socket = server->accept(); auto socket = server->accept();
try { try {
VerifyLock(); verifyLock();
ret = decode_function(socket); ret = decodeFunction(socket);
} catch (const RuntimeError &e) { } catch (const RuntimeError &e) {
// We had an error needs to be sent to client // We had an error needs to be sent to client
char mess[MAX_STR_LENGTH]{}; char mess[MAX_STR_LENGTH]{};
@ -106,37 +86,27 @@ void ClientInterface::startTCPServer() {
socket.Send(FAIL); socket.Send(FAIL);
socket.Send(mess); socket.Send(mess);
} }
// if tcp command was to exit server // if tcp command was to exit server
if (ret == GOODBYE) { if (ret == GOODBYE) {
FILE_LOG(logINFO) << "Shutting down UDP Socket"; break;
if (receiver) {
receiver->shutDownUDPSockets();
}
FILE_LOG(logINFOBLUE)
<< "Exiting [ TCP server Tid: " << syscall(SYS_gettid)
<< "]";
pthread_exit(nullptr);
} }
} catch (const RuntimeError &e) { } catch (const RuntimeError &e) {
FILE_LOG(logERROR) << "Accept failed"; FILE_LOG(logERROR) << "Accept failed";
} }
// destructor to kill this thread
if (killTcpThread) {
break;
}
}
// if user entered exit
if (killTCPServerThread) {
if (ret != GOODBYE) {
if (receiver) { if (receiver) {
receiver->shutDownUDPSockets(); receiver->shutDownUDPSockets();
} }
FILE_LOG(logINFOBLUE) << "Exiting [ TCP server Tid: " << syscall(SYS_gettid) << "]";
} }
FILE_LOG(logINFOBLUE)
<< "Exiting [ TCP server Tid: " << syscall(SYS_gettid) << "]";
pthread_exit(nullptr);
}
}
}
// clang-format off // clang-format off
int ClientInterface::function_table(){ int ClientInterface::functionTable(){
flist[F_EXEC_RECEIVER_COMMAND] = &ClientInterface::exec_command; flist[F_EXEC_RECEIVER_COMMAND] = &ClientInterface::exec_command;
flist[F_EXIT_RECEIVER] = &ClientInterface::exit_server; flist[F_EXIT_RECEIVER] = &ClientInterface::exit_server;
flist[F_LOCK_RECEIVER] = &ClientInterface::lock_receiver; flist[F_LOCK_RECEIVER] = &ClientInterface::lock_receiver;
@ -207,35 +177,35 @@ int ClientInterface::function_table(){
for (int i = NUM_DET_FUNCTIONS + 1; i < NUM_REC_FUNCTIONS ; i++) { for (int i = NUM_DET_FUNCTIONS + 1; i < NUM_REC_FUNCTIONS ; i++) {
// FILE_LOG(logDEBUG1) << "function fnum: " << i << " (" << FILE_LOG(logDEBUG1) << "function fnum: " << i << " (" <<
// getFunctionNameFromEnum((enum detFuncs)i) << ") located at " << flist[i]; getFunctionNameFromEnum((enum detFuncs)i) << ") located at " << flist[i];
} }
return OK; return OK;
} }
// clang-format on // clang-format on
int ClientInterface::decode_function(Interface &socket) { int ClientInterface::decodeFunction(Interface &socket) {
ret = FAIL; ret = FAIL;
socket.Receive(fnum); socket.Receive(fnum);
if (fnum <= NUM_DET_FUNCTIONS || fnum >= NUM_REC_FUNCTIONS) { if (fnum <= NUM_DET_FUNCTIONS || fnum >= NUM_REC_FUNCTIONS) {
throw RuntimeError("Unrecognized Function enum " + throw RuntimeError("Unrecognized Function enum " +
std::to_string(fnum) + "\n"); std::to_string(fnum) + "\n");
} else { } else {
// FILE_LOG(logDEBUG1) << "calling function fnum: " << fnum << " (" FILE_LOG(logDEBUG1) << "calling function fnum: " << fnum << " ("
// << getFunctionNameFromEnum((enum detFuncs)fnum) << getFunctionNameFromEnum((enum detFuncs)fnum)
// << ")"; << ")";
ret = (this->*flist[fnum])(socket); ret = (this->*flist[fnum])(socket);
// FILE_LOG(logDEBUG1) FILE_LOG(logDEBUG1)
// << "Function " << getFunctionNameFromEnum((enum detFuncs)fnum) << "Function " << getFunctionNameFromEnum((enum detFuncs)fnum)
// << " finished"; << " finished";
} }
return ret; return ret;
} }
void ClientInterface::functionNotImplemented() { void ClientInterface::functionNotImplemented() {
std::ostringstream os; std::ostringstream os;
// os << "Function: " << getFunctionNameFromEnum((enum detFuncs)fnum) os << "Function: " << getFunctionNameFromEnum((enum detFuncs)fnum)
// << ", is is not implemented for this detector"; << ", is is not implemented for this detector";
throw RuntimeError(os.str()); throw RuntimeError(os.str());
} }
@ -259,13 +229,13 @@ void ClientInterface::validate(T arg, T retval, std::string modename,
} }
} }
void ClientInterface::VerifyLock() { void ClientInterface::verifyLock() {
if (lockStatus && server->getThisClient() != server->getLockedBy()) { if (lockedByClient && server->getThisClient() != server->getLockedBy()) {
throw sls::SocketError("Receiver locked\n"); throw sls::SocketError("Receiver locked\n");
} }
} }
void ClientInterface::VerifyIdle(Interface &socket) { void ClientInterface::verifyIdle(Interface &socket) {
if (impl()->getStatus() != IDLE) { if (impl()->getStatus() != IDLE) {
std::ostringstream oss; std::ostringstream oss;
oss << "Can not execute " << getFunctionNameFromEnum((enum detFuncs)fnum) oss << "Can not execute " << getFunctionNameFromEnum((enum detFuncs)fnum)
@ -306,15 +276,15 @@ int ClientInterface::lock_receiver(Interface &socket) {
auto lock = socket.Receive<int>(); auto lock = socket.Receive<int>();
FILE_LOG(logDEBUG1) << "Locking Server to " << lock; FILE_LOG(logDEBUG1) << "Locking Server to " << lock;
if (lock >= 0) { if (lock >= 0) {
if (!lockStatus || (server->getLockedBy() == server->getThisClient())) { if (!lockedByClient || (server->getLockedBy() == server->getThisClient())) {
lockStatus = lock; lockedByClient = lock;
lock ? server->setLockedBy(server->getThisClient()) lock ? server->setLockedBy(server->getThisClient())
: server->setLockedBy(sls::IpAddr{}); : server->setLockedBy(sls::IpAddr{});
} else { } else {
throw RuntimeError("Receiver locked\n"); throw RuntimeError("Receiver locked\n");
} }
} }
return socket.sendResult(lockStatus); return socket.sendResult(lockedByClient);
} }
int ClientInterface::get_last_client_ip(Interface &socket) { int ClientInterface::get_last_client_ip(Interface &socket) {
@ -458,7 +428,7 @@ int ClientInterface::set_detector_type(Interface &socket) {
// if object exists, verify unlocked and idle, else only verify lock // if object exists, verify unlocked and idle, else only verify lock
// (connecting first time) // (connecting first time)
if (receiver != nullptr) { if (receiver != nullptr) {
VerifyIdle(socket); verifyIdle(socket);
} }
switch (arg) { switch (arg) {
case GOTTHARD: case GOTTHARD:
@ -473,11 +443,11 @@ int ClientInterface::set_detector_type(Interface &socket) {
break; break;
} }
if (receiver == nullptr) { try {
receiver = sls::make_unique<Implementation>(); myDetectorType = GENERIC;
} receiver = sls::make_unique<Implementation>(arg);
myDetectorType = arg; myDetectorType = arg;
if (impl()->setDetectorType(myDetectorType) == FAIL) { } catch (...) {
throw RuntimeError("Could not set detector type"); throw RuntimeError("Could not set detector type");
} }
@ -504,7 +474,7 @@ int ClientInterface::set_detector_hostname(Interface &socket) {
socket.Receive(hostname); socket.Receive(hostname);
if (strlen(hostname) != 0) { if (strlen(hostname) != 0) {
VerifyIdle(socket); verifyIdle(socket);
impl()->setDetectorHostname(hostname); impl()->setDetectorHostname(hostname);
} }
auto s = impl()->getDetectorHostname(); auto s = impl()->getDetectorHostname();
@ -524,9 +494,12 @@ int ClientInterface::set_roi(Interface &socket) {
if (myDetectorType != GOTTHARD) if (myDetectorType != GOTTHARD)
functionNotImplemented(); functionNotImplemented();
VerifyIdle(socket); verifyIdle(socket);
if (impl()->setROI(arg) == FAIL) try {
impl()->setROI(arg);
} catch(const RuntimeError &e) {
throw RuntimeError("Could not set ROI"); throw RuntimeError("Could not set ROI");
}
return socket.Send(OK); return socket.Send(OK);
} }
@ -543,7 +516,11 @@ int ClientInterface::set_num_analog_samples(Interface &socket) {
if (myDetectorType != CHIPTESTBOARD && myDetectorType != MOENCH) { if (myDetectorType != CHIPTESTBOARD && myDetectorType != MOENCH) {
functionNotImplemented(); functionNotImplemented();
} }
ret = impl()->setNumberofAnalogSamples(value); try {
impl()->setNumberofAnalogSamples(value);
} catch(const RuntimeError &e) {
throw RuntimeError("Could not set num analog samples to " + std::to_string(value) + " due to fifo structure memory allocation.");
}
return socket.Send(OK); return socket.Send(OK);
} }
@ -554,7 +531,11 @@ int ClientInterface::set_num_digital_samples(Interface &socket) {
if (myDetectorType != CHIPTESTBOARD && myDetectorType != MOENCH) { if (myDetectorType != CHIPTESTBOARD && myDetectorType != MOENCH) {
functionNotImplemented(); functionNotImplemented();
} }
ret = impl()->setNumberofDigitalSamples(value); try {
impl()->setNumberofDigitalSamples(value);
} catch(const RuntimeError &e) {
throw RuntimeError("Could not set num digital samples to " + std::to_string(value) + " due to fifo structure memory allocation.");
}
return socket.Send(OK); return socket.Send(OK);
} }
@ -590,7 +571,7 @@ int ClientInterface::set_subdeadtime(Interface &socket) {
int ClientInterface::set_dynamic_range(Interface &socket) { int ClientInterface::set_dynamic_range(Interface &socket) {
auto dr = socket.Receive<int>(); auto dr = socket.Receive<int>();
if (dr >= 0) { if (dr >= 0) {
VerifyIdle(socket); verifyIdle(socket);
FILE_LOG(logDEBUG1) << "Setting dynamic range: " << dr; FILE_LOG(logDEBUG1) << "Setting dynamic range: " << dr;
bool exists = false; bool exists = false;
switch(myDetectorType) { switch(myDetectorType) {
@ -613,8 +594,9 @@ int ClientInterface::set_dynamic_range(Interface &socket) {
if (!exists) { if (!exists) {
modeNotImplemented("Dynamic range", dr); modeNotImplemented("Dynamic range", dr);
} else { } else {
ret = impl()->setDynamicRange(dr); try {
if (ret == FAIL) { impl()->setDynamicRange(dr);
} catch(const RuntimeError &e) {
throw RuntimeError("Could not allocate memory for fifo or " throw RuntimeError("Could not allocate memory for fifo or "
"could not start listening/writing threads"); "could not start listening/writing threads");
} }
@ -629,12 +611,9 @@ int ClientInterface::set_dynamic_range(Interface &socket) {
int ClientInterface::set_streaming_frequency(Interface &socket) { int ClientInterface::set_streaming_frequency(Interface &socket) {
auto index = socket.Receive<int>(); auto index = socket.Receive<int>();
if (index >= 0) { if (index >= 0) {
VerifyIdle(socket); verifyIdle(socket);
FILE_LOG(logDEBUG1) << "Setting streaming frequency: " << index; FILE_LOG(logDEBUG1) << "Setting streaming frequency: " << index;
ret = impl()->setStreamingFrequency(index); impl()->setStreamingFrequency(index);
if (ret == FAIL) {
throw RuntimeError("Could not allocate memory for listening fifo");
}
} }
int retval = impl()->getStreamingFrequency(); int retval = impl()->getStreamingFrequency();
validate(index, retval, "set streaming frequency", DEC); validate(index, retval, "set streaming frequency", DEC);
@ -650,11 +629,7 @@ int ClientInterface::get_status(Interface &socket) {
int ClientInterface::start_receiver(Interface &socket) { int ClientInterface::start_receiver(Interface &socket) {
if (impl()->getStatus() == IDLE) { if (impl()->getStatus() == IDLE) {
FILE_LOG(logDEBUG1) << "Starting Receiver"; FILE_LOG(logDEBUG1) << "Starting Receiver";
std::string err; impl()->startReceiver();
ret = impl()->startReceiver(err);
if (ret == FAIL) {
throw RuntimeError(err);
}
} }
return socket.Send(OK); return socket.Send(OK);
} }
@ -715,7 +690,7 @@ int ClientInterface::set_file_name(Interface &socket) {
int ClientInterface::set_file_index(Interface &socket) { int ClientInterface::set_file_index(Interface &socket) {
auto index = socket.Receive<int64_t>(); auto index = socket.Receive<int64_t>();
if (index >= 0) { if (index >= 0) {
VerifyIdle(socket); verifyIdle(socket);
FILE_LOG(logDEBUG1) << "Setting file index: " << index; FILE_LOG(logDEBUG1) << "Setting file index: " << index;
impl()->setFileIndex(index); impl()->setFileIndex(index);
} }
@ -752,7 +727,7 @@ int ClientInterface::get_frames_caught(Interface &socket) {
int ClientInterface::enable_file_write(Interface &socket) { int ClientInterface::enable_file_write(Interface &socket) {
auto enable = socket.Receive<int>(); auto enable = socket.Receive<int>();
if (enable >= 0) { if (enable >= 0) {
VerifyIdle(socket); verifyIdle(socket);
FILE_LOG(logDEBUG1) << "Setting File write enable:" << enable; FILE_LOG(logDEBUG1) << "Setting File write enable:" << enable;
impl()->setFileWriteEnable(enable); impl()->setFileWriteEnable(enable);
} }
@ -765,7 +740,7 @@ int ClientInterface::enable_file_write(Interface &socket) {
int ClientInterface::enable_master_file_write(Interface &socket) { int ClientInterface::enable_master_file_write(Interface &socket) {
auto enable = socket.Receive<int>(); auto enable = socket.Receive<int>();
if (enable >= 0) { if (enable >= 0) {
VerifyIdle(socket); verifyIdle(socket);
FILE_LOG(logDEBUG1) << "Setting Master File write enable:" << enable; FILE_LOG(logDEBUG1) << "Setting Master File write enable:" << enable;
impl()->setMasterFileWriteEnable(enable); impl()->setMasterFileWriteEnable(enable);
} }
@ -778,7 +753,7 @@ int ClientInterface::enable_master_file_write(Interface &socket) {
int ClientInterface::enable_overwrite(Interface &socket) { int ClientInterface::enable_overwrite(Interface &socket) {
auto index = socket.Receive<int>(); auto index = socket.Receive<int>();
if (index >= 0) { if (index >= 0) {
VerifyIdle(socket); verifyIdle(socket);
FILE_LOG(logDEBUG1) << "Setting File overwrite enable:" << index; FILE_LOG(logDEBUG1) << "Setting File overwrite enable:" << index;
impl()->setOverwriteEnable(index); impl()->setOverwriteEnable(index);
} }
@ -795,9 +770,13 @@ int ClientInterface::enable_tengiga(Interface &socket) {
functionNotImplemented(); functionNotImplemented();
if (val >= 0) { if (val >= 0) {
VerifyIdle(socket); verifyIdle(socket);
FILE_LOG(logDEBUG1) << "Setting 10GbE:" << val; FILE_LOG(logDEBUG1) << "Setting 10GbE:" << val;
ret = impl()->setTenGigaEnable(val); try {
impl()->setTenGigaEnable(val);
} catch(const RuntimeError &e) {
throw RuntimeError("Could not set 10GbE.");
}
} }
int retval = impl()->getTenGigaEnable(); int retval = impl()->getTenGigaEnable();
validate(val, retval, "set 10GbE", DEC); validate(val, retval, "set 10GbE", DEC);
@ -808,9 +787,13 @@ int ClientInterface::enable_tengiga(Interface &socket) {
int ClientInterface::set_fifo_depth(Interface &socket) { int ClientInterface::set_fifo_depth(Interface &socket) {
auto value = socket.Receive<int>(); auto value = socket.Receive<int>();
if (value >= 0) { if (value >= 0) {
VerifyIdle(socket); verifyIdle(socket);
FILE_LOG(logDEBUG1) << "Setting fifo depth:" << value; FILE_LOG(logDEBUG1) << "Setting fifo depth:" << value;
try {
impl()->setFifoDepth(value); impl()->setFifoDepth(value);
} catch(const RuntimeError &e) {
throw RuntimeError("Could not set fifo depth due to fifo structure memory allocation.");
}
} }
int retval = impl()->getFifoDepth(); int retval = impl()->getFifoDepth();
validate(value, retval, std::string("set fifo depth"), DEC); validate(value, retval, std::string("set fifo depth"), DEC);
@ -824,7 +807,7 @@ int ClientInterface::set_activate(Interface &socket) {
functionNotImplemented(); functionNotImplemented();
if (enable >= 0) { if (enable >= 0) {
VerifyIdle(socket); verifyIdle(socket);
FILE_LOG(logDEBUG1) << "Setting activate:" << enable; FILE_LOG(logDEBUG1) << "Setting activate:" << enable;
impl()->setActivate(static_cast<bool>(enable)); impl()->setActivate(static_cast<bool>(enable));
} }
@ -837,9 +820,13 @@ int ClientInterface::set_activate(Interface &socket) {
int ClientInterface::set_data_stream_enable(Interface &socket) { int ClientInterface::set_data_stream_enable(Interface &socket) {
auto index = socket.Receive<int>(); auto index = socket.Receive<int>();
if (index >= 0) { if (index >= 0) {
VerifyIdle(socket); verifyIdle(socket);
FILE_LOG(logDEBUG1) << "Setting data stream enable:" << index; FILE_LOG(logDEBUG1) << "Setting data stream enable:" << index;
try {
impl()->setDataStreamEnable(index); impl()->setDataStreamEnable(index);
} catch(const RuntimeError &e) {
throw RuntimeError("Could not set data stream enable to " + std::to_string(index));
}
} }
auto retval = static_cast<int>(impl()->getDataStreamEnable()); auto retval = static_cast<int>(impl()->getDataStreamEnable());
validate(index, retval, "set data stream enable", DEC); validate(index, retval, "set data stream enable", DEC);
@ -850,7 +837,7 @@ int ClientInterface::set_data_stream_enable(Interface &socket) {
int ClientInterface::set_streaming_timer(Interface &socket) { int ClientInterface::set_streaming_timer(Interface &socket) {
auto index = socket.Receive<int>(); auto index = socket.Receive<int>();
if (index >= 0) { if (index >= 0) {
VerifyIdle(socket); verifyIdle(socket);
FILE_LOG(logDEBUG1) << "Setting streaming timer:" << index; FILE_LOG(logDEBUG1) << "Setting streaming timer:" << index;
impl()->setStreamingTimer(index); impl()->setStreamingTimer(index);
} }
@ -867,7 +854,7 @@ int ClientInterface::set_flipped_data(Interface &socket) {
functionNotImplemented(); functionNotImplemented();
if (arg >= 0) { if (arg >= 0) {
VerifyIdle(socket); verifyIdle(socket);
FILE_LOG(logDEBUG1) << "Setting flipped data:" << arg; FILE_LOG(logDEBUG1) << "Setting flipped data:" << arg;
impl()->setFlippedDataX(arg); impl()->setFlippedDataX(arg);
} }
@ -881,7 +868,7 @@ int ClientInterface::set_file_format(Interface &socket) {
fileFormat f = GET_FILE_FORMAT; fileFormat f = GET_FILE_FORMAT;
socket.Receive(f); socket.Receive(f);
if (f >= 0) { if (f >= 0) {
VerifyIdle(socket); verifyIdle(socket);
FILE_LOG(logDEBUG1) << "Setting file format:" << f; FILE_LOG(logDEBUG1) << "Setting file format:" << f;
impl()->setFileFormat(f); impl()->setFileFormat(f);
} }
@ -894,7 +881,7 @@ int ClientInterface::set_file_format(Interface &socket) {
int ClientInterface::set_detector_posid(Interface &socket) { int ClientInterface::set_detector_posid(Interface &socket) {
auto arg = socket.Receive<int>(); auto arg = socket.Receive<int>();
if (arg >= 0) { if (arg >= 0) {
VerifyIdle(socket); verifyIdle(socket);
FILE_LOG(logDEBUG1) << "Setting detector position id:" << arg; FILE_LOG(logDEBUG1) << "Setting detector position id:" << arg;
impl()->setDetectorPositionId(arg); impl()->setDetectorPositionId(arg);
} }
@ -908,7 +895,7 @@ int ClientInterface::set_multi_detector_size(Interface &socket) {
int arg[]{-1, -1}; int arg[]{-1, -1};
socket.Receive(arg); socket.Receive(arg);
if ((arg[0] > 0) && (arg[1] > 0)) { if ((arg[0] > 0) && (arg[1] > 0)) {
VerifyIdle(socket); verifyIdle(socket);
FILE_LOG(logDEBUG1) FILE_LOG(logDEBUG1)
<< "Setting multi detector size:" << arg[0] << "," << arg[1]; << "Setting multi detector size:" << arg[0] << "," << arg[1];
impl()->setMultiDetectorSize(arg); impl()->setMultiDetectorSize(arg);
@ -922,7 +909,7 @@ int ClientInterface::set_multi_detector_size(Interface &socket) {
int ClientInterface::set_streaming_port(Interface &socket) { int ClientInterface::set_streaming_port(Interface &socket) {
auto port = socket.Receive<int>(); auto port = socket.Receive<int>();
if (port >= 0) { if (port >= 0) {
VerifyIdle(socket); verifyIdle(socket);
FILE_LOG(logDEBUG1) << "Setting streaming port:" << port; FILE_LOG(logDEBUG1) << "Setting streaming port:" << port;
impl()->setStreamingPort(port); impl()->setStreamingPort(port);
} }
@ -935,7 +922,7 @@ int ClientInterface::set_streaming_port(Interface &socket) {
int ClientInterface::set_streaming_source_ip(Interface &socket) { int ClientInterface::set_streaming_source_ip(Interface &socket) {
sls::IpAddr arg = 0u; sls::IpAddr arg = 0u;
socket.Receive(arg); socket.Receive(arg);
VerifyIdle(socket); verifyIdle(socket);
FILE_LOG(logDEBUG1) << "Setting streaming source ip:" << arg; FILE_LOG(logDEBUG1) << "Setting streaming source ip:" << arg;
impl()->setStreamingSourceIP(arg); impl()->setStreamingSourceIP(arg);
sls::IpAddr retval = impl()->getStreamingSourceIP(); sls::IpAddr retval = impl()->getStreamingSourceIP();
@ -951,7 +938,7 @@ int ClientInterface::set_streaming_source_ip(Interface &socket) {
int ClientInterface::set_silent_mode(Interface &socket) { int ClientInterface::set_silent_mode(Interface &socket) {
auto value = socket.Receive<int>(); auto value = socket.Receive<int>();
if (value >= 0) { if (value >= 0) {
VerifyIdle(socket); verifyIdle(socket);
FILE_LOG(logDEBUG1) << "Setting silent mode:" << value; FILE_LOG(logDEBUG1) << "Setting silent mode:" << value;
impl()->setSilentMode(value); impl()->setSilentMode(value);
} }
@ -967,9 +954,13 @@ int ClientInterface::enable_gap_pixels(Interface &socket) {
functionNotImplemented(); functionNotImplemented();
if (enable >= 0) { if (enable >= 0) {
VerifyIdle(socket); verifyIdle(socket);
FILE_LOG(logDEBUG1) << "Setting gap pixels enable:" << enable; FILE_LOG(logDEBUG1) << "Setting gap pixels enable:" << enable;
try {
impl()->setGapPixelsEnable(static_cast<bool>(enable)); impl()->setGapPixelsEnable(static_cast<bool>(enable));
} catch(const RuntimeError &e) {
throw RuntimeError("Could not set gap pixels enable to " + std::to_string(enable));
}
} }
auto retval = static_cast<int>(impl()->getGapPixelsEnable()); auto retval = static_cast<int>(impl()->getGapPixelsEnable());
validate(enable, retval, "set gap pixels enable", DEC); validate(enable, retval, "set gap pixels enable", DEC);
@ -978,7 +969,7 @@ int ClientInterface::enable_gap_pixels(Interface &socket) {
} }
int ClientInterface::restream_stop(Interface &socket) { int ClientInterface::restream_stop(Interface &socket) {
VerifyIdle(socket); verifyIdle(socket);
if (!impl()->getDataStreamEnable()) { if (!impl()->getDataStreamEnable()) {
throw RuntimeError( throw RuntimeError(
"Could not restream stop packet as data Streaming is disabled"); "Could not restream stop packet as data Streaming is disabled");
@ -993,7 +984,7 @@ int ClientInterface::set_additional_json_header(Interface &socket) {
char arg[MAX_STR_LENGTH]{}; char arg[MAX_STR_LENGTH]{};
char retval[MAX_STR_LENGTH]{}; char retval[MAX_STR_LENGTH]{};
socket.Receive(arg); socket.Receive(arg);
VerifyIdle(socket); verifyIdle(socket);
FILE_LOG(logDEBUG1) << "Setting additional json header: " << arg; FILE_LOG(logDEBUG1) << "Setting additional json header: " << arg;
impl()->setAdditionalJsonHeader(arg); impl()->setAdditionalJsonHeader(arg);
sls::strcpy_safe(retval, impl()->getAdditionalJsonHeader().c_str()); sls::strcpy_safe(retval, impl()->getAdditionalJsonHeader().c_str());
@ -1011,12 +1002,9 @@ int ClientInterface::get_additional_json_header(Interface &socket) {
int ClientInterface::set_udp_socket_buffer_size(Interface &socket) { int ClientInterface::set_udp_socket_buffer_size(Interface &socket) {
auto index = socket.Receive<int64_t>(); auto index = socket.Receive<int64_t>();
if (index >= 0) { if (index >= 0) {
VerifyIdle(socket); verifyIdle(socket);
FILE_LOG(logDEBUG1) << "Setting UDP Socket Buffer size: " << index; FILE_LOG(logDEBUG1) << "Setting UDP Socket Buffer size: " << index;
if (impl()->setUDPSocketBufferSize(index) == FAIL) { impl()->setUDPSocketBufferSize(index);
throw RuntimeError(
"Could not create dummy UDP Socket to test buffer size");
}
} }
int64_t retval = impl()->getUDPSocketBufferSize(); int64_t retval = impl()->getUDPSocketBufferSize();
if (index != 0) if (index != 0)
@ -1037,7 +1025,7 @@ int ClientInterface::get_real_udp_socket_buffer_size(
int ClientInterface::set_frames_per_file(Interface &socket) { int ClientInterface::set_frames_per_file(Interface &socket) {
auto index = socket.Receive<int>(); auto index = socket.Receive<int>();
if (index >= 0) { if (index >= 0) {
VerifyIdle(socket); verifyIdle(socket);
FILE_LOG(logDEBUG1) << "Setting frames per file: " << index; FILE_LOG(logDEBUG1) << "Setting frames per file: " << index;
impl()->setFramesPerFile(index); impl()->setFramesPerFile(index);
} }
@ -1078,7 +1066,7 @@ int ClientInterface::check_version_compatibility(Interface &socket) {
int ClientInterface::set_discard_policy(Interface &socket) { int ClientInterface::set_discard_policy(Interface &socket) {
auto index = socket.Receive<int>(); auto index = socket.Receive<int>();
if (index >= 0) { if (index >= 0) {
VerifyIdle(socket); verifyIdle(socket);
FILE_LOG(logDEBUG1) << "Setting frames discard policy: " << index; FILE_LOG(logDEBUG1) << "Setting frames discard policy: " << index;
impl()->setFrameDiscardPolicy(static_cast<frameDiscardPolicy>(index)); impl()->setFrameDiscardPolicy(static_cast<frameDiscardPolicy>(index));
} }
@ -1091,7 +1079,7 @@ int ClientInterface::set_discard_policy(Interface &socket) {
int ClientInterface::set_padding_enable(Interface &socket) { int ClientInterface::set_padding_enable(Interface &socket) {
auto index = socket.Receive<int>(); auto index = socket.Receive<int>();
if (index >= 0) { if (index >= 0) {
VerifyIdle(socket); verifyIdle(socket);
FILE_LOG(logDEBUG1) << "Setting frames padding enable: " << index; FILE_LOG(logDEBUG1) << "Setting frames padding enable: " << index;
impl()->setFramePaddingEnable(static_cast<bool>(index)); impl()->setFramePaddingEnable(static_cast<bool>(index));
} }
@ -1108,7 +1096,7 @@ int ClientInterface::set_deactivated_padding_enable(
functionNotImplemented(); functionNotImplemented();
if (enable >= 0) { if (enable >= 0) {
VerifyIdle(socket); verifyIdle(socket);
FILE_LOG(logDEBUG1) << "Setting deactivated padding enable: " << enable; FILE_LOG(logDEBUG1) << "Setting deactivated padding enable: " << enable;
impl()->setDeactivatedPadding(enable > 0); impl()->setDeactivatedPadding(enable > 0);
} }
@ -1125,9 +1113,13 @@ int ClientInterface::set_readout_mode(Interface &socket) {
functionNotImplemented(); functionNotImplemented();
if (arg >= 0) { if (arg >= 0) {
VerifyIdle(socket); verifyIdle(socket);
FILE_LOG(logDEBUG1) << "Setting readout mode: " << arg; FILE_LOG(logDEBUG1) << "Setting readout mode: " << arg;
try {
impl()->setReadoutMode(arg); impl()->setReadoutMode(arg);
} catch(const RuntimeError &e) {
throw RuntimeError("Could not set read out mode due to fifo memory allocation.");
}
} }
auto retval = impl()->getReadoutMode(); auto retval = impl()->getReadoutMode();
validate(static_cast<int>(arg), static_cast<int>(retval), validate(static_cast<int>(arg), static_cast<int>(retval),
@ -1138,9 +1130,13 @@ int ClientInterface::set_readout_mode(Interface &socket) {
int ClientInterface::set_adc_mask(Interface &socket) { int ClientInterface::set_adc_mask(Interface &socket) {
auto arg = socket.Receive<uint32_t>(); auto arg = socket.Receive<uint32_t>();
VerifyIdle(socket); verifyIdle(socket);
FILE_LOG(logDEBUG1) << "Setting 1Gb ADC enable mask: " << arg; FILE_LOG(logDEBUG1) << "Setting 1Gb ADC enable mask: " << arg;
try {
impl()->setADCEnableMask(arg); impl()->setADCEnableMask(arg);
} catch(const RuntimeError &e) {
throw RuntimeError("Could not set adc enable mask due to fifo memory allcoation");
}
auto retval = impl()->getADCEnableMask(); auto retval = impl()->getADCEnableMask();
if (retval != arg) { if (retval != arg) {
std::ostringstream os; std::ostringstream os;
@ -1160,7 +1156,7 @@ int ClientInterface::set_dbit_list(Interface &socket) {
FILE_LOG(logDEBUG1) << it << " "; FILE_LOG(logDEBUG1) << it << " ";
} }
FILE_LOG(logDEBUG1) << "\n"; FILE_LOG(logDEBUG1) << "\n";
VerifyIdle(socket); verifyIdle(socket);
impl()->setDbitList(args); impl()->setDbitList(args);
return socket.Send(OK); return socket.Send(OK);
} }
@ -1175,7 +1171,7 @@ int ClientInterface::get_dbit_list(Interface &socket) {
int ClientInterface::set_dbit_offset(Interface &socket) { int ClientInterface::set_dbit_offset(Interface &socket) {
auto arg = socket.Receive<int>(); auto arg = socket.Receive<int>();
if (arg >= 0) { if (arg >= 0) {
VerifyIdle(socket); verifyIdle(socket);
FILE_LOG(logDEBUG1) << "Setting Dbit offset: " << arg; FILE_LOG(logDEBUG1) << "Setting Dbit offset: " << arg;
impl()->setDbitOffset(arg); impl()->setDbitOffset(arg);
} }
@ -1188,11 +1184,12 @@ int ClientInterface::set_dbit_offset(Interface &socket) {
int ClientInterface::set_quad_type(Interface &socket) { int ClientInterface::set_quad_type(Interface &socket) {
auto quadEnable = socket.Receive<int>(); auto quadEnable = socket.Receive<int>();
if (quadEnable >= 0) { if (quadEnable >= 0) {
VerifyIdle(socket); verifyIdle(socket);
FILE_LOG(logDEBUG1) << "Setting quad:" << quadEnable; FILE_LOG(logDEBUG1) << "Setting quad:" << quadEnable;
ret = impl()->setQuad(quadEnable == 0 ? false : true); try {
if (ret == FAIL) { impl()->setQuad(quadEnable == 0 ? false : true);
throw RuntimeError("Could not set Quad due to fifo structure"); } catch(const RuntimeError &e) {
throw RuntimeError("Could not set quad to " + std::to_string(quadEnable) + " due to fifo strucutre memory allocation");
} }
} }
int retval = impl()->getQuad() ? 1 : 0; int retval = impl()->getQuad() ? 1 : 0;
@ -1204,7 +1201,7 @@ int ClientInterface::set_quad_type(Interface &socket) {
int ClientInterface::set_read_n_lines(Interface &socket) { int ClientInterface::set_read_n_lines(Interface &socket) {
auto arg = socket.Receive<int>(); auto arg = socket.Receive<int>();
if (arg >= 0) { if (arg >= 0) {
VerifyIdle(socket); verifyIdle(socket);
FILE_LOG(logDEBUG1) << "Setting Read N Lines:" << arg; FILE_LOG(logDEBUG1) << "Setting Read N Lines:" << arg;
impl()->setReadNLines(arg); impl()->setReadNLines(arg);
} }
@ -1217,7 +1214,7 @@ int ClientInterface::set_read_n_lines(Interface &socket) {
int ClientInterface::set_udp_ip(Interface &socket) { int ClientInterface::set_udp_ip(Interface &socket) {
auto arg = socket.Receive<sls::IpAddr>(); auto arg = socket.Receive<sls::IpAddr>();
VerifyIdle(socket); verifyIdle(socket);
FILE_LOG(logINFO) << "Received UDP IP: " << arg; FILE_LOG(logINFO) << "Received UDP IP: " << arg;
// getting eth // getting eth
std::string eth = sls::IpToInterfaceName(arg.str()); std::string eth = sls::IpToInterfaceName(arg.str());
@ -1244,7 +1241,7 @@ int ClientInterface::set_udp_ip(Interface &socket) {
int ClientInterface::set_udp_ip2(Interface &socket) { int ClientInterface::set_udp_ip2(Interface &socket) {
auto arg = socket.Receive<sls::IpAddr>(); auto arg = socket.Receive<sls::IpAddr>();
VerifyIdle(socket); verifyIdle(socket);
if (myDetectorType != JUNGFRAU) { if (myDetectorType != JUNGFRAU) {
throw RuntimeError("UDP Destination IP2 not implemented for this detector"); throw RuntimeError("UDP Destination IP2 not implemented for this detector");
} }
@ -1271,7 +1268,7 @@ int ClientInterface::set_udp_ip2(Interface &socket) {
int ClientInterface::set_udp_port(Interface &socket) { int ClientInterface::set_udp_port(Interface &socket) {
auto arg = socket.Receive<int>(); auto arg = socket.Receive<int>();
VerifyIdle(socket); verifyIdle(socket);
FILE_LOG(logDEBUG1) << "Setting UDP Port:" << arg; FILE_LOG(logDEBUG1) << "Setting UDP Port:" << arg;
impl()->setUDPPortNumber(arg); impl()->setUDPPortNumber(arg);
return socket.Send(OK); return socket.Send(OK);
@ -1279,7 +1276,7 @@ int ClientInterface::set_udp_port(Interface &socket) {
int ClientInterface::set_udp_port2(Interface &socket) { int ClientInterface::set_udp_port2(Interface &socket) {
auto arg = socket.Receive<int>(); auto arg = socket.Receive<int>();
VerifyIdle(socket); verifyIdle(socket);
if (myDetectorType != JUNGFRAU && myDetectorType != EIGER) { if (myDetectorType != JUNGFRAU && myDetectorType != EIGER) {
throw RuntimeError("UDP Destination Port2 not implemented for this detector"); throw RuntimeError("UDP Destination Port2 not implemented for this detector");
} }
@ -1291,22 +1288,28 @@ int ClientInterface::set_udp_port2(Interface &socket) {
int ClientInterface::set_num_interfaces(Interface &socket) { int ClientInterface::set_num_interfaces(Interface &socket) {
auto arg = socket.Receive<int>(); auto arg = socket.Receive<int>();
arg = (arg > 1 ? 2 : 1); arg = (arg > 1 ? 2 : 1);
VerifyIdle(socket); verifyIdle(socket);
if (myDetectorType != JUNGFRAU) { if (myDetectorType != JUNGFRAU) {
throw RuntimeError("Number of interfaces not implemented for this detector"); throw RuntimeError("Number of interfaces not implemented for this detector");
} }
FILE_LOG(logDEBUG1) << "Setting Number of UDP Interfaces:" << arg; FILE_LOG(logDEBUG1) << "Setting Number of UDP Interfaces:" << arg;
if (impl()->setNumberofUDPInterfaces(arg) == FAIL) { try {
throw RuntimeError("Failed to set number of interfaces"); impl()->setNumberofUDPInterfaces(arg);
} catch(const RuntimeError &e) {
throw RuntimeError("Failed to set number of interfaces to " + std::to_string(arg));
} }
return socket.Send(OK); return socket.Send(OK);
} }
int ClientInterface::set_adc_mask_10g(Interface &socket) { int ClientInterface::set_adc_mask_10g(Interface &socket) {
auto arg = socket.Receive<uint32_t>(); auto arg = socket.Receive<uint32_t>();
VerifyIdle(socket); verifyIdle(socket);
FILE_LOG(logDEBUG1) << "Setting 10Gb ADC enable mask: " << arg; FILE_LOG(logDEBUG1) << "Setting 10Gb ADC enable mask: " << arg;
try {
impl()->setTenGigaADCEnableMask(arg); impl()->setTenGigaADCEnableMask(arg);
} catch(const RuntimeError &e) {
throw RuntimeError("Could not set 10Gb adc enable mask due to fifo memory allcoation");
}
auto retval = impl()->getTenGigaADCEnableMask(); auto retval = impl()->getTenGigaADCEnableMask();
if (retval != arg) { if (retval != arg) {
std::ostringstream os; std::ostringstream os;

View File

@ -30,7 +30,7 @@ DataProcessor::DataProcessor(int ind, detectorType dtype, Fifo* f,
bool* fp, bool* act, bool* depaden, bool* sm, bool* qe, bool* fp, bool* act, bool* depaden, bool* sm, bool* qe,
std::vector <int> * cdl, int* cdo, int* cad) : std::vector <int> * cdl, int* cdo, int* cad) :
ThreadObject(ind), ThreadObject(ind, TypeName),
runningFlag(false), runningFlag(false),
generalData(nullptr), generalData(nullptr),
fifo(f), fifo(f),
@ -62,11 +62,7 @@ DataProcessor::DataProcessor(int ind, detectorType dtype, Fifo* f,
rawDataModifyReadyCallBack(nullptr), rawDataModifyReadyCallBack(nullptr),
pRawDataReady(nullptr) pRawDataReady(nullptr)
{ {
if(ThreadObject::CreateThread() == FAIL)
throw sls::RuntimeError("Could not create processing thread");
FILE_LOG(logDEBUG) << "DataProcessor " << ind << " created"; FILE_LOG(logDEBUG) << "DataProcessor " << ind << " created";
memset((void*)&timerBegin, 0, sizeof(timespec)); memset((void*)&timerBegin, 0, sizeof(timespec));
} }
@ -74,13 +70,9 @@ DataProcessor::DataProcessor(int ind, detectorType dtype, Fifo* f,
DataProcessor::~DataProcessor() { DataProcessor::~DataProcessor() {
delete file; delete file;
delete [] tempBuffer; delete [] tempBuffer;
ThreadObject::DestroyThread();
} }
/** getters */ /** getters */
std::string DataProcessor::GetType(){
return TypeName;
}
bool DataProcessor::IsRunning() { bool DataProcessor::IsRunning() {
return runningFlag; return runningFlag;
@ -158,16 +150,6 @@ void DataProcessor::SetGeneralData(GeneralData* g) {
} }
int DataProcessor::SetThreadPriority(int priority) {
struct sched_param param;
param.sched_priority = priority;
if (pthread_setschedparam(thread, SCHED_FIFO, &param) == EPERM)
return FAIL;
FILE_LOG(logINFO) << "Processor Thread Priority set to " << priority;
return OK;
}
void DataProcessor::SetFileFormat(const fileFormat f) { void DataProcessor::SetFileFormat(const fileFormat f) {
if ((file != nullptr) && file->GetFileType() != f) { if ((file != nullptr) && file->GetFileType() != f) {
//remember the pointer values before they are destroyed //remember the pointer values before they are destroyed
@ -220,16 +202,14 @@ void DataProcessor::SetupFileWriter(bool fwe, int* nd, uint32_t* maxf,
} }
// only the first file // only the first file
int DataProcessor::CreateNewFile(masterAttributes& attr) { void DataProcessor::CreateNewFile(masterAttributes& attr) {
if (file == nullptr) if (file == nullptr) {
return FAIL; throw sls::RuntimeError("file object not contstructed");
}
file->CloseAllFiles(); file->CloseAllFiles();
file->resetSubFileIndex(); file->resetSubFileIndex();
if (file->CreateMasterFile(*masterFileWriteEnable, attr) == FAIL) file->CreateMasterFile(*masterFileWriteEnable, attr);
return FAIL; file->CreateFile();
if (file->CreateFile() == FAIL)
return FAIL;
return OK;
} }
@ -240,7 +220,11 @@ void DataProcessor::CloseFiles() {
void DataProcessor::EndofAcquisition(bool anyPacketsCaught, uint64_t numf) { void DataProcessor::EndofAcquisition(bool anyPacketsCaught, uint64_t numf) {
if ((file != nullptr) && file->GetFileType() == HDF5) { if ((file != nullptr) && file->GetFileType() == HDF5) {
try {
file->EndofAcquisition(anyPacketsCaught, numf); file->EndofAcquisition(anyPacketsCaught, numf);
} catch (const sls::RuntimeError &e) {
;// ignore for now //TODO: send error to client via stop receiver
}
} }
} }
@ -352,10 +336,15 @@ void DataProcessor::ProcessAnImage(char* buf) {
// write to file // write to file
if (file != nullptr) if (file != nullptr) {
try {
file->WriteToFile(buf + FIFO_HEADER_NUMBYTES, file->WriteToFile(buf + FIFO_HEADER_NUMBYTES,
sizeof(sls_receiver_header) + (uint32_t)(*((uint32_t*)buf)), //+ size of data (resizable from previous call back sizeof(sls_receiver_header) + (uint32_t)(*((uint32_t*)buf)), //+ size of data (resizable from previous call back
fnum-firstIndex, nump); fnum-firstIndex, nump);
} catch(const sls::RuntimeError &e) {
; //ignore write exception for now (TODO: send error message via stopReceiver tcp)
}
}
} }

View File

@ -18,7 +18,7 @@ const std::string DataStreamer::TypeName = "DataStreamer";
DataStreamer::DataStreamer(int ind, Fifo* f, uint32_t* dr, ROI* r, DataStreamer::DataStreamer(int ind, Fifo* f, uint32_t* dr, ROI* r,
uint64_t* fi, int fd, std::string* ajh, int* nd, bool* gpEnable, bool* qe) : uint64_t* fi, int fd, std::string* ajh, int* nd, bool* gpEnable, bool* qe) :
ThreadObject(ind), ThreadObject(ind, TypeName),
runningFlag(0), runningFlag(0),
generalData(nullptr), generalData(nullptr),
fifo(f), fifo(f),
@ -38,25 +38,16 @@ DataStreamer::DataStreamer(int ind, Fifo* f, uint32_t* dr, ROI* r,
numDet[0] = nd[0]; numDet[0] = nd[0];
numDet[1] = nd[1]; numDet[1] = nd[1];
if(ThreadObject::CreateThread() == FAIL)
throw sls::RuntimeError("Could not create streaming thread");
FILE_LOG(logDEBUG) << "DataStreamer " << ind << " created"; FILE_LOG(logDEBUG) << "DataStreamer " << ind << " created";
// memset(fileNametoStream, 0, MAX_STR_LENGTH);
} }
DataStreamer::~DataStreamer() { DataStreamer::~DataStreamer() {
CloseZmqSocket(); CloseZmqSocket();
delete [] completeBuffer; delete [] completeBuffer;
ThreadObject::DestroyThread();
} }
/** getters */ /** getters */
std::string DataStreamer::GetType(){
return TypeName;
}
bool DataStreamer::IsRunning() { bool DataStreamer::IsRunning() {
return runningFlag; return runningFlag;
@ -82,7 +73,6 @@ void DataStreamer::ResetParametersforNewAcquisition(const std::string& fname){
startedFlag = false; startedFlag = false;
firstIndex = 0; firstIndex = 0;
// strcpy(fileNametoStream, fname);
fileNametoStream = fname; fileNametoStream = fname;
if (completeBuffer) { if (completeBuffer) {
delete[] completeBuffer; delete[] completeBuffer;
@ -109,15 +99,6 @@ void DataStreamer::SetGeneralData(GeneralData* g) {
generalData->Print(); generalData->Print();
} }
int DataStreamer::SetThreadPriority(int priority) {
struct sched_param param;
param.sched_priority = priority;
if (pthread_setschedparam(thread, SCHED_FIFO, &param) == EPERM)
return FAIL;
FILE_LOG(logINFO) << "Streamer Thread Priority set to " << priority;
return OK;
}
void DataStreamer::SetNumberofDetectors(int* nd) { void DataStreamer::SetNumberofDetectors(int* nd) {
numDet[0] = nd[0]; numDet[0] = nd[0];
numDet[1] = nd[1]; numDet[1] = nd[1];
@ -258,14 +239,12 @@ int DataStreamer::SendHeader(sls_receiver_header* rheader, uint32_t size, uint32
int DataStreamer::RestreamStop() { void DataStreamer::RestreamStop() {
//send dummy header //send dummy header
int ret = zmqSocket->SendHeaderData(index, true, SLS_DETECTOR_JSON_HEADER_VERSION); int ret = zmqSocket->SendHeaderData(index, true, SLS_DETECTOR_JSON_HEADER_VERSION);
if (!ret) { if (!ret) {
FILE_LOG(logERROR) << "Could not Restream Dummy Header via ZMQ for port " << zmqSocket->GetPortNumber(); throw sls::RuntimeError("Could not restream Dummy Header via ZMQ for port " + std::to_string(zmqSocket->GetPortNumber()));
return FAIL;
} }
return OK;
} }

View File

@ -23,8 +23,7 @@ Fifo::Fifo(int ind, uint32_t fifoItemSize, uint32_t depth):
status_fifoBound(0), status_fifoBound(0),
status_fifoFree(depth){ status_fifoFree(depth){
FILE_LOG(logDEBUG3) << __SHORT_AT__ << " called"; FILE_LOG(logDEBUG3) << __SHORT_AT__ << " called";
if(CreateFifos(fifoItemSize) == FAIL) CreateFifos(fifoItemSize);
throw sls::RuntimeError("Could not create FIFO");
} }
@ -35,7 +34,7 @@ Fifo::~Fifo() {
int Fifo::CreateFifos(uint32_t fifoItemSize) { void Fifo::CreateFifos(uint32_t fifoItemSize) {
FILE_LOG(logDEBUG3) << __SHORT_AT__ << " called"; FILE_LOG(logDEBUG3) << __SHORT_AT__ << " called";
//destroy if not already //destroy if not already
@ -49,8 +48,7 @@ int Fifo::CreateFifos(uint32_t fifoItemSize) {
size_t mem_len = fifoItemSize * fifoDepth * sizeof(char); size_t mem_len = fifoItemSize * fifoDepth * sizeof(char);
memory = (char*) malloc (mem_len); memory = (char*) malloc (mem_len);
if (memory == nullptr){ if (memory == nullptr){
FILE_LOG(logERROR) << "Could not allocate memory for fifos"; throw sls::RuntimeError("Could not allocate memory for fifos");
return FAIL;
} }
memset(memory, 0, mem_len); memset(memory, 0, mem_len);
FILE_LOG(logDEBUG) << "Memory Allocated " << index << ": " << mem_len << " bytes"; FILE_LOG(logDEBUG) << "Memory Allocated " << index << ": " << mem_len << " bytes";
@ -64,7 +62,6 @@ int Fifo::CreateFifos(uint32_t fifoItemSize) {
} }
} }
FILE_LOG(logINFO) << "Fifo " << index << " reconstructed Depth (rx_fifodepth): " << fifoFree->getDataValue(); FILE_LOG(logINFO) << "Fifo " << index << " reconstructed Depth (rx_fifodepth): " << fifoFree->getDataValue();
return OK;
} }

View File

@ -13,7 +13,6 @@
#include <string.h> #include <string.h>
pthread_mutex_t HDF5File::Mutex = PTHREAD_MUTEX_INITIALIZER;
H5File* HDF5File::masterfd = 0; H5File* HDF5File::masterfd = 0;
hid_t HDF5File::virtualfd = 0; hid_t HDF5File::virtualfd = 0;
@ -128,7 +127,7 @@ void HDF5File::UpdateDataType() {
} }
int HDF5File::CreateFile() { void HDF5File::CreateFile() {
numFilesinAcquisition++; numFilesinAcquisition++;
numFramesInFile = 0; numFramesInFile = 0;
numActualPacketsInFile = 0; numActualPacketsInFile = 0;
@ -142,29 +141,26 @@ int HDF5File::CreateFile() {
uint64_t framestosave = ((*maxFramesPerFile == 0) ? *numImages : // infinite images uint64_t framestosave = ((*maxFramesPerFile == 0) ? *numImages : // infinite images
(((extNumImages - subFileIndex) > (*maxFramesPerFile)) ? // save up to maximum at a time (((extNumImages - subFileIndex) > (*maxFramesPerFile)) ? // save up to maximum at a time
(*maxFramesPerFile) : (extNumImages-subFileIndex))); (*maxFramesPerFile) : (extNumImages-subFileIndex)));
pthread_mutex_lock(&Mutex);
if (HDF5FileStatic::CreateDataFile(index, *overWriteEnable, currentFileName, (*numImages > 1), std::lock_guard<std::mutex> lock(mutex);
HDF5FileStatic::CreateDataFile(index, *overWriteEnable, currentFileName, (*numImages > 1),
subFileIndex, framestosave, nPixelsY, ((*dynamicRange==4) ? (nPixelsX/2) : nPixelsX), subFileIndex, framestosave, nPixelsY, ((*dynamicRange==4) ? (nPixelsX/2) : nPixelsX),
datatype, filefd, dataspace, dataset, datatype, filefd, dataspace, dataset,
HDF5_WRITER_VERSION, MAX_CHUNKED_IMAGES, HDF5_WRITER_VERSION, MAX_CHUNKED_IMAGES,
dataspace_para, dataset_para, dataspace_para, dataset_para,
parameterNames, parameterDataTypes) == FAIL) { parameterNames, parameterDataTypes);
pthread_mutex_unlock(&Mutex);
return FAIL;
}
pthread_mutex_unlock(&Mutex);
if(!(*silentMode)) { if(!(*silentMode)) {
FILE_LOG(logINFO) << *udpPortNumber << ": HDF5 File created: " << currentFileName; FILE_LOG(logINFO) << *udpPortNumber << ": HDF5 File created: " << currentFileName;
} }
return OK;
} }
void HDF5File::CloseCurrentFile() { void HDF5File::CloseCurrentFile() {
pthread_mutex_lock(&Mutex); {
std::lock_guard<std::mutex> lock(mutex);
HDF5FileStatic::CloseDataFile(index, filefd); HDF5FileStatic::CloseDataFile(index, filefd);
pthread_mutex_unlock(&Mutex); }
for (unsigned int i = 0; i < dataset_para.size(); ++i) for (unsigned int i = 0; i < dataset_para.size(); ++i)
delete dataset_para[i]; delete dataset_para[i];
dataset_para.clear(); dataset_para.clear();
@ -177,14 +173,14 @@ void HDF5File::CloseCurrentFile() {
void HDF5File::CloseAllFiles() { void HDF5File::CloseAllFiles() {
numFilesinAcquisition = 0; numFilesinAcquisition = 0;
pthread_mutex_lock(&Mutex); {
std::lock_guard<std::mutex> lock(mutex);
HDF5FileStatic::CloseDataFile(index, filefd); HDF5FileStatic::CloseDataFile(index, filefd);
if (master && (*detIndex==0)) { if (master && (*detIndex==0)) {
HDF5FileStatic::CloseMasterDataFile(masterfd); HDF5FileStatic::CloseMasterDataFile(masterfd);
HDF5FileStatic::CloseVirtualDataFile(virtualfd); HDF5FileStatic::CloseVirtualDataFile(virtualfd);
} }
pthread_mutex_unlock(&Mutex); }
for (unsigned int i = 0; i < dataset_para.size(); ++i) for (unsigned int i = 0; i < dataset_para.size(); ++i)
delete dataset_para[i]; delete dataset_para[i];
dataset_para.clear(); dataset_para.clear();
@ -195,7 +191,7 @@ void HDF5File::CloseAllFiles() {
} }
int HDF5File::WriteToFile(char* buffer, int buffersize, uint64_t fnum, uint32_t nump) { void HDF5File::WriteToFile(char* buffer, int buffersize, uint64_t fnum, uint32_t nump) {
// check if maxframesperfile = 0 for infinite // check if maxframesperfile = 0 for infinite
if ((*maxFramesPerFile) && (numFramesInFile >= (*maxFramesPerFile))) { if ((*maxFramesPerFile) && (numFramesInFile >= (*maxFramesPerFile))) {
@ -205,42 +201,35 @@ int HDF5File::WriteToFile(char* buffer, int buffersize, uint64_t fnum, uint32_t
} }
numFramesInFile++; numFramesInFile++;
numActualPacketsInFile += nump; numActualPacketsInFile += nump;
pthread_mutex_lock(&Mutex);
std::lock_guard<std::mutex> lock(mutex);
// extend dataset (when receiver start followed by many status starts (jungfrau))) // extend dataset (when receiver start followed by many status starts (jungfrau)))
if (fnum >= extNumImages) { if (fnum >= extNumImages) {
if (HDF5FileStatic::ExtendDataset(index, dataspace, dataset, HDF5FileStatic::ExtendDataset(index, dataspace, dataset,
dataspace_para, dataset_para, *numImages) == OK) { dataspace_para, dataset_para, *numImages);
if (!(*silentMode)) { if (!(*silentMode)) {
FILE_LOG(logINFO) << index << " Extending HDF5 dataset by " << FILE_LOG(logINFO) << index << " Extending HDF5 dataset by " <<
extNumImages << ", Total x Dimension: " << (extNumImages + *numImages); extNumImages << ", Total x Dimension: " << (extNumImages + *numImages);
} }
extNumImages += *numImages; extNumImages += *numImages;
} }
}
if (HDF5FileStatic::WriteDataFile(index, buffer + sizeof(sls_receiver_header), HDF5FileStatic::WriteDataFile(index, buffer + sizeof(sls_receiver_header),
// infinite then no need for %maxframesperfile // infinite then no need for %maxframesperfile
((*maxFramesPerFile == 0) ? fnum : fnum%(*maxFramesPerFile)), ((*maxFramesPerFile == 0) ? fnum : fnum%(*maxFramesPerFile)),
nPixelsY, ((*dynamicRange==4) ? (nPixelsX/2) : nPixelsX), nPixelsY, ((*dynamicRange==4) ? (nPixelsX/2) : nPixelsX),
dataspace, dataset, datatype) == OK) { dataspace, dataset, datatype);
if (HDF5FileStatic::WriteParameterDatasets(index, dataspace_para, HDF5FileStatic::WriteParameterDatasets(index, dataspace_para,
// infinite then no need for %maxframesperfile // infinite then no need for %maxframesperfile
((*maxFramesPerFile == 0) ? fnum : fnum%(*maxFramesPerFile)), ((*maxFramesPerFile == 0) ? fnum : fnum%(*maxFramesPerFile)),
dataset_para, (sls_receiver_header*) (buffer), dataset_para, (sls_receiver_header*) (buffer),
parameterDataTypes) == OK) { parameterDataTypes);
pthread_mutex_unlock(&Mutex);
return OK;
}
}
pthread_mutex_unlock(&Mutex);
FILE_LOG(logERROR) << index << "Write to file failed";
return FAIL;
} }
int HDF5File::CreateMasterFile(bool mfwenable, masterAttributes& attr) { void HDF5File::CreateMasterFile(bool mfwenable, masterAttributes& attr) {
//beginning of every acquisition //beginning of every acquisition
numFramesInFile = 0; numFramesInFile = 0;
@ -254,14 +243,11 @@ int HDF5File::CreateMasterFile(bool mfwenable, masterAttributes& attr) {
if(!(*silentMode)) { if(!(*silentMode)) {
FILE_LOG(logINFO) << "Master File: " << masterFileName; FILE_LOG(logINFO) << "Master File: " << masterFileName;
} }
pthread_mutex_lock(&Mutex); std::lock_guard<std::mutex> lock(mutex);
attr.version = HDF5_WRITER_VERSION; attr.version = HDF5_WRITER_VERSION;
int ret = HDF5FileStatic::CreateMasterDataFile(masterfd, masterFileName, HDF5FileStatic::CreateMasterDataFile(masterfd, masterFileName,
*overWriteEnable, attr); *overWriteEnable, attr);
pthread_mutex_unlock(&Mutex);
return ret;
} }
return OK;
} }
@ -286,15 +272,14 @@ void HDF5File::EndofAcquisition(bool anyPacketsCaught, uint64_t numf) {
// called only by the one maser receiver // called only by the one maser receiver
int HDF5File::CreateVirtualFile(uint64_t numf) { void HDF5File::CreateVirtualFile(uint64_t numf) {
pthread_mutex_lock(&Mutex); std::lock_guard<std::mutex> lock(mutex);
std::string vname = HDF5FileStatic::CreateVirtualFileName(*filePath, *fileNamePrefix, *fileIndex); std::string vname = HDF5FileStatic::CreateVirtualFileName(*filePath, *fileNamePrefix, *fileIndex);
if(!(*silentMode)) { if(!(*silentMode)) {
FILE_LOG(logINFO) << "Virtual File: " << vname; FILE_LOG(logINFO) << "Virtual File: " << vname;
} }
HDF5FileStatic::CreateVirtualDataFile(vname,
int ret = HDF5FileStatic::CreateVirtualDataFile(vname,
virtualfd, masterFileName, virtualfd, masterFileName,
*filePath, *fileNamePrefix, *fileIndex, (*numImages > 1), *filePath, *fileNamePrefix, *fileIndex, (*numImages > 1),
*detIndex, *numUnitsPerDetector, *detIndex, *numUnitsPerDetector,
@ -305,21 +290,17 @@ int HDF5File::CreateVirtualFile(uint64_t numf) {
numDetY, numDetX, nPixelsY, ((*dynamicRange==4) ? (nPixelsX/2) : nPixelsX), numDetY, numDetX, nPixelsY, ((*dynamicRange==4) ? (nPixelsX/2) : nPixelsX),
HDF5_WRITER_VERSION, HDF5_WRITER_VERSION,
parameterNames, parameterDataTypes); parameterNames, parameterDataTypes);
pthread_mutex_unlock(&Mutex);
return ret;
} }
// called only by the one maser receiver // called only by the one maser receiver
int HDF5File::LinkVirtualFileinMasterFile() { void HDF5File::LinkVirtualFileinMasterFile() {
//dataset name //dataset name
std::ostringstream osfn; std::ostringstream osfn;
osfn << "/data"; osfn << "/data";
if ((*numImages > 1)) osfn << "_f" << std::setfill('0') << std::setw(12) << 0; if ((*numImages > 1)) osfn << "_f" << std::setfill('0') << std::setw(12) << 0;
std::string dsetname = osfn.str(); std::string dsetname = osfn.str();
pthread_mutex_lock(&Mutex); std::lock_guard<std::mutex> lock(mutex);
int ret = HDF5FileStatic::LinkVirtualInMaster(masterFileName, currentFileName, HDF5FileStatic::LinkVirtualInMaster(masterFileName, currentFileName,
dsetname, parameterNames); dsetname, parameterNames);
pthread_mutex_unlock(&Mutex);
return ret;
} }

View File

@ -18,9 +18,10 @@
/** cosntructor & destructor */ /** cosntructor & destructor */
Implementation::Implementation() { Implementation::Implementation(const detectorType d) {
FILE_LOG(logDEBUG3) << __SHORT_AT__ << " called"; FILE_LOG(logDEBUG3) << __SHORT_AT__ << " called";
InitializeMembers(); InitializeMembers();
setDetectorType(d);
} }
Implementation::~Implementation() { Implementation::~Implementation() {
@ -160,23 +161,12 @@ void Implementation::SetLocalNetworkParameters() {
void Implementation::SetThreadPriorities() { void Implementation::SetThreadPriorities() {
FILE_LOG(logDEBUG3) << __SHORT_AT__ << " called"; FILE_LOG(logDEBUG3) << __SHORT_AT__ << " called";
for (const auto &it : listener) { for (const auto &it : listener) {
if (it->SetThreadPriority(LISTENER_PRIORITY) == FAIL) { it->SetThreadPriority(LISTENER_PRIORITY);
FILE_LOG(logWARNING) << "Could not prioritize listener threads. "
"(No Root Privileges?)";
return;
} }
} }
std::ostringstream osfn;
osfn << "Priorities set - "
"Listener:"
<< LISTENER_PRIORITY;
FILE_LOG(logINFO) << osfn.str();
}
int Implementation::SetupFifoStructure() { void Implementation::SetupFifoStructure() {
FILE_LOG(logDEBUG3) << __SHORT_AT__ << " called"; FILE_LOG(logDEBUG3) << __SHORT_AT__ << " called";
fifo.clear(); fifo.clear();
@ -189,11 +179,8 @@ int Implementation::SetupFifoStructure() {
(generalData->imageSize) + (generalData->fifoBufferHeaderSize), (generalData->imageSize) + (generalData->fifoBufferHeaderSize),
fifoDepth)); fifoDepth));
} catch (...) { } catch (...) {
FILE_LOG(logERROR)
<< "Could not allocate memory for fifo structure of index "
<< i;
fifo.clear(); fifo.clear();
return FAIL; throw sls::RuntimeError("Could not allocate memory for fifo structure " + std::to_string(i));
} }
// set the listener & dataprocessor threads to point to the right fifo // set the listener & dataprocessor threads to point to the right fifo
if (listener.size()) if (listener.size())
@ -210,7 +197,6 @@ int Implementation::SetupFifoStructure() {
fifoDepth) fifoDepth)
<< " bytes"; << " bytes";
FILE_LOG(logINFO) << numThreads << " Fifo structure(s) reconstructed"; FILE_LOG(logINFO) << numThreads << " Fifo structure(s) reconstructed";
return OK;
} }
@ -221,10 +207,8 @@ int Implementation::SetupFifoStructure() {
* * * *
* ************************************************/ * ************************************************/
int Implementation::setDetectorType(const detectorType d) { void Implementation::setDetectorType(const detectorType d) {
FILE_LOG(logDEBUG3) << __SHORT_AT__ << " called"; FILE_LOG(logDEBUG3) << __SHORT_AT__ << " called";
DeleteMembers();
InitializeMembers();
myDetectorType = d; myDetectorType = d;
switch (myDetectorType) { switch (myDetectorType) {
case GOTTHARD: case GOTTHARD:
@ -237,8 +221,7 @@ int Implementation::setDetectorType(const detectorType d) {
<< " Receiver *****"; << " Receiver *****";
break; break;
default: default:
FILE_LOG(logERROR) << "This is an unknown receiver type " << (int)d; throw sls::RuntimeError("This is an unknown receiver type " + std::to_string(static_cast<int>(d)));
return FAIL;
} }
// set detector specific variables // set detector specific variables
@ -270,10 +253,7 @@ int Implementation::setDetectorType(const detectorType d) {
framesPerFile = generalData->maxFramesPerFile; framesPerFile = generalData->maxFramesPerFile;
SetLocalNetworkParameters(); SetLocalNetworkParameters();
if (SetupFifoStructure() == FAIL) { SetupFifoStructure();
FILE_LOG(logERROR) << "Could not allocate memory for fifo structure";
return FAIL;
}
// create threads // create threads
for (int i = 0; i < numThreads; ++i) { for (int i = 0; i < numThreads; ++i) {
@ -293,12 +273,9 @@ int Implementation::setDetectorType(const detectorType d) {
&silentMode, &quadEnable, &ctbDbitList, &ctbDbitOffset, &silentMode, &quadEnable, &ctbDbitList, &ctbDbitOffset,
&ctbAnalogDataBytes)); &ctbAnalogDataBytes));
} catch (...) { } catch (...) {
FILE_LOG(logERROR)
<< "Could not create listener/dataprocessor threads (index:"
<< i << ")";
listener.clear(); listener.clear();
dataProcessor.clear(); dataProcessor.clear();
return FAIL; throw sls::RuntimeError("Could not create listener/dataprocessor threads (index:" + std::to_string(i) + ")");
} }
} }
@ -311,7 +288,6 @@ int Implementation::setDetectorType(const detectorType d) {
SetThreadPriorities(); SetThreadPriorities();
FILE_LOG(logDEBUG) << " Detector type set to " << sls::ToString(d); FILE_LOG(logDEBUG) << " Detector type set to " << sls::ToString(d);
return OK;
} }
int *Implementation::getMultiDetectorSize() const { int *Implementation::getMultiDetectorSize() const {
@ -404,14 +380,12 @@ uint32_t Implementation::getFifoDepth() const {
return fifoDepth; return fifoDepth;
} }
int Implementation::setFifoDepth(const uint32_t i) { void Implementation::setFifoDepth(const uint32_t i) {
if (fifoDepth != i) { if (fifoDepth != i) {
fifoDepth = i; fifoDepth = i;
if (SetupFifoStructure() == FAIL) SetupFifoStructure();
throw sls::RuntimeError("Failed to setup fifo structure");
} }
FILE_LOG(logINFO) << "Fifo Depth: " << i; FILE_LOG(logINFO) << "Fifo Depth: " << i;
return OK;
} }
slsDetectorDefs::frameDiscardPolicy slsDetectorDefs::frameDiscardPolicy
@ -625,18 +599,14 @@ std::vector<uint64_t> Implementation::getNumMissingPackets() const {
return mp; return mp;
} }
int Implementation::startReceiver(std::string& err) { void Implementation::startReceiver() {
FILE_LOG(logDEBUG3) << __SHORT_AT__ << " called"; FILE_LOG(logDEBUG3) << __SHORT_AT__ << " called";
FILE_LOG(logINFO) << "Starting Receiver"; FILE_LOG(logINFO) << "Starting Receiver";
stoppedFlag = false; stoppedFlag = false;
ResetParametersforNewAcquisition(); ResetParametersforNewAcquisition();
// listener // listener
if (CreateUDPSockets() == FAIL) { CreateUDPSockets();
err.assign("Could not create UDP Socket(s).");
FILE_LOG(logERROR) << err;
return FAIL;
}
// callbacks // callbacks
if (startAcquisitionCallBack) { if (startAcquisitionCallBack) {
@ -651,11 +621,7 @@ int Implementation::startReceiver(std::string& err) {
// processor->writer // processor->writer
if (fileWriteEnable) { if (fileWriteEnable) {
if (SetupWriter() == FAIL) { SetupWriter();
err.assign("Could not create file.\n");
FILE_LOG(logERROR) << err;
return FAIL;
}
} else } else
FILE_LOG(logINFO) << "File Write Disabled"; FILE_LOG(logINFO) << "File Write Disabled";
@ -669,7 +635,6 @@ int Implementation::startReceiver(std::string& err) {
FILE_LOG(logINFO) << "Receiver Started"; FILE_LOG(logINFO) << "Receiver Started";
FILE_LOG(logINFO) << "Status: " << sls::ToString(status); FILE_LOG(logINFO) << "Status: " << sls::ToString(status);
return OK;
} }
void Implementation::setStoppedFlag(bool stopped) { void Implementation::setStoppedFlag(bool stopped) {
@ -817,14 +782,12 @@ void Implementation::closeFiles() {
dataProcessor[0]->EndofAcquisition(anycaught, maxIndexCaught); dataProcessor[0]->EndofAcquisition(anycaught, maxIndexCaught);
} }
int Implementation::restreamStop() { void Implementation::restreamStop() {
FILE_LOG(logDEBUG3) << __SHORT_AT__ << " called"; FILE_LOG(logDEBUG3) << __SHORT_AT__ << " called";
for (const auto &it : dataStreamer) { for (const auto &it : dataStreamer) {
if (it->RestreamStop() == FAIL) it->RestreamStop();
throw sls::RuntimeError("Could not restream stop packet");
} }
FILE_LOG(logINFO) << "Restreaming Dummy Header via ZMQ successful"; FILE_LOG(logINFO) << "Restreaming Dummy Header via ZMQ successful";
return OK;
} }
void Implementation::ResetParametersforNewAcquisition() { void Implementation::ResetParametersforNewAcquisition() {
@ -844,29 +807,23 @@ void Implementation::ResetParametersforNewAcquisition() {
} }
} }
int Implementation::CreateUDPSockets() { void Implementation::CreateUDPSockets() {
FILE_LOG(logDEBUG3) << __SHORT_AT__ << " called"; FILE_LOG(logDEBUG3) << __SHORT_AT__ << " called";
bool error = false;
try{
for (unsigned int i = 0; i < listener.size(); ++i) { for (unsigned int i = 0; i < listener.size(); ++i) {
if (listener[i]->CreateUDPSockets() == FAIL) { listener[i]->CreateUDPSockets();
error = true;
break;
} }
} } catch(const sls::RuntimeError &e) {
if (error) {
shutDownUDPSockets(); shutDownUDPSockets();
return FAIL; throw sls::RuntimeError("Could not create UDP Socket(s).");
} }
FILE_LOG(logDEBUG) << "UDP socket(s) created successfully."; FILE_LOG(logDEBUG) << "UDP socket(s) created successfully.";
return OK;
} }
int Implementation::SetupWriter() { void Implementation::SetupWriter() {
FILE_LOG(logDEBUG3) << __SHORT_AT__ << " called"; FILE_LOG(logDEBUG3) << __SHORT_AT__ << " called";
bool error = false;
masterAttributes attr; masterAttributes attr;
attr.detectorType = myDetectorType; attr.detectorType = myDetectorType;
attr.dynamicRange = dynamicRange; attr.dynamicRange = dynamicRange;
@ -892,18 +849,16 @@ int Implementation::SetupWriter() {
for (auto &i : ctbDbitList) { for (auto &i : ctbDbitList) {
attr.dbitlist |= (1 << i); attr.dbitlist |= (1 << i);
} }
for (unsigned int i = 0; i < dataProcessor.size(); ++i)
if (dataProcessor[i]->CreateNewFile(attr) == FAIL) { try {
error = true; for (unsigned int i = 0; i < dataProcessor.size(); ++i) {
break; dataProcessor[i]->CreateNewFile(attr);
} }
if (error) { } catch(const sls::RuntimeError &e) {
shutDownUDPSockets(); shutDownUDPSockets();
closeFiles(); closeFiles();
return FAIL; throw sls::RuntimeError("Could not create file.");
} }
return OK;
} }
void Implementation::StartRunning() { void Implementation::StartRunning() {
@ -935,7 +890,7 @@ int Implementation::getNumberofUDPInterfaces() const {
return numUDPInterfaces; return numUDPInterfaces;
} }
int Implementation::setNumberofUDPInterfaces(const int n) { void Implementation::setNumberofUDPInterfaces(const int n) {
FILE_LOG(logDEBUG3) << __SHORT_AT__ << " called"; FILE_LOG(logDEBUG3) << __SHORT_AT__ << " called";
if (numUDPInterfaces != n) { if (numUDPInterfaces != n) {
@ -959,8 +914,7 @@ int Implementation::setNumberofUDPInterfaces(const int n) {
udpSocketBufferSize = generalData->defaultUdpSocketBufferSize; udpSocketBufferSize = generalData->defaultUdpSocketBufferSize;
// fifo // fifo
if (SetupFifoStructure() == FAIL) SetupFifoStructure();
return FAIL;
// create threads // create threads
for (int i = 0; i < numThreads; ++i) { for (int i = 0; i < numThreads; ++i) {
@ -984,12 +938,9 @@ int Implementation::setNumberofUDPInterfaces(const int n) {
&ctbDbitOffset, &ctbAnalogDataBytes)); &ctbDbitOffset, &ctbAnalogDataBytes));
dataProcessor[i]->SetGeneralData(generalData); dataProcessor[i]->SetGeneralData(generalData);
} catch (...) { } catch (...) {
FILE_LOG(logERROR)
<< "Could not create listener/dataprocessor threads (index:"
<< i << ")";
listener.clear(); listener.clear();
dataProcessor.clear(); dataProcessor.clear();
return FAIL; throw sls::RuntimeError("Could not create listener/dataprocessor threads (index:" + std::to_string(i) + ")");
} }
// streamer threads // streamer threads
if (dataStreamEnable) { if (dataStreamEnable) {
@ -1009,14 +960,11 @@ int Implementation::setNumberofUDPInterfaces(const int n) {
&numThreads, streamingPort, streamingSrcIP); &numThreads, streamingPort, streamingSrcIP);
} catch (...) { } catch (...) {
FILE_LOG(logERROR)
<< "Could not create datastreamer threads (index:" << i
<< ")";
if (dataStreamEnable) { if (dataStreamEnable) {
dataStreamer.clear(); dataStreamer.clear();
dataStreamEnable = false; dataStreamEnable = false;
} }
return FAIL; throw sls::RuntimeError("Could not create datastreamer threads (index:" + std::to_string(i) + ")");
} }
} }
} }
@ -1041,13 +989,10 @@ int Implementation::setNumberofUDPInterfaces(const int n) {
} }
// test socket buffer size with current set up // test socket buffer size with current set up
if (setUDPSocketBufferSize(0) == FAIL) { setUDPSocketBufferSize(0);
return FAIL;
}
} }
FILE_LOG(logINFO) << "Number of Interfaces: " << numUDPInterfaces; FILE_LOG(logINFO) << "Number of Interfaces: " << numUDPInterfaces;
return OK;
} }
std::string Implementation::getEthernetInterface() const { std::string Implementation::getEthernetInterface() const {
@ -1103,22 +1048,17 @@ int64_t Implementation::getUDPSocketBufferSize() const {
return udpSocketBufferSize; return udpSocketBufferSize;
} }
int Implementation::setUDPSocketBufferSize(const int64_t s) { void Implementation::setUDPSocketBufferSize(const int64_t s) {
int64_t size = (s == 0) ? udpSocketBufferSize : s; int64_t size = (s == 0) ? udpSocketBufferSize : s;
size_t listSize = listener.size(); size_t listSize = listener.size();
if (myDetectorType == JUNGFRAU && (int)listSize != numUDPInterfaces) { if (myDetectorType == JUNGFRAU && (int)listSize != numUDPInterfaces) {
FILE_LOG(logERROR) << "Number of Interfaces " << numUDPInterfaces throw sls::RuntimeError("Number of Interfaces " + std::to_string(numUDPInterfaces) + " do not match listener size " + std::to_string(listSize));
<< " do not match listener size " << listSize;
return FAIL;
} }
for (unsigned int i = 0; i < listSize; ++i) { for (unsigned int i = 0; i < listSize; ++i) {
if (listener[i]->CreateDummySocketForUDPSocketBufferSize(size) == FAIL) listener[i]->CreateDummySocketForUDPSocketBufferSize(size);
return FAIL;
} }
return OK;
} }
int64_t Implementation::getActualUDPSocketBufferSize() const { int64_t Implementation::getActualUDPSocketBufferSize() const {
@ -1137,7 +1077,7 @@ bool Implementation::getDataStreamEnable() const {
return dataStreamEnable; return dataStreamEnable;
} }
int Implementation::setDataStreamEnable(const bool enable) { void Implementation::setDataStreamEnable(const bool enable) {
if (dataStreamEnable != enable) { if (dataStreamEnable != enable) {
dataStreamEnable = enable; dataStreamEnable = enable;
@ -1164,14 +1104,13 @@ int Implementation::setDataStreamEnable(const bool enable) {
} catch (...) { } catch (...) {
dataStreamer.clear(); dataStreamer.clear();
dataStreamEnable = false; dataStreamEnable = false;
return FAIL; throw sls::RuntimeError("Could not set data stream enable.");
} }
} }
SetThreadPriorities(); SetThreadPriorities();
} }
} }
FILE_LOG(logINFO) << "Data Send to Gui: " << dataStreamEnable; FILE_LOG(logINFO) << "Data Send to Gui: " << dataStreamEnable;
return OK;
} }
uint32_t Implementation::getStreamingFrequency() const { uint32_t Implementation::getStreamingFrequency() const {
@ -1179,12 +1118,11 @@ uint32_t Implementation::getStreamingFrequency() const {
return streamingFrequency; return streamingFrequency;
} }
int Implementation::setStreamingFrequency(const uint32_t freq) { void Implementation::setStreamingFrequency(const uint32_t freq) {
if (streamingFrequency != freq) { if (streamingFrequency != freq) {
streamingFrequency = freq; streamingFrequency = freq;
} }
FILE_LOG(logINFO) << "Streaming Frequency: " << streamingFrequency; FILE_LOG(logINFO) << "Streaming Frequency: " << streamingFrequency;
return OK;
} }
uint32_t Implementation::getStreamingTimer() const { uint32_t Implementation::getStreamingTimer() const {
@ -1307,7 +1245,7 @@ uint32_t Implementation::getNumberofAnalogSamples() const {
return numberOfAnalogSamples; return numberOfAnalogSamples;
} }
int Implementation::setNumberofAnalogSamples(const uint32_t i) { void Implementation::setNumberofAnalogSamples(const uint32_t i) {
if (numberOfAnalogSamples != i) { if (numberOfAnalogSamples != i) {
numberOfAnalogSamples = i; numberOfAnalogSamples = i;
@ -1318,13 +1256,11 @@ int Implementation::setNumberofAnalogSamples(const uint32_t i) {
for (const auto &it : dataProcessor) for (const auto &it : dataProcessor)
it->SetPixelDimension(); it->SetPixelDimension();
if (SetupFifoStructure() == FAIL) SetupFifoStructure();
return FAIL;
} }
FILE_LOG(logINFO) << "Number of Analog Samples: " << numberOfAnalogSamples; FILE_LOG(logINFO) << "Number of Analog Samples: " << numberOfAnalogSamples;
FILE_LOG(logINFO) << "Packets per Frame: " FILE_LOG(logINFO) << "Packets per Frame: "
<< (generalData->packetsPerFrame); << (generalData->packetsPerFrame);
return OK;
} }
uint32_t Implementation::getNumberofDigitalSamples() const { uint32_t Implementation::getNumberofDigitalSamples() const {
@ -1332,7 +1268,7 @@ uint32_t Implementation::getNumberofDigitalSamples() const {
return numberOfDigitalSamples; return numberOfDigitalSamples;
} }
int Implementation::setNumberofDigitalSamples(const uint32_t i) { void Implementation::setNumberofDigitalSamples(const uint32_t i) {
if (numberOfDigitalSamples != i) { if (numberOfDigitalSamples != i) {
numberOfDigitalSamples = i; numberOfDigitalSamples = i;
@ -1343,14 +1279,12 @@ int Implementation::setNumberofDigitalSamples(const uint32_t i) {
for (const auto &it : dataProcessor) for (const auto &it : dataProcessor)
it->SetPixelDimension(); it->SetPixelDimension();
if (SetupFifoStructure() == FAIL) SetupFifoStructure();
return FAIL;
} }
FILE_LOG(logINFO) << "Number of Digital Samples: " FILE_LOG(logINFO) << "Number of Digital Samples: "
<< numberOfDigitalSamples; << numberOfDigitalSamples;
FILE_LOG(logINFO) << "Packets per Frame: " FILE_LOG(logINFO) << "Packets per Frame: "
<< (generalData->packetsPerFrame); << (generalData->packetsPerFrame);
return OK;
} }
uint32_t Implementation::getDynamicRange() const { uint32_t Implementation::getDynamicRange() const {
@ -1358,7 +1292,7 @@ uint32_t Implementation::getDynamicRange() const {
return dynamicRange; return dynamicRange;
} }
int Implementation::setDynamicRange(const uint32_t i) { void Implementation::setDynamicRange(const uint32_t i) {
if (dynamicRange != i) { if (dynamicRange != i) {
dynamicRange = i; dynamicRange = i;
@ -1369,12 +1303,10 @@ int Implementation::setDynamicRange(const uint32_t i) {
// to update npixelsx, npixelsy in file writer // to update npixelsx, npixelsy in file writer
for (const auto &it : dataProcessor) for (const auto &it : dataProcessor)
it->SetPixelDimension(); it->SetPixelDimension();
if (SetupFifoStructure() == FAIL) SetupFifoStructure();
return FAIL;
} }
} }
FILE_LOG(logINFO) << "Dynamic Range: " << dynamicRange; FILE_LOG(logINFO) << "Dynamic Range: " << dynamicRange;
return OK;
} }
slsDetectorDefs::ROI Implementation::getROI() const { slsDetectorDefs::ROI Implementation::getROI() const {
@ -1382,7 +1314,7 @@ slsDetectorDefs::ROI Implementation::getROI() const {
return roi; return roi;
} }
int Implementation::setROI(slsDetectorDefs::ROI arg) { void Implementation::setROI(slsDetectorDefs::ROI arg) {
if (roi.xmin != arg.xmin || roi.xmax != arg.xmax) { if (roi.xmin != arg.xmin || roi.xmax != arg.xmax) {
roi.xmin = arg.xmin; roi.xmin = arg.xmin;
roi.xmax = arg.xmax; roi.xmax = arg.xmax;
@ -1392,14 +1324,12 @@ int Implementation::setROI(slsDetectorDefs::ROI arg) {
framesPerFile = generalData->maxFramesPerFile; framesPerFile = generalData->maxFramesPerFile;
for (const auto &it : dataProcessor) for (const auto &it : dataProcessor)
it->SetPixelDimension(); it->SetPixelDimension();
if (SetupFifoStructure() == FAIL) SetupFifoStructure();
return FAIL;
} }
FILE_LOG(logINFO) << "ROI: [" << roi.xmin << ", " << roi.xmax << "]";; FILE_LOG(logINFO) << "ROI: [" << roi.xmin << ", " << roi.xmax << "]";;
FILE_LOG(logINFO) << "Packets per Frame: " FILE_LOG(logINFO) << "Packets per Frame: "
<< (generalData->packetsPerFrame); << (generalData->packetsPerFrame);
return OK;
} }
bool Implementation::getTenGigaEnable() const { bool Implementation::getTenGigaEnable() const {
@ -1407,7 +1337,7 @@ bool Implementation::getTenGigaEnable() const {
return tengigaEnable; return tengigaEnable;
} }
int Implementation::setTenGigaEnable(const bool b) { void Implementation::setTenGigaEnable(const bool b) {
if (tengigaEnable != b) { if (tengigaEnable != b) {
tengigaEnable = b; tengigaEnable = b;
// side effects // side effects
@ -1427,13 +1357,11 @@ int Implementation::setTenGigaEnable(const bool b) {
break; break;
} }
if (SetupFifoStructure() == FAIL) SetupFifoStructure();
return FAIL;
} }
FILE_LOG(logINFO) << "Ten Giga: " << (tengigaEnable ? "enabled" : "disabled"); FILE_LOG(logINFO) << "Ten Giga: " << (tengigaEnable ? "enabled" : "disabled");
FILE_LOG(logINFO) << "Packets per Frame: " FILE_LOG(logINFO) << "Packets per Frame: "
<< (generalData->packetsPerFrame); << (generalData->packetsPerFrame);
return OK;
} }
int Implementation::getFlippedDataX() const { int Implementation::getFlippedDataX() const {
@ -1465,7 +1393,7 @@ bool Implementation::getGapPixelsEnable() const {
return gapPixelsEnable; return gapPixelsEnable;
} }
int Implementation::setGapPixelsEnable(const bool b) { void Implementation::setGapPixelsEnable(const bool b) {
if (gapPixelsEnable != b) { if (gapPixelsEnable != b) {
gapPixelsEnable = b; gapPixelsEnable = b;
@ -1473,11 +1401,9 @@ int Implementation::setGapPixelsEnable(const bool b) {
generalData->SetGapPixelsEnable(b, dynamicRange, quadEnable); generalData->SetGapPixelsEnable(b, dynamicRange, quadEnable);
for (const auto &it : dataProcessor) for (const auto &it : dataProcessor)
it->SetPixelDimension(); it->SetPixelDimension();
if (SetupFifoStructure() == FAIL) SetupFifoStructure();
return FAIL;
} }
FILE_LOG(logINFO) << "Gap Pixels Enable: " << gapPixelsEnable; FILE_LOG(logINFO) << "Gap Pixels Enable: " << gapPixelsEnable;
return OK;
} }
bool Implementation::getQuad() const { bool Implementation::getQuad() const {
@ -1485,7 +1411,7 @@ bool Implementation::getQuad() const {
return quadEnable; return quadEnable;
} }
int Implementation::setQuad(const bool b) { void Implementation::setQuad(const bool b) {
if (quadEnable != b) { if (quadEnable != b) {
quadEnable = b; quadEnable = b;
@ -1493,8 +1419,7 @@ int Implementation::setQuad(const bool b) {
// to update npixelsx, npixelsy in file writer // to update npixelsx, npixelsy in file writer
for (const auto &it : dataProcessor) for (const auto &it : dataProcessor)
it->SetPixelDimension(); it->SetPixelDimension();
if (SetupFifoStructure() == FAIL) SetupFifoStructure();
return FAIL;
if (!quadEnable) { if (!quadEnable) {
for (const auto &it : dataStreamer) { for (const auto &it : dataStreamer) {
@ -1513,7 +1438,6 @@ int Implementation::setQuad(const bool b) {
} }
} }
FILE_LOG(logINFO) << "Quad Enable: " << quadEnable; FILE_LOG(logINFO) << "Quad Enable: " << quadEnable;
return OK;
} }
bool Implementation::getActivate() const { bool Implementation::getActivate() const {
@ -1557,7 +1481,7 @@ Implementation::getReadoutMode() const {
return readoutType; return readoutType;
} }
int Implementation::setReadoutMode(const readoutMode f) { void Implementation::setReadoutMode(const readoutMode f) {
if (readoutType != f) { if (readoutType != f) {
readoutType = f; readoutType = f;
@ -1568,14 +1492,12 @@ int Implementation::setReadoutMode(const readoutMode f) {
tengigaEnable, readoutType); tengigaEnable, readoutType);
for (const auto &it : dataProcessor) for (const auto &it : dataProcessor)
it->SetPixelDimension(); it->SetPixelDimension();
if (SetupFifoStructure() == FAIL) SetupFifoStructure();
return FAIL;
} }
FILE_LOG(logINFO) << "Readout Mode: " << sls::ToString(f); FILE_LOG(logINFO) << "Readout Mode: " << sls::ToString(f);
FILE_LOG(logINFO) << "Packets per Frame: " FILE_LOG(logINFO) << "Packets per Frame: "
<< (generalData->packetsPerFrame); << (generalData->packetsPerFrame);
return OK;
} }
uint32_t Implementation::getADCEnableMask() const { uint32_t Implementation::getADCEnableMask() const {
@ -1583,7 +1505,7 @@ uint32_t Implementation::getADCEnableMask() const {
return adcEnableMaskOneGiga; return adcEnableMaskOneGiga;
} }
int Implementation::setADCEnableMask(uint32_t mask) { void Implementation::setADCEnableMask(uint32_t mask) {
if (adcEnableMaskOneGiga != mask) { if (adcEnableMaskOneGiga != mask) {
adcEnableMaskOneGiga = mask; adcEnableMaskOneGiga = mask;
@ -1594,15 +1516,13 @@ int Implementation::setADCEnableMask(uint32_t mask) {
for (const auto &it : dataProcessor) for (const auto &it : dataProcessor)
it->SetPixelDimension(); it->SetPixelDimension();
if (SetupFifoStructure() == FAIL) SetupFifoStructure();
return FAIL;
} }
FILE_LOG(logINFO) << "ADC Enable Mask for 1Gb mode: 0x" << std::hex << adcEnableMaskOneGiga FILE_LOG(logINFO) << "ADC Enable Mask for 1Gb mode: 0x" << std::hex << adcEnableMaskOneGiga
<< std::dec; << std::dec;
FILE_LOG(logINFO) << "Packets per Frame: " FILE_LOG(logINFO) << "Packets per Frame: "
<< (generalData->packetsPerFrame); << (generalData->packetsPerFrame);
return OK;
} }
uint32_t Implementation::getTenGigaADCEnableMask() const { uint32_t Implementation::getTenGigaADCEnableMask() const {
@ -1610,7 +1530,7 @@ uint32_t Implementation::getTenGigaADCEnableMask() const {
return adcEnableMaskTenGiga; return adcEnableMaskTenGiga;
} }
int Implementation::setTenGigaADCEnableMask(uint32_t mask) { void Implementation::setTenGigaADCEnableMask(uint32_t mask) {
if (adcEnableMaskTenGiga != mask) { if (adcEnableMaskTenGiga != mask) {
adcEnableMaskTenGiga = mask; adcEnableMaskTenGiga = mask;
@ -1621,15 +1541,13 @@ int Implementation::setTenGigaADCEnableMask(uint32_t mask) {
for (const auto &it : dataProcessor) for (const auto &it : dataProcessor)
it->SetPixelDimension(); it->SetPixelDimension();
if (SetupFifoStructure() == FAIL) SetupFifoStructure();
return FAIL;
} }
FILE_LOG(logINFO) << "ADC Enable Mask for 10Gb mode: 0x" << std::hex << adcEnableMaskTenGiga FILE_LOG(logINFO) << "ADC Enable Mask for 10Gb mode: 0x" << std::hex << adcEnableMaskTenGiga
<< std::dec; << std::dec;
FILE_LOG(logINFO) << "Packets per Frame: " FILE_LOG(logINFO) << "Packets per Frame: "
<< (generalData->packetsPerFrame); << (generalData->packetsPerFrame);
return OK;
} }
std::vector<int> Implementation::getDbitList() const { std::vector<int> Implementation::getDbitList() const {

View File

@ -24,7 +24,7 @@ Listener::Listener(int ind, detectorType dtype, Fifo* f, std::atomic<runStatus>*
uint32_t* portno, std::string* e, uint64_t* nf, uint32_t* dr, uint32_t* portno, std::string* e, uint64_t* nf, uint32_t* dr,
int64_t* us, int64_t* as, uint32_t* fpf, int64_t* us, int64_t* as, uint32_t* fpf,
frameDiscardPolicy* fdp, bool* act, bool* depaden, bool* sm) : frameDiscardPolicy* fdp, bool* act, bool* depaden, bool* sm) :
ThreadObject(ind), ThreadObject(ind, TypeName),
runningFlag(0), runningFlag(0),
generalData(nullptr), generalData(nullptr),
fifo(f), fifo(f),
@ -55,9 +55,6 @@ Listener::Listener(int ind, detectorType dtype, Fifo* f, std::atomic<runStatus>*
numFramesStatistic(0), numFramesStatistic(0),
oddStartingPacket(true) oddStartingPacket(true)
{ {
if(ThreadObject::CreateThread() == FAIL)
throw sls::RuntimeError("Could not create listener thread");
FILE_LOG(logDEBUG) << "Listener " << ind << " created"; FILE_LOG(logDEBUG) << "Listener " << ind << " created";
} }
@ -67,15 +64,9 @@ Listener::~Listener() {
sem_post(&semaphore_socket); sem_post(&semaphore_socket);
sem_destroy(&semaphore_socket); sem_destroy(&semaphore_socket);
} }
ThreadObject::DestroyThread();
} }
/** getters */ /** getters */
std::string Listener::GetType(){
return TypeName;
}
bool Listener::IsRunning() { bool Listener::IsRunning() {
return runningFlag; return runningFlag;
} }
@ -155,19 +146,10 @@ void Listener::SetGeneralData(GeneralData* g) {
} }
int Listener::SetThreadPriority(int priority) { void Listener::CreateUDPSockets() {
struct sched_param param;
param.sched_priority = priority;
if (pthread_setschedparam(thread, SCHED_FIFO, &param) == EPERM)
return FAIL;
FILE_LOG(logINFO) << "Listener Thread Priority set to " << priority;
return OK;
}
int Listener::CreateUDPSockets() {
if (!(*activated)) { if (!(*activated)) {
return OK; return;
} }
//if eth is mistaken with ip address //if eth is mistaken with ip address
@ -186,8 +168,7 @@ int Listener::CreateUDPSockets() {
*udpSocketBufferSize); *udpSocketBufferSize);
FILE_LOG(logINFO) << index << ": UDP port opened at port " << *udpPortNumber; FILE_LOG(logINFO) << index << ": UDP port opened at port " << *udpPortNumber;
} catch (...) { } catch (...) {
FILE_LOG(logERROR) << "Could not create UDP socket on port " << *udpPortNumber; throw sls::RuntimeError("Could not create UDP socket on port "+ std::to_string(*udpPortNumber));
return FAIL;
} }
udpSocketAlive = true; udpSocketAlive = true;
@ -195,8 +176,6 @@ int Listener::CreateUDPSockets() {
// doubled due to kernel bookkeeping (could also be less due to permissions) // doubled due to kernel bookkeeping (could also be less due to permissions)
*actualUDPSocketBufferSize = udpSocket->getActualUDPSocketBufferSize(); *actualUDPSocketBufferSize = udpSocket->getActualUDPSocketBufferSize();
return OK;
} }
@ -216,12 +195,12 @@ void Listener::ShutDownUDPSocket() {
} }
int Listener::CreateDummySocketForUDPSocketBufferSize(int64_t s) { void Listener::CreateDummySocketForUDPSocketBufferSize(int64_t s) {
FILE_LOG(logINFO) << "Testing UDP Socket Buffer size " << s << " with test port " << *udpPortNumber; FILE_LOG(logINFO) << "Testing UDP Socket Buffer size " << s << " with test port " << *udpPortNumber;
if (!(*activated)) { if (!(*activated)) {
*actualUDPSocketBufferSize = (s*2); *actualUDPSocketBufferSize = (s*2);
return OK; return;
} }
int64_t temp = *udpSocketBufferSize; int64_t temp = *udpSocketBufferSize;
@ -247,12 +226,8 @@ int Listener::CreateDummySocketForUDPSocketBufferSize(int64_t s) {
} }
} catch (...) { } catch (...) {
FILE_LOG(logERROR) << "Could not create a test UDP socket on port " << *udpPortNumber; throw sls::RuntimeError("Could not create a test UDP socket on port " + std::to_string(*udpPortNumber));
return FAIL;
} }
return OK;
} }
void Listener::SetHardCodedPosition(uint16_t r, uint16_t c) { void Listener::SetHardCodedPosition(uint16_t r, uint16_t c) {

View File

@ -6,103 +6,71 @@
#include "ThreadObject.h" #include "ThreadObject.h"
#include "container_utils.h"
#include <iostream> #include <iostream>
#include <syscall.h> #include <syscall.h>
ThreadObject::ThreadObject(int ind): ThreadObject::ThreadObject(int threadIndex, std::string threadType)
index(ind), : index(threadIndex), type(threadType) {
alive(false), FILE_LOG(logDEBUG) << type << " thread created: " << index;
killThread(false),
thread(0) sem_init(&semaphore,1,0);
{
PrintMembers(); try {
threadObject = sls::make_unique<std::thread>(&ThreadObject::RunningThread, this);
} catch (...) {
throw sls::RuntimeError("Could not create " + type + " thread with index " + std::to_string(index));
}
} }
ThreadObject::~ThreadObject() { ThreadObject::~ThreadObject() {
DestroyThread();
}
void ThreadObject::PrintMembers() {
FILE_LOG(logDEBUG) << "Index : " << index
<< "\nalive: " << alive
<< "\nkillThread: " << killThread
<< "\npthread: " << thread;
}
void ThreadObject::DestroyThread() {
if(alive){
killThread = true; killThread = true;
sem_post(&semaphore); sem_post(&semaphore);
pthread_join(thread,nullptr);
threadObject->join();
sem_destroy(&semaphore); sem_destroy(&semaphore);
killThread = false;
alive = false;
FILE_LOG(logDEBUG) << GetType() << " thread with index " << index << " destroyed successfully.";
}
}
int ThreadObject::CreateThread() {
if(alive){
FILE_LOG(logERROR) << "Cannot create thread " << index << ". Already alive";
return FAIL;
}
sem_init(&semaphore,1,0);
killThread = false;
if(pthread_create(&thread, nullptr,StartThread, (void*) this)){
FILE_LOG(logERROR) << "Could not create " << GetType() << " thread with index " << index;
return FAIL;
}
alive = true;
FILE_LOG(logDEBUG) << GetType() << " thread " << index << " created successfully.";
return OK;
}
void* ThreadObject::StartThread(void* thisPointer) {
((ThreadObject*)thisPointer)->RunningThread();
return thisPointer;
} }
void ThreadObject::RunningThread() { void ThreadObject::RunningThread() {
FILE_LOG(logINFOBLUE) << "Created [ " << GetType() << "Thread " << index << ", " FILE_LOG(logINFOBLUE) << "Created [ " << type << "Thread " << index << ", Tid: " << syscall(SYS_gettid) << "]";
"Tid: " << syscall(SYS_gettid) << "]"; FILE_LOG(logDEBUG) << type << " thread " << index << " created successfully.";
while(true) { while(true) {
while(IsRunning()) { while(IsRunning()) {
ThreadExecution(); ThreadExecution();
}
}//end of inner loop
//wait till the next acquisition //wait till the next acquisition
sem_wait(&semaphore); sem_wait(&semaphore);
if(killThread) { if(killThread) {
FILE_LOG(logINFOBLUE) << "Exiting [ " << GetType() << break;
" Thread " << index << ", Tid: " << syscall(SYS_gettid) << "]"; }
pthread_exit(nullptr);
} }
}//end of outer loop FILE_LOG(logDEBUG) << type << " thread with index " << index << " destroyed successfully.";
FILE_LOG(logINFOBLUE) << "Exiting [ " << type << " Thread " << index << ", Tid: " << syscall(SYS_gettid) << "]";
} }
void ThreadObject::Continue() { void ThreadObject::Continue() {
sem_post(&semaphore); sem_post(&semaphore);
} }
void ThreadObject::SetThreadPriority(int priority) {
struct sched_param param;
param.sched_priority = priority;
if (pthread_setschedparam(threadObject->native_handle(), SCHED_FIFO, &param) == EPERM) {
if (!index) {
FILE_LOG(logWARNING) << "Could not prioritize " << type << " thread. "
"(No Root Privileges?)";
}
} else {
FILE_LOG(logINFO) << "Priorities set - " << type << ": " << priority;
}
}

View File

@ -4,9 +4,9 @@
#define APIRECEIVER 0x190722 #define APIRECEIVER 0x190722
#define APIGUI 0x190723 #define APIGUI 0x190723
#define APIMOENCH 0x190820 #define APIMOENCH 0x190820
#define APIEIGER 0x191111
#define APIGOTTHARD2 0x191127 #define APIGOTTHARD2 0x191127
#define APIMYTHEN3 0x191127 #define APIMYTHEN3 0x191127
#define APICTB 0x191127 #define APICTB 0x191127
#define APIGOTTHARD 0x191127 #define APIGOTTHARD 0x191127
#define APIJUNGFRAU 0x191127 #define APIJUNGFRAU 0x191127
#define APIEIGER 0x191129