format support lib

This commit is contained in:
Erik Frojdh 2020-05-05 10:07:19 +02:00
parent e599bb7c24
commit ea4044e4b1
38 changed files with 775 additions and 854 deletions

View File

@ -52,7 +52,6 @@ set(ClangFormat_EXCLUDE_PATTERNS "build/"
"slsDetectorCalibration/" "slsDetectorCalibration/"
"slsDetectorServers/" "slsDetectorServers/"
"ctbGui/" "ctbGui/"
"slsSupportLib/"
"manual/" "manual/"
"slsDetectorGui/" "slsDetectorGui/"
"python/" "python/"

View File

@ -272,7 +272,7 @@ void DataProcessor::ProcessAnImage(char *buf) {
buf + FIFO_HEADER_NUMBYTES, buf + FIFO_HEADER_NUMBYTES,
sizeof(sls_receiver_header) + sizeof(sls_receiver_header) +
(uint32_t)(*((uint32_t *)buf)), //+ size of data (resizable (uint32_t)(*((uint32_t *)buf)), //+ size of data (resizable
//from previous call back // from previous call back
fnum - firstIndex, nump); fnum - firstIndex, nump);
} catch (const sls::RuntimeError &e) { } catch (const sls::RuntimeError &e) {
; // ignore write exception for now (TODO: send error message via ; // ignore write exception for now (TODO: send error message via

View File

@ -344,8 +344,9 @@ uint32_t Listener::ListenToAnImage(char *buf) {
// copy packet // copy packet
switch (myDetectorType) { switch (myDetectorType) {
// for gotthard, 1st packet: 4 bytes fnum, CACA // for gotthard, 1st packet: 4 bytes fnum, CACA
// + CACA, 639*2 bytes data 2nd packet: 4 bytes fnum, previous 1*2 bytes // + CACA, 639*2 bytes data 2nd packet: 4 bytes
//data + 640*2 bytes data !! // fnum, previous 1*2 bytes
// data + 640*2 bytes data !!
case GOTTHARD: case GOTTHARD:
if (!pnum) if (!pnum)
memcpy(buf + fifohsize, &carryOverPacket[hsize + 4], dsize - 2); memcpy(buf + fifohsize, &carryOverPacket[hsize + 4], dsize - 2);
@ -514,8 +515,9 @@ uint32_t Listener::ListenToAnImage(char *buf) {
// copy packet // copy packet
switch (myDetectorType) { switch (myDetectorType) {
// for gotthard, 1st packet: 4 bytes fnum, CACA // for gotthard, 1st packet: 4 bytes fnum, CACA
// + CACA, 639*2 bytes data 2nd packet: 4 bytes fnum, previous 1*2 bytes // + CACA, 639*2 bytes data 2nd packet: 4 bytes
//data + 640*2 bytes data !! // fnum, previous 1*2 bytes
// data + 640*2 bytes data !!
case GOTTHARD: case GOTTHARD:
if (!pnum) if (!pnum)
memcpy(buf + fifohsize + (pnum * dsize), memcpy(buf + fifohsize + (pnum * dsize),

3
slsSupportLib/include/DataSocket.h Executable file → Normal file
View File

@ -18,12 +18,11 @@ class DataSocket {
DataSocket &operator=(DataSocket &&move) noexcept; DataSocket &operator=(DataSocket &&move) noexcept;
void swap(DataSocket &other) noexcept; void swap(DataSocket &other) noexcept;
//No copy since the class manage the underlying socket // No copy since the class manage the underlying socket
DataSocket(const DataSocket &) = delete; DataSocket(const DataSocket &) = delete;
DataSocket &operator=(DataSocket const &) = delete; DataSocket &operator=(DataSocket const &) = delete;
int getSocketId() const { return sockfd_; } int getSocketId() const { return sockfd_; }
int Send(const void *buffer, size_t size); int Send(const void *buffer, size_t size);
template <typename T> int Send(T &&data) { template <typename T> int Send(T &&data) {
return Send(&data, sizeof(data)); return Send(&data, sizeof(data));

View File

@ -104,7 +104,8 @@ template <typename T, size_t Capacity> class FixedCapacityContainer {
} }
} }
template <typename Container> bool is_equal(const Container &c) const noexcept { template <typename Container>
bool is_equal(const Container &c) const noexcept {
if (current_size != c.size()) { if (current_size != c.size()) {
return false; return false;
} else { } else {

2
slsSupportLib/include/ServerSocket.h Executable file → Normal file
View File

@ -18,7 +18,7 @@ class ServerSocket : public DataSocket {
IpAddr getLastClient() const noexcept { return lastClient; } IpAddr getLastClient() const noexcept { return lastClient; }
IpAddr getThisClient() const noexcept { return thisClient; } IpAddr getThisClient() const noexcept { return thisClient; }
IpAddr getLockedBy() const noexcept { return lockedBy; } IpAddr getLockedBy() const noexcept { return lockedBy; }
bool differentClients() const noexcept {return lastClient != thisClient;} bool differentClients() const noexcept { return lastClient != thisClient; }
void setLockedBy(IpAddr addr) { lockedBy = addr; } void setLockedBy(IpAddr addr) { lockedBy = addr; }
void setLastClient(IpAddr addr) { lastClient = addr; } void setLastClient(IpAddr addr) { lastClient = addr; }
int getPort() const noexcept { return serverPort; } int getPort() const noexcept { return serverPort; }

View File

@ -9,9 +9,10 @@ using us = std::chrono::microseconds;
using ms = std::chrono::milliseconds; using ms = std::chrono::milliseconds;
using s = std::chrono::seconds; using s = std::chrono::seconds;
//Absolute value of std::chrono::duration // Absolute value of std::chrono::duration
template <class Rep, class Period> template <class Rep, class Period>
constexpr std::chrono::duration<Rep, Period> abs(std::chrono::duration<Rep, Period> d) { constexpr std::chrono::duration<Rep, Period>
abs(std::chrono::duration<Rep, Period> d) {
return d >= d.zero() ? d : -d; return d >= d.zero() ? d : -d;
} }

19
slsSupportLib/include/Timer.h Executable file → Normal file
View File

@ -4,35 +4,32 @@
#include <iostream> #include <iostream>
#include <string> #include <string>
namespace sls{ namespace sls {
class Timer { class Timer {
using clock = std::chrono::high_resolution_clock; using clock = std::chrono::high_resolution_clock;
using time_point = std::chrono::time_point<clock>; using time_point = std::chrono::time_point<clock>;
public: public:
Timer(std::string name = "0") Timer(std::string name = "0") : t0(clock::now()), name_(name) {}
: t0(clock::now()), name_(name) {
}
double elapsed_ms() { double elapsed_ms() {
return std::chrono::duration<double, std::milli>(clock::now() - t0).count(); return std::chrono::duration<double, std::milli>(clock::now() - t0)
.count();
} }
double elapsed_s() { double elapsed_s() {
return std::chrono::duration<double>(clock::now() - t0).count(); return std::chrono::duration<double>(clock::now() - t0).count();
} }
void print_elapsed() { void print_elapsed() {
std::cout << "Timer \"" << name_ << "\": Elapsed time " << elapsed_ms() << " ms\n"; std::cout << "Timer \"" << name_ << "\": Elapsed time " << elapsed_ms()
} << " ms\n";
void restart() {
t0 = clock::now();
} }
void restart() { t0 = clock::now(); }
private: private:
time_point t0; time_point t0;
std::string name_; std::string name_;
}; };
}; // namespace sls
}; //namespace sls
#endif // TIMER_H #endif // TIMER_H

View File

@ -31,19 +31,20 @@ template <typename... Ts> struct has_str_helper {};
template <typename T> template <typename T>
struct has_str<T, typename std::conditional< struct has_str<T, typename std::conditional<
false, false, has_str_helper<decltype(std::declval<T>().str())>,
has_str_helper<decltype(std::declval<T>().str())>,
void>::type> : public std::true_type {}; void>::type> : public std::true_type {};
/** /**
* Has emplace_back method * Has emplace_back method
*/ */
template <typename T, typename _ = void> struct has_emplace_back : std::false_type {}; template <typename T, typename _ = void>
struct has_emplace_back : std::false_type {};
template <typename... Ts> struct has_emplace_back_helper {}; template <typename... Ts> struct has_emplace_back_helper {};
template <typename T> template <typename T>
struct has_emplace_back<T, typename std::conditional< struct has_emplace_back<
T, typename std::conditional<
false, false,
has_emplace_back_helper<decltype(std::declval<T>().emplace_back())>, has_emplace_back_helper<decltype(std::declval<T>().emplace_back())>,
void>::type> : public std::true_type {}; void>::type> : public std::true_type {};
@ -71,7 +72,6 @@ struct is_container<
decltype(std::declval<T>().empty())>, decltype(std::declval<T>().empty())>,
void>::type> : public std::true_type {}; void>::type> : public std::true_type {};
/** /**
* Type trait to evaluate if template parameter is * Type trait to evaluate if template parameter is
* complying with a standard container * complying with a standard container

18
slsSupportLib/include/ZmqSocket.h Executable file → Normal file
View File

@ -15,7 +15,6 @@
// #define ZMQ_DETAIL // #define ZMQ_DETAIL
#define ROIVERBOSITY #define ROIVERBOSITY
class zmq_msg_t; class zmq_msg_t;
#include <map> #include <map>
@ -71,13 +70,11 @@ struct zmqHeader {
class ZmqSocket { class ZmqSocket {
public: public:
// Socket Options for optimization // Socket Options for optimization
// ZMQ_LINGER default is already -1 means no messages discarded. use this // ZMQ_LINGER default is already -1 means no messages discarded. use this
// options if optimizing required ZMQ_SNDHWM default is 0 means no limit. use // options if optimizing required ZMQ_SNDHWM default is 0 means no limit.
// this to optimize if optimizing required // use this to optimize if optimizing required eg. int value = -1; if
// eg. int value = -1; // (zmq_setsockopt(socketDescriptor, ZMQ_LINGER, &value,sizeof(value))) {
// if (zmq_setsockopt(socketDescriptor, ZMQ_LINGER, &value,sizeof(value))) {
// Close(); // Close();
/** /**
* Constructor for a client * Constructor for a client
@ -183,7 +180,7 @@ class ZmqSocket {
* @returns 0 if error or end of acquisition, else 1 (call * @returns 0 if error or end of acquisition, else 1 (call
* CloseHeaderMessage after parsing header) * CloseHeaderMessage after parsing header)
*/ */
int ReceiveHeader(const int index, zmqHeader& zHeader, uint32_t version); int ReceiveHeader(const int index, zmqHeader &zHeader, uint32_t version);
/** /**
* Receive Data * Receive Data
@ -200,7 +197,6 @@ class ZmqSocket {
void PrintError(); void PrintError();
private: private:
/** /**
* Receive Message * Receive Message
* @param index self index for debugging * @param index self index for debugging
@ -218,8 +214,8 @@ class ZmqSocket {
* @param version version that has to match, -1 to not care * @param version version that has to match, -1 to not care
* @returns true if successful else false * @returns true if successful else false
*/ */
int ParseHeader(const int index, int length, char *buff, int ParseHeader(const int index, int length, char *buff, zmqHeader &zHeader,
zmqHeader& zHeader, uint32_t version); uint32_t version);
/** /**
* Class to close socket descriptors automatically * Class to close socket descriptors automatically
@ -251,6 +247,4 @@ class ZmqSocket {
/** Socket descriptor */ /** Socket descriptor */
mySocketDescriptors sockfd; mySocketDescriptors sockfd;
}; };

15
slsSupportLib/include/ansi.h Executable file → Normal file
View File

@ -17,10 +17,11 @@
#define RESET "\x1b[0m" #define RESET "\x1b[0m"
#define BOLD "\x1b[1m" #define BOLD "\x1b[1m"
//on background black // on background black
#define bprintf(code, format, ...) printf(code BG_BLACK format RESET, ##__VA_ARGS__) #define bprintf(code, format, ...) \
printf(code BG_BLACK format RESET, ##__VA_ARGS__)
//normal printout // normal printout
#define cprintf(code, format, ...) printf(code format RESET, ##__VA_ARGS__) #define cprintf(code, format, ...) printf(code format RESET, ##__VA_ARGS__)
/* /*
@ -30,11 +31,9 @@ example 1 (a snippet):
#ifdef MARTIN #ifdef MARTIN
cprintf(BLUE, "LL Write - Len: %2d - If: %X - Data: ",buffer_len, ll->ll_fifo_base); cprintf(BLUE, "LL Write - Len: %2d - If: %X - Data: ",buffer_len,
for (i=0; i < buffer_len/4; i++) ll->ll_fifo_base); for (i=0; i < buffer_len/4; i++) cprintf(BLUE, "%.8X
cprintf(BLUE, "%.8X ",*(((unsigned *) buffer)+i)); ",*(((unsigned *) buffer)+i)); printf("\n"); #endif
printf("\n");
#endif
#ifdef MARTIN #ifdef MARTIN
cprintf(CYAN, "LL Read - If: %X - Data: ",ll->ll_fifo_base); cprintf(CYAN, "LL Read - If: %X - Data: ",ll->ll_fifo_base);

1
slsSupportLib/include/container_utils.h Executable file → Normal file
View File

@ -146,7 +146,6 @@ Squash(const Container &c, typename Container::value_type default_value = {}) {
return default_value; return default_value;
} }
} // namespace sls } // namespace sls
#endif // CONTAINER_UTILS_H #endif // CONTAINER_UTILS_H

18
slsSupportLib/include/file_utils.h Executable file → Normal file
View File

@ -1,13 +1,11 @@
#pragma once #pragma once
#include "sls_detector_defs.h" #include "sls_detector_defs.h"
#include <cstdio> #include <cstdio>
#include <fstream> #include <fstream>
#include <string> #include <string>
/** (used by multi and sls) /** (used by multi and sls)
* reads a short int raw data file * reads a short int raw data file
* @param infile input file stream * @param infile input file stream
@ -16,8 +14,8 @@
* @param offset start channel value * @param offset start channel value
* @returns OK or FAIL if it could not read the file or data=NULL * @returns OK or FAIL if it could not read the file or data=NULL
*/ */
int readDataFile(std::ifstream &infile, short int *data, int nch, int offset=0); int readDataFile(std::ifstream &infile, short int *data, int nch,
int offset = 0);
/** (used by multi and sls) /** (used by multi and sls)
* reads a short int rawdata file * reads a short int rawdata file
@ -28,7 +26,6 @@ int readDataFile(std::ifstream &infile, short int *data, int nch, int offset=0);
*/ */
int readDataFile(std::string fname, short int *data, int nch); int readDataFile(std::string fname, short int *data, int nch);
/** (used by multi and sls) /** (used by multi and sls)
* writes a short int raw data file * writes a short int raw data file
* @param outfile output file stream * @param outfile output file stream
@ -37,9 +34,8 @@ int readDataFile(std::string fname, short int *data, int nch);
* @param offset start channel number * @param offset start channel number
* @returns OK or FAIL if it could not write the file or data=NULL * @returns OK or FAIL if it could not write the file or data=NULL
*/ */
int writeDataFile(std::ofstream &outfile,int nch, short int *data, int offset=0); int writeDataFile(std::ofstream &outfile, int nch, short int *data,
int offset = 0);
/** (used by multi and sls) /** (used by multi and sls)
* writes a short int raw data file * writes a short int raw data file
@ -48,9 +44,7 @@ int writeDataFile(std::ofstream &outfile,int nch, short int *data, int offset=0
* @param data array of data values * @param data array of data values
* @returns OK or FAIL if it could not write the file or data=NULL * @returns OK or FAIL if it could not write the file or data=NULL
*/ */
int writeDataFile(std::string fname,int nch, short int *data); int writeDataFile(std::string fname, int nch, short int *data);
// mkdir -p path implemented by recursive calls // mkdir -p path implemented by recursive calls
void mkdir_p(const std::string& path, std::string dir=""); void mkdir_p(const std::string &path, std::string dir = "");

View File

@ -2,26 +2,38 @@
/*Utility to log to console*/ /*Utility to log to console*/
#include "ansi.h" //Colors #include "ansi.h" //Colors
#include <sys/time.h>
#include <iostream> #include <iostream>
#include <sstream> #include <sstream>
#include <sys/time.h>
enum TLogLevel {logERROR, logWARNING, logINFOBLUE, logINFOGREEN, logINFORED, logINFO, enum TLogLevel {
logDEBUG, logDEBUG1, logDEBUG2, logDEBUG3, logDEBUG4, logDEBUG5}; logERROR,
logWARNING,
logINFOBLUE,
logINFOGREEN,
logINFORED,
logINFO,
logDEBUG,
logDEBUG1,
logDEBUG2,
logDEBUG3,
logDEBUG4,
logDEBUG5
};
// Compiler should optimize away anything below this value // Compiler should optimize away anything below this value
#ifndef LOG_MAX_REPORTING_LEVEL #ifndef LOG_MAX_REPORTING_LEVEL
#define LOG_MAX_REPORTING_LEVEL logINFO #define LOG_MAX_REPORTING_LEVEL logINFO
#endif #endif
#define __AT__ std::string(__FILE__) + std::string("::") + std::string(__func__) + std::string("(): ") #define __AT__ \
std::string(__FILE__) + std::string("::") + std::string(__func__) + \
std::string("(): ")
#define __SHORT_FORM_OF_FILE__ \ #define __SHORT_FORM_OF_FILE__ \
(strrchr(__FILE__,'/') \ (strrchr(__FILE__, '/') ? strrchr(__FILE__, '/') + 1 : __FILE__)
? strrchr(__FILE__,'/')+1 \ #define __SHORT_AT__ \
: __FILE__ \ std::string(__SHORT_FORM_OF_FILE__) + std::string("::") + \
) std::string(__func__) + std::string("(): ")
#define __SHORT_AT__ std::string(__SHORT_FORM_OF_FILE__) + std::string("::") + std::string(__func__) + std::string("(): ")
namespace sls { namespace sls {
class Logger { class Logger {

6
slsSupportLib/include/network_utils.h Executable file → Normal file
View File

@ -60,9 +60,9 @@ class MacAddr {
}; };
IpAddr HostnameToIp(const char *hostname); IpAddr HostnameToIp(const char *hostname);
std::string IpToInterfaceName(const std::string& ip); std::string IpToInterfaceName(const std::string &ip);
MacAddr InterfaceNameToMac(const std::string& inf); MacAddr InterfaceNameToMac(const std::string &inf);
IpAddr InterfaceNameToIp(const std::string& ifn); IpAddr InterfaceNameToIp(const std::string &ifn);
std::ostream &operator<<(std::ostream &out, const IpAddr &addr); std::ostream &operator<<(std::ostream &out, const IpAddr &addr);
std::ostream &operator<<(std::ostream &out, const MacAddr &addr); std::ostream &operator<<(std::ostream &out, const MacAddr &addr);

60
slsSupportLib/include/sls_detector_defs.h Executable file → Normal file
View File

@ -15,18 +15,17 @@
#endif #endif
#ifdef __cplusplus #ifdef __cplusplus
//C++ includes // C++ includes
#include "sls_detector_exceptions.h" #include "sls_detector_exceptions.h"
#include <algorithm> #include <algorithm>
#include <bitset> #include <bitset>
#include <cstdint> #include <cstdint>
#include <string> #include <string>
#else #else
//C includes // C includes
#include <stdint.h> #include <stdint.h>
#endif #endif
#define BIT32_MASK 0xFFFFFFFF #define BIT32_MASK 0xFFFFFFFF
#define MAX_RX_DBIT 64 #define MAX_RX_DBIT 64
@ -65,7 +64,6 @@
#define DEFAULT_STREAMING_TIMER_IN_MS 200 #define DEFAULT_STREAMING_TIMER_IN_MS 200
#ifdef __cplusplus #ifdef __cplusplus
class slsDetectorDefs { class slsDetectorDefs {
public: public:
@ -143,7 +141,7 @@ class slsDetectorDefs {
#define MAX_NUM_PACKETS 512 #define MAX_NUM_PACKETS 512
using sls_bitset = std::bitset<MAX_NUM_PACKETS>; using sls_bitset = std::bitset<MAX_NUM_PACKETS>;
using bitset_storage = uint8_t[MAX_NUM_PACKETS / 8]; using bitset_storage = uint8_t[MAX_NUM_PACKETS / 8];
struct sls_receiver_header{ struct sls_receiver_header {
sls_detector_header detHeader; /**< is the detector header */ sls_detector_header detHeader; /**< is the detector header */
sls_bitset packetsMask; /**< is the packets caught bit mask */ sls_bitset packetsMask; /**< is the packets caught bit mask */
}; };
@ -171,24 +169,23 @@ class slsDetectorDefs {
xmin,xmax,ymin,ymax define the limits of the region xmin,xmax,ymin,ymax define the limits of the region
*/ */
#ifdef __cplusplus #ifdef __cplusplus
struct ROI { struct ROI {
int xmin{-1}; /**< is the roi xmin (in channel number) */ int xmin{-1}; /**< is the roi xmin (in channel number) */
int xmax{-1}; /**< is the roi xmax (in channel number)*/ int xmax{-1}; /**< is the roi xmax (in channel number)*/
}__attribute__((packed)); } __attribute__((packed));
#else #else
typedef struct { typedef struct {
int xmin; /**< is the roi xmin (in channel number) */ int xmin; /**< is the roi xmin (in channel number) */
int xmax; /**< is the roi xmax (in channel number)*/ int xmax; /**< is the roi xmax (in channel number)*/
} ROI; } ROI;
#endif #endif
/** /**
type of action performed (for text client) type of action performed (for text client)
*/ */
enum { GET_ACTION, PUT_ACTION, READOUT_ACTION, HELP_ACTION }; enum { GET_ACTION, PUT_ACTION, READOUT_ACTION, HELP_ACTION };
/** /**
dimension indexes dimension indexes
*/ */
@ -202,11 +199,10 @@ class slsDetectorDefs {
int x{0}; int x{0};
int y{0}; int y{0};
xy() = default; xy() = default;
xy(int x, int y):x(x),y(y){}; xy(int x, int y) : x(x), y(y){};
}__attribute__((packed)); } __attribute__((packed));
#endif #endif
/** /**
use of the external signals use of the external signals
*/ */
@ -383,28 +379,15 @@ class slsDetectorDefs {
#define TRIMBITMASK 0x3f #define TRIMBITMASK 0x3f
enum clockIndex { enum clockIndex { ADC_CLOCK, DBIT_CLOCK, RUN_CLOCK, SYNC_CLOCK };
ADC_CLOCK,
DBIT_CLOCK,
RUN_CLOCK,
SYNC_CLOCK
};
/** /**
* read out mode (ctb, moench) * read out mode (ctb, moench)
*/ */
enum readoutMode { enum readoutMode { ANALOG_ONLY, DIGITAL_ONLY, ANALOG_AND_DIGITAL };
ANALOG_ONLY,
DIGITAL_ONLY,
ANALOG_AND_DIGITAL
};
/** chip speed */ /** chip speed */
enum speedLevel { enum speedLevel { FULL_SPEED, HALF_SPEED, QUARTER_SPEED };
FULL_SPEED,
HALF_SPEED,
QUARTER_SPEED
};
/** port type */ /** port type */
enum portType { enum portType {
@ -455,10 +438,7 @@ class slsDetectorDefs {
/** /**
* timing source for gotthard2 * timing source for gotthard2
*/ */
enum timingSourceType { enum timingSourceType { TIMING_INTERNAL, TIMING_EXTERNAL };
TIMING_INTERNAL,
TIMING_EXTERNAL
};
#ifdef __cplusplus #ifdef __cplusplus
/** /**
@ -496,7 +476,7 @@ class slsDetectorDefs {
ROI roi; ROI roi;
uint32_t countermask{0}; uint32_t countermask{0};
burstMode burstType{BURST_OFF}; burstMode burstType{BURST_OFF};
}__attribute__((packed)); } __attribute__((packed));
#endif #endif
#ifdef __cplusplus #ifdef __cplusplus
@ -573,7 +553,8 @@ struct detParameters {
nDacs = 14; nDacs = 14;
break; break;
default: default:
throw sls::RuntimeError("Unknown detector type! " + std::to_string(type)); throw sls::RuntimeError("Unknown detector type! " +
std::to_string(type));
} }
} }
}; };
@ -659,11 +640,10 @@ typedef struct {
} sls_detector_module; } sls_detector_module;
#endif #endif
#ifdef __cplusplus #ifdef __cplusplus
//TODO! discuss this // TODO! discuss this
#include <vector> //hmm... but currently no way around #include <vector> //hmm... but currently no way around
namespace sls{ namespace sls {
using Positions = const std::vector<int> &; using Positions = const std::vector<int> &;
using defs = slsDetectorDefs; using defs = slsDetectorDefs;
} // namespace sls } // namespace sls

43
slsSupportLib/include/sls_detector_exceptions.h Executable file → Normal file
View File

@ -4,57 +4,52 @@
#include <iostream> #include <iostream>
#include <stdexcept> #include <stdexcept>
namespace sls{ namespace sls {
struct RuntimeError : public std::runtime_error { struct RuntimeError : public std::runtime_error {
public: public:
RuntimeError(): runtime_error("SLS Detector Package Failed") { RuntimeError() : runtime_error("SLS Detector Package Failed") {
LOG(logERROR) << "SLS Detector Package Failed"; LOG(logERROR) << "SLS Detector Package Failed";
} }
RuntimeError(const std::string& msg): runtime_error(msg) { RuntimeError(const std::string &msg) : runtime_error(msg) {
LOG(logERROR) << msg;
}
RuntimeError(const char* msg): runtime_error(msg) {
LOG(logERROR) << msg; LOG(logERROR) << msg;
} }
RuntimeError(const char *msg) : runtime_error(msg) { LOG(logERROR) << msg; }
}; };
struct SharedMemoryError : public RuntimeError { struct SharedMemoryError : public RuntimeError {
public: public:
SharedMemoryError(const std::string& msg):RuntimeError(msg) {} SharedMemoryError(const std::string &msg) : RuntimeError(msg) {}
}; };
struct SocketError : public RuntimeError { struct SocketError : public RuntimeError {
public: public:
SocketError(const std::string& msg):RuntimeError(msg) {} SocketError(const std::string &msg) : RuntimeError(msg) {}
}; };
struct ZmqSocketError : public RuntimeError { struct ZmqSocketError : public RuntimeError {
public: public:
ZmqSocketError(const std::string& msg):RuntimeError(msg) {} ZmqSocketError(const std::string &msg) : RuntimeError(msg) {}
}; };
struct NotImplementedError : public RuntimeError { struct NotImplementedError : public RuntimeError {
public: public:
NotImplementedError(const std::string& msg):RuntimeError(msg) {} NotImplementedError(const std::string &msg) : RuntimeError(msg) {}
}; };
struct DetectorError : public RuntimeError { struct DetectorError : public RuntimeError {
public: public:
DetectorError(const std::string& msg):RuntimeError(msg) {} DetectorError(const std::string &msg) : RuntimeError(msg) {}
}; };
struct ReceiverError : public RuntimeError { struct ReceiverError : public RuntimeError {
public: public:
ReceiverError(const std::string& msg):RuntimeError(msg) {} ReceiverError(const std::string &msg) : RuntimeError(msg) {}
}; };
struct GuiError : public RuntimeError { struct GuiError : public RuntimeError {
public: public:
GuiError(const std::string& msg):RuntimeError(msg) {} GuiError(const std::string &msg) : RuntimeError(msg) {}
}; };
} // namespace sls } // namespace sls

View File

@ -8,9 +8,8 @@
*@short functions indices to call on server (detector/receiver) *@short functions indices to call on server (detector/receiver)
*/ */
enum detFuncs {
enum detFuncs{ F_EXEC_COMMAND = 0,
F_EXEC_COMMAND=0,
F_GET_DETECTOR_TYPE, F_GET_DETECTOR_TYPE,
F_SET_EXTERNAL_SIGNAL_FLAG, F_SET_EXTERNAL_SIGNAL_FLAG,
F_SET_TIMING_MODE, F_SET_TIMING_MODE,
@ -200,7 +199,8 @@ enum detFuncs{
F_GET_RECEIVER_PARAMETERS, F_GET_RECEIVER_PARAMETERS,
NUM_DET_FUNCTIONS, NUM_DET_FUNCTIONS,
RECEIVER_ENUM_START = 256, /**< detector function should not exceed this (detector server should not compile anyway) */ RECEIVER_ENUM_START = 256, /**< detector function should not exceed this
(detector server should not compile anyway) */
F_EXEC_RECEIVER_COMMAND, F_EXEC_RECEIVER_COMMAND,
F_EXIT_RECEIVER, F_EXIT_RECEIVER,
@ -295,6 +295,7 @@ enum detFuncs{
NUM_REC_FUNCTIONS NUM_REC_FUNCTIONS
}; };
// clang-format off
#ifdef __cplusplus #ifdef __cplusplus
static const char* getFunctionNameFromEnum(enum detFuncs func) { static const char* getFunctionNameFromEnum(enum detFuncs func) {
switch (func) { switch (func) {
@ -586,3 +587,4 @@ static const char* getFunctionNameFromEnum(enum detFuncs func) {
}; };
#endif #endif
// clang-format on

0
slsSupportLib/src/ClientSocket.cpp Executable file → Normal file
View File

4
slsSupportLib/src/DataSocket.cpp Executable file → Normal file
View File

@ -136,8 +136,6 @@ void DataSocket::shutDownSocket() {
close(); close();
} }
void DataSocket::shutdown(){ void DataSocket::shutdown() { ::shutdown(sockfd_, SHUT_RDWR); }
::shutdown(sockfd_, SHUT_RDWR);
}
} // namespace sls } // namespace sls

7
slsSupportLib/src/ServerSocket.cpp Executable file → Normal file
View File

@ -1,5 +1,5 @@
#include "ServerInterface.h"
#include "ServerSocket.h" #include "ServerSocket.h"
#include "ServerInterface.h"
#include "DataSocket.h" #include "DataSocket.h"
#include "logger.h" #include "logger.h"
@ -29,7 +29,8 @@ ServerSocket::ServerSocket(int port)
if (bind(getSocketId(), (struct sockaddr *)&serverAddr, if (bind(getSocketId(), (struct sockaddr *)&serverAddr,
sizeof(serverAddr)) != 0) { sizeof(serverAddr)) != 0) {
close(); close();
throw sls::SocketError("Server ERROR: cannot bind socket. Please check if another instance is running."); throw sls::SocketError("Server ERROR: cannot bind socket. Please check "
"if another instance is running.");
} }
if (listen(getSocketId(), DEFAULT_BACKLOG) != 0) { if (listen(getSocketId(), DEFAULT_BACKLOG) != 0) {
close(); close();
@ -38,7 +39,7 @@ ServerSocket::ServerSocket(int port)
} }
ServerInterface ServerSocket::accept() { ServerInterface ServerSocket::accept() {
lastClient = thisClient; //update from previous connection lastClient = thisClient; // update from previous connection
struct sockaddr_in clientAddr; struct sockaddr_in clientAddr;
socklen_t addr_size = sizeof clientAddr; socklen_t addr_size = sizeof clientAddr;
int newSocket = int newSocket =

View File

@ -403,7 +403,6 @@ template <> defs::burstMode StringTo(const std::string &s) {
throw sls::RuntimeError("Unknown burst mode " + s); throw sls::RuntimeError("Unknown burst mode " + s);
} }
template <> defs::timingSourceType StringTo(const std::string &s) { template <> defs::timingSourceType StringTo(const std::string &s) {
if (s == "internal") if (s == "internal")
return defs::TIMING_INTERNAL; return defs::TIMING_INTERNAL;

View File

@ -56,7 +56,7 @@ UdpRxSocket::UdpRxSocket(int port, ssize_t packet_size, const char *hostname,
UdpRxSocket::~UdpRxSocket() { Shutdown(); } UdpRxSocket::~UdpRxSocket() { Shutdown(); }
ssize_t UdpRxSocket::getPacketSize() const noexcept { return packet_size_; } ssize_t UdpRxSocket::getPacketSize() const noexcept { return packet_size_; }
bool UdpRxSocket::ReceivePacket(char *dst) noexcept{ bool UdpRxSocket::ReceivePacket(char *dst) noexcept {
auto bytes_received = auto bytes_received =
recvfrom(sockfd_, dst, packet_size_, 0, nullptr, nullptr); recvfrom(sockfd_, dst, packet_size_, 0, nullptr, nullptr);
return bytes_received == packet_size_; return bytes_received == packet_size_;
@ -64,14 +64,13 @@ bool UdpRxSocket::ReceivePacket(char *dst) noexcept{
ssize_t UdpRxSocket::ReceiveDataOnly(char *dst) noexcept { ssize_t UdpRxSocket::ReceiveDataOnly(char *dst) noexcept {
auto r = recvfrom(sockfd_, dst, packet_size_, 0, nullptr, nullptr); auto r = recvfrom(sockfd_, dst, packet_size_, 0, nullptr, nullptr);
constexpr ssize_t eiger_header_packet = constexpr ssize_t eiger_header_packet = 40; // only detector that has this
40; // only detector that has this
if (r == eiger_header_packet) { if (r == eiger_header_packet) {
LOG(logWARNING) << "Got header pkg"; LOG(logWARNING) << "Got header pkg";
r = recvfrom(sockfd_, dst, packet_size_, 0, nullptr, nullptr); r = recvfrom(sockfd_, dst, packet_size_, 0, nullptr, nullptr);
} }
return r; return r;
} }
size_t UdpRxSocket::getBufferSize() const { size_t UdpRxSocket::getBufferSize() const {
size_t ret = 0; size_t ret = 0;
@ -92,5 +91,5 @@ void UdpRxSocket::Shutdown() {
close(sockfd_); close(sockfd_);
sockfd_ = -1; sockfd_ = -1;
} }
} }
} // namespace sls } // namespace sls

View File

@ -1,12 +1,12 @@
#include "ZmqSocket.h" #include "ZmqSocket.h"
#include <zmq.h>
#include <vector>
#include <arpa/inet.h> //inet_ntoa #include <arpa/inet.h> //inet_ntoa
#include <errno.h> #include <errno.h>
#include <iostream> #include <iostream>
#include <netdb.h> //gethostbyname() #include <netdb.h> //gethostbyname()
#include <string.h> #include <string.h>
#include <unistd.h> //usleep in some machines #include <unistd.h> //usleep in some machines
#include <vector>
#include <zmq.h>
using namespace rapidjson; using namespace rapidjson;
ZmqSocket::ZmqSocket(const char *const hostname_or_ip, ZmqSocket::ZmqSocket(const char *const hostname_or_ip,
@ -145,8 +145,7 @@ int ZmqSocket::ConvertInternetAddresstoIpString(struct addrinfo *res, char *ip,
return 1; return 1;
} }
int ZmqSocket::SendHeader( int ZmqSocket::SendHeader(int index, zmqHeader header) {
int index, zmqHeader header) {
/** Json Header Format */ /** Json Header Format */
const char jsonHeaderFormat[] = "{" const char jsonHeaderFormat[] = "{"
@ -183,44 +182,25 @@ int ZmqSocket::SendHeader(
; //"}\n"; ; //"}\n";
char buf[MAX_STR_LENGTH] = ""; char buf[MAX_STR_LENGTH] = "";
sprintf(buf, jsonHeaderFormat, sprintf(buf, jsonHeaderFormat, header.jsonversion, header.dynamicRange,
header.jsonversion, header.fileIndex, header.ndetx, header.ndety, header.npixelsx,
header.dynamicRange, header.npixelsy, header.imageSize, header.acqIndex,
header.fileIndex, header.frameIndex, header.progress, header.fname.c_str(),
header.ndetx, header.data ? 1 : 0, header.completeImage ? 1 : 0,
header.ndety,
header.npixelsx,
header.npixelsy,
header.imageSize,
header.acqIndex,
header.frameIndex,
header.progress,
header.fname.c_str(),
header.data ? 1 : 0,
header.completeImage ? 1 : 0,
header.frameNumber, header.frameNumber, header.expLength, header.packetNumber,
header.expLength, header.bunchId, header.timestamp, header.modId, header.row,
header.packetNumber, header.column, header.reserved, header.debug, header.roundRNumber,
header.bunchId, header.detType, header.version,
header.timestamp,
header.modId,
header.row,
header.column,
header.reserved,
header.debug,
header.roundRNumber,
header.detType,
header.version,
// additional stuff // additional stuff
header.flippedDataX, header.flippedDataX, header.quad);
header.quad);
if (header.addJsonHeader.size() > 0) { if (header.addJsonHeader.size() > 0) {
strcat(buf, ", "); strcat(buf, ", ");
strcat(buf, "\"addJsonHeader\": {"); strcat(buf, "\"addJsonHeader\": {");
for (auto it = header.addJsonHeader.begin(); it != header.addJsonHeader.end(); ++it) { for (auto it = header.addJsonHeader.begin();
it != header.addJsonHeader.end(); ++it) {
if (it != header.addJsonHeader.begin()) { if (it != header.addJsonHeader.begin()) {
strcat(buf, ", "); strcat(buf, ", ");
} }
@ -260,7 +240,7 @@ int ZmqSocket::SendData(char *buf, int length) {
return 1; return 1;
} }
int ZmqSocket::ReceiveHeader(const int index, zmqHeader& zHeader, int ZmqSocket::ReceiveHeader(const int index, zmqHeader &zHeader,
uint32_t version) { uint32_t version) {
std::vector<char> buffer(MAX_STR_LENGTH); std::vector<char> buffer(MAX_STR_LENGTH);
int len = int len =
@ -292,7 +272,7 @@ int ZmqSocket::ReceiveHeader(const int index, zmqHeader& zHeader,
}; };
int ZmqSocket::ParseHeader(const int index, int length, char *buff, int ZmqSocket::ParseHeader(const int index, int length, char *buff,
zmqHeader& zHeader, uint32_t version) { zmqHeader &zHeader, uint32_t version) {
Document document; Document document;
if (document.Parse(buff, length).HasParseError()) { if (document.Parse(buff, length).HasParseError()) {
LOG(logERROR) << index << " Could not parse. len:" << length LOG(logERROR) << index << " Could not parse. len:" << length
@ -348,10 +328,12 @@ int ZmqSocket::ParseHeader(const int index, int length, char *buff,
zHeader.completeImage = document["completeImage"].GetUint(); zHeader.completeImage = document["completeImage"].GetUint();
if (document.HasMember("addJsonHeader")) { if (document.HasMember("addJsonHeader")) {
const Value& V = document["addJsonHeader"]; const Value &V = document["addJsonHeader"];
zHeader.addJsonHeader.clear(); zHeader.addJsonHeader.clear();
for (Value::ConstMemberIterator iter = V.MemberBegin(); iter != V.MemberEnd(); ++iter){ for (Value::ConstMemberIterator iter = V.MemberBegin();
zHeader.addJsonHeader[iter->name.GetString()] = iter->value.GetString(); iter != V.MemberEnd(); ++iter) {
zHeader.addJsonHeader[iter->name.GetString()] =
iter->value.GetString();
} }
} }
@ -451,7 +433,7 @@ void ZmqSocket::PrintError() {
} }
} }
//Nested class to do RAII handling of socket descriptors // Nested class to do RAII handling of socket descriptors
ZmqSocket::mySocketDescriptors::mySocketDescriptors() ZmqSocket::mySocketDescriptors::mySocketDescriptors()
: server(false), contextDescriptor(0), socketDescriptor(0){}; : server(false), contextDescriptor(0), socketDescriptor(0){};
ZmqSocket::mySocketDescriptors::~mySocketDescriptors() { ZmqSocket::mySocketDescriptors::~mySocketDescriptors() {

54
slsSupportLib/src/file_utils.cpp Executable file → Normal file
View File

@ -2,32 +2,32 @@
#include "logger.h" #include "logger.h"
#include "sls_detector_exceptions.h" #include "sls_detector_exceptions.h"
#include <errno.h>
#include <iostream> #include <iostream>
#include <sstream> #include <sstream>
#include <sys/stat.h> #include <sys/stat.h>
#include <sys/types.h> #include <sys/types.h>
#include <errno.h>
int readDataFile(std::ifstream &infile, short int *data, int nch, int offset) { int readDataFile(std::ifstream &infile, short int *data, int nch, int offset) {
int ichan, iline=0; int ichan, iline = 0;
short int idata; short int idata;
int interrupt=0; int interrupt = 0;
std::string str; std::string str;
while (infile.good() and interrupt==0) { while (infile.good() and interrupt == 0) {
getline(infile,str); getline(infile, str);
std::istringstream ssstr(str); std::istringstream ssstr(str);
ssstr >> ichan >> idata; ssstr >> ichan >> idata;
if (ssstr.fail() || ssstr.bad()) { if (ssstr.fail() || ssstr.bad()) {
interrupt=1; interrupt = 1;
break; break;
} }
if (iline<nch) { if (iline < nch) {
if (ichan>=offset) { if (ichan >= offset) {
data[iline]=idata; data[iline] = idata;
iline++; iline++;
} }
} else { } else {
interrupt=1; interrupt = 1;
break; break;
} }
return iline; return iline;
@ -35,15 +35,13 @@ int readDataFile(std::ifstream &infile, short int *data, int nch, int offset) {
return iline; return iline;
} }
int readDataFile(std::string fname, short int *data, int nch) { int readDataFile(std::string fname, short int *data, int nch) {
std::ifstream infile; std::ifstream infile;
int iline=0; int iline = 0;
std::string str; std::string str;
infile.open(fname.c_str(), std::ios_base::in); infile.open(fname.c_str(), std::ios_base::in);
if (infile.is_open()) { if (infile.is_open()) {
iline=readDataFile(infile, data, nch, 0); iline = readDataFile(infile, data, nch, 0);
infile.close(); infile.close();
} else { } else {
LOG(logERROR) << "Could not read file " << fname; LOG(logERROR) << "Could not read file " << fname;
@ -52,22 +50,20 @@ int readDataFile(std::string fname, short int *data, int nch) {
return iline; return iline;
} }
int writeDataFile(std::ofstream &outfile, int nch, short int *data,
int offset) {
int writeDataFile(std::ofstream &outfile,int nch, short int *data, int offset) { if (data == nullptr)
if (data==nullptr)
return slsDetectorDefs::FAIL; return slsDetectorDefs::FAIL;
for (int ichan=0; ichan<nch; ichan++) for (int ichan = 0; ichan < nch; ichan++)
outfile << ichan+offset << " " << *(data+ichan) << std::endl; outfile << ichan + offset << " " << *(data + ichan) << std::endl;
return slsDetectorDefs::OK; return slsDetectorDefs::OK;
} }
int writeDataFile(std::string fname, int nch, short int *data) {
int writeDataFile(std::string fname,int nch, short int *data) {
std::ofstream outfile; std::ofstream outfile;
if (data==nullptr) if (data == nullptr)
return slsDetectorDefs::FAIL; return slsDetectorDefs::FAIL;
outfile.open (fname.c_str(),std::ios_base::out); outfile.open(fname.c_str(), std::ios_base::out);
if (outfile.is_open()) { if (outfile.is_open()) {
writeDataFile(outfile, nch, data, 0); writeDataFile(outfile, nch, data, 0);
outfile.close(); outfile.close();
@ -78,9 +74,7 @@ int writeDataFile(std::string fname,int nch, short int *data) {
} }
} }
void mkdir_p(const std::string &path, std::string dir) {
void mkdir_p(const std::string& path, std::string dir) {
if (path.length() == 0) if (path.length() == 0)
return; return;
@ -90,7 +84,7 @@ void mkdir_p(const std::string& path, std::string dir) {
if (path[i] == '/') if (path[i] == '/')
break; break;
} }
if(mkdir(dir.c_str(), S_IRWXU | S_IRWXG | S_IROTH | S_IXOTH) != 0){ if (mkdir(dir.c_str(), S_IRWXU | S_IRWXG | S_IROTH | S_IXOTH) != 0) {
if (errno != EEXIST) if (errno != EEXIST)
throw sls::RuntimeError("Could not create: " + dir); throw sls::RuntimeError("Could not create: " + dir);
} }
@ -98,7 +92,3 @@ void mkdir_p(const std::string& path, std::string dir) {
if (i + 1 < path.length()) if (i + 1 < path.length())
mkdir_p(path.substr(i + 1), dir); mkdir_p(path.substr(i + 1), dir);
} }

5
slsSupportLib/src/network_utils.cpp Executable file → Normal file
View File

@ -1,5 +1,6 @@
#include "sls_detector_exceptions.h" #include "sls_detector_exceptions.h"
#include "network_utils.h"
#include <algorithm> #include <algorithm>
#include <arpa/inet.h> #include <arpa/inet.h>
#include <cassert> #include <cassert>
@ -15,7 +16,6 @@
#include <sys/socket.h> #include <sys/socket.h>
#include <sys/types.h> #include <sys/types.h>
#include <unistd.h> #include <unistd.h>
#include "network_utils.h"
namespace sls { namespace sls {
@ -85,7 +85,8 @@ IpAddr HostnameToIp(const char *hostname) {
hints.ai_socktype = SOCK_STREAM; hints.ai_socktype = SOCK_STREAM;
if (getaddrinfo(hostname, nullptr, &hints, &result)) { if (getaddrinfo(hostname, nullptr, &hints, &result)) {
freeaddrinfo(result); freeaddrinfo(result);
throw RuntimeError("Could not convert hostname (" + std::string(hostname) + ") to ip"); throw RuntimeError("Could not convert hostname (" +
std::string(hostname) + ") to ip");
} }
uint32_t ip = ((sockaddr_in *)result->ai_addr)->sin_addr.s_addr; uint32_t ip = ((sockaddr_in *)result->ai_addr)->sin_addr.s_addr;
freeaddrinfo(result); freeaddrinfo(result);

View File

@ -10,19 +10,18 @@ TEST_CASE("FixedCapacityContainer is a container") {
REQUIRE(sls::is_container<FixedCapacityContainer<int, 7>>::value == true); REQUIRE(sls::is_container<FixedCapacityContainer<int, 7>>::value == true);
} }
TEST_CASE("Comparing FixedCapacity containers"){ TEST_CASE("Comparing FixedCapacity containers") {
FixedCapacityContainer<int, 5> a{0,1,2}; FixedCapacityContainer<int, 5> a{0, 1, 2};
FixedCapacityContainer<int, 5> b{0,1,2}; FixedCapacityContainer<int, 5> b{0, 1, 2};
FixedCapacityContainer<int, 5> c{0,1,2,4}; FixedCapacityContainer<int, 5> c{0, 1, 2, 4};
REQUIRE(a==b);
REQUIRE_FALSE(a!=b);
REQUIRE_FALSE(a==c);
REQUIRE(a!=c);
REQUIRE(c!=a);
REQUIRE_FALSE(c==a);
REQUIRE_FALSE(b==c);
REQUIRE(a == b);
REQUIRE_FALSE(a != b);
REQUIRE_FALSE(a == c);
REQUIRE(a != c);
REQUIRE(c != a);
REQUIRE_FALSE(c == a);
REQUIRE_FALSE(b == c);
} }
TEST_CASE("Compare array and fixed capacity container") { TEST_CASE("Compare array and fixed capacity container") {

View File

@ -37,10 +37,10 @@ TEST_CASE("The server recive the same message as we send", "[support]") {
auto server_message = s.get(); auto server_message = s.get();
CHECK(server_message == sent_message); CHECK(server_message == sent_message);
CHECK(std::string(received_message.data()) == "OK" ); CHECK(std::string(received_message.data()) == "OK");
CHECK(client.getSocketId() == -1); CHECK(client.getSocketId() == -1);
} }
TEST_CASE("throws on no server", "[support]"){ TEST_CASE("throws on no server", "[support]") {
CHECK_THROWS(sls::DetectorSocket("localhost", 1950)); CHECK_THROWS(sls::DetectorSocket("localhost", 1950));
} }

View File

@ -1,16 +1,16 @@
#include "TimeHelper.h" #include "TimeHelper.h"
#include "ToString.h" #include "ToString.h"
#include "catch.hpp"
#include "network_utils.h" #include "network_utils.h"
#include "sls_detector_defs.h" #include "sls_detector_defs.h"
#include "catch.hpp"
#include <array> #include <array>
#include <map> #include <map>
#include <vector> #include <vector>
// using namespace sls; // using namespace sls;
using sls::defs;
using sls::StringTo; using sls::StringTo;
using sls::ToString; using sls::ToString;
using sls::defs;
using namespace sls::time; using namespace sls::time;
TEST_CASE("Integer conversions", "[support]") { TEST_CASE("Integer conversions", "[support]") {
@ -45,7 +45,6 @@ TEST_CASE("conversion from duration to string", "[support]") {
REQUIRE(ToString(us(-100)) == "-100us"); REQUIRE(ToString(us(-100)) == "-100us");
} }
TEST_CASE("Convert vector of time", "[support]") { TEST_CASE("Convert vector of time", "[support]") {
std::vector<ns> vec{ns(150), us(10), ns(600)}; std::vector<ns> vec{ns(150), us(10), ns(600)};
REQUIRE(ToString(vec) == "[150ns, 10us, 600ns]"); REQUIRE(ToString(vec) == "[150ns, 10us, 600ns]");
@ -85,27 +84,26 @@ TEST_CASE("Array") {
REQUIRE(ToString(arr) == "[1, 2, 3]"); REQUIRE(ToString(arr) == "[1, 2, 3]");
} }
TEST_CASE("Convert types with str method"){ TEST_CASE("Convert types with str method") {
sls::IpAddr addr; sls::IpAddr addr;
REQUIRE(ToString(addr) == "0.0.0.0"); REQUIRE(ToString(addr) == "0.0.0.0");
REQUIRE(ToString(sls::IpAddr{}) == "0.0.0.0"); REQUIRE(ToString(sls::IpAddr{}) == "0.0.0.0");
} }
TEST_CASE("String to string", "[support]"){ TEST_CASE("String to string", "[support]") {
std::string s = "hej"; std::string s = "hej";
REQUIRE(ToString(s) == "hej"); REQUIRE(ToString(s) == "hej");
} }
TEST_CASE("vector of strings"){ TEST_CASE("vector of strings") {
std::vector<std::string> vec{"5", "s"}; std::vector<std::string> vec{"5", "s"};
REQUIRE(ToString(vec) == "[5, s]"); REQUIRE(ToString(vec) == "[5, s]");
std::vector<std::string> vec2{"some", "strange", "words", "75"}; std::vector<std::string> vec2{"some", "strange", "words", "75"};
REQUIRE(ToString(vec2) == "[some, strange, words, 75]"); REQUIRE(ToString(vec2) == "[some, strange, words, 75]");
} }
TEST_CASE("run status"){ TEST_CASE("run status") {
using defs = slsDetectorDefs; using defs = slsDetectorDefs;
REQUIRE(ToString(defs::runStatus::ERROR) == "error"); REQUIRE(ToString(defs::runStatus::ERROR) == "error");
REQUIRE(ToString(defs::runStatus::WAITING) == "waiting"); REQUIRE(ToString(defs::runStatus::WAITING) == "waiting");
@ -126,7 +124,7 @@ TEST_CASE("string to std::chrono::duration", "[support]") {
REQUIRE_THROWS(StringTo<ns>("asvn")); REQUIRE_THROWS(StringTo<ns>("asvn"));
} }
TEST_CASE("string to detectorType"){ TEST_CASE("string to detectorType") {
using dt = slsDetectorDefs::detectorType; using dt = slsDetectorDefs::detectorType;
REQUIRE(StringTo<dt>("Eiger") == dt::EIGER); REQUIRE(StringTo<dt>("Eiger") == dt::EIGER);
REQUIRE(StringTo<dt>("Gotthard") == dt::GOTTHARD); REQUIRE(StringTo<dt>("Gotthard") == dt::GOTTHARD);
@ -137,14 +135,13 @@ TEST_CASE("string to detectorType"){
REQUIRE(StringTo<dt>("Gotthard2") == dt::GOTTHARD2); REQUIRE(StringTo<dt>("Gotthard2") == dt::GOTTHARD2);
} }
TEST_CASE("vec"){ TEST_CASE("vec") {
using rs = slsDetectorDefs::runStatus; using rs = slsDetectorDefs::runStatus;
std::vector<rs> vec{rs::ERROR, rs::IDLE}; std::vector<rs> vec{rs::ERROR, rs::IDLE};
REQUIRE(ToString(vec) == "[error, idle]"); REQUIRE(ToString(vec) == "[error, idle]");
} }
TEST_CASE("uint32 from string") {
TEST_CASE("uint32 from string"){
REQUIRE(StringTo<uint32_t>("0") == 0); REQUIRE(StringTo<uint32_t>("0") == 0);
REQUIRE(StringTo<uint32_t>("5") == 5u); REQUIRE(StringTo<uint32_t>("5") == 5u);
REQUIRE(StringTo<uint32_t>("16") == 16u); REQUIRE(StringTo<uint32_t>("16") == 16u);
@ -153,10 +150,9 @@ TEST_CASE("uint32 from string"){
REQUIRE(StringTo<uint32_t>("0x15") == 21u); REQUIRE(StringTo<uint32_t>("0x15") == 21u);
REQUIRE(StringTo<uint32_t>("0x15") == 0x15); REQUIRE(StringTo<uint32_t>("0x15") == 0x15);
REQUIRE(StringTo<uint32_t>("0xffffff") == 0xffffff); REQUIRE(StringTo<uint32_t>("0xffffff") == 0xffffff);
} }
TEST_CASE("uint64 from string"){ TEST_CASE("uint64 from string") {
REQUIRE(StringTo<uint64_t>("0") == 0); REQUIRE(StringTo<uint64_t>("0") == 0);
REQUIRE(StringTo<uint64_t>("5") == 5u); REQUIRE(StringTo<uint64_t>("5") == 5u);
REQUIRE(StringTo<uint64_t>("16") == 16u); REQUIRE(StringTo<uint64_t>("16") == 16u);
@ -164,11 +160,9 @@ TEST_CASE("uint64 from string"){
REQUIRE(StringTo<uint64_t>("0x14") == 20u); REQUIRE(StringTo<uint64_t>("0x14") == 20u);
REQUIRE(StringTo<uint64_t>("0x15") == 21u); REQUIRE(StringTo<uint64_t>("0x15") == 21u);
REQUIRE(StringTo<uint64_t>("0xffffff") == 0xffffff); REQUIRE(StringTo<uint64_t>("0xffffff") == 0xffffff);
} }
TEST_CASE("int from string") {
TEST_CASE("int from string"){
REQUIRE(StringTo<int>("-1") == -1); REQUIRE(StringTo<int>("-1") == -1);
REQUIRE(StringTo<int>("-0x1") == -0x1); REQUIRE(StringTo<int>("-0x1") == -0x1);
REQUIRE(StringTo<int>("-0x1") == -1); REQUIRE(StringTo<int>("-0x1") == -1);
@ -179,11 +173,9 @@ TEST_CASE("int from string"){
REQUIRE(StringTo<int>("0x14") == 20); REQUIRE(StringTo<int>("0x14") == 20);
REQUIRE(StringTo<int>("0x15") == 21); REQUIRE(StringTo<int>("0x15") == 21);
REQUIRE(StringTo<int>("0xffffff") == 0xffffff); REQUIRE(StringTo<int>("0xffffff") == 0xffffff);
} }
TEST_CASE("int64_t from string") {
TEST_CASE("int64_t from string"){
REQUIRE(StringTo<int64_t>("-1") == -1); REQUIRE(StringTo<int64_t>("-1") == -1);
REQUIRE(StringTo<int64_t>("-0x1") == -0x1); REQUIRE(StringTo<int64_t>("-0x1") == -0x1);
REQUIRE(StringTo<int64_t>("-0x1") == -1); REQUIRE(StringTo<int64_t>("-0x1") == -1);
@ -194,11 +186,9 @@ TEST_CASE("int64_t from string"){
REQUIRE(StringTo<int64_t>("0x14") == 20); REQUIRE(StringTo<int64_t>("0x14") == 20);
REQUIRE(StringTo<int64_t>("0x15") == 21); REQUIRE(StringTo<int64_t>("0x15") == 21);
REQUIRE(StringTo<int64_t>("0xffffff") == 0xffffff); REQUIRE(StringTo<int64_t>("0xffffff") == 0xffffff);
} }
TEST_CASE("std::map of strings") {
TEST_CASE("std::map of strings"){
std::map<std::string, std::string> m; std::map<std::string, std::string> m;
m["key"] = "value"; m["key"] = "value";
auto s = ToString(m); auto s = ToString(m);
@ -209,10 +199,9 @@ TEST_CASE("std::map of strings"){
m["test"] = "tree"; m["test"] = "tree";
REQUIRE(ToString(m) == "{chrusi: musi, key: value, test: tree}"); REQUIRE(ToString(m) == "{chrusi: musi, key: value, test: tree}");
} }
TEST_CASE("std::map of ints"){ TEST_CASE("std::map of ints") {
std::map<int, int> m; std::map<int, int> m;
m[5] = 10; m[5] = 10;
@ -221,10 +210,9 @@ TEST_CASE("std::map of ints"){
REQUIRE(ToString(m) == "{5: 10, 500: 50}"); REQUIRE(ToString(m) == "{5: 10, 500: 50}");
m[372] = 999; m[372] = 999;
REQUIRE(ToString(m) == "{5: 10, 372: 999, 500: 50}"); REQUIRE(ToString(m) == "{5: 10, 372: 999, 500: 50}");
} }
TEST_CASE("Detector type"){ TEST_CASE("Detector type") {
auto dt = defs::detectorType::EIGER; auto dt = defs::detectorType::EIGER;
REQUIRE(ToString(dt) == "Eiger"); REQUIRE(ToString(dt) == "Eiger");
REQUIRE(StringTo<defs::detectorType>("Eiger") == dt); REQUIRE(StringTo<defs::detectorType>("Eiger") == dt);

View File

@ -1,12 +1,12 @@
#include "TypeTraits.h" #include "TypeTraits.h"
#include "catch.hpp" #include "catch.hpp"
#include <array> #include <array>
#include <vector>
#include <sstream>
#include <chrono> #include <chrono>
#include <initializer_list> #include <initializer_list>
#include <sstream>
#include <vector>
//Dummy classes only used here for testing // Dummy classes only used here for testing
class DummyWithStr { class DummyWithStr {
public: public:
std::string str(); std::string str();
@ -32,7 +32,7 @@ TEST_CASE("Check for str() on ostream") {
REQUIRE(sls::has_str<std::ostringstream>::value == true); REQUIRE(sls::has_str<std::ostringstream>::value == true);
} }
TEST_CASE("sls::is_duration"){ TEST_CASE("sls::is_duration") {
REQUIRE(sls::is_duration<std::chrono::nanoseconds>::value == true); REQUIRE(sls::is_duration<std::chrono::nanoseconds>::value == true);
REQUIRE(sls::is_duration<std::chrono::seconds>::value == true); REQUIRE(sls::is_duration<std::chrono::seconds>::value == true);
REQUIRE(sls::is_duration<std::chrono::hours>::value == true); REQUIRE(sls::is_duration<std::chrono::hours>::value == true);
@ -41,11 +41,11 @@ TEST_CASE("sls::is_duration"){
REQUIRE(sls::is_duration<std::vector<int>>::value == false); REQUIRE(sls::is_duration<std::vector<int>>::value == false);
} }
TEST_CASE("initializer list"){ TEST_CASE("initializer list") {
REQUIRE(sls::is_light_container<std::initializer_list<int>>::value == true); REQUIRE(sls::is_light_container<std::initializer_list<int>>::value == true);
} }
TEST_CASE("Check for emplace back"){ TEST_CASE("Check for emplace back") {
//we know vector should have this its the type trait that is tested // we know vector should have this its the type trait that is tested
REQUIRE(sls::has_emplace_back<std::vector<int>>::value == true); REQUIRE(sls::has_emplace_back<std::vector<int>>::value == true);
} }

View File

@ -1,17 +1,17 @@
#include "UdpRxSocket.h" #include "UdpRxSocket.h"
#include "catch.hpp" #include "catch.hpp"
#include "sls_detector_exceptions.h" #include "sls_detector_exceptions.h"
#include <future>
#include <thread>
#include <vector>
#include <cstdint> #include <cstdint>
#include <errno.h> #include <errno.h>
#include <future>
#include <iostream> #include <iostream>
#include <netdb.h> #include <netdb.h>
#include <netinet/in.h> #include <netinet/in.h>
#include <string.h> #include <string.h>
#include <sys/socket.h> #include <sys/socket.h>
#include <thread>
#include <unistd.h> #include <unistd.h>
#include <vector>
constexpr int default_port = 50001; constexpr int default_port = 50001;
@ -44,7 +44,7 @@ int open_socket(int port) {
return fd; return fd;
} }
TEST_CASE("Get packet size returns the packet size we set in the constructor"){ TEST_CASE("Get packet size returns the packet size we set in the constructor") {
constexpr int port = 50001; constexpr int port = 50001;
constexpr ssize_t packet_size = 8000; constexpr ssize_t packet_size = 8000;
sls::UdpRxSocket s{port, packet_size}; sls::UdpRxSocket s{port, packet_size};
@ -64,10 +64,9 @@ TEST_CASE("Receive data from a vector") {
auto n = write(fd, data_to_send.data(), packet_size); auto n = write(fd, data_to_send.data(), packet_size);
CHECK(n == packet_size); CHECK(n == packet_size);
CHECK(udpsock.ReceivePacket((char*)data_received.data())); CHECK(udpsock.ReceivePacket((char *)data_received.data()));
close(fd); close(fd);
CHECK(data_to_send == data_received); CHECK(data_to_send == data_received);
} }
TEST_CASE("Shutdown socket without hanging when waiting for data") { TEST_CASE("Shutdown socket without hanging when waiting for data") {

12
slsSupportLib/tests/test-container_utils.cpp Executable file → Normal file
View File

@ -113,8 +113,7 @@ TEST_CASE("Compare a vector containing two vectors", "[support]") {
CHECK(minusOneIfDifferent(d) == d[2]); CHECK(minusOneIfDifferent(d) == d[2]);
} }
TEST_CASE("vector of bool", "[support]") {
TEST_CASE("vector of bool", "[support]"){
std::vector<bool> a{true, true, true}; std::vector<bool> a{true, true, true};
std::vector<bool> b{false, false, false}; std::vector<bool> b{false, false, false};
std::vector<bool> c{true, false, true}; std::vector<bool> c{true, false, true};
@ -124,14 +123,13 @@ TEST_CASE("vector of bool", "[support]"){
CHECK(minusOneIfDifferent(c) == -1); CHECK(minusOneIfDifferent(c) == -1);
} }
TEST_CASE("compare a vector of arrays", "[support]"){ TEST_CASE("compare a vector of arrays", "[support]") {
std::vector<std::array<uint64_t, 3>> vec0{{5,6,8},{5,6,8},{5,6,8}}; std::vector<std::array<uint64_t, 3>> vec0{{5, 6, 8}, {5, 6, 8}, {5, 6, 8}};
CHECK(minusOneIfDifferent(vec0) == std::array<uint64_t, 3>{5,6,8}); CHECK(minusOneIfDifferent(vec0) == std::array<uint64_t, 3>{5, 6, 8});
std::array<uint64_t, 3> arr; std::array<uint64_t, 3> arr;
arr.fill(-1); arr.fill(-1);
std::vector<std::array<uint64_t, 3>> vec1{{5,90,8},{5,6,8},{5,6,8}}; std::vector<std::array<uint64_t, 3>> vec1{{5, 90, 8}, {5, 6, 8}, {5, 6, 8}};
CHECK(minusOneIfDifferent(vec1) == arr); CHECK(minusOneIfDifferent(vec1) == arr);
} }

View File

@ -1,8 +1,8 @@
#include "catch.hpp" #include "catch.hpp"
#include "logger.h" #include "logger.h"
#include <iostream>
#include <fstream>
#include <chrono> #include <chrono>
#include <fstream>
#include <iostream>
using sls::Logger; using sls::Logger;
@ -27,25 +27,23 @@ TEST_CASE("Test output") {
Logger::ReportingLevel() = logERROR; Logger::ReportingLevel() = logERROR;
//Redirect std::clog to local buffer // Redirect std::clog to local buffer
std::ostringstream local; std::ostringstream local;
auto clog_buff = std::clog.rdbuf(); auto clog_buff = std::clog.rdbuf();
std::clog.rdbuf(local.rdbuf()); std::clog.rdbuf(local.rdbuf());
//Try printing something with too low level // Try printing something with too low level
LOG(logDEBUG) << "This should not be printed"; LOG(logDEBUG) << "This should not be printed";
CHECK(local.str().empty()); CHECK(local.str().empty());
//Try printing something with a higher level // Try printing something with a higher level
LOG(logERROR) << "This should be printed"; LOG(logERROR) << "This should be printed";
CHECK(!local.str().empty()); CHECK(!local.str().empty());
std::clog.rdbuf(clog_buff); // restore std::clog.rdbuf(clog_buff); // restore
Logger::ReportingLevel() = old_value; //reset Logger::ReportingLevel() = old_value; // reset
// Check that the message is in the printed string
//Check that the message is in the printed string
auto r = local.str(); auto r = local.str();
auto pos = r.find("This should be printed"); auto pos = r.find("This should be printed");
CHECK(pos != std::string::npos); CHECK(pos != std::string::npos);
} }

2
slsSupportLib/tests/test-network_utils.cpp Executable file → Normal file
View File

@ -105,7 +105,7 @@ TEST_CASE("MAC Output operator gives same result as string", "[support]") {
CHECK(os.str() == addr.str()); CHECK(os.str() == addr.str());
} }
TEST_CASE("Copy construct a MacAddr"){ TEST_CASE("Copy construct a MacAddr") {
MacAddr addr{"00:50:c2:46:d9:a6"}; MacAddr addr{"00:50:c2:46:d9:a6"};
MacAddr addr2(addr); MacAddr addr2(addr);
CHECK(addr == addr2); CHECK(addr == addr2);

73
slsSupportLib/tests/test-string_utils.cpp Executable file → Normal file
View File

@ -5,33 +5,29 @@
#include "string_utils.h" #include "string_utils.h"
TEST_CASE("copy a string") { TEST_CASE("copy a string") {
char src[10] = "hej"; char src[10] = "hej";
REQUIRE(src[3]=='\0'); REQUIRE(src[3] == '\0');
char dst[20]; char dst[20];
sls::strcpy_safe(dst, src); sls::strcpy_safe(dst, src);
REQUIRE(dst[0]=='h'); REQUIRE(dst[0] == 'h');
REQUIRE(dst[1]=='e'); REQUIRE(dst[1] == 'e');
REQUIRE(dst[2]=='j'); REQUIRE(dst[2] == 'j');
REQUIRE(dst[3]=='\0'); REQUIRE(dst[3] == '\0');
} }
#ifdef NDEBUG #ifdef NDEBUG
//This test can only run in release since we assert on the length of the string // This test can only run in release since we assert on the length of the string
TEST_CASE("copy a long string"){ TEST_CASE("copy a long string") {
auto src = "some very very long sting that does not fit"; auto src = "some very very long sting that does not fit";
char dst[3]; char dst[3];
sls::strcpy_safe(dst, src); sls::strcpy_safe(dst, src);
REQUIRE(dst[0]=='s'); REQUIRE(dst[0] == 's');
REQUIRE(dst[1]=='o'); REQUIRE(dst[1] == 'o');
REQUIRE(dst[2]=='\0'); REQUIRE(dst[2] == '\0');
} }
#endif #endif
TEST_CASE("Concat") { TEST_CASE("Concat") {
@ -44,65 +40,64 @@ TEST_CASE("Concat") {
// make sure we didn't modify the string // make sure we didn't modify the string
REQUIRE(v == v2); REQUIRE(v == v2);
SECTION("add a different value"){ SECTION("add a different value") {
v.emplace_back("two"); v.emplace_back("two");
REQUIRE(v!=v2); REQUIRE(v != v2);
REQUIRE( sls::concatenateIfDifferent(v) == "one+one+one+two+"); REQUIRE(sls::concatenateIfDifferent(v) == "one+one+one+two+");
} }
} }
TEST_CASE("split a string with end delimiter"){ TEST_CASE("split a string with end delimiter") {
std::string s("abra+kadabra+"); std::string s("abra+kadabra+");
auto r =sls::split(s, '+'); auto r = sls::split(s, '+');
REQUIRE(r.size()==2); REQUIRE(r.size() == 2);
REQUIRE(r[0]=="abra"); REQUIRE(r[0] == "abra");
REQUIRE(r[1]=="kadabra"); REQUIRE(r[1] == "kadabra");
} }
TEST_CASE("split a string without end delimiter"){ TEST_CASE("split a string without end delimiter") {
std::string s("abra+kadabra+filibom"); std::string s("abra+kadabra+filibom");
auto r =sls::split(s, '+'); auto r = sls::split(s, '+');
REQUIRE(r.size()==3); REQUIRE(r.size() == 3);
REQUIRE(r[0]=="abra"); REQUIRE(r[0] == "abra");
REQUIRE(r[1]=="kadabra"); REQUIRE(r[1] == "kadabra");
REQUIRE(r[2]=="filibom"); REQUIRE(r[2] == "filibom");
} }
TEST_CASE("concatenate non empty strings"){ TEST_CASE("concatenate non empty strings") {
std::vector<std::string> vec{"hej", "kalas", "", "foto"}; std::vector<std::string> vec{"hej", "kalas", "", "foto"};
REQUIRE(vec.size()==4); REQUIRE(vec.size() == 4);
auto ret = sls::concatenateNonEmptyStrings(vec); auto ret = sls::concatenateNonEmptyStrings(vec);
REQUIRE(ret == "hej+kalas+foto+"); REQUIRE(ret == "hej+kalas+foto+");
} }
TEST_CASE("concatenate non empty strings with only emty"){ TEST_CASE("concatenate non empty strings with only emty") {
std::vector<std::string> vec{"", "", ""}; std::vector<std::string> vec{"", "", ""};
REQUIRE(vec.size()==3); REQUIRE(vec.size() == 3);
auto ret = sls::concatenateNonEmptyStrings(vec); auto ret = sls::concatenateNonEmptyStrings(vec);
REQUIRE(ret.empty()); REQUIRE(ret.empty());
} }
TEST_CASE("concatenate non empty strings with one element"){ TEST_CASE("concatenate non empty strings with one element") {
std::vector<std::string> vec{"", "hej", "", "", ""}; std::vector<std::string> vec{"", "hej", "", "", ""};
REQUIRE(vec.size()==5); REQUIRE(vec.size() == 5);
auto ret = sls::concatenateNonEmptyStrings(vec); auto ret = sls::concatenateNonEmptyStrings(vec);
REQUIRE(ret=="hej+"); REQUIRE(ret == "hej+");
} }
TEST_CASE("Remove char from string") {
TEST_CASE("Remove char from string"){
char str[] = "sometest"; char str[] = "sometest";
sls::removeChar(str, 'e'); sls::removeChar(str, 'e');
REQUIRE(std::string(str) == "somtst"); REQUIRE(std::string(str) == "somtst");
} }
TEST_CASE("Remove char from empty string"){ TEST_CASE("Remove char from empty string") {
char str[50] = {}; char str[50] = {};
sls::removeChar(str, 'e'); sls::removeChar(str, 'e');
REQUIRE(std::string(str) == ""); REQUIRE(std::string(str) == "");
} }
TEST_CASE("Many characters in a row"){ TEST_CASE("Many characters in a row") {
char str[] = "someeequitellll::ongstring"; char str[] = "someeequitellll::ongstring";
sls::removeChar(str, 'l'); sls::removeChar(str, 'l');
REQUIRE(std::string(str) == "someeequite::ongstring"); REQUIRE(std::string(str) == "someeequite::ongstring");