diff --git a/slsDetectorSoftware/Makefile b/slsDetectorSoftware/Makefile index eb3708d50..2f5ff4153 100644 --- a/slsDetectorSoftware/Makefile +++ b/slsDetectorSoftware/Makefile @@ -69,14 +69,14 @@ gotthardVirtualServer: $(SRC_MYTHEN_SVC) %.o : %.cpp %.h Makefile - $(CXX) -o $@ -c $< $(INCLUDES) $(DFLAGS) -fPIC $(EPICSFLAGS) -lpthread -lrt $(LIBZMQ) #$(FLAGS) + $(CXX) -o $@ -c $< $(INCLUDES) $(DFLAGS) -fPIC $(EPICSFLAGS) -pthread -lrt $(LIBZMQ) $(FLAGS) package: $(OBJS) $(DESTDIR)/libSlsDetector.so $(DESTDIR)/libSlsDetector.a $(DESTDIR)/libSlsDetector.so: $(OBJS) - $(CXX) -shared -Wl,-soname,libSlsDetector.so -o libSlsDetector.so $(OBJS) -lc $(INCLUDES) $(DFLAGS) $(FLAGS) $(EPICSFLAGS) -L/usr/lib64 -lpthread -lrt $(LIBZMQ) + $(CXX) -shared -Wl,-soname,libSlsDetector.so -o libSlsDetector.so $(OBJS) -lc $(INCLUDES) $(DFLAGS) $(FLAGS) $(EPICSFLAGS) -L/usr/lib64 -pthread -lrt $(LIBZMQ) $(shell test -d $(DESTDIR) || mkdir -p $(DESTDIR)) mv libSlsDetector.so $(DESTDIR) diff --git a/slsDetectorSoftware/commonFiles/communication_funcs.c b/slsDetectorSoftware/commonFiles/communication_funcs.c index c72722c92..4c19812ed 100755 --- a/slsDetectorSoftware/commonFiles/communication_funcs.c +++ b/slsDetectorSoftware/commonFiles/communication_funcs.c @@ -308,7 +308,7 @@ int receiveData(int file_des, void* buf,int length, intType itype){ int ret = receiveDataOnly(file_des, buf, length); #ifndef PCCOMPILE #ifdef EIGERD - swapData(buf, length, itype); + if (ret >= 0) swapData(buf, length, itype); #endif #endif return ret; @@ -316,9 +316,9 @@ int receiveData(int file_des, void* buf,int length, intType itype){ int sendDataOnly(int file_des, void* buf,int length) { - - - return write(file_des, buf, length); + int ret = write(file_des, buf, length); //value of -1 is other end socket crash as sigpipe is ignored + if (ret < 0) cprintf(BG_RED, "Error writing to socket. Possible socket crash\n"); + return ret; } @@ -328,37 +328,32 @@ int receiveData(int file_des, void* buf,int length, intType itype){ int nreceiving; int nreceived; if (file_des<0) return -1; +<<<<<<< HEAD #ifdef VERY_VERBOSE printf("want to receive %d Bytes\n", length); #endif +======= +#ifdef VERY_VERBOSE + printf("want to receive %d Bytes\n", length); +#endif +>>>>>>> e564542ad33a64e66ad6153066741c69c707f99d - while(length>0){ + while(length > 0) { nreceiving = (length>send_rec_max_size) ? send_rec_max_size:length; - - //#ifdef VERY_VERBOSE - // printf("want to receive %d Bytes\n", nreceiving); - //#endif nreceived = read(file_des,(char*)buf+total_received,nreceiving); - //#ifdef VERY_VERBOSE - // printf("read %d \n", nreceived); - //#endif - if(!nreceived) break; - // if(nreceived<0) break; + if(!nreceived){ + if(!total_received) { + return -1; //to handle it + } + break; + } length-=nreceived; total_received+=nreceived; - // cout<<"nrec: "<0) strcpy(thisClientIP,dummyClientIP); - //if (strcmp(lastClientIP,"none")==0) - //strcpy(lastClientIP,thisClientIP); - if (strcmp(lastClientIP,thisClientIP)) differentClients=1; else diff --git a/slsDetectorSoftware/commonFiles/error_defs.h b/slsDetectorSoftware/commonFiles/error_defs.h index fed6af415..c353670c6 100644 --- a/slsDetectorSoftware/commonFiles/error_defs.h +++ b/slsDetectorSoftware/commonFiles/error_defs.h @@ -19,11 +19,12 @@ using namespace std; /** Error flags */ /*Assumption: Only upto 63 detectors */ -#define CRITICAL_ERROR_MASK 0xFFFFFFFF #define MULTI_DETECTORS_NOT_ADDED 0x8000000000000000ULL +#define CRITICAL_ERROR_MASK 0xFFFFFFF +// 0xFFFFFFF000000000ULL #define CANNOT_CONNECT_TO_DETECTOR 0x4000000000000000ULL #define CANNOT_CONNECT_TO_RECEIVER 0x2000000000000000ULL #define COULDNOT_SET_CONTROL_PORT 0x1000000000000000ULL @@ -40,10 +41,12 @@ using namespace std; #define COULD_NOT_CONFIGURE_MAC 0x0002000000000000ULL #define COULDNOT_START_RECEIVER 0x0001000000000000ULL // default error like starting threads #define COULDNOT_STOP_RECEIVER 0x0000800000000000ULL +#define RECEIVER_DET_POSID_NOT_SET 0x0000400000000000ULL +#define RECEIVER_MULTI_DET_SIZE_NOT_SET 0x0000200000000000ULL -// 0xFFFFFFFF00000000ULL - +// 0xFFFFFFF000000000ULL +// 0x0000000FFFFFFFFFULL #define COULDNOT_SET_NETWORK_PARAMETER 0x0000000000000001ULL #define COULDNOT_SET_ROI 0x0000000000000002ULL #define RECEIVER_READ_FREQUENCY 0x0000000000000004ULL @@ -74,8 +77,10 @@ using namespace std; #define RECEIVER_READ_TIMER 0x0000000008000000ULL #define RECEIVER_ACQ_TIME_NOT_SET 0x0000000010000000ULL #define RECEIVER_FLIPPED_DATA_NOT_SET 0x0000000020000000ULL +#define THRESHOLD_NOT_SET 0x0000000040000000ULL +#define RECEIVER_FILE_FORMAT 0x0000000080000000ULL +// 0x0000000FFFFFFFFFULL -// 0x00000000FFFFFFFFULL /** @short class returning all error messages for error mask */ class errorDefs { @@ -134,6 +139,12 @@ public: if(slsErrorMask&DETECTOR_ACTIVATE) retval.append("Could not activate/deactivate detector\n"); + if(slsErrorMask&RECEIVER_DET_POSID_NOT_SET) + retval.append("Could not set detector position id\n"); + + if(slsErrorMask&RECEIVER_MULTI_DET_SIZE_NOT_SET) + retval.append("Could not set multi detector size\n"); + @@ -234,6 +245,13 @@ public: if(slsErrorMask&RECEIVER_FLIPPED_DATA_NOT_SET) retval.append("Could not set receiver flipped data/bottom\n"); + if(slsErrorMask&THRESHOLD_NOT_SET) + retval.append("Could not set threshold\n"); + + if(slsErrorMask&RECEIVER_FILE_FORMAT) + retval.append("Could not set receiver file format\n"); + + //------------------------------------------------------ length of message diff --git a/slsDetectorSoftware/commonFiles/sls_detector_defs.h b/slsDetectorSoftware/commonFiles/sls_detector_defs.h index faa425780..17470b6bf 100755 --- a/slsDetectorSoftware/commonFiles/sls_detector_defs.h +++ b/slsDetectorSoftware/commonFiles/sls_detector_defs.h @@ -19,9 +19,6 @@ /** header length for data :gotthard*/ #define HEADERLENGTH 12 -#define DEFAULT_SUBFRAME_EXPOSURE_VAL 2621440 /** default value for sub frame value 2.6ms*/ -#define MAX_SUBFRAME_EXPOSURE_VAL_IN_10NS 0x1FFFFFFF /** 29 bit register for max subframe exposure value */ - /** maximum rois */ #define MAX_ROIS 100 @@ -129,7 +126,7 @@ class slsDetectorDefs: public virtual slsReceiverDefs{ typedef struct { int module; /**< is the module number */ int serialnumber; /**< is the module serial number */ - int nchan; /**< is the number of channels per chip */ + int nchan; /**< is the number of channels on the module*/ int nchip; /**< is the number of chips on the module */ int ndac; /**< is the number of dacs on the module */ int nadc; /**< is the number of adcs on the module */ diff --git a/slsDetectorSoftware/commonFiles/sls_detector_funcs.h b/slsDetectorSoftware/commonFiles/sls_detector_funcs.h index 4d8ba0cae..12ddb896f 100644 --- a/slsDetectorSoftware/commonFiles/sls_detector_funcs.h +++ b/slsDetectorSoftware/commonFiles/sls_detector_funcs.h @@ -8,7 +8,7 @@ #ifndef SLS_DETECTOR_FUNCS_H #define SLS_DETECTOR_FUNCS_H -enum { +enum detFuncs{ // General purpose functions F_EXEC_COMMAND=0, /**< command is executed */ @@ -109,10 +109,14 @@ enum { F_PROGRAM_FPGA, /**< program FPGA */ F_RESET_FPGA, /**< reset FPGA */ F_POWER_CHIP, /**< power chip */ + F_ACTIVATE, /** < activate */ + F_PREPARE_ACQUISITION, /** < prepare acquisition */ + F_CLEANUP_ACQUISITION, /** < clean up after acquisition */ /* Always append functions hereafter!!! */ /* Always append functions before!!! */ - TOO_MANY_FUNCTIONS_DEFINED=128 //you should get a compilation error if there are already so many functions defined. It conflicts with sls_receiver_funcs.h + NUM_DET_FUNCTIONS, + TOO_MANY_FUNCTIONS_DEFINED=127 //you should get a compilation error if there are already so many functions defined. It conflicts with sls_receiver_funcs.h }; diff --git a/slsDetectorSoftware/eigerDetectorServer/Beb.c b/slsDetectorSoftware/eigerDetectorServer/Beb.c index 5299f1d37..417cf4b5a 100644 --- a/slsDetectorSoftware/eigerDetectorServer/Beb.c +++ b/slsDetectorSoftware/eigerDetectorServer/Beb.c @@ -180,24 +180,31 @@ void Beb_GetModuleConfiguration(int* master, int* top, int* normal){ void Beb_EndofDataSend(int tengiga){ //mapping new memory u_int32_t* csp0base=0; - int l_framepktcounter2, l_txndelaycounter, l_framedelaycounter, r_framepktcounter2, r_txndelaycounter, r_framedelaycounter; - int l_framepktcounter2_new, l_txndelaycounter_new, l_framedelaycounter_new, r_framepktcounter2_new, r_txndelaycounter_new, r_framedelaycounter_new; - int addr_l_framepktcounter2, addr_l_txndelaycounter, addr_l_framedelaycounter, addr_r_framepktcounter2, addr_r_txndelaycounter, addr_r_framedelaycounter; + int l_framepktLsbcounter, l_framepktMsbcounter, l_txndelaycounter, l_framedelaycounter; + int r_framepktLsbcounter, r_framepktMsbcounter, r_txndelaycounter, r_framedelaycounter; + int l_framepktLsbcounter_new, l_framepktMsbcounter_new, l_txndelaycounter_new, l_framedelaycounter_new; + int r_framepktLsbcounter_new, r_framepktMsbcounter_new, r_txndelaycounter_new, r_framedelaycounter_new; + int addr_l_framepktLsbcounter, addr_l_framepktMsbcounter, addr_l_txndelaycounter, addr_l_framedelaycounter; + int addr_r_framepktLsbcounter, addr_r_framepktMsbcounter, addr_r_txndelaycounter, addr_r_framedelaycounter; switch(tengiga){ case 0: - addr_l_framepktcounter2 = ONE_GIGA_LEFT_PKT_SEND_COUNTER; + addr_l_framepktLsbcounter = ONE_GIGA_LEFT_INDEX_LSB_COUNTER; + addr_l_framepktMsbcounter = ONE_GIGA_LEFT_INDEX_MSB_COUNTER; addr_l_txndelaycounter = ONE_GIGA_LEFT_TXN_DELAY_COUNTER; addr_l_framedelaycounter = ONE_GIGA_LEFT_FRAME_DELAY_COUNTER; - addr_r_framepktcounter2 = ONE_GIGA_RIGHT_PKT_SEND_COUNTER; + addr_r_framepktLsbcounter = ONE_GIGA_RIGHT_INDEX_LSB_COUNTER; + addr_r_framepktMsbcounter = ONE_GIGA_RIGHT_INDEX_MSB_COUNTER; addr_r_txndelaycounter = ONE_GIGA_RIGHT_TXN_DELAY_COUNTER; addr_r_framedelaycounter = ONE_GIGA_RIGHT_FRAME_DELAY_COUNTER; break; case 1: - addr_l_framepktcounter2 = TEN_GIGA_LEFT_PKT_SEND_COUNTER; + addr_l_framepktLsbcounter = TEN_GIGA_LEFT_INDEX_LSB_COUNTER; + addr_l_framepktMsbcounter = TEN_GIGA_LEFT_INDEX_MSB_COUNTER; addr_l_txndelaycounter = TEN_GIGA_LEFT_TXN_DELAY_COUNTER; addr_l_framedelaycounter = TEN_GIGA_LEFT_FRAME_DELAY_COUNTER; - addr_r_framepktcounter2 = TEN_GIGA_RIGHT_PKT_SEND_COUNTER; + addr_r_framepktLsbcounter = TEN_GIGA_RIGHT_INDEX_LSB_COUNTER; + addr_r_framepktMsbcounter = TEN_GIGA_RIGHT_INDEX_MSB_COUNTER; addr_r_txndelaycounter = TEN_GIGA_RIGHT_TXN_DELAY_COUNTER; addr_r_framedelaycounter = TEN_GIGA_RIGHT_FRAME_DELAY_COUNTER; break; @@ -211,23 +218,27 @@ void Beb_EndofDataSend(int tengiga){ return; }else{ //read data first time - l_framepktcounter2 = Beb_Read32(csp0base, addr_l_framepktcounter2); + l_framepktLsbcounter = Beb_Read32(csp0base, addr_l_framepktLsbcounter); + l_framepktMsbcounter = Beb_Read32(csp0base, addr_l_framepktMsbcounter); l_txndelaycounter = Beb_Read32(csp0base, addr_l_txndelaycounter); l_framedelaycounter = Beb_Read32(csp0base, addr_l_framedelaycounter); - r_framepktcounter2 = Beb_Read32(csp0base, addr_r_framepktcounter2); + r_framepktLsbcounter = Beb_Read32(csp0base, addr_r_framepktLsbcounter); + r_framepktMsbcounter = Beb_Read32(csp0base, addr_r_framepktMsbcounter); r_txndelaycounter = Beb_Read32(csp0base, addr_r_txndelaycounter); r_framedelaycounter = Beb_Read32(csp0base, addr_r_framedelaycounter); //#ifdef VERBOSE printf("\nLeft\n" - "Framepacketcounter: %d\n" + "FramepacketLsbcounter: %d\n" + "FramepacketMsbcounter: %d\n" "Txndelaycounter:%d\n" "Framedelaycounter:%d\n" "\nRight\n" - "Framepacketcounter: %d\n" + "FramepacketLsbcounter: %d\n" + "FramepacketMsbcounter: %d\n" "Txndelaycounter:%d\n" "Framedelaycounter:%d\n\n", - l_framepktcounter2,l_txndelaycounter,l_framedelaycounter, - r_framepktcounter2,r_txndelaycounter,r_framedelaycounter); + l_framepktLsbcounter,l_framepktMsbcounter,l_txndelaycounter,l_framedelaycounter, + r_framepktLsbcounter,r_framepktMsbcounter,r_txndelaycounter,r_framedelaycounter); //#endif //keep comparing with previous values @@ -239,33 +250,42 @@ void Beb_EndofDataSend(int tengiga){ usleep(maxtimer); //read new values - l_framepktcounter2_new = Beb_Read32(csp0base, addr_l_framepktcounter2); + l_framepktLsbcounter_new = Beb_Read32(csp0base, addr_l_framepktLsbcounter); + l_framepktMsbcounter_new = Beb_Read32(csp0base, addr_l_framepktMsbcounter); l_txndelaycounter_new = Beb_Read32(csp0base, addr_l_txndelaycounter); l_framedelaycounter_new = Beb_Read32(csp0base, addr_l_framedelaycounter); - r_framepktcounter2_new = Beb_Read32(csp0base, addr_r_framepktcounter2); + r_framepktLsbcounter_new = Beb_Read32(csp0base, addr_r_framepktLsbcounter); + r_framepktMsbcounter_new = Beb_Read32(csp0base, addr_r_framepktMsbcounter); r_txndelaycounter_new = Beb_Read32(csp0base, addr_r_txndelaycounter); r_framedelaycounter_new = Beb_Read32(csp0base, addr_r_framedelaycounter); //#ifdef VERBOSE printf("\nLeft\n" - "Framepacketcounter: %d\n" + "FramepacketLsbcounter: %d\n" + "FramepacketMsbcounter: %d\n" "Txndelaycounter:%d\n" "Framedelaycounter:%d\n" "\nRight\n" - "Framepacketcounter: %d\n" + "FramepacketLsbcounter: %d\n" + "FramepacketMsbcounter: %d\n" "Txndelaycounter:%d\n" "Framedelaycounter:%d\n\n", - l_framepktcounter2_new,l_txndelaycounter_new,l_framedelaycounter_new, - r_framepktcounter2_new,r_txndelaycounter_new,r_framedelaycounter_new); + l_framepktLsbcounter_new,l_framepktMsbcounter_new,l_txndelaycounter_new,l_framedelaycounter_new, + r_framepktLsbcounter_new,r_framepktMsbcounter_new,r_txndelaycounter_new,r_framedelaycounter_new); //#endif - if ((l_framepktcounter2 == l_framepktcounter2_new) && (r_framepktcounter2 == r_framepktcounter2_new)) + if ((l_framepktLsbcounter == l_framepktLsbcounter_new) && + (l_framepktMsbcounter == l_framepktMsbcounter_new) && + (r_framepktLsbcounter == r_framepktLsbcounter_new) && + (r_framepktMsbcounter == r_framepktMsbcounter_new)) break; //update old values - l_framepktcounter2 = l_framepktcounter2_new; + l_framepktLsbcounter = l_framepktLsbcounter_new; + l_framepktMsbcounter = l_framepktMsbcounter_new; l_txndelaycounter = l_txndelaycounter_new; l_framedelaycounter = l_framedelaycounter_new; - r_framepktcounter2 = r_framepktcounter2_new; + r_framepktLsbcounter = r_framepktLsbcounter_new; + r_framepktMsbcounter = r_framepktMsbcounter_new; r_txndelaycounter = r_txndelaycounter_new; r_framedelaycounter = r_framedelaycounter_new; @@ -392,7 +412,7 @@ int Beb_Activate(int enable){ } -int Beb_SetNetworkParameter(enum detNetworkParameter mode, int val){ +int Beb_SetNetworkParameter(enum NETWORKINDEX mode, int val){ if(!Beb_activated) return val; diff --git a/slsDetectorSoftware/eigerDetectorServer/Beb.cxx b/slsDetectorSoftware/eigerDetectorServer/Beb.cxx deleted file mode 100644 index 80746bbe6..000000000 --- a/slsDetectorSoftware/eigerDetectorServer/Beb.cxx +++ /dev/null @@ -1,470 +0,0 @@ - -/** - * @author Ian Johnson - * @version 1.0 - */ - - -//return reversed 1 means good, 0 means failed - - - -#include -#include -#include -#include -#include -#include -#include - - -#include "xfs_types.h" -#include "xparameters.h" - -#include "Beb.h" - -using namespace std; - -BebInfo::BebInfo(unsigned int beb_num){beb_number=beb_num;serial_address=0;src_mac_1GbE="";src_mac_10GbE="";src_ip_1GbE="";src_ip_10GbE=""; src_port_1GbE=src_port_10GbE=0;} -bool BebInfo::SetHeaderInfo(bool ten_gig, string src_mac, string src_ip, unsigned int src_port){ - if(ten_gig){ src_mac_10GbE = src_mac; src_ip_10GbE = src_ip; src_port_10GbE = src_port;} - else { src_mac_1GbE = src_mac; src_ip_1GbE = src_ip; src_port_1GbE = src_port;} - return 1; -} - -bool BebInfo::SetSerialAddress(unsigned int a){ - //address pre shifted - if(a>0xff) return 0; - serial_address = 0x04000000 | ((a&0xff)<<16); - return 1; -} - -void BebInfo::Print(){ - cout<<"\t"<Print(); - cout<InitNewMemory(XPAR_PLB_LL_NEW_MEMORY, arg1)) - printf("New Memory FAIL\n"); - else - printf("New Memory OK\n"); - -} - -Beb::~Beb(){ - delete ll; - delete [] send_data_raw; - delete [] recv_data_raw; -} - -void Beb::ClearBebInfos(){ - for(unsigned int i=0;iSetSerialAddress(0xff)) beb_infos.push_back(b0); //all bebs for reset and possibly get request data? - - if(!ReadSetUpFromFile("/home/root/executables/setup_beb.txt")) return 0; -/* - //loop through file to fill vector. - BebInfo* b = new BebInfo(26); - b->SetSerialAddress(0); //0xc4000000 - b->SetHeaderInfo(0,"00:50:c2:46:d9:34","129.129.205.78",42000 + 26); // 1 GbE, ip address can be acquire from the network "arp" - b->SetHeaderInfo(1,"00:50:c2:46:d9:35","10.0.26.1",52000 + 26); //10 GbE, everything calculable/setable - beb_infos.push_back(b); -*/ - - return CheckSourceStuffBebInfo(); -} - - - -bool Beb::SetBebSrcHeaderInfos(unsigned int beb_number, bool ten_gig, string src_mac, string src_ip,unsigned int src_port){ - //so that the values can be reset externally for now.... - - unsigned int i = GetBebInfoIndex(beb_number); - if(!i) return 0; //i must be greater than 0, zero is the global send - beb_infos[i]->SetHeaderInfo(ten_gig,src_mac,src_ip,src_port); - - cout<<"Printing Beb info number ("<Print(); - cout<>cmd_st; - if(!strcmp("add_beb",cmd_st)){ - if(!(iss>>value_i[0]>>value_i[1]>>str_mac1>>str_ip1>>str_mac10>>str_ip10)){ - cout<<"Error adding beb from "<SetSerialAddress(value_i[1]); - b->SetHeaderInfo(0,str_mac1,str_ip1,42000+value_i[0]); - b->SetHeaderInfo(1,str_mac10,str_ip10,52000+value_i[0]); - beb_infos.push_back(b); - } - } - - infile.close(); - - return 1; -} - - - -bool Beb::CheckSourceStuffBebInfo(){ - for(unsigned int i=1;iGetBebNumber(),0,"00:00:00:00:00:00","10.0.0.1",20000)||!SetHeaderData(beb_infos[i]->GetBebNumber(),1,"00:00:00:00:00:00","10.0.0.1",20000)){ - cout<<"Error in BebInfo for module number "<GetBebNumber()<<"."<Print(); - return 0; - } - } - return 1; -} - -unsigned int Beb::GetBebInfoIndex(unsigned int beb_numb){ - if(!beb_numb) return 0; - - for(unsigned int i=1;iGetBebNumber()) return i; - return 0; -} - - - -bool Beb::WriteTo(unsigned int index){ - if(index>=beb_infos.size()){ - cout<<"WriteTo index error."<GetSerialAddress(); - if(ll->Write(4,send_data_raw)!=4) return 0; - - send_data_raw[0] = 0xc0000000; - if((send_ndata+1)*4!=ll->Write((send_ndata+1)*4,send_data_raw)) return 0; - - return 1; -} - - -void Beb::SwapDataFun(bool little_endian, unsigned int n, unsigned int *d){ - if(little_endian) for(unsigned int i=0;i>8) | ((d[i]&0xff000000)>>24)); //little_endian - else for(unsigned int i=0;i>16)); -} - - -bool Beb::SetByteOrder(){ - send_data_raw[0] = 0x8fff0000; - if(ll->Write(4,send_data_raw)!=4) return 0; - - while((ll->Read(recv_buffer_size*4,recv_data_raw)/4)>0) cout<<"\t) Cleanning buffer ..."<GetSrcMAC(ten_gig),beb_infos[i]->GetSrcIP(ten_gig),beb_infos[i]->GetSrcPort(ten_gig),dst_mac,dst_ip,dst_port); -} - -bool Beb::SetHeaderData(string src_mac, string src_ip, unsigned int src_port, string dst_mac, string dst_ip, unsigned int dst_port){ - /* example header*/ - //static unsigned int* word_ptr = new unsigned int [16]; - static udp_header_type udp_header = { - {0x00, 0x50, 0xc5, 0xb2, 0xcb, 0x46}, // DST MAC - {0x00, 0x50, 0xc2, 0x46, 0xd9, 0x02}, // SRC MAC - {0x08, 0x00}, - {0x45}, - {0x00}, - {0x00, 0x00}, - {0x00, 0x00}, - {0x40}, - {0x00}, - {0xff}, - {0x11}, - {0x00, 0x00}, - {129, 205, 205, 128}, // Src IP - {129, 205, 205, 122}, // Dst IP - {0x0f, 0xa1}, - {0x13, 0x89}, - {0x00, 0x00}, //{0x00, 0x11}, - {0x00, 0x00} - }; - - if(!SetMAC(src_mac,&(udp_header.src_mac[0]))) return 0; - if(!SetIP(src_ip,&(udp_header.src_ip[0]))) return 0; - if(!SetPortNumber(src_port,&(udp_header.src_port[0]))) return 0; - - if(!SetMAC(dst_mac,&(udp_header.dst_mac[0]))) return 0; - if(!SetIP(dst_ip,&(udp_header.dst_ip[0]))) return 0; - if(!SetPortNumber(dst_port,&(udp_header.dst_port[0]))) return 0; - - - AdjustIPChecksum(&udp_header); - - unsigned int* base_ptr = (unsigned int *) &udp_header; - unsigned int num_words = ( sizeof(udp_header_type) + 3 ) / 4; - // for(unsigned int i=0; i "<3))||(i==3&&(ip.length()<1||ip.length()>3))){ - cout<<"Error: in ip address -> "<> 8) & 0xff ; - dst_ptr[1] = port_number & 0xff; - return 1; -} - - -void Beb::AdjustIPChecksum(udp_header_type *ip){ - unsigned char *cptr = (unsigned char *) ip->ver_headerlen; - - ip->ip_header_checksum[0] = 0; - ip->ip_header_checksum[1] = 0; - ip->total_length[0] = 0; - ip->total_length[1] = 28; // IP + UDP Header Length - - // calc ip checksum - unsigned int ip_checksum = 0; - for(unsigned int i=0; i<10; i++){ - ip_checksum += ( (cptr[2*i] << 8) + (cptr[2*i + 1]) ); - if (ip_checksum & 0x00010000) ip_checksum = (ip_checksum + 1) & 0x0000ffff; - } - - ip->ip_header_checksum[0] = (ip_checksum >> 8) & 0xff ; - ip->ip_header_checksum[1] = ip_checksum & 0xff ; -} - - - -bool Beb::SendMultiReadRequest(unsigned int beb_number, unsigned int left_right, bool ten_gig, unsigned int dst_number, unsigned int npackets, unsigned int packet_size, bool stop_read_when_fifo_empty){ - - unsigned int i = GetBebInfoIndex(beb_number); //zero is the global send - - send_ndata = 3; - if(left_right == 1) send_data[0] = 0x00040000; - else if(left_right == 2) send_data[0] = 0x00080000; - else if(left_right == 3) send_data[0] = 0x000c0000; - else return 0; - - //packet_size/=2; - if(dst_number>0x3f) return 0; - if(packet_size>0x3ff) return 0; - if(npackets==0||npackets>0x100) return 0; - npackets--; - - - send_data[1] = 0x62000000 | (!stop_read_when_fifo_empty) << 27 | (ten_gig==1) << 24 | packet_size << 14 | dst_number << 8 | npackets; - send_data[2] = 0; - - SwapDataFun(0,2,&(send_data[1])); - - if(!WriteTo(i)) return 0; - - return 1; -} - - -bool Beb::SetUpTransferParameters(short the_bit_mode){ - if(the_bit_mode!=4&&the_bit_mode!=8&&the_bit_mode!=16&&the_bit_mode!=32) return 0; - bit_mode = the_bit_mode; - - //nimages = the_number_of_images; - // on_dst = 0; - - return 1; -} - -bool Beb::RequestNImages(unsigned int beb_number, unsigned int left_right, bool ten_gig, unsigned int dst_number, unsigned int nimages, bool test_just_send_out_packets_no_wait){ - if(dst_number>64) return 0; - - unsigned int header_size = 4; //4*64 bits - unsigned int packet_size = ten_gig ? 0x200 : 0x80; // 4k or 1k packets - unsigned int npackets = ten_gig ? bit_mode*4 : bit_mode*16; - bool in_two_requests = (!ten_gig&&bit_mode==32); - if(in_two_requests) npackets/=2; - - //cout<<"here: "< -#include -#include -#include -#include // std::remove_if - -#include -#include -#include -#include -#include - -#include "Beb.h" -#include "slsDetectorServer_defs.h" //include port number - -using namespace std; - -enum cmd_string {evNotFound, - evRequestImages,evTestRequest, - evSetBitMode, - evSetupTableEntry,evSetDstParameters, - evTest,evTestSend, - evExitServer}; - -map enum_map; - -void init(){ - - enum_map["requestimages"] = evRequestImages; // - enum_map["testrequest"] = evTestRequest; // - - enum_map["setbitmode"] = evSetBitMode; // (resets on_dst and dst_requested) - - enum_map["setuptableentry"] = evSetupTableEntry; - enum_map["setdstparameters"] = evSetDstParameters; // (resets on_dst and dst_requested) - - enum_map["test"] = evTest; - enum_map["testsend"] = evTestSend; - enum_map["exitserver"] = evExitServer; - -} - -int server_list_s; -int server_conn_s; -int AccpetConnectionAndWaitForData(char* buffer, int maxlength); -bool WriteNClose(const char* buffer, int length); -bool SetupListenSocket(unsigned short int port); - - -string LowerCase(string str); -string GetNextString(string str,bool start_from_beginning=0); -void AddNumber(string& str, int n, int location=-1);//-1 means append - -int main(int argc, char* argv[]){ - cout<1) - bebs = new Beb(atoi(argv[1])); - else - bebs = new Beb(-1); - - // unsigned short int port_number = atoi(argv[1]); - - unsigned short int port_number = BEB_PORT; - if(!SetupListenSocket(port_number)) return 1; - - - int length=1000; - char data[1000]; - - int stop = 0; - time_t rawtime; - struct tm *timeinfo; - - bool send_to_ten_gig = 0; - int ndsts_in_use=32; - unsigned int nimages_per_request=1; - - int on_dst=0; - bool dst_requested[32] = {0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0}; - - while(!stop){ - - cout< "<0){ - return_start_pos = return_message.length(); - - switch(enum_map.find(LowerCase(cmd))->second){ - - case evRequestImages : - tmp_str[0] = GetNextString(data); - n[0] = atoi(tmp_str[0].data()); //dst number - if(tmp_str[0].length()<1||n[0]<0||n[0]>=ndsts_in_use){ - return_message.append("\tError executing: RequestImages (note dst_number must be less than ndsts_in_use that is set with SetDstParameters\n"); - ret_val = 1; - }else{ - dst_requested[n[0]] = 1; - ret_val=0; - tmp_str[1] = " ( "; - while(dst_requested[on_dst]){ - //waits on data - if((ret_val = (!bebs->RequestNImages(0,1,send_to_ten_gig,on_dst,nimages_per_request)||!bebs->RequestNImages(0,2,send_to_ten_gig,0x20|on_dst,nimages_per_request)))) break; - AddNumber(tmp_str[1],on_dst);tmp_str[1].append(" "); - dst_requested[on_dst++]=0; - on_dst%=ndsts_in_use; - } - if(ret_val) return_message.append("\tError executing: RequestImages "); - else{ return_message.append("\tExecuted: RequestImages "); AddNumber(return_message,n[0]);} - return_message.append(tmp_str[1]); - return_message.append(" )\n"); - } - break; - - case evTestRequest : - tmp_str[0] = GetNextString(data); - n[0] = atoi(tmp_str[0].data()); //dst number - if(tmp_str[0].length()<1||n[0]<0||n[0]>=ndsts_in_use){ - return_message.append("\tError executing: TestRequest (note dst_number must be less than 2xndsts_in_use that is set with SetDstParameters\n"); - ret_val = 1; - }else{ - ret_val = (!bebs->RequestNImages(0,1,send_to_ten_gig,n[0],nimages_per_request,1)||!bebs->RequestNImages(0,2,send_to_ten_gig,0x20|n[0],nimages_per_request,1)); - if(ret_val) return_message.append("\tError executing: TestRequest \n"); - else{ return_message.append("\tExecuted: TestRequest "); AddNumber(return_message,n[0]); return_message.append("\n");} - } - break; - - case evSetBitMode : - on_dst = 0; - for(n[0]=0;n[0]<32;n[0]++) dst_requested[n[0]] = 0; //clear dst requested - n[0] = atoi(GetNextString(data).data()); - if((ret_val = !bebs->SetUpTransferParameters(n[0]))) return_message.append("\tError executing: SetBitMode \n"); - else{ return_message.append("\tExecuted: SetBitMode ");AddNumber(return_message,n[0]);return_message.append("\n");} - break; - - case evSetDstParameters : //move below // - on_dst = 0; - for(n[0]=0;n[0]<32;n[0]++) dst_requested[n[0]] = 0; //clear dst requested - n[0] = atoi(GetNextString(data).data()); //<1GbE(0) or 10GbE(1)> - n[1] = atoi(GetNextString(data).data()); // - n[2] = atoi(GetNextString(data).data()); // 0)> - - if((n[0]!=0&&n[0]!=1)||(n[1]<1||n[1]>32)||n[2]<1){ - return_message.append("\tError executing: SetDstParameters <1GbE(0) or 10GbE(1)> \n"); - ret_val=1; - } - else{ - send_to_ten_gig = n[0]; - ndsts_in_use=n[1]; - nimages_per_request=n[2]; - return_message.append("\tExecuted: SetDstParameters "); - AddNumber(return_message,n[0]);return_message.append(" "); - AddNumber(return_message,n[1]);return_message.append(" "); - AddNumber(return_message,n[2]);return_message.append(" "); - ret_val=0; - } - break; - - case evSetupTableEntry : - n[0] = atoi(GetNextString(data).data()); //beb_number; - n[1] = atoi(GetNextString(data).data()); //<1GbE(0) or 10GbE(1)> - n[2] = atoi(GetNextString(data).data()); //header_number - tmp_str[0] = GetNextString(data); //src_mac - tmp_str[1] = GetNextString(data); //src_ip - n[3] = atoi(GetNextString(data).data()); //src_port - tmp_str[2] = GetNextString(data); //dst_mac - tmp_str[3] = GetNextString(data); //dst_ip - n[4] = atoi((tmp_str[4]=GetNextString(data)).data()); //dst_port - - if(n[0]<1||(n[1]!=0&&n[1]!=1)||(n[2]<0||n[2]>63)||tmp_str[0].length()<1||tmp_str[1].length()<1||n[3]<0||tmp_str[2].length()<1||tmp_str[3].length()<1||n[4]<0||tmp_str[4].length()<1){ - return_message.append("\tError executing: SetupTableEntry <1GbE(0) or 10GbE(1)> \n"); - ret_val = 1; - }else{ - for(int i=0;i<32;i++)/** modified for Aldo*/ - ret_val = !bebs->SetBebSrcHeaderInfos(n[0],n[1],tmp_str[0],tmp_str[1],n[3])||!bebs->SetUpUDPHeader(n[0],n[1],n[2]+i,tmp_str[2],tmp_str[3],n[4]); - - if(ret_val) return_message.append("\tError Executing: SetupTableEntry "); - else return_message.append("\tExecuted: SetupTableEntry "); - AddNumber(return_message,n[0]);return_message.append(" "); - AddNumber(return_message,n[1]);return_message.append(" "); - AddNumber(return_message,n[2]);return_message.append(" "); - return_message.append(tmp_str[0]);return_message.append(" "); - return_message.append(tmp_str[1]);return_message.append(" "); - AddNumber(return_message,n[3]);return_message.append(" "); - return_message.append(tmp_str[2]);return_message.append(" "); - return_message.append(tmp_str[3]);return_message.append(" "); - AddNumber(return_message,n[4]); - } - break; - - case evTest : - n[0] = atoi(GetNextString(data).data()); - if(n[0]<1){ - return_message.append("\tError executing: Test \n"); - ret_val = 1; - }else{ - ret_val = !bebs->Test(n[0]); - if(ret_val) return_message.append("\tError Executing: Test "); - else return_message.append("\tExecuted: Test "); - AddNumber(return_message,n[0]); - } - break; - - - case evTestSend : - n[0] = atoi(GetNextString(data).data()); //beb_number; - n[1] = atoi(GetNextString(data).data()); //giga bit, ten giga bit - n[2] = atoi((tmp_str[0]=GetNextString(data)).data()); //header_number - - if(n[0]<1||(n[1]!=0&&n[1]!=1)||(n[2]<0||n[2]>63)||tmp_str[0].length()<1){ - return_message.append("\tError executing: TestSend <1GbE(0) or 10GbE(1)> \n"); - ret_val = 1; - }else{ - ret_val = !bebs->SendMultiReadRequest(n[0],1,n[1],n[2],1,0); - - if(ret_val) return_message.append("\tError Executing: TestSend "); - else return_message.append("\tExecuted: TestSend "); - AddNumber(return_message,n[0]);return_message.append(" "); - AddNumber(return_message,n[1]);return_message.append(" "); - AddNumber(return_message,n[2]);return_message.append(" "); - } - break; - - case evExitServer : - return_message.append("\tExiting Server ....\n"); - stop = 1; - ret_val = -200; - break; - - default : - return_message.append("\tWarning command \""); - return_message.append(cmd); - return_message.append("\" not found.\n"); - return_message.append("\t\tValid commands: "); - map::iterator it = enum_map.begin(); - while(it!=enum_map.end()){ - return_message.append((it++)->first); - return_message.append(" "); - } - - ret_val=-100; - break; - } - - return_message.append("\n"); - AddNumber(return_message,ret_val,return_start_pos); - if(ret_val!=0) break; - - cmd = GetNextString(data); - } - return_message.append("\n\n\n"); - - AddNumber(return_message,ret_val,0); - cout<0) return sub; - } - - return ""; -} - - - -void AddNumber(string& str, int n, int location){ - static char retval_st[100]; - sprintf(retval_st,"%d",n); - - if(location<0) str.append(retval_st); - else str.insert(location,retval_st); -} - - -bool SetupListenSocket(unsigned short int port){ - server_list_s=0; - server_conn_s=0; - - if((server_list_s = socket(AF_INET, SOCK_STREAM, 0))<0) return 0; - - struct sockaddr_in servaddr; /* socket address structure */ - memset(&servaddr, 0, sizeof(servaddr)); - servaddr.sin_family = AF_INET; - servaddr.sin_addr.s_addr = htonl(INADDR_ANY); - servaddr.sin_port = htons(port); - - if(bind(server_list_s,(struct sockaddr *) &servaddr,sizeof(servaddr))<0) return 0; - - if(listen(server_list_s,32) < 0){ // 1024 /* Backlog for listen() */ - return 0; - } - - return 1; -} - - -int AccpetConnectionAndWaitForData(char* buffer, int maxlength){ - if(server_list_s==0||maxlength<=0) return 0; - - if((server_conn_s = accept(server_list_s,NULL,NULL))< 0) return 0; - - int nread = read(server_conn_s,buffer,maxlength-1); - - if(nread<0) return 0; - - buffer[nread]='\0'; - return nread; -} - -bool WriteNClose(const char* buffer, int length){ - if(server_conn_s==0||length<=0) return 0; - - int nsent = write(server_conn_s,buffer,length); - if(close(server_conn_s)<0) return 0; - - server_conn_s=0; - return (nsent==length); -} - - - - diff --git a/slsDetectorSoftware/eigerDetectorServer/Commands.txt b/slsDetectorSoftware/eigerDetectorServer/Commands.txt deleted file mode 100644 index e03e20865..000000000 --- a/slsDetectorSoftware/eigerDetectorServer/Commands.txt +++ /dev/null @@ -1,28 +0,0 @@ - -Internal setup: - setdac - trimbits - rate correction tau - high voltage - - -Setup: - photon energy - dynamic range (4,8,16,32) - number of images - exposure time - exposure period - readout speed(full speed, 1/2 speed, 1/4 or super slow) - readout mode (parallel, non-parallel or super safe) - trigger mode (internal,external start of series, external start of acquisitions, external window) - trigger polarity (pos/neg) - external gating (on, pos/neg) - - -Acquisition: - start acquisition - stop acquisition - acquisition in progress - wait until daq is finished - status (needs to be implemented) - diff --git a/slsDetectorSoftware/eigerDetectorServer/Eiger.cxx b/slsDetectorSoftware/eigerDetectorServer/Eiger.cxx deleted file mode 100644 index 43ac6c5fc..000000000 --- a/slsDetectorSoftware/eigerDetectorServer/Eiger.cxx +++ /dev/null @@ -1,1027 +0,0 @@ - -/** - * @author Ian Johnson - * @version 1.0 - */ - - -#include -#include -#include - -#include -#include -#include -#include - - -#include "EigerRegisterDefs.h" -#include "Eiger.h" - -using namespace std; - -//GetDAQStatusRegister(512,current_mode_bits_from_fpga)){ - -const unsigned int Module::ndacs = 16; -const string Module::dac_names[16] = {"SvP","Vtr","Vrf","Vrs","SvN","Vtgstv","Vcmp_ll","Vcmp_lr","cal","Vcmp_rl","rxb_rb","rxb_lb","Vcmp_rr","Vcp","Vcn","Vis"}; - - -Module::Module(unsigned int number, unsigned int address_top){ - module_number = number; - top_address_valid = 1; - top_left_address = 0x100 | (0xff & address_top); - top_right_address = 0x200 | (0xff & address_top); - bottom_address_valid = 0; - bottom_left_address = 0; - bottom_right_address = 0; - - high_voltage = -1; - top_dac = new float [ndacs]; - bottom_dac = new float [ndacs]; - for(unsigned int i=0;iGetModuleNumber()); - ReadSetUpFile(modules[i]->GetModuleNumber(),st); - } - - return CheckSetup(); -} - - -bool Eiger::ReadSetUpFileToAddModules(string file_name){ - static ifstream infile; - static string line; - static char cmd_st[2000]; - static int value_i[3]; - - infile.open(file_name.c_str(),ios::in); - if(!infile.is_open()) return 0; - - cout<>cmd_st; - if(!strcmp("add_module",cmd_st)){ - if(!(iss>>value_i[0]>>value_i[1]>>value_i[2])){ - cout<<"Error adding module from "<>value_i[0]>>value_i[1])){ - cout<<"Error adding half module from "<TopAddressIsValid()){ - feb_list[nfebs++] = modules[i]->GetTopRightAddress(); - feb_list[nfebs++] = modules[i]->GetTopLeftAddress(); - } - if(modules[i]->BottomAddressIsValid()){ - feb_list[nfebs++] = modules[i]->GetBottomRightAddress(); - feb_list[nfebs++] = modules[i]->GetBottomLeftAddress(); - } - } - - SendCompleteFebList(nfebs,feb_list); - delete [] feb_list; - - cout<GetModuleNumber()<<" "; - if(modules[i]->TopAddressIsValid()) cout<GetTopBaseAddress()<<" (top) "<BottomAddressIsValid()) cout<GetBottomBaseAddress()<<" (bottom)"<GetModuleNumber()==module_number){ - module_index=i; - return 1; - } - } - - return 0; -} - -bool Eiger::CheckModuleAddresses(unsigned int top_address, unsigned int bottom_address){ - bool found_t = 0; - bool found_b = 0; - for(unsigned int i=0;iGetTopBaseAddress() || top_address==modules[i]->GetBottomBaseAddress())) found_t=1; - if(bottom_address!=0 && (bottom_address==modules[i]->GetTopBaseAddress() || bottom_address==modules[i]->GetBottomBaseAddress())) found_b=1; - } - - if(top_address==bottom_address) cout<<"\tWarning: top and bottom address are the same "<>cmd_st; - - if(cmd_st[0]=='#'||!strcmp("add_module",cmd_st)||!strcmp("add_half_module",cmd_st)){ ;// cout<<"do nothing "<>value_i[0])) cout<<"Error reading iodelay from "<>value_f; - SetHighVoltage(module_num,value_f); - }else if(!strcmp("photon_energy",cmd_st)){ - iss>>value_f; - SetPhotonEnergy(value_f); - }else if(!strcmp("dynamic_range",cmd_st)){ - iss>>value_i[0]; - SetDynamicRange(value_i[0]); - }else if(!strcmp("readout_speed",cmd_st)){ - iss>>value_i[0]; - SetReadoutSpeed(value_i[0]); - }else if(!strcmp("readout_mode",cmd_st)){ - iss>>value_i[0]; - SetReadoutMode(value_i[0]); - }else{ - iss>>value_f; - if(module_num>0) sprintf(cmd_st,"mod%d::%s",module_num,cmd_st); - if(!SetDAC(cmd_st,value_f)) cout<<"error in string: "<GetTopIDelay(j)<0){ - cout<<"Warning: module "<GetModuleNumber()<<"'s idelay top number "<GetBottomIDelay(j)<0){ - cout<<"Warning: module "<GetModuleNumber()<<"'s idelay bottom number "<GetHighVoltage()<0){ - cout<<"Warning: module "<GetModuleNumber()<<"'s high voltage not set."<GetTopDACVoltage(j)<0){ - cout<<"Warning: module "<GetModuleNumber()<<"'s top \""<GetBottomDACVoltage(j)<0){ - cout<<"Warning: module "<GetModuleNumber()<<"'s bottom \""<TopAddressIsValid()) n_half_modules++; - if(modules[i]->BottomAddressIsValid()) n_half_modules++; - } - - return n_half_modules; -} - -bool Eiger::SetPhotonEnergy(unsigned int full_energy_eV){ - photon_energy_eV = full_energy_eV; - cout<<"Setting photon energy to: "<3){ - cout<<"Error SetIDelay chip_pos "<TopAddressIsValid()){ - if(SendIDelays(modules[module_index]->GetTopLeftAddress(),chip_pos%2==0,0xffffffff,ndelay_units)){ - if(module_index!=0) modules[module_index]->SetTopIDelay(chip_pos,ndelay_units); - else for(unsigned int i=0;iSetTopIDelay(chip_pos,ndelay_units); - }else{ - cout<<"Error could not set idelay module number "<BottomAddressIsValid()){ - if(SendIDelays(modules[module_index]->GetBottomLeftAddress(),chip_pos%2==0,0xffffffff,ndelay_units)){ - if(module_index!=0) modules[module_index]->SetBottomIDelay(chip_pos,ndelay_units); - else for(unsigned int i=0;iSetBottomIDelay(chip_pos,ndelay_units); - }else{ - cout<<"Error could not set idelay module number "<TopAddressIsValid()){ - if(SendIDelays(modules[module_index]->GetTopRightAddress(),chip_pos%2==0,0xffffffff,ndelay_units)){ - if(module_index!=0) modules[module_index]->SetTopIDelay(chip_pos,ndelay_units); - else for(unsigned int i=0;iSetTopIDelay(chip_pos,ndelay_units); - }else{ - cout<<"Error could not set idelay module number "<BottomAddressIsValid()){ - if(SendIDelays(modules[module_index]->GetBottomRightAddress(),chip_pos%2==0,0xffffffff,ndelay_units)){ - if(module_index!=0) modules[module_index]->SetBottomIDelay(chip_pos,ndelay_units); - else for(unsigned int i=0;iSetBottomIDelay(chip_pos,ndelay_units); - }else{ - cout<<"Error could not set idelay module number "<0x3ff) ndelay_units=0x3ff; - // this is global - unsigned int delay_data_valid_nclks = 15 - ((ndelay_units&0x3c0)>>6); //data valid delay upto 15 clks - ndelay_units &= 0x3f; //up to 64 delay units - // ndelay_unit |= 0x40; //and one bit for a full clock delay for the enabled pixels is zero for now - - unsigned int set_left_delay_channels = chip_lr ? channels:0; - unsigned int set_right_delay_channels = chip_lr ? 0:channels; - - cout<<"\tSetting delays of "; - if(set_left_delay_channels!=0) cout<<"left chips of dst_num "<vmax) return 0; - digital = int(((value-vmin)/(vmax-vmin))*(nsteps-1) + 0.5); - return 1; -} - -float Eiger::DACToVoltage(unsigned int digital,unsigned int nsteps,float vmin,float vmax){ - return vmin+(vmax-vmin)*digital/(nsteps-1); -} - - -bool Eiger::SetHighVoltage(unsigned int module_num,float value){ - unsigned int module_index=0; - if(!GetModuleIndex(module_num,module_index)||!modules[module_index]->TopAddressIsValid()){ - cout<<"Error could not set high voltage module number "<GetTopRightAddress(),value)) return 0; - - if(module_index!=0) modules[module_index]->SetHighVoltage(value); - else for(unsigned int i=0;iSetHighVoltage(value); - - cout<<"\tHigh voltage of dst "<GetTopRightAddress()<<" set to "<GetHighVoltage()<<"."<TopAddressIsValid()){ - float v = value; - if(!SendDACValue(modules[module_index]->GetTopRightAddress(),dac_ch,v)) return 0; - if(module_index!=0) modules[module_index]->SetTopDACVoltage(dac_ch,v); - else for(unsigned int i=0;iSetTopDACVoltage(dac_ch,v); - - } - if(bottom&&modules[module_index]->BottomAddressIsValid()){ - float v = value; - if(!SendDACValue(modules[module_index]->GetBottomRightAddress(),dac_ch,v)) return 0; - if(module_index!=0) modules[module_index]->SetBottomDACVoltage(dac_ch,v); - else for(unsigned int i=0;iSetBottomDACVoltage(dac_ch,v); - } - - return 1; -} - -bool Eiger::GetDAC(std::string s, float& ret_value){ - cout<<"Function Eiger::GetDAC need to be finished....."<=Module::ndacs){ - cout<<"Warning: Eiger::GetDACName index out of range, "<15){ - cout<<"Warning invalid ch for SetDAC."<>3)<<((7-i)*4);//upper - trimbits_to_load_r[offset+chip_sc] |= ( 0x7 & trimbits[263679 - (row_set*16480+super_column_start_position_r+i)])<<((7-i)*4);//low - trimbits_to_load_r[offset+chip_sc+32] |= ((0x38 & trimbits[263679 - (row_set*16480+super_column_start_position_r+i)])>>3)<<((7-i)*4);//upper - } - } - } - - if(!WriteMemory(0,0,0,1024,trimbits_to_load_r)||!WriteMemory(1,0,0,1024,trimbits_to_load_l)||!StartDAQOnlyNWaitForFinish()) return 0; - } - } - - memcpy(last_downloaded_trimbits,trimbits,trimbit_size*sizeof(unsigned char)); - - return SetStaticBits(); //send the static bits -} - - -unsigned char* Eiger::GetTrimbits(){ - return last_downloaded_trimbits; -} - - - - -bool Eiger::SetCommandRegister(unsigned int cmd){ - // if(fifo_enabled){ - // return WriteRegister(-1,DAQ_REG_CHIP_CMDS,cmd | DAQ_FIFO_ENABLE); - // } - return WriteRegister(0xfff,DAQ_REG_CHIP_CMDS,cmd); -} - - -bool Eiger::GetDAQStatusRegister(int socket_num, unsigned int &ret_status){ - - if(!ReadRegister(socket_num,DAQ_REG_STATUS,ret_status)){ - cout<<"Error: reading status register."<> 16; - return 1; -} - - -bool Eiger::StartDAQOnlyNWaitForFinish(int sleep_time_us){ - if(!WriteRegister(0xfff,DAQ_REG_CTRL,0)||!WriteRegister(0xfff,DAQ_REG_CTRL,DAQ_CTRL_START)){ - cout<<"Warning: could not start."<full,1->half,2->quarter or 3->super_slow - acquireNReadoutMode &= (~DAQ_CHIP_CONTROLLER_SUPER_SLOW_SPEED); - if(readout_speed==1){ - acquireNReadoutMode |= DAQ_CHIP_CONTROLLER_HALF_SPEED; - cout<<"Everything at half speed, ie. reading with 50 MHz main clk (half speed) ...."<parallel,1->non-parallel,2-> safe_mode - acquireNReadoutMode &= (~DAQ_NEXPOSURERS_PARALLEL_MODE); - if(readout_mode==1){ - acquireNReadoutMode |= DAQ_NEXPOSURERS_NORMAL_NONPARALLEL_MODE; - cout<<"Readout mode set to normal non-parallel readout mode ... "< internal exposure time and period, - //"01"-> external acquistion start and internal exposure time and period, - //"10"-> external start trigger and internal exposure time, - //"11"-> external triggered start and stop of exposures - triggerMode = (~DAQ_NEXPOSURERS_EXTERNAL_IMAGE_START_AND_STOP); - - if(trigger_mode == 1){ - triggerMode = DAQ_NEXPOSURERS_EXTERNAL_ACQUISITION_START; - cout<<"Trigger mode: external start of acquisition sequence, internal exposure length and period."<(pow(2,29)-1)*pow(10,7)){ - float max_time = 10e-9*(pow(2,28)-1)*pow(10,7); - cout<<"Warning: time exceeds ("<pow(2,29)-1){ power_of_ten++; n_clk_cycles = round(n_clk_cycles/10.0);} - decoded_time = int(n_clk_cycles)<<3 | int(power_of_ten); - } - - return decoded_time; -} - - -bool Eiger::ResetDataStream(){ - //for(int i=0;i<10;i++) cout<<"Warning need to think about reseting data stream ...."< -#include - -#include "Feb.h" - - -class Module{ - - private: - unsigned int module_number; - bool top_address_valid; - unsigned int top_left_address; - unsigned int top_right_address; - bool bottom_address_valid; - unsigned int bottom_left_address; - unsigned int bottom_right_address; - - unsigned int idelay_top[4]; //ll,lr,rl,ll - unsigned int idelay_bottom[4]; //ll,lr,rl,ll - float high_voltage; - float* top_dac; - float* bottom_dac; - - public: - Module(unsigned int number, unsigned int address_top); //for half module() - Module(unsigned int number, unsigned int address_top, unsigned int address_bottom); - ~Module(); - - static const unsigned int ndacs; - static const std::string dac_names[16]; - - unsigned int GetModuleNumber() {return module_number;} - bool TopAddressIsValid() {return top_address_valid;} - unsigned int GetTopBaseAddress() {return (top_left_address&0xff);} - unsigned int GetTopLeftAddress() {return top_left_address;} - unsigned int GetTopRightAddress() {return top_right_address;} - unsigned int GetBottomBaseAddress() {return (bottom_left_address&0xff);} - bool BottomAddressIsValid() {return bottom_address_valid;} - unsigned int GetBottomLeftAddress() {return bottom_left_address;} - unsigned int GetBottomRightAddress() {return bottom_right_address;} - - unsigned int SetTopIDelay(unsigned int chip,unsigned int value) { return TopAddressIsValid() &&chip<4 ? (idelay_top[chip]=value) : 0;} //chip 0=ll,1=lr,0=rl,1=rr - unsigned int GetTopIDelay(unsigned int chip) { return chip<4 ? idelay_top[chip] : 0;} //chip 0=ll,1=lr,0=rl,1=rr - unsigned int SetBottomIDelay(unsigned int chip,unsigned int value) { return BottomAddressIsValid() &&chip<4 ? (idelay_bottom[chip]=value) : 0;} //chip 0=ll,1=lr,0=rl,1=rr - unsigned int GetBottomIDelay(unsigned int chip) { return chip<4 ? idelay_bottom[chip] : 0;} //chip 0=ll,1=lr,0=rl,1=rr - - float SetHighVoltage(float value) { return TopAddressIsValid() ? (high_voltage=value) : -1;} - float GetHighVoltage() { return high_voltage;} - - float SetTopDACVoltage(unsigned int i, float value) { return (i modules; - void ClearModules(); - - unsigned int staticBits; //program=1,m4=2,m8=4,test=8,rotest=16,cs_bar_left=32,cs_bar_right=64 - unsigned int acquireNReadoutMode; //safe or parallel, half or full speed - unsigned int triggerMode; //internal timer, external start, external window, signal polarity (external trigger and enable) - unsigned int externalEnableMode; //external enabling engaged and it's polarity - unsigned int subFrameMode; - - unsigned int photon_energy_eV; - - unsigned int nimages; - float exposure_time_in_sec; - float exposure_period_in_sec; - - unsigned int trimbit_size; - unsigned char* last_downloaded_trimbits; - - void PrintModuleList(); - bool GetModuleIndex(unsigned int module_number, unsigned int& module_index); - bool CheckModuleAddresses(unsigned int top_address, unsigned int bottom_address); - bool AddModule(unsigned int module_number, unsigned int top_address); - bool AddModule(unsigned int module_number, unsigned int top_address, unsigned int bottom_address, bool half_module=0); - - bool GetDACNumber(std::string s, unsigned int& n); - bool SendDACValue(unsigned int dst_num, unsigned int ch, float& value); - bool VoltageToDAC(float value, unsigned int& digital, unsigned int nsteps, float vmin, float vmax); - float DACToVoltage(unsigned int digital,unsigned int nsteps,float vmin,float vmax); - - bool SendHighVoltage(unsigned int module_index, float& value); - - bool SendIDelays(unsigned int dst_num, bool chip_lr, unsigned int channels, unsigned int ndelay_units); - - bool SetStaticBits(); - bool SetStaticBits(unsigned int the_static_bits); - - unsigned int ConvertTimeToRegister(float time_in_sec); - - bool SetCommandRegister(unsigned int cmd); - bool GetDAQStatusRegister(int socket_num, unsigned int &ret_status); - bool StartDAQOnlyNWaitForFinish(int sleep_time_us=5000); - bool ResetDataStream(); - - bool ResetChipCompletely(); - - public: - Eiger(); - virtual ~Eiger(); - - bool Init(); - bool ReadSetUpFileToAddModules(std::string file_name); - bool ReadSetUpFile(unsigned int module_num, std::string file_name); - bool CheckSetup(); - - unsigned int GetNModules(); - unsigned int GetNHalfModules(); - - //bool SetHighVoltage(float value); - bool SetHighVoltage(unsigned int module_num,float value); - - bool SetPhotonEnergy(unsigned int full_energy_eV); - unsigned int GetPhotonEnergy(){return photon_energy_eV;} - - bool SetIDelays(unsigned int module_num, unsigned int ndelay_units); - bool SetIDelays(unsigned int module_num, unsigned int chip_pos, unsigned int ndelay_units); - - bool SetDAC(std::string s, float value); - bool GetDAC(std::string s, float& ret_value); - bool GetDACName(unsigned int dac_num, std::string &s); - - bool SetTrimbits(unsigned char* trimbits); - unsigned char* GetTrimbits(); - - - - bool Reset(); - bool StartAcquisition(); - bool StopAcquisition(); - bool AcquisitionInProgress(); - bool WaitForFinishedFlag(int sleep_time_us=5000); - - //functions for setting up exposure - void PrintAcquisitionSetup(); - bool SetNImages(unsigned int n_images); - unsigned int GetNImages(); - bool SetExposureTime(float the_exposure_time_in_sec); - float GetExposureTime(); - bool SetExposurePeriod(float the_exposure_period_in_sec); - float GetExposurePeriod(); - bool SetDynamicRange(unsigned int four_eight_sixteen_or_thirtytwo); - unsigned int GetDynamicRange(); - bool SetReadoutSpeed(unsigned int readout_speed=0); //0->full,1->half,2->quarter or 3->super_slow - bool SetReadoutMode(unsigned int readout_mode=0); //0->parallel,1->non-parallel,2-> safe_mode - bool SetTriggerMode(unsigned int trigger_mode=0, bool polarity=1); - bool SetExternalEnableMode(bool use_external_enable=0, bool polarity=1); - - - //functions for testing - bool SetTestModeVariable(bool on=1); - bool GetTestModeVariable(); - - bool FebTest(){return Feb::Test();} - -}; - - -#endif diff --git a/slsDetectorSoftware/eigerDetectorServer/EigerBackEndFunctions.c b/slsDetectorSoftware/eigerDetectorServer/EigerBackEndFunctions.c deleted file mode 100644 index 1378160f5..000000000 --- a/slsDetectorSoftware/eigerDetectorServer/EigerBackEndFunctions.c +++ /dev/null @@ -1,200 +0,0 @@ - -/** - * @author Ian Johnson - * @version 1.0 - */ - - -#include -#include -#include -#include - - - -#include "slsDetectorServer_defs.h" //include port number - -struct sockaddr_in eiger_back_socket_addr; -int eiger_back_max_message_length = 1024; -char eiger_back_message[1024]; -int eiger_back_message_length = 0; -int eiger_back_ret_val=0; - - -int bit_mode=0; -int ten_giga=0; - -int EigerBackInit(){ - static int passed = 0; - - if(!passed){ - struct hostent *dst_host; - if((dst_host = gethostbyname("localhost")) == NULL){ //or look into getaddrinfo(3) - fprintf(stderr,"ERROR, no such host\n"); - return 0; - }else{ - //struct sockaddr_in eiger_back_socket_addr; - int port = BEB_PORT; - bzero((char *) &eiger_back_socket_addr, sizeof(eiger_back_socket_addr)); - eiger_back_socket_addr.sin_family = AF_INET; - bcopy((char *)dst_host->h_addr,(char *)&eiger_back_socket_addr.sin_addr.s_addr,dst_host->h_length); - eiger_back_socket_addr.sin_port = htons(port); - passed = 1; - } - } - - return passed; -} - - -int EigerBackSendCMD(){ - if(!EigerBackInit()||eiger_back_message_length<=0) return 0; - - int sockfd = socket(AF_INET,SOCK_STREAM,0); - if(sockfd<0){ - fprintf(stderr,"ERROR opening socket\n"); - return 0; - } - - if(connect(sockfd,(struct sockaddr *) &eiger_back_socket_addr,sizeof(eiger_back_socket_addr))<0){ - fprintf(stderr,"ERROR connecting\n"); - return 0; - } - - int n = write(sockfd,eiger_back_message,eiger_back_message_length); - int ret_length = read(sockfd,eiger_back_message,eiger_back_max_message_length); - - close(sockfd); - - if(n<0||ret_length<0) return 0; - - - //fprintf(stdout,"%s\n",eiger_back_message); - if(eiger_back_ret_val>0){ - int i=0; - eiger_back_message[1]='\0'; - if(atoi(eiger_back_message)!=0) return 0; - - for(i=2;i <1GbE(0) or 10GbE(1)> -int EigerSetupTableEntryLeft(int ipad, long long int macad, long long int detectormacadd, int detipad, int udpport){ - char src_mac[50], src_ip[50],dst_mac[50], dst_ip[50]; - - int src_port = 0xE185; - int dst_port = udpport; - sprintf(src_ip,"%d.%d.%d.%d",(detipad>>24)&0xff,(detipad>>16)&0xff,(detipad>>8)&0xff,(detipad)&0xff); - sprintf(dst_ip,"%d.%d.%d.%d",(ipad>>24)&0xff,(ipad>>16)&0xff,(ipad>>8)&0xff,(ipad)&0xff); - sprintf(src_mac,"%02x:%02x:%02x:%02x:%02x:%02x",(unsigned int)((detectormacadd>>40)&0xFF), - (unsigned int)((detectormacadd>>32)&0xFF), - (unsigned int)((detectormacadd>>24)&0xFF), - (unsigned int)((detectormacadd>>16)&0xFF), - (unsigned int)((detectormacadd>>8)&0xFF), - (unsigned int)((detectormacadd>>0)&0xFF)); - sprintf(dst_mac,"%02x:%02x:%02x:%02x:%02x:%02x",(unsigned int)((macad>>40)&0xFF), - (unsigned int)((macad>>32)&0xFF), - (unsigned int)((macad>>24)&0xFF), - (unsigned int)((macad>>16)&0xFF), - (unsigned int)((macad>>8)&0xFF), - (unsigned int)((macad>>0)&0xFF)); - - printf("Seting up Table Entry Left:\n"); - printf("src_port:%d\n",src_port); - printf("dst_port:%d\n",dst_port); - printf("src_ip:%s\n",src_ip); - printf("dst_ip:%s\n",dst_ip); - printf("src_mac:%s\n",src_mac); - printf("dst_mac:%s\n\n",dst_mac); - - - - eiger_back_ret_val=0; - eiger_back_message_length = sprintf(eiger_back_message,"setuptableentry %d %d %d %s %s %d %s %s %d",34,ten_giga,0,src_mac,src_ip,src_port,dst_mac,dst_ip,dst_port); - return EigerBackSendCMD(); -} - - -int EigerSetupTableEntryRight(int ipad, long long int macad, long long int detectormacadd, int detipad, int udpport){ - char src_mac[50], src_ip[50],dst_mac[50], dst_ip[50]; - - int src_port = 0xE185; - int dst_port = udpport+1; - sprintf(src_ip,"%d.%d.%d.%d",(detipad>>24)&0xff,(detipad>>16)&0xff,(detipad>>8)&0xff,(detipad)&0xff); - sprintf(dst_ip,"%d.%d.%d.%d",(ipad>>24)&0xff,(ipad>>16)&0xff,(ipad>>8)&0xff,(ipad)&0xff); - sprintf(src_mac,"%02x:%02x:%02x:%02x:%02x:%02x",(unsigned int)((detectormacadd>>40)&0xFF), - (unsigned int)((detectormacadd>>32)&0xFF), - (unsigned int)((detectormacadd>>24)&0xFF), - (unsigned int)((detectormacadd>>16)&0xFF), - (unsigned int)((detectormacadd>>8)&0xFF), - (unsigned int)((detectormacadd>>0)&0xFF)); - sprintf(dst_mac,"%02x:%02x:%02x:%02x:%02x:%02x",(unsigned int)((macad>>40)&0xFF), - (unsigned int)((macad>>32)&0xFF), - (unsigned int)((macad>>24)&0xFF), - (unsigned int)((macad>>16)&0xFF), - (unsigned int)((macad>>8)&0xFF), - (unsigned int)((macad>>0)&0xFF)); - - printf("Seting up Table Entry Right:\n"); - printf("src_port:%d\n",src_port); - printf("dst_port:%d\n",dst_port); - printf("src_ip:%s\n",src_ip); - printf("dst_ip:%s\n",dst_ip); - printf("src_mac:%s\n",src_mac); - printf("dst_mac:%s\n\n",dst_mac); - - eiger_back_ret_val=0; - eiger_back_message_length = sprintf(eiger_back_message,"setuptableentry %d %d %d %s %s %d %s %s %d",34,ten_giga,32,src_mac,src_ip,src_port,dst_mac,dst_ip,dst_port); - return EigerBackSendCMD(); -} - - - - -int RequestImages(){ - printf("Going to request images\n"); - eiger_back_ret_val=0; - eiger_back_message_length = sprintf(eiger_back_message,"requestimages %d",0); // dst_number - return EigerBackSendCMD(); -} - -int SetDestinationParameters(int i){ - eiger_back_ret_val=0; - eiger_back_message_length = sprintf(eiger_back_message,"setdstparameters %d %d %d",ten_giga,1,i);// number of dsts - return EigerBackSendCMD(); -} - - -void SetTenGigbaBitEthernet(int val){ - ten_giga = val; -} - - -int GetTenGigbaBitEthernet(){ - return ten_giga; -} diff --git a/slsDetectorSoftware/eigerDetectorServer/EigerHighLevelFunctions.c b/slsDetectorSoftware/eigerDetectorServer/EigerHighLevelFunctions.c deleted file mode 100644 index 445a9a2cb..000000000 --- a/slsDetectorSoftware/eigerDetectorServer/EigerHighLevelFunctions.c +++ /dev/null @@ -1,363 +0,0 @@ - -/** - * @author Ian Johnson - * @version 1.0 - */ - -#include -#include -#include -#include - -#include "slsDetectorServer_defs.h" //include port number - - - -int eiger_nexposures = 1; -float eiger_exposuretime = 0; -float eiger_exposureperiod = 0; -int eiger_ncycles = 1; -int eiger_ngates = 0; -int eiger_getphotonenergy = 0; -int eiger_dynamicrange = 0; -int eiger_readoutspeed = 0; -int eiger_readoutmode = 0; -int eiger_highvoltage = 0; -int eiger_iodelay = 0; -int eiger_triggermode = 0; -int eiger_extgating = 0; -int eiger_extgatingpolarity = 0; - -const unsigned int ndacs = 16; -const char* dac_names[16] = {"SvP","Vtr","Vrf","Vrs","SvN","Vtgstv","Vcmp_ll","Vcmp_lr","cal","Vcmp_rl","rxb_rb","rxb_lb","Vcmp_rr","Vcp","Vcn","Vis"}; - -int saved_trimbits[256*256*4]; - - -int EigerGetNumberOfExposures(){return eiger_nexposures;} -float EigerGetExposureTime(){return eiger_exposuretime;} -float EigerGetExposurePeriod(){return eiger_exposureperiod;} -int EigerGetNumberOfCycles(){return eiger_ncycles;} -/*int EigerGetNumberOfGates(){return eiger_ngates;}*/ -unsigned int EigerGetDynamicRange(){return eiger_dynamicrange;} -int EigerGetPhotonEnergy(){return eiger_getphotonenergy;} -int EigerGetReadoutSpeed(){return eiger_readoutspeed;} -int EigerGetReadoutMode(){return eiger_readoutmode;} -int EigerGetHighVoltage(){return eiger_highvoltage;} -int EigerGetIODelay(){return eiger_iodelay;} -int EigerGetTriggerMode(){return eiger_triggermode;} -int EigerGetExternalGating(){return eiger_extgating;} -int EigerGetExternalGatingPolarity(){return eiger_extgatingpolarity;} - -int EigerInit(){ - saved_trimbits[0] = -1; - - -} - - -int EigerSendCMD(){ - if(!EigerInit()||eiger_message_length<=0) return 0; - - int sockfd = socket(AF_INET,SOCK_STREAM,0); - if(sockfd<0){ - fprintf(stderr,"ERROR opening socket\n"); - return 0; - } - - if(connect(sockfd,(struct sockaddr *) &eiger_socket_addr,sizeof(eiger_socket_addr))<0){ - fprintf(stderr,"ERROR connecting\n"); - return 0; - } - - int n = write(sockfd,eiger_message,eiger_message_length); - - int ret_length = read(sockfd,eiger_message,eiger_max_message_length); - - close(sockfd); - - if(n<0||ret_length<0) return 0; - - - //fprintf(stdout,"%s\n",eiger_message); - if(eiger_ret_val>0){ - int i=0; - eiger_message[1]='\0'; - if(atoi(eiger_message)!=0) return 0; - - for(i=2;i0&&ireadout ->expose -> ..., with store is always closed -#define DAQ_NEXPOSURERS_PARALLEL_MODE 0x00600000 //parallel acquire/read mode - -//DAQ_NEXPOSURERS_READOUT_COMPLETE_IMAGES is old now hard-wired in the firmware that every image comes with a header -//#define DAQ_NEXPOSURERS_READOUT_COMPLETE_IMAGES 0x00800000 //DAQ_IGNORE_INITIAL_CRAP and DAQ_CLKOUT_LAST_4_BITS_AND_RETURN_TO_START - -#define DAQ_NEXPOSURERS_EXTERNAL_ENABLING 0x01000000 -#define DAQ_NEXPOSURERS_EXTERNAL_ENABLING_POLARITY 0x02000000 -#define DAQ_NEXPOSURERS_EXTERNAL_TRIGGER_POLARITY 0x04000000 - -#define DAQ_NEXPOSURERS_INTERNAL_ACQUISITION 0x00000000 //internally controlled -#define DAQ_NEXPOSURERS_EXTERNAL_ACQUISITION_START 0x08000000 //external acquisition start -#define DAQ_NEXPOSURERS_EXTERNAL_IMAGE_START 0x10000000 //external image start -#define DAQ_NEXPOSURERS_EXTERNAL_IMAGE_START_AND_STOP 0x18000000 //externally controlly, external image start and stop - -#define DAQ_NEXPOSURERS_ACTIVATE_AUTO_SUBIMAGING 0x20000000 -#define DAQ_NEXPOSURERS_ACTIVATE_RATE_CORRECTION 0x40000000 - -//#define DAQ_MASTER_HALF_MODULE 0x80000000 currently not used - - -//chips static bits -#define DAQ_STATIC_BIT_PROGRAM 0x00000001 -#define DAQ_STATIC_BIT_M4 0x00000002 //these are the status bits, not bit mode -#define DAQ_STATIC_BIT_M8 0x00000004 //these are the status bits, not bit mode -#define DAQ_STATIC_BIT_M12 0x00000000 //these are the status bits, not bit mode, ie. "00" is 12 bit mode -#define DAQ_STATIC_BIT_CHIP_TEST 0x00000008 -#define DAQ_STATIC_BIT_ROTEST 0x00000010 -#define DAQ_CS_BAR_LEFT 0x00000020 -#define DAQ_CS_BAR_RIGHT 0x00000040 - - -//status flags -#define DAQ_STATUS_DAQ_RUNNING 0x01 -#define DAQ_DATA_COLLISION_ERROR 0x02 - -#define DAQ_STATUS_CURRENT_M4 0x04 -#define DAQ_STATUS_CURRENT_M8 0x08 -#define DAQ_STATUS_CURRENT_M12 0x00 //in 12 bit mode both are cleared -#define DAQ_STATUS_CURRENT_TESTMODE 0x10 -#define DAQ_STATUS_TOKEN_OUT 0x20 -#define DAQ_STATUS_SERIAL_OUT 0x40 -#define DAQ_STATUS_PIXELS_ARE_ENABLED 0x80 -#define DAQ_STATUS_DAQ_RUN_TOGGLE 0x200 - -//data delay registers -#define CHIP_DATA_OUT_DELAY_REG_CTRL 1 -#define CHIP_DATA_OUT_DELAY_REG2 2 -#define CHIP_DATA_OUT_DELAY_REG3 3 -#define CHIP_DATA_OUT_DELAY_REG4 4 -#define CHIP_DATA_OUT_DELAY_SET 0x20000000 - - -//module configuration -#define TOP_BIT_MASK 0x00f -#define MASTER_BIT_MASK 0x200 diff --git a/slsDetectorSoftware/eigerDetectorServer/EigerTest.cxx b/slsDetectorSoftware/eigerDetectorServer/EigerTest.cxx deleted file mode 100644 index 4e95bd560..000000000 --- a/slsDetectorSoftware/eigerDetectorServer/EigerTest.cxx +++ /dev/null @@ -1,38 +0,0 @@ - -/** - * @author Ian Johnson - * @version 1.0 - */ - - -#include -#include - -#include - -#include "Eiger.h" - - -using namespace std; - -int main(int argc, char* argv[]){ - - cout<<"\n\n\n\n\n\n\n\n\n\n"<1) ? atoi(argv[1]):5; - - //Feb *f = new Feb(); - // f->Test(); - //delete f; - //return 0; - - Eiger* e = new Eiger(); - e->SetNImages(n); - e->SetDynamicRange(32); - e->SetExposureTime(0.02); - e->SetExposurePeriod(0.050); - e->StartAcquisition(); - - delete e; - - return 0; -} diff --git a/slsDetectorSoftware/eigerDetectorServer/Feb.cxx b/slsDetectorSoftware/eigerDetectorServer/Feb.cxx deleted file mode 100644 index 8bb6bbebc..000000000 --- a/slsDetectorSoftware/eigerDetectorServer/Feb.cxx +++ /dev/null @@ -1,326 +0,0 @@ - -/** - * @author Ian Johnson - * @version 1.0 - */ - - -//return reversed 1 means good, 0 means failed - - -#include -#include -//#include -//#include -//#include -//#include - -#include "xparameters.h" - -#include "Feb.h" - -using namespace std; - -Feb::Feb(){ - - nfebs = 0; - feb_numb = 0; - - send_ndata = 0; - send_buffer_size = 1026; - send_data_raw = new unsigned int [send_buffer_size+1]; - send_data = &send_data_raw[1]; - - recv_ndata = 0; - recv_buffer_size = 1026; - recv_data_raw = new unsigned int [recv_buffer_size+1]; - recv_data = &recv_data_raw[1]; - - ll = new LocalLinkInterface(XPAR_PLB_LL_FIFO_AURORA_DUAL_CTRL_FEB_RIGHT_BASEADDR); - -} - -Feb::~Feb(){ - delete ll; - if(feb_numb) delete [] feb_numb; - delete [] send_data_raw; - delete [] recv_data_raw; -} - -void Feb::SendCompleteFebList(unsigned int n,unsigned int* list){ - if(feb_numb) delete [] feb_numb; - nfebs = n; - feb_numb = new unsigned int [n]; - for(unsigned int i=0;i0xfff) return 0; - - send_data_raw[0] = 0x90000000 | (ch<<16); //we - if(ll->Write(4,send_data_raw)!=4) return 0; - - send_data_raw[0] = 0xc0000000; //data - return ((send_ndata+1)*4==ll->Write((send_ndata+1)*4,send_data_raw)); -} - -bool Feb::ReadFrom(unsigned int ch, unsigned int ntrys){ - if(ch>=0xfff) return 0; - - recv_data_raw[0] = 0xa0000000 | (ch<<16); //read data - ll->Write(4,recv_data_raw); - usleep(20); - - recv_ndata=-1; - for(unsigned int t=0;tRead(recv_buffer_size*4,recv_data_raw)/4)>0){ - recv_ndata--; - break; - } - cout<<"\t Read try number: "<=0); -} - -void Feb::PrintData(){ - cout<<"Sent data: "<1&&recv_ndata>1){ - cout<<"\t\t Tail sent: "<Write(4,send_data_raw)!=4) return 0; - - cout<<"Feb::CheckingCommunication ...."<Read(recv_buffer_size*4,recv_data_raw)/4)>0) cout<<"\t) Cleanning buffer ..."<=nfebs){ - cout<<"Error invalid sub number "<send_buffer_size-2) return 0; - - send_ndata = nreads+2; - send_data[0] = 0x20000000 | nreads << 14; //cmd -> read "00" , nreads - - for(unsigned int i=0;isend_buffer_size-2) return 0; - - //cout<<"Write register : "< write nwrites and how many - send_data[2*nwrites+1] = 0; //tail - - for(unsigned int i=0;isend_buffer_size-2) return 0; - - send_ndata = nwrites+2; - send_data[0] = 0xc0000000 | mem_num << 24 | nwrites << 14 | start_address; //cmd -> write to memory, nwrites, mem number, start address - send_data[nwrites+1] = 0; //tail - for(unsigned int i=0;i -#include -#include -#include -#include -#include - -#include -#include -#include -#include -#include - - - -#include "FebRegisterDefs.h" -#include "FebControl.h" - -using namespace std; - -//GetDAQStatusRegister(512,current_mode_bits_from_fpga)){ - -const unsigned int Module::ndacs = 16; -const string Module::dac_names[16] = {"SvP","Vtr","Vrf","Vrs","SvN","Vtgstv","Vcmp_ll","Vcmp_lr","cal","Vcmp_rl","rxb_rb","rxb_lb","Vcmp_rr","Vcp","Vcn","Vis"}; - - -Module::Module(unsigned int number, unsigned int address_top){ - module_number = number; - top_address_valid = 1; - top_left_address = 0x100 | (0xff & address_top); - top_right_address = 0x200 | (0xff & address_top); - bottom_address_valid = 0; - bottom_left_address = 0; - bottom_right_address = 0; - - high_voltage = -1; - top_dac = new int [ndacs]; - bottom_dac = new int [ndacs]; - for(unsigned int i=0;iGetModuleNumber()); - ReadSetUpFile(modules[i]->GetModuleNumber(),st); - } - - - return CheckSetup(); -} - - -bool FebControl::ReadSetUpFileToAddModules(string file_name){ - static ifstream infile; - static string line; - static char cmd_st[2000]; - static int value_i[3]; - - infile.open(file_name.c_str(),ios::in); - if(!infile.is_open()) return 0; - - cout<>cmd_st; - if(!strcmp("add_module",cmd_st)){ - if(!(iss>>value_i[0]>>value_i[1]>>value_i[2])){ - cout<<"Error adding module from "<>value_i[0]>>value_i[1])){ - cout<<"Error adding half module from "<TopAddressIsValid()){ - feb_list[nfebs++] = modules[i]->GetTopRightAddress(); - feb_list[nfebs++] = modules[i]->GetTopLeftAddress(); - } - if(modules[i]->BottomAddressIsValid()){ - feb_list[nfebs++] = modules[i]->GetBottomRightAddress(); - feb_list[nfebs++] = modules[i]->GetBottomLeftAddress(); - } - } - - FebInterface::SendCompleteList(nfebs,feb_list); - delete [] feb_list; - - cout<GetModuleNumber()<<" "; - if(modules[i]->TopAddressIsValid()) cout<GetTopBaseAddress()<<" (top) "<BottomAddressIsValid()) cout<GetBottomBaseAddress()<<" (bottom)"<GetModuleNumber()==module_number){ - module_index=i; - return 1; - } - } - - return 0; -} - -bool FebControl::CheckModuleAddresses(Module* m){ - bool found_t = 0; - bool found_b = 0; - for(unsigned int i=0;iTopAddressIsValid() && modules[i]->GetTopBaseAddress() && m->GetTopBaseAddress()==modules[i]->GetTopBaseAddress()) || - (m->TopAddressIsValid() && modules[i]->GetBottomBaseAddress() && m->GetTopBaseAddress()==modules[i]->GetBottomBaseAddress())) found_t=1; - if((m->BottomAddressIsValid() && modules[i]->GetTopBaseAddress() && m->GetBottomBaseAddress()==modules[i]->GetTopBaseAddress()) || - (m->BottomAddressIsValid() && modules[i]->GetBottomBaseAddress() && m->GetBottomBaseAddress()==modules[i]->GetBottomBaseAddress())) found_b=1; - } - - if(found_t) cout<<"\tWarning: top address "<< m->GetTopBaseAddress()<<" already used."<GetBottomBaseAddress()<<" already used."<TopAddressIsValid()&&m->BottomAddressIsValid()&&m->GetTopBaseAddress()==m->GetBottomBaseAddress(); - if(top_bottom_same) cout<<"\tWarning: top and bottom address are the same "<GetTopBaseAddress()<<"."<TopAddressIsValid()&&m->BottomAddressIsValid()){ - cout<<"\tAdding full module number "<GetModuleNumber()<<" with top and bottom base addresses: "<GetTopBaseAddress()<<" "<GetBottomBaseAddress()<TopAddressIsValid()){ - cout<<"\tAdding half module number "<GetModuleNumber()<<" with top base address: "<GetTopBaseAddress()<BottomAddressIsValid()){ - cout<<"\tAdding half module number "<GetModuleNumber()<<" with bottom base address: "<GetBottomBaseAddress()<>cmd_st; - - if(cmd_st[0]=='#'||!strcmp("add_module",cmd_st)||!strcmp("add_half_module",cmd_st)){ ;// cout<<"do nothing "<>value_i[0])) cout<<"Error reading iodelay from "<>value_f; - SetHighVoltage(module_num,value_f); - }else if(!strcmp("photon_energy",cmd_st)){ - iss>>value_f; - SetPhotonEnergy(value_f); - }else if(!strcmp("dynamic_range",cmd_st)){ - iss>>value_i[0]; - SetDynamicRange(value_i[0]); - }else if(!strcmp("readout_speed",cmd_st)){ - iss>>value_i[0]; - SetReadoutSpeed(value_i[0]); - }else if(!strcmp("readout_mode",cmd_st)){ - iss>>value_i[0]; - SetReadoutMode(value_i[0]); - }else{ - iss>>value_f; - if(module_num>0) sprintf(cmd_st,"mod%d::%s",module_num,cmd_st); - if(!SetDAC(cmd_st,value_f,1)) cout<<"error in string: "<GetTopIDelay(j)<0){ - cout<<"Warning: module "<GetModuleNumber()<<"'s idelay top number "<GetBottomIDelay(j)<0){ - cout<<"Warning: module "<GetModuleNumber()<<"'s idelay bottom number "<GetHighVoltage()<0){ - cout<<"Warning: module "<GetModuleNumber()<<"'s high voltage not set."<GetTopDACValue(j)<0){ - cout<<"Warning: module "<GetModuleNumber()<<"'s top \""<GetBottomDACValue(j)<0){ - cout<<"Warning: module "<GetModuleNumber()<<"'s bottom \""<TopAddressIsValid()) n_half_modules++; - if(modules[i]->BottomAddressIsValid()) n_half_modules++; - } - - return n_half_modules; -} - -bool FebControl::SetPhotonEnergy(unsigned int full_energy_eV){ - photon_energy_eV = full_energy_eV; - cout<<"Setting photon energy to: "<3){ - cout<<"Error SetIDelay chip_pos "<TopAddressIsValid()){ - if(SendIDelays(modules[module_index]->GetTopLeftAddress(),chip_pos%2==0,0xffffffff,ndelay_units)){ - if(module_index!=0) modules[module_index]->SetTopIDelay(chip_pos,ndelay_units); - else{ - for(unsigned int i=0;iSetTopIDelay(chip_pos,ndelay_units); - for(unsigned int i=0;iSetBottomIDelay(chip_pos,ndelay_units); - } - }else{ - cout<<"Error could not set idelay module number "<BottomAddressIsValid()){ - if(SendIDelays(modules[module_index]->GetBottomLeftAddress(),chip_pos%2==0,0xffffffff,ndelay_units)){ - if(module_index!=0) modules[module_index]->SetBottomIDelay(chip_pos,ndelay_units); - else{ - for(unsigned int i=0;iSetTopIDelay(chip_pos,ndelay_units); - for(unsigned int i=0;iSetBottomIDelay(chip_pos,ndelay_units); - } - }else{ - cout<<"Error could not set idelay module number "<TopAddressIsValid()){ - if(SendIDelays(modules[module_index]->GetTopRightAddress(),chip_pos%2==0,0xffffffff,ndelay_units)){ - if(module_index!=0) modules[module_index]->SetTopIDelay(chip_pos,ndelay_units); - else for(unsigned int i=0;iSetTopIDelay(chip_pos,ndelay_units); - }else{ - cout<<"Error could not set idelay module number "<BottomAddressIsValid()){ - if(SendIDelays(modules[module_index]->GetBottomRightAddress(),chip_pos%2==0,0xffffffff,ndelay_units)){ - if(module_index!=0) modules[module_index]->SetBottomIDelay(chip_pos,ndelay_units); - else for(unsigned int i=0;iSetBottomIDelay(chip_pos,ndelay_units); - }else{ - cout<<"Error could not set idelay module number "<0x3ff) ndelay_units=0x3ff; - // this is global - unsigned int delay_data_valid_nclks = 15 - ((ndelay_units&0x3c0)>>6); //data valid delay upto 15 clks - ndelay_units &= 0x3f; - - unsigned int set_left_delay_channels = chip_lr ? channels:0; - unsigned int set_right_delay_channels = chip_lr ? 0:channels; - - cout<<"\tSetting delays of "; - if(set_left_delay_channels!=0) cout<<"left chips of dst_num "<vmax) return 0; - digital = int(((value-vmin)/(vmax-vmin))*(nsteps-1) + 0.5); - return 1; -} - -float FebControl::DACToVoltage(unsigned int digital,unsigned int nsteps,float vmin,float vmax){ - return vmin+(vmax-vmin)*digital/(nsteps-1); -} - - -bool FebControl::SetHighVoltage(float value){ - return SetHighVoltage(0,value); -} - -bool FebControl::SetHighVoltage(unsigned int module_num,float value){ - unsigned int module_index=0; - if(!GetModuleIndex(module_num,module_index)||!modules[module_index]->TopAddressIsValid()){ - cout<<"Error could not set high voltage module number "<GetTopRightAddress(),value)) return 0; - - if(module_index!=0) modules[module_index]->SetHighVoltage(value); - else for(unsigned int i=0;iSetHighVoltage(value); - - cout<<"\tHigh voltage of dst "<GetTopRightAddress()<<" set to "<GetHighVoltage()<<"."<4095){ - cout<<"Waring: SetDac bad value, "<TopAddressIsValid()){ - if(!SendDACValue(modules[module_index]->GetTopRightAddress(),dac_ch,v)) return 0; - if(module_index!=0) modules[module_index]->SetTopDACValue(dac_ch,v); - else for(unsigned int i=0;iSetTopDACValue(dac_ch,v); - } - - if(bottom&&modules[module_index]->BottomAddressIsValid()){ - if(!SendDACValue(modules[module_index]->GetBottomRightAddress(),dac_ch,v)) return 0; - if(module_index!=0) modules[module_index]->SetBottomDACValue(dac_ch,v); - else for(unsigned int i=0;iSetBottomDACValue(dac_ch,v); - } - - return 1; -} - -bool FebControl::GetDAC(std::string s, int& ret_value, bool voltage_mv){ - - unsigned int module_index, dac_ch; - bool top, bottom; - if(!DecodeDACString(s,module_index,top,bottom,dac_ch)) return 0; - - ret_value = top ? modules[module_index]->GetTopDACValue(dac_ch) : modules[module_index]->GetBottomDACValue(dac_ch); - - if(voltage_mv) ret_value = DACToVoltage(ret_value,4096,0,2048); - - return 1; -} - - -bool FebControl::GetDACName(unsigned int dac_num, std::string &s){ - if(dac_num>=Module::ndacs){ - cout<<"Warning: FebControl::GetDACName index out of range, "<15){ - cout<<"Warning invalid ch for SetDAC."<>3)<<((7-i)*4);//upper - trimbits_to_load_r[offset+chip_sc] |= ( 0x7 & trimbits[row_set*16480+super_column_start_position_r+i])<<((7-i)*4);//low - trimbits_to_load_r[offset+chip_sc+32] |= ((0x38 & trimbits[row_set*16480+super_column_start_position_r+i])>>3)<<((7-i)*4);//upper -/* - trimbits_to_load_l[offset+chip_sc] |= ( 0x7 & trimbits[263679 - (row_set*16480+super_column_start_position_l+i)])<<((7-i)*4);//low - trimbits_to_load_l[offset+chip_sc+32] |= ((0x38 & trimbits[263679 - (row_set*16480+super_column_start_position_l+i)])>>3)<<((7-i)*4);//upper - trimbits_to_load_r[offset+chip_sc] |= ( 0x7 & trimbits[263679 - (row_set*16480+super_column_start_position_r+i)])<<((7-i)*4);//low - trimbits_to_load_r[offset+chip_sc+32] |= ((0x38 & trimbits[263679 - (row_set*16480+super_column_start_position_r+i)])>>3)<<((7-i)*4);//upper - */ - - } // end column loop i - } //end supercolumn loop sc - } //end row loop - -/* - if(!WriteMemory(modules[0]->GetTopLeftAddress(),0,0,1024,trimbits_to_load_r)||!WriteMemory(modules[0]->GetTopRightAddress(),0,0,1024,trimbits_to_load_l)||!StartDAQOnlyNWaitForFinish()){ - cout <<" some errror!"<< endl; - return 0; - } -*/ - if(!WriteMemory(modules[0]->GetTopLeftAddress(),0,0,1023,trimbits_to_load_r)||!WriteMemory(modules[0]->GetTopRightAddress(),0,0,1023,trimbits_to_load_l)||!StartDAQOnlyNWaitForFinish()){ - cout <<" some errror!"<< endl; - return 0; - } - - } //end row_set loop (groups of 16 rows) - } // end l_r loop - memcpy(last_downloaded_trimbits,trimbits,trimbit_size*sizeof(unsigned char)); - return SetStaticBits(); //send the static bits -} - - -unsigned int* FebControl::GetTrimbits(){ - return last_downloaded_trimbits; -} - - - - -unsigned int FebControl::AddressToAll(){ - if(modules.size()==0) return 0; - return modules[0]->GetTopLeftAddress()|modules[0]->GetTopRightAddress(); -} - -bool FebControl::SetCommandRegister(unsigned int cmd){ - return WriteRegister(AddressToAll(),DAQ_REG_CHIP_CMDS,cmd); -} - - -bool FebControl::GetDAQStatusRegister(unsigned int dst_address, unsigned int &ret_status){ - - if(!ReadRegister(dst_address,DAQ_REG_STATUS,ret_status)){ - cout<<"Error: reading status register."<> 16; - return 1; -} - - -bool FebControl::StartDAQOnlyNWaitForFinish(int sleep_time_us){ - if(!WriteRegister(AddressToAll(),DAQ_REG_CTRL,0)||!WriteRegister(AddressToAll(),DAQ_REG_CTRL,DAQ_CTRL_START)){ - cout<<"Warning: could not start."<GetTopRightAddress(),status_reg_r))) - return 0; - if(status_reg_r&DAQ_STATUS_DAQ_RUNNING) return 1; - - /* - if(!(GetDAQStatusRegister(modules[i]->GetTopLeftAddress(),status_reg_r)&&GetDAQStatusRegister(modules[i]->GetTopRightAddress(),status_reg_l))){ - for(int i=0;i<2;i++) cout<<"Waring trouble reading status register. Returning zero to avoid inifite loops, this could cause trouble!"<full,1->half,2->quarter or 3->super_slow - acquireNReadoutMode &= (~DAQ_CHIP_CONTROLLER_SUPER_SLOW_SPEED); - if(readout_speed==1){ - acquireNReadoutMode |= DAQ_CHIP_CONTROLLER_HALF_SPEED; - cout<<"Everything at half speed, ie. reading with 50 MHz main clk (half speed) ...."<parallel,1->non-parallel,2-> safe_mode - acquireNReadoutMode &= (~DAQ_NEXPOSURERS_PARALLEL_MODE); - if(readout_mode==1){ - acquireNReadoutMode |= DAQ_NEXPOSURERS_NORMAL_NONPARALLEL_MODE; - cout<<"Readout mode set to normal non-parallel readout mode ... "< internal exposure time and period, - //"01"-> external acquistion start and internal exposure time and period, - //"10"-> external start trigger and internal exposure time, - //"11"-> external triggered start and stop of exposures - triggerMode = (~DAQ_NEXPOSURERS_EXTERNAL_IMAGE_START_AND_STOP); - - if(trigger_mode == 1){ - triggerMode = DAQ_NEXPOSURERS_EXTERNAL_ACQUISITION_START; - cout<<"Trigger mode: external start of acquisition sequence, internal exposure length and period."<(pow(2,29)-1)*pow(10,7)){ - float max_time = 10e-9*(pow(2,28)-1)*pow(10,7); - cout<<"Warning: time exceeds ("<pow(2,29)-1){ power_of_ten++; n_clk_cycles = round(n_clk_cycles/10.0);} - decoded_time = int(n_clk_cycles)<<3 | int(power_of_ten); - } - - return decoded_time; -} - -bool FebControl::ResetChipCompletely(){ - if(!SetCommandRegister(DAQ_RESET_COMPLETELY) || !StartDAQOnlyNWaitForFinish()){ - cout<<"Warning: could not ResetChipCompletely()."<h_addr,(char *)&serv_addr.sin_addr.s_addr,server->h_length); - serv_addr.sin_port = htons(port); - - return 1; -} - -int FebControl::WriteNRead(char* message, int length, int max_length){ - - int sockfd = socket(AF_INET, SOCK_STREAM, 0); - if(sockfd <0){ - fprintf(stderr,"ERROR opening socket\n"); - return 0; - } - - if(connect(sockfd,(struct sockaddr *) &serv_addr,sizeof(serv_addr)) < 0){ - fprintf(stderr,"ERROR connecting\n"); - return 0; - } - - int n = write(sockfd,message,length); - if(n<0) printf("ERROR writing to socket"); - - length = read(sockfd,message,max_length); - if(length<0) printf("ERROR reading to socket"); - - close(sockfd); - - return length; -} - - -bool FebControl::StartAcquisition(){ - - static unsigned int reg_nums[20]; - static unsigned int reg_vals[20]; - - PrintAcquisitionSetup(); - - // if(!Reset()||!ResetDataStream()){ - if(!Reset()){ - cout<<"Trouble reseting daq or data stream..."< -#include -//#include -//#include -//#include -//#include - -#include "xparameters.h" - -#include "FebInterface.h" - -using namespace std; - -FebInterface::FebInterface(){ - - nfebs = 0; - feb_numb = 0; - - send_ndata = 0; - send_buffer_size = 1026; - send_data_raw = new unsigned int [send_buffer_size+1]; - send_data = &send_data_raw[1]; - - recv_ndata = 0; - recv_buffer_size = 1026; - recv_data_raw = new unsigned int [recv_buffer_size+1]; - recv_data = &recv_data_raw[1]; - - ll = new LocalLinkInterface(XPAR_PLB_LL_FIFO_AURORA_DUAL_CTRL_FEB_RIGHT_BASEADDR); - -} - -FebInterface::~FebInterface(){ - delete ll; - if(feb_numb) delete [] feb_numb; - delete [] send_data_raw; - delete [] recv_data_raw; -} - -void FebInterface::SendCompleteList(unsigned int n,unsigned int* list){ - if(feb_numb) delete [] feb_numb; - nfebs = n; - feb_numb = new unsigned int [n]; - for(unsigned int i=0;i0xfff) return 0; - - send_data_raw[0] = 0x8fff0000; - if(ll->Write(4,send_data_raw)!=4) return 0; - - send_data_raw[0] = 0x90000000 | (ch<<16); - if(ll->Write(4,send_data_raw)!=4) return 0; - - send_data_raw[0] = 0xc0000000; - return ((send_ndata+1)*4==ll->Write((send_ndata+1)*4,send_data_raw)); -} - -bool FebInterface::ReadFrom(unsigned int ch, unsigned int ntrys){ - if(ch>=0xfff) return 0; - - recv_data_raw[0] = 0xa0000000 | (ch<<16); - ll->Write(4,recv_data_raw); - usleep(20); - - recv_ndata=-1; - for(unsigned int t=0;tRead(recv_buffer_size*4,recv_data_raw)/4)>0){ - recv_ndata--; - break; - } - usleep(1000); - } - - return (recv_ndata>=0); -} - - - -bool FebInterface::SetByteOrder(){ - - send_data_raw[0] = 0x8fff0000; - if(ll->Write(4,send_data_raw)!=4) return 0; - - send_ndata = 2; - send_data[0] = 0; - send_data[1] = 0; - - unsigned int dst = 0xff; - for(unsigned int i=0;isend_buffer_size-2) return 0; - - send_ndata = nreads+2; - send_data[0] = 0x20000000 | nreads << 14; - - for(unsigned int i=0;isend_buffer_size-2) return 0; - - //cout<<"Write register : "<send_buffer_size-2) {cout<<"error herer: nwrites:"< write to memory, nwrites, mem number, start address - send_data[nwrites+1] = 0; - for(unsigned int i=0;i -#include -#include -#include -#include // std::remove_if - -#include -#include -#include -#include -#include - -#include "FebControl.h" -#include "slsDetectorServer_defs.h" //include port number - -using namespace std; - -enum cmd_string {evNotFound, - evReinitialize,evReset, - - evSetInputDelays, - evSetDACValue,evGetDACValue,evSetDACVoltage,evGetDACVoltage,evSetHighVoltage,//evGetHighVoltage, - - evSetTrimBits, - evSetAllTrimBits, - evGetTrimBits, - //evLoadTrimBitFile, - - evSetBitMode, - evSetPhotonEnergy, - // evSetPhotonEnergyCalibrationParameters,evActivateRateCorrection,evDeactivateRateCorrection,evSetRateCorrectionTau, - - evSetReadoutSpeed,evSetReadoutMode, - - //temp solution - // evNotFound1,evNotFound2,evNotFound3, - - evSetNumberOfExposures,evSetExposureTime,evSetExposurePeriod, - // evSetTriggerPolarityToPositive,evSetTriggerPolarityToNegative, - evSetTriggerMode, - evSetExternalGating, - evStartAcquisition,evStopAcquisition,evIsDaqStillRunning, - evWaitUntilDaqFinished, - evExitServer -}; - -map enum_map; - -void init(){ - - enum_map["reinitialize"] = evReinitialize; - enum_map["reset"] = evReset; - enum_map["setinputdelays"] = evSetInputDelays; - enum_map["setdacvalue"] = evSetDACValue; - enum_map["getdacvalue"] = evGetDACValue; - enum_map["setdacvoltage"] = evSetDACVoltage; - enum_map["getdacvoltage"] = evGetDACVoltage; - enum_map["sethighvoltage"] = evSetHighVoltage; - enum_map["settrimbits"] = evSetTrimBits; - enum_map["setalltrimbits"] = evSetAllTrimBits; - enum_map["gettrimbits"] = evGetTrimBits; - // enum_map["loadtrimbitfile"] = evLoadTrimBitFile; - enum_map["setbitmode"] = evSetBitMode; - enum_map["setphotonenergy"] = evSetPhotonEnergy; - // enum_map["setphotonenergycalibrationparameters"] = evSetPhotonEnergyCalibrationParameters; - // enum_map["activateratecorrection"] = evActivateRateCorrection; - // enum_map["deactivateratecorrection"] = evDeactivateRateCorrection; - // enum_map["setratecorrectiontau"] = evSetRateCorrectionTau; - enum_map["setreadoutspeed"] = evSetReadoutSpeed; - enum_map["setreadoutmode"] = evSetReadoutMode; - enum_map["setnumberofexposures"] = evSetNumberOfExposures; - enum_map["setexposuretime"] = evSetExposureTime; - enum_map["setexposureperiod"] = evSetExposurePeriod; - // enum_map["settriggerpolaritytopositive"] = evSetTriggerPolarityToPositive; - // enum_map["settriggerpolaritytonegative"] = evSetTriggerPolarityToNegative; - enum_map["settriggermode"] = evSetTriggerMode; - enum_map["setexternalgating"] = evSetExternalGating; - enum_map["startacquisition"] = evStartAcquisition; - enum_map["stopacquisition"] = evStopAcquisition; - enum_map["isdaqstillrunning"] = evIsDaqStillRunning; - enum_map["waituntildaqfinished"] = evWaitUntilDaqFinished; - enum_map["exitserver"] = evExitServer; -} - -int server_list_s; -int server_conn_s; -int AccpetConnectionAndWaitForData(char* buffer, int maxlength); -bool WriteNClose(const char* buffer, int length); -bool SetupListenSocket(unsigned short int port); - - -string LowerCase(string str); -string GetNextString(string str,bool start_from_beginning=0); -void AddNumber(string& str, int n, int location=-1, bool space_after=0);//-1 means append -void AddNumber(string& str, float v, int location=-1, bool space_after=0);//-1 means append - -int main(int argc, char* argv[]){ - cout< "<0){ - int ret_parameter = 0; - return_start_pos = return_message.length(); - - switch(enum_map.find(LowerCase(cmd))->second){ - - case evReinitialize : - if(feb_controler->Init()){ - return_message.append("\tExecuted: Reinitialize\n"); - ret_val = 0; - }else{ - return_message.append("\tError executing: Reinitialize\n"); - ret_val = 1; - } - break; - - case evReset : - if(feb_controler->Reset()){ - return_message.append("\tExecuted: Reset\n"); - ret_val = 0; - }else{ - return_message.append("\tError executing: Reset\n"); - ret_val = 1; - } - break; - - - - case evSetInputDelays : - tmp_str[0] = GetNextString(data); - n[0] = atoi(tmp_str[0].data()); - - if(tmp_str[0].length()>0&&feb_controler->SetIDelays(0,n[0])){ - return_message.append("\tExecuted: SetInputDelays "); AddNumber(return_message,n[0]); return_message.append("\n"); - ret_val = 0; - }else{ - return_message.append("\tError executing: SetInputDelays \n"); - ret_val = 1; - } - break; - - - - case evSetDACValue : - tmp_str[0] = GetNextString(data); - tmp_str[1] = GetNextString(data); - n[0] = atoi(tmp_str[1].data()); - - if(tmp_str[0].length()>0&&tmp_str[1].length()>0&&feb_controler->SetDAC(tmp_str[0],n[0])){ - return_message.append("\tExecuted: SetDACValue "); return_message.append(tmp_str[0]+" "); AddNumber(return_message,n[0]); return_message.append("\n"); - ret_val = 0; - }else{ - return_message.append("\tError executing: SetDACValue \n"); - ret_val = 1; - } - break; - - case evGetDACValue : - tmp_str[0] = GetNextString(data); - - if(tmp_str[0].length()>0&&feb_controler->GetDAC(tmp_str[0],ret_parameter)){ - return_message.append("\tExecuted: GetDACValue "); return_message.append(tmp_str[0]+" -> ");AddNumber(return_message,ret_parameter); return_message.append("\n"); - ret_val = 0; - }else{ - return_message.append("\tError executing: GetDACValue \n"); - ret_val = 1; - } - break; - - case evSetDACVoltage : - tmp_str[0] = GetNextString(data); - tmp_str[1] = GetNextString(data); - n[0] = atoi(tmp_str[1].data()); - - if(tmp_str[0].length()>0&&tmp_str[1].length()>0&&feb_controler->SetDAC(tmp_str[0],n[0],1)){ - return_message.append("\tExecuted: SetDACVoltage "); return_message.append(tmp_str[0]+" "); AddNumber(return_message,n[0]); return_message.append("\n"); - ret_val = 0; - }else{ - return_message.append("\tError executing: SetDACVoltage \n"); - ret_val = 1; - } - break; - - case evGetDACVoltage : - tmp_str[0] = GetNextString(data); - - if(tmp_str[0].length()>0&&feb_controler->GetDAC(tmp_str[0],ret_parameter,1)){ - return_message.append("\tExecuted: GetDACVoltage "); return_message.append(tmp_str[0]+" -> ");AddNumber(return_message,ret_parameter); return_message.append(" mV\n"); - ret_val = 0; - }else{ - return_message.append("\tError executing: GetDACVoltage \n"); - ret_val = 1; - } - break; - - case evSetHighVoltage : - tmp_str[0] = GetNextString(data); - v[0] = atof(tmp_str[0].data()); - - if(tmp_str[0].length()>0&&feb_controler->SetHighVoltage(v[0])){ - return_message.append("\tExecuted: SetHighVoltage "); AddNumber(return_message,v[0]); return_message.append("\n"); - ret_val = 0; - }else{ - return_message.append("\tError executing: SetHighVoltage \n"); - ret_val = 1; - } - break; - - case evSetTrimBits : - tmp_str[0] = GetNextString(data); - if(feb_controler->LoadTrimbitFile()){ - /* if(1){*/ - /*tmp_str[0] = GetNextString(data); - feb_controler->SetTrimbits(0,(unsigned char*)(tmp_str[0].c_str()));*/ - return_message.append("\tExecuted: SetTrimBits\n"); - ret_val = 0; - }else{ - return_message.append("\tError executing: SetTrimBits \n"); - ret_val = 1; - } - break; - - case evSetAllTrimBits : - tmp_str[0] = GetNextString(data); - n[0] = atoi(tmp_str[0].data()); - if(feb_controler->SaveAllTrimbitsTo(n[0])){ - /*feb_controler->SetTrimbits(0,(unsigned char*)(tmp_str[0].c_str()));*/ - /*if(1){*/ - return_message.append("\tExecuted: SetAllTrimBits\n"); - ret_val = 0; - }else{ - return_message.append("\tError executing: SetAllTrimBits \n"); - ret_val = 1; - } - break; - - - case evGetTrimBits : - if(feb_controler->SaveTrimbitFile()){ - /*if(1){*/ - /*tmp_str[0] = GetNextString(data); - feb_controler->GetTrimbits();*/ - return_message.append("\tExecuted: GetTrimBits\n"); - ret_val = 0; - }else{ - return_message.append("\tError executing: GetTrimBits \n"); - ret_val = 1; - } - break; - - - // case evLoadTrimBitFile : - - case evSetBitMode : - tmp_str[0] = GetNextString(data); - n[0] = atoi(tmp_str[0].data()); - - if(tmp_str[0].length()>0&&feb_controler->SetDynamicRange(n[0])){ - return_message.append("\tExecuted: SetBitMode "); AddNumber(return_message,n[0]); return_message.append("\n"); - ret_val = 0; - }else{ - return_message.append("\tError executing: SetBitMode \n"); - ret_val = 1; - } - break; - - case evSetPhotonEnergy : - tmp_str[0] = GetNextString(data); - n[0] = atoi(tmp_str[0].data()); - if(tmp_str[0].length()>0&&feb_controler->SetPhotonEnergy(n[0])){ - return_message.append("\tExecuted: SetPhotonEnergy "); AddNumber(return_message,n[0]); return_message.append("\n"); - ret_val = 0; - }else{ - return_message.append("\tError executing: SetPhotonEnergy \n"); - ret_val = 1; - } - break; - - // case evSetPhotonEnergyCalibrationParameters : - // case evActivateRateCorrection : - // case evDeactivateRateCorrection : - // case evSetRateCorrectionTau : - - - case evSetReadoutSpeed : - tmp_str[0] = GetNextString(data); - n[0] = atoi(tmp_str[0].data()); - if(tmp_str[0].length()>0&&feb_controler->SetReadoutSpeed(n[0])){ - return_message.append("\tExecuted: SetReadoutSpeed "); AddNumber(return_message,n[0]); return_message.append("\n"); - ret_val = 0; - }else{ - return_message.append("\tError executing: SetReadoutSpeed \n"); - ret_val = 1; - } - break; - - case evSetReadoutMode : - tmp_str[0] = GetNextString(data); - n[0] = atoi(tmp_str[0].data()); - if(tmp_str[0].length()>0&&feb_controler->SetReadoutMode(n[0])){ - return_message.append("\tExecuted: SetReadoutMode "); AddNumber(return_message,n[0]); return_message.append("\n"); - ret_val = 0; - }else{ - return_message.append("\tError executing: SetReadoutMode parallel,1->non-parallel,2-> safe_mode>\n"); - ret_val = 1; - } - break; - - case evSetNumberOfExposures : - tmp_str[0] = GetNextString(data); - n[0] = atoi(tmp_str[0].data()); - if(tmp_str[0].length()>0&&feb_controler->SetNExposures(n[0])){ - return_message.append("\tExecuted: SetNumberOfExposures "); AddNumber(return_message,n[0]); return_message.append("\n"); - ret_val = 0; - }else{ - return_message.append("\tError executing: SetNumberOfExposures \n"); - ret_val = 1; - } - break; - - case evSetExposureTime : - tmp_str[0] = GetNextString(data); - v[0] = atof(tmp_str[0].data()); - if(tmp_str[0].length()>0&&feb_controler->SetExposureTime(v[0])){ - return_message.append("\tExecuted: SetExposureTime "); AddNumber(return_message,v[0]); return_message.append("\n"); - ret_val = 0; - }else{ - return_message.append("\tError executing: SetExposureTime \n"); - ret_val = 1; - } - break; - - case evSetExposurePeriod : - tmp_str[0] = GetNextString(data); - v[0] = atof(tmp_str[0].data()); - if(tmp_str[0].length()>0&&feb_controler->SetExposurePeriod(v[0])){ - return_message.append("\tExecuted: SetExposurePeriod "); AddNumber(return_message,v[0]); return_message.append("\n"); - ret_val = 0; - }else{ - return_message.append("\tError executing: SetExposurePeriod \n"); - ret_val = 1; - } - break; - // case evSetTriggerPolarityToPositive : - // case evSetTriggerPolarityToNegative : - case evSetTriggerMode : - tmp_str[0] = GetNextString(data); - n[0] = atoi(tmp_str[0].data()); - if(tmp_str[0].length()>0&&feb_controler->SetTriggerMode(n[0])){ - return_message.append("\tExecuted: SetTriggerMode "); AddNumber(return_message,n[0]); return_message.append("\n"); - ret_val = 0; - }else{ - return_message.append("\tError executing: SetTriggerMode \n"); - ret_val = 1; - } - break; - - case evSetExternalGating : - tmp_str[0] = GetNextString(data); - tmp_str[1] = GetNextString(data); - n[0] = atoi(tmp_str[0].data()); - n[1] = atoi(tmp_str[1].data()); - if(tmp_str[0].length()<1 || tmp_str[1].length()<1 || (n[0]!=0&&n[0]!=1) || (n[1]!=0&&n[1]!=1)){ - return_message.append("\tError executing: setexternalgating \n"); - ret_val = 1; - } - feb_controler->SetExternalEnableMode(n[0],n[1]); - ret_val = 0; - break; - - case evStartAcquisition : - if(feb_controler->StartAcquisition()){ - return_message.append("\tExecuted: StartAcquisition\n"); - ret_val = 0; - }else{ - return_message.append("\tError executing: StartAcquisition\n"); - ret_val = 1; - } - break; - - case evStopAcquisition : - if(feb_controler->StopAcquisition()){ - return_message.append("\tExecuted: StopAcquisition\n"); - ret_val = 0; - }else{ - return_message.append("\tError executing: StopAcquisition\n"); - ret_val = 1; - } - break; - - - case evIsDaqStillRunning : - return_message.append("\tExecuted: evIsDaqStillRunning\n"); - ret_parameter = feb_controler->AcquisitionInProgress(); - ret_val = 0; - break; - - - case evWaitUntilDaqFinished : - if(feb_controler->WaitForFinishedFlag()){ - return_message.append("\tExecuted: WaitUntilDaqFinished\n"); - ret_val = 0; - }else{ - return_message.append("\tError executing: WaitUntilDaqFinished\n"); - ret_val = 1; - } - break; - - - case evExitServer : - return_message.append("\tExiting Server ....\n"); - stop = 1; - ret_val = -200; - break; - - - default : - return_message.append("\tWarning command \""); - return_message.append(cmd); - return_message.append("\" not found.\n"); - return_message.append("\t\tValid commands: "); - map::iterator it = enum_map.begin(); - while(it!=enum_map.end()){ - return_message.append((it++)->first); - return_message.append(" "); - } - - ret_val=-100; - break; - } - - // return_message.append("\n"); - //AddNumber(return_message,ret_parameter,return_start_pos); - AddNumber(return_message,ret_val,return_start_pos,1); - AddNumber(return_message,ret_parameter,0,1); - if(ret_val!=0) break; - - cmd = GetNextString(data); - } - /*return_message.append("\n\n\n");*/ - - AddNumber(return_message,ret_val,0,1); - cout<0) return sub; - } - - return ""; -} - - -void AddNumber(string& str, int n, int location, bool space_after){ - static char retval_st[100]; - if(space_after) sprintf(retval_st,"%d ",n); - else sprintf(retval_st,"%d",n); - - if(location<0) str.append(retval_st); - else str.insert(location,retval_st); -} - -void AddNumber(string& str, float v, int location, bool space_after){ - static char retval_st[100]; - if(space_after) sprintf(retval_st,"%f ",v); - else sprintf(retval_st,"%f",v); - - if(location<0) str.append(retval_st); - else str.insert(location,retval_st); -} - - -bool SetupListenSocket(unsigned short int port){ - server_list_s=0; - server_conn_s=0; - - if((server_list_s = socket(AF_INET, SOCK_STREAM, 0))<0) return 0; - - struct sockaddr_in servaddr; /* socket address structure */ - memset(&servaddr, 0, sizeof(servaddr)); - servaddr.sin_family = AF_INET; - servaddr.sin_addr.s_addr = htonl(INADDR_ANY); - servaddr.sin_port = htons(port); - - if(bind(server_list_s,(struct sockaddr *) &servaddr,sizeof(servaddr))<0) return 0; - - if(listen(server_list_s,32) < 0){ // 1024 /* Backlog for listen() */ - return 0; - } - - return 1; -} - - -int AccpetConnectionAndWaitForData(char* buffer, int maxlength){ - if(server_list_s==0||maxlength<=0) return 0; - - if((server_conn_s = accept(server_list_s,NULL,NULL))< 0) return 0; - - int nread = read(server_conn_s,buffer,maxlength-1); - - if(nread<0) return 0; - - buffer[nread]='\0'; - return nread; -} - -bool WriteNClose(const char* buffer, int length){ - if(server_conn_s==0||length<=0) return 0; - - int nsent = write(server_conn_s,buffer,length); - if(close(server_conn_s)<0) return 0; - - server_conn_s=0; - return (nsent==length); -} - - - diff --git a/slsDetectorSoftware/eigerDetectorServer/HardwareIO.cxx b/slsDetectorSoftware/eigerDetectorServer/HardwareIO.cxx deleted file mode 100644 index 3c6cff40b..000000000 --- a/slsDetectorSoftware/eigerDetectorServer/HardwareIO.cxx +++ /dev/null @@ -1,87 +0,0 @@ - -//Class initially from Gerd and was called mmap_test.c -//return reversed 1 means good, 0 means failed - - -//#include -//#include -//#include -//#include -//#include - -#include "HardwareIO.h" - -xfs_u8 HardwareIO::xfs_in8(xfs_u32 InAddress) -{ - /* read the contents of the I/O location and then synchronize the I/O - * such that the I/O operation completes before proceeding on - */ - - xfs_u8 IoContents; - __asm__ volatile ("eieio; lbz %0,0(%1)":"=r" (IoContents):"b" - (InAddress)); - return IoContents; -} - -/*****************************************************************************/ - -xfs_u16 HardwareIO::xfs_in16(xfs_u32 InAddress) -{ - /* read the contents of the I/O location and then synchronize the I/O - * such that the I/O operation completes before proceeding on - */ - - xfs_u16 IoContents; - __asm__ volatile ("eieio; lhz %0,0(%1)":"=r" (IoContents):"b" - (InAddress)); - return IoContents; -} - -/*****************************************************************************/ - -xfs_u32 HardwareIO::xfs_in32(xfs_u32 InAddress) -{ - /* read the contents of the I/O location and then synchronize the I/O - * such that the I/O operation completes before proceeding on - */ - - xfs_u32 IoContents; - __asm__ volatile ("eieio; lwz %0,0(%1)":"=r" (IoContents):"b" - (InAddress)); - return IoContents; -} - -/*****************************************************************************/ - -void HardwareIO::xfs_out8(xfs_u32 OutAddress, xfs_u8 Value) -{ - /* write the contents of the I/O location and then synchronize the I/O - * such that the I/O operation completes before proceeding on - */ - - __asm__ volatile ("stb %0,0(%1); eieio"::"r" (Value), "b"(OutAddress)); -} - -/*****************************************************************************/ -void HardwareIO::xfs_out16(xfs_u32 OutAddress, xfs_u16 Value) -{ - /* write the contents of the I/O location and then synchronize the I/O - * such that the I/O operation completes before proceeding on - */ - - __asm__ volatile ("sth %0,0(%1); eieio"::"r" (Value), "b"(OutAddress)); -} - -/*****************************************************************************/ - -void HardwareIO::xfs_out32(xfs_u32 OutAddress, xfs_u32 Value) -{ - /* write the contents of the I/O location and then synchronize the I/O - * such that the I/O operation completes before proceeding on - */ - - __asm__ volatile ("stw %0,0(%1); eieio"::"r" (Value), "b"(OutAddress)); -} - - - diff --git a/slsDetectorSoftware/eigerDetectorServer/LocalLinkInterface.cxx b/slsDetectorSoftware/eigerDetectorServer/LocalLinkInterface.cxx deleted file mode 100644 index a8b3311ac..000000000 --- a/slsDetectorSoftware/eigerDetectorServer/LocalLinkInterface.cxx +++ /dev/null @@ -1,277 +0,0 @@ - -//Class initially from Gerd and was called mmap_test.c -//return reversed 1 means good, 0 means failed - - -#include -#include -//#include - - -#include "HardwareMMappingDefs.h" - -#include "LocalLinkInterface.h" - - - -LocalLinkInterface::LocalLinkInterface(unsigned int ll_fifo_badr){ - // printf("\n v 1 \n"); - printf("Initialize PLB LL FIFOs\n"); - ll_fifo_base=0; - ll_fifo_ctrl_reg=0; - if(Init(ll_fifo_badr)){ - Reset(); - printf("\tFIFO Status : 0x%08x\n",StatusVector()); - }else printf("\tError LocalLink Mappping : 0x%08x\n",ll_fifo_badr); - - printf("\n\n"); -} - -LocalLinkInterface::~LocalLinkInterface(){}; - -LocalLinkInterface::LocalLinkInterface(){ - printf("Initialize new memory\n"); - } - -int LocalLinkInterface::InitNewMemory (unsigned int addr, int ifg){ - unsigned int CSP0BASE; - int fd; - - /*fd = open("/dev/mem", O_RDWR | O_SYNC, 0); - if (fd == -1) { - printf("\nCan't find /dev/mem!\n"); - return 0; - } - printf("/dev/mem opened\n"); - - - CSP0BASE = (u_int32_t)mmap(0, 0x1000, PROT_READ|PROT_WRITE, MAP_FILE|MAP_SHARED, fd, addr); - if (CSP0BASE == (u_int32_t)MAP_FAILED) { - printf("\nCan't map memmory area!!\n"); - return 0; - } - printf("CSP0 mapped\n"); - - - volatile u_int8_t *ptr1; - - ptr1=(u_int8_t*)(CSP0BASE); - - printf("pointer val=%x\n",(void*)ptr1); - - printf("ifg_control=%02x\n",*ptr1); - - *ptr1=ifg; - - printf("ifg_control new=%02x\n",*ptr1); - - close(fd); -*/ - return 1; -} - - - -bool LocalLinkInterface::Init(unsigned int ll_fifo_badr){ - int fd; - void *plb_ll_fifo_ptr; - - if ((fd=open("/dev/mem", O_RDWR)) < 0){ - fprintf(stderr, "Could not open /dev/mem\n"); - return 0; - } - - plb_ll_fifo_ptr = mmap(0, getpagesize(), PROT_READ | PROT_WRITE, MAP_FILE | MAP_SHARED, fd, ll_fifo_badr); - close(fd); - - if (plb_ll_fifo_ptr == MAP_FAILED){ - perror ("mmap"); - return 0; - } - - ll_fifo_base = (xfs_u32) plb_ll_fifo_ptr; - ll_fifo_ctrl_reg = 0; - - return 1; -} - - - -bool LocalLinkInterface::Reset(){ - return Reset(PLB_LL_FIFO_CTRL_RESET_STD); -} - -bool LocalLinkInterface::Reset(unsigned int rst_mask){ - ll_fifo_ctrl_reg |= rst_mask; - printf("\tCTRL Register bits: 0x%08x\n",ll_fifo_ctrl_reg); - - xfs_out32(ll_fifo_base+4*PLB_LL_FIFO_REG_CTRL,ll_fifo_ctrl_reg); - xfs_out32(ll_fifo_base+4*PLB_LL_FIFO_REG_CTRL,ll_fifo_ctrl_reg); - xfs_out32(ll_fifo_base+4*PLB_LL_FIFO_REG_CTRL,ll_fifo_ctrl_reg); - xfs_out32(ll_fifo_base+4*PLB_LL_FIFO_REG_CTRL,ll_fifo_ctrl_reg); - - ll_fifo_ctrl_reg &= (~rst_mask); - - xfs_out32(ll_fifo_base+4*PLB_LL_FIFO_REG_CTRL,ll_fifo_ctrl_reg); - // printf("FIFO CTRL Address: 0x%08x\n FIFO CTRL Register: 0x%08x\n",PLB_LL_FIFO_REG_CTRL,plb_ll_fifo[PLB_LL_FIFO_REG_CTRL]); - return 1; -} - - - -unsigned int LocalLinkInterface::StatusVector(){ - return xfs_in32(ll_fifo_base+4*PLB_LL_FIFO_REG_STATUS); -} - -int LocalLinkInterface::Write(unsigned int buffer_len, void *buffer){ - // note: buffer must be word (4 byte) aligned - // frame_len in byte - int vacancy=0; - int i; - int words_send = 0; - int last_word; - unsigned int *word_ptr; - unsigned int fifo_ctrl; - xfs_u32 status; - - if (buffer_len < 1) return -1; - - last_word = (buffer_len-1)/4; - word_ptr = (unsigned int *)buffer; - - while (words_send <= last_word) - { - while (!vacancy)//wait for Fifo to be empty again - { - status = xfs_in32(ll_fifo_base+4*PLB_LL_FIFO_REG_STATUS); - if((status & PLB_LL_FIFO_STATUS_ALMOSTFULL) == 0) vacancy = 1; - } - - //Just to know: #define PLB_LL_FIFO_ALMOST_FULL_THRESHOLD_WORDS 100 - for (i=0; ((i>>> SOF\n\r"); - buffer_ptr = 0; - sof = 1; - } - - fifo_val = xfs_in32(ll_fifo_base+4*PLB_LL_FIFO_REG_FIFO); //read from fifo - - if ((buffer_ptr > 0) || sof) - { - if ( (buffer_len >> 2) > buffer_ptr) - { - word_ptr[buffer_ptr++] = fifo_val; //write to buffer - } - else - { - buffer_ptr = 0; - return -2; // buffer overflow - } - - if (status & PLB_LL_FIFO_STATUS_LL_EOF) - { - len = (buffer_ptr << 2) -3 + ( (status & PLB_LL_FIFO_STATUS_LL_REM)>>PLB_LL_FIFO_STATUS_LL_REM_SHIFT ); -// printf(">>>>status=0x%08x EOF len = %d \n\r\n\r",status, len); - buffer_ptr = 0; - return len; - } - - } - } - } - while(!(status & PLB_LL_FIFO_STATUS_EMPTY)); - - return 0; -} - -bool LocalLinkInterface::ctrl_reg_write_mask(unsigned int mask, unsigned int val){ - // printf("Fifo CTRL Reg(1): 0x%08x\n",plb_ll_fifo_ctrl_reg); - ll_fifo_ctrl_reg &= (~mask); - //printf("Fifo CTRL Reg(2): 0x%08x\n",plb_ll_fifo_ctrl_reg); - ll_fifo_ctrl_reg |= ( mask & val); -// printf("Fifo CTRL Reg: 0x%08x\n",plb_ll_fifo_ctrl_reg); - xfs_out32(ll_fifo_base+4*PLB_LL_FIFO_REG_CTRL,ll_fifo_ctrl_reg); -// printf("Fifo STAT Reg: 0x%08x\n", plb_ll_fifo[PLB_LL_FIFO_REG_STATUS]); - return 1; -} - - -int LocalLinkInterface::Test(unsigned int buffer_len, void *buffer){ - - int len; - unsigned int rec_buff_len = 4096; - unsigned int rec_buffer[4097]; - - - Write(buffer_len,buffer); - usleep(10000); - - do{ - len = Read(rec_buff_len,rec_buffer); - printf("receive length: %i\n",len); - - if (len > 0){ - rec_buffer[len]=0; - printf((char*) rec_buffer); - printf("\n"); - } - } while(len > 0); - - printf("\n\n\n\n"); - return 1; -} - -void LocalLinkInterface::llfifo_print_frame(unsigned char* fbuff, int len){ - printf("\n\r----Frame of len : %d Byte\n\r",len); - for(int i=0;i - -#include "xparameters.h" - -#include "LocalLinkInterface.h" - -int main(){ - - char s[2000]; - sprintf(s,"papamama"); - - LocalLinkInterface* l0 = new LocalLinkInterface(XPAR_PLB_LL_FIFO_AURORA_DUAL_CTRL_FEB_LEFT_BASEADDR); - l0->Test(8,s); - LocalLinkInterface* l1 = new LocalLinkInterface(XPAR_PLB_LL_FIFO_AURORA_RX4_TX1_LEFT_BASEADDR); - l1->Test(8,s); - LocalLinkInterface* l2 = new LocalLinkInterface(XPAR_PLB_LL_FIFO_AURORA_DUAL_CTRL_FEB_RIGHT_BASEADDR); - l2->Test(8,s); - LocalLinkInterface* l3 = new LocalLinkInterface(XPAR_PLB_LL_FIFO_AURORA_RX4_TX1_RIGHT_BASEADDR); - l3->Test(8,s); - - delete l0; - delete l1; - delete l2; - delete l3; - - return 1; -} diff --git a/slsDetectorSoftware/eigerDetectorServer/Makefile b/slsDetectorSoftware/eigerDetectorServer/Makefile index 3a9cc6c59..ccf582d27 100755 --- a/slsDetectorSoftware/eigerDetectorServer/Makefile +++ b/slsDetectorSoftware/eigerDetectorServer/Makefile @@ -1,5 +1,4 @@ CC = powerpc-4xx-softfloat-gcc -CCX = powerpc-4xx-softfloat-g++ BLACKFIN_CC = bfin-uclinux-gcc CFLAGS += -Wall -DDACS_INT -DEIGERD -DSLS_DETECTOR_FUNCTION_LIST -DDACS_INT -DSTOP_SERVER #-DVERBOSEI #-DVERBOSE #-DVIRTUAL -DPCCOMPILE -DMARTIN LDLIBS += -lm -lstdc++ @@ -10,13 +9,10 @@ INSTMODE = 0777 SRC_CLNT = communication_funcs.c slsDetectorServer.c slsDetectorServer_funcs.c slsDetectorFunctionList.c FebControl.c Beb.c HardwareIO.c LocalLinkInterface.c Feb.c FebInterface.c -#SRC_CLNT2 = FebServer.cxx FebControl.cxx FebInterface.cxx LocalLinkInterface.cxx HardwareIO.cxx -#SRC_CLNT3 = BebServer.cxx Beb.cxx LocalLinkInterface.cxx HardwareIO.cxx - OBJS = $(SRC_CLNT:.c=.o) -all: clean $(PROGS) hv9m_blackfin_server #feb_debug beb_debug +all: clean $(PROGS) #hv9m_blackfin_server boot: $(OBJS) @@ -27,14 +23,7 @@ $(PROGS): $(CC) -o $@ $(SRC_CLNT) $(CFLAGS) $(LDLIBS) mv $(PROGS) $(DESTDIR) -feb_debug:$(SRC_CLNT2) - $(CCX) -o feb_debug $(SRC_CLNT2) -I. - mv feb_debug $(DESTDIR) - -beb_debug:$(SRC_CLNT3) - $(CCX) -o beb_debug $(SRC_CLNT3) -I. - mv beb_debug $(DESTDIR) - + hv9m_blackfin_server:9mhvserial_bf.c $(BLACKFIN_CC) -o hv9m_blackfin_server 9mhvserial_bf.c -Wall #-DVERBOSE mv hv9m_blackfin_server $(DESTDIR) diff --git a/slsDetectorSoftware/eigerDetectorServer/Test.cxx b/slsDetectorSoftware/eigerDetectorServer/Test.cxx deleted file mode 100644 index 8e07d609b..000000000 --- a/slsDetectorSoftware/eigerDetectorServer/Test.cxx +++ /dev/null @@ -1,38 +0,0 @@ - -/** - * @author Ian Johnson - * @version 1.0 - */ - - -#include -#include - -#include "xparameters.h" - -#include "Feb.h" - - -using namespace std; - -int main(){ - - cout<<"\n\n\n\n\n\n\n\n\n\n"<ReadRegister(0,0,v); - feb->ReadRegister(0,0xffffffff,v); - cout<ReadRegister(1,0,v); - feb->ReadRegister(1,0xffffffff,v); - - delete feb; - - return 1; -} diff --git a/slsDetectorSoftware/eigerDetectorServer/bin/eigerDetectorServerv2.2.0.16.5 b/slsDetectorSoftware/eigerDetectorServer/bin/eigerDetectorServerv2.2.0.16.5 deleted file mode 100755 index 9fdf4f404..000000000 Binary files a/slsDetectorSoftware/eigerDetectorServer/bin/eigerDetectorServerv2.2.0.16.5 and /dev/null differ diff --git a/slsDetectorSoftware/eigerDetectorServer/bin/eigerDetectorServerv3.0.0.16.0 b/slsDetectorSoftware/eigerDetectorServer/bin/eigerDetectorServerv3.0.0.16.0 new file mode 100755 index 000000000..d7836a000 Binary files /dev/null and b/slsDetectorSoftware/eigerDetectorServer/bin/eigerDetectorServerv3.0.0.16.0 differ diff --git a/slsDetectorSoftware/eigerDetectorServer/bin/hv9m_blackfin_server b/slsDetectorSoftware/eigerDetectorServer/bin/hv9m_blackfin_server deleted file mode 100755 index a23826d2f..000000000 Binary files a/slsDetectorSoftware/eigerDetectorServer/bin/hv9m_blackfin_server and /dev/null differ diff --git a/slsDetectorSoftware/eigerDetectorServer/build.sh b/slsDetectorSoftware/eigerDetectorServer/build.sh deleted file mode 100755 index 876ac32f5..000000000 --- a/slsDetectorSoftware/eigerDetectorServer/build.sh +++ /dev/null @@ -1,19 +0,0 @@ - -echo -e "\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n" - -. /opt/eldk-5.1/powerpc-4xx-softfloat/environment-setup-ppc440-linux - -#powerpc-4xx-softfloat-g++ -Wall -o test Test.cxx HardwareIO.cxx LocalLinkInterface.cxx Feb.cxx -I . -#powerpc-4xx-softfloat-g++ -Wall -o hardware_interface_test HardwareInterfaceTest.cxx HardwareInterface.cxx HardwareMMapping.cxx -I . - - -#powerpc-4xx-softfloat-g++ -Wall -o eiger_test EigerTest.cxx Eiger.cxx HardwareIO.cxx LocalLinkInterface.cxx Feb.cxx -I . - -powerpc-4xx-softfloat-g++ -Wall -o feb_debug FebServer.cxx FebControl.cxx FebInterface.cxx LocalLinkInterface.cxx HardwareIO.cxx -I . - -powerpc-4xx-softfloat-g++ -Wall -o beb_debug BebServer.cxx Beb.cxx LocalLinkInterface.cxx HardwareIO.cxx -I . - - -cp eiger_test rootfs_executables/. - - diff --git a/slsDetectorSoftware/eigerDetectorServer/doxy_eiger.config b/slsDetectorSoftware/eigerDetectorServer/doxy_eiger.config deleted file mode 100644 index 9f9de954a..000000000 --- a/slsDetectorSoftware/eigerDetectorServer/doxy_eiger.config +++ /dev/null @@ -1,94 +0,0 @@ -# If the EXTRACT_ALL tag is set to YES doxygen will assume all entities in -# documentation are documented, even if no documentation was available. -# Private class members and static file members will be hidden unless -# the EXTRACT_PRIVATE and EXTRACT_STATIC tags are set to YES - -EXTRACT_ALL = YES - -# If the EXTRACT_PRIVATE tag is set to YES all private members of a class -# will be included in the documentation. - -EXTRACT_PRIVATE = NO - - - -# If the EXTRACT_STATIC tag is set to YES all static members of a file -# will be included in the documentation. - -EXTRACT_STATIC = YES - -# If the EXTRACT_LOCAL_CLASSES tag is set to YES classes (and structs) -# defined locally in source files will be included in the documentation. -# If set to NO only classes defined in header files are included. - -EXTRACT_LOCAL_CLASSES = YES - -# This flag is only useful for Objective-C code. When set to YES local -# methods, which are defined in the implementation section but not in -# the interface are included in the documentation. -# If set to NO (the default) only methods in the interface are included. - -EXTRACT_LOCAL_METHODS = YES - -# If this flag is set to YES, the members of anonymous namespaces will be -# extracted and appear in the documentation as a namespace called -# 'anonymous_namespace{file}', where file will be replaced with the base -# name of the file that contains the anonymous namespace. By default -# anonymous namespace are hidden. - -EXTRACT_ANON_NSPACES = NO - -# If the HIDE_UNDOC_MEMBERS tag is set to YES, Doxygen will hide all -# undocumented members of documented classes, files or namespaces. -# If set to NO (the default) these members will be included in the -# various overviews, but no documentation section is generated. -# This option has no effect if EXTRACT_ALL is enabled. - -HIDE_UNDOC_MEMBERS = NO - -# If the HIDE_UNDOC_CLASSES tag is set to YES, Doxygen will hide all -# undocumented classes that are normally visible in the class hierarchy. -# If set to NO (the default) these classes will be included in the various -# overviews. This option has no effect if EXTRACT_ALL is enabled. - -HIDE_UNDOC_CLASSES = NO - -# If the HIDE_FRIEND_COMPOUNDS tag is set to YES, Doxygen will hide all -# friend (class|struct|union) declarations. -# If set to NO (the default) these declarations will be included in the -# documentation. - -HIDE_FRIEND_COMPOUNDS = NO - -INTERNAL_DOCS = NO - -SHOW_INCLUDE_FILES = NO - -SHOW_FILES = NO - -SHOW_NAMESPACES = NO - -COMPACT_LATEX = YES - -PAPER_TYPE = a4 - -PDF_HYPERLINKS = YES - -USE_PDFLATEX = YES - -LATEX_HIDE_INDICES = YES - -PREDEFINED = __cplusplus - -HAVE_DOT = YES -CALL_GRAPH = YES -CALLER_GRAPH = YES - - -INPUT = Beb.h Eiger.h FebControl.h FebInterface.h gitInfoEiger.h HardwareIO.h LocalLinkInterface.h sls_detector_funcs.h slsDetectorServer_defs.h sls_receiver_defs.h xfs_types.h communication_funcs.h EigerRegisterDefs.h Feb.h FebRegisterDefs.h gitInfoEigerTmp.h HardwareMMappingDefs.h sls_detector_defs.h slsDetectorFunctionList.h slsDetectorServer_funcs.h sls_receiver_funcs.h xparameters.h Beb.cxx BebServer.cxx Eiger.cxx EigerTest.cxx FebControl.cxx Feb.cxx FebInterface.cxx FebServer.cxx HardwareIO.cxx LocalLinkInterface.cxx LocalLinkTest.cxx Test.cxx - - - - -OUTPUT_DIRECTORY = docs - diff --git a/slsDetectorSoftware/eigerDetectorServer/gitInfo.txt b/slsDetectorSoftware/eigerDetectorServer/gitInfo.txt index ca2583820..b403b62b9 100644 --- a/slsDetectorSoftware/eigerDetectorServer/gitInfo.txt +++ b/slsDetectorSoftware/eigerDetectorServer/gitInfo.txt @@ -1,9 +1,9 @@ Path: slsDetectorsPackage/slsDetectorSoftware/eigerDetectorServer URL: origin git@git.psi.ch:sls_detectors_software/sls_detector_software.git/eigerDetectorServer Repository Root: origin git@git.psi.ch:sls_detectors_software/sls_detector_software.git -Repsitory UUID: 230d6b36e9852214f4ba5ae7c92647f35000b24d -Revision: 263 +Repsitory UUID: 6d38c0622a2936f70345e7d53aaf1c9e2de4cbd6 +Revision: 285 Branch: developer Last Changed Author: Dhanya_Maliakal -Last Changed Rev: 1313 -Last Changed Date: 2016-11-30 10:36:34 +0100 +Last Changed Rev: 1401 +Last Changed Date: 2017-06-12 18:53:18 +0200 diff --git a/slsDetectorSoftware/eigerDetectorServer/gitInfoEiger.h b/slsDetectorSoftware/eigerDetectorServer/gitInfoEiger.h index b4ce91247..1539e7f79 100644 --- a/slsDetectorSoftware/eigerDetectorServer/gitInfoEiger.h +++ b/slsDetectorSoftware/eigerDetectorServer/gitInfoEiger.h @@ -1,11 +1,11 @@ //#define SVNPATH "" #define SVNURL "git@git.psi.ch:sls_detectors_software/sls_detector_software.git/eigerDetectorServer" //#define SVNREPPATH "" -#define SVNREPUUID "230d6b36e9852214f4ba5ae7c92647f35000b24d" -//#define SVNREV 0x1313 +#define SVNREPUUID "6d38c0622a2936f70345e7d53aaf1c9e2de4cbd6" +//#define SVNREV 0x1401 //#define SVNKIND "" //#define SVNSCHED "" #define SVNAUTH "Dhanya_Maliakal" -#define SVNREV 0x1313 -#define SVNDATE 0x20161130 +#define SVNREV 0x1401 +#define SVNDATE 0x20170612 // diff --git a/slsDetectorSoftware/eigerDetectorServer/renameServer.sh b/slsDetectorSoftware/eigerDetectorServer/renameServer.sh index 9aca06728..54d5d2622 100644 --- a/slsDetectorSoftware/eigerDetectorServer/renameServer.sh +++ b/slsDetectorSoftware/eigerDetectorServer/renameServer.sh @@ -1,3 +1,4 @@ mv bin/eigerDetectorServer bin/$2 +cp bin/$2 /tftpboot git rm -f bin/$1 git add bin/$2 diff --git a/slsDetectorSoftware/eigerDetectorServer/setup.txt b/slsDetectorSoftware/eigerDetectorServer/setup.txt deleted file mode 100644 index 64c3600e1..000000000 --- a/slsDetectorSoftware/eigerDetectorServer/setup.txt +++ /dev/null @@ -1,53 +0,0 @@ - - -#detector setup - #add_module module_number base_address_top (for half module) - #add_module module_number base_address_top base_address_bottom (for full module) -add_half_module 17 0 -#add_half_module 17 1 for bottom -#add_module 18 10 12 -#add_module 2 13 15 -#add_module 1 120 22 - - -#default setting -photon_energy 8000 -dynamic_range 16 -readout_speed 1 #(0-full,1-half,2-quarter and 3-superslow) -readout_mode 0 #(0-parallel,1-non_parallel,2-safe_mode) - - -#default dacs -SvP 0 -Vtr 1280 -Vrf 1550 -Vrs 700 -SvN 2000 -Vtgstv 1278 -Vcmp_ll 750 -Vcmp_lr 750 -cal 2000 -Vcmp_rl 750 -rxb_rb 600 -rxb_lb 600 -Vcmp_rr 750 -Vcp 100 -Vcn 1000 -Vis 775 - -#default high_voltage -high_voltage 152 - -#default iodelays -iodelay 675 - -#newgoodiodelay 643 -#halfspeed_add_about 32 -#goodiodelay 1467 -#goodiodelay 1550 - - - - - - diff --git a/slsDetectorSoftware/eigerDetectorServer/setup_beb.txt b/slsDetectorSoftware/eigerDetectorServer/setup_beb.txt deleted file mode 100644 index 148cc17e9..000000000 --- a/slsDetectorSoftware/eigerDetectorServer/setup_beb.txt +++ /dev/null @@ -1,12 +0,0 @@ - - -#detector setup -#add_beb base_address mac_1GBE ip_1GBE mac_10GBE ip_10GBE - -add_beb 26 0 00:50:c2:46:d9:34 129.129.205.78 00:50:c2:46:d9:35 10.0.26.1 - - - - - - diff --git a/slsDetectorSoftware/eigerDetectorServer/slsDetectorFunctionList.c b/slsDetectorSoftware/eigerDetectorServer/slsDetectorFunctionList.c index b675703c6..c05d9c6ef 100644 --- a/slsDetectorSoftware/eigerDetectorServer/slsDetectorFunctionList.c +++ b/slsDetectorSoftware/eigerDetectorServer/slsDetectorFunctionList.c @@ -28,8 +28,6 @@ int *detectorChips=NULL; int *detectorChans=NULL; dacs_t *detectorDacs=NULL; dacs_t *detectorAdcs=NULL; -int* detectorGain = NULL; -int* detectorOffset = NULL; int eiger_highvoltage = 0; int eiger_iodelay = 0; @@ -53,24 +51,7 @@ unsigned int nimages_per_request=1; int on_dst=0; int dst_requested[32] = {0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0}; -int default_dac_values[16] = { - 0, //SvP - 2480, //Vtr - 3300, //Vrf - 1400, //Vrs - 4000, //SvN - 2556, //Vtgstv - 1000, //Vcmp_ll - 1000, //Vcmp_lr - 4000, //cal - 1000, //Vcmp_rl - 1100, //rxb_rb - 1100, //rxb_lb - 1000, //Vcmp_rr - 1000, //Vcp - 2000, //Vcn - 1550 //Vis -}; + int default_gain_values[3] = {517000,517000,517000}; int default_offset_values[3] = {3851000,3851000,3851000}; @@ -81,165 +62,64 @@ int master = 0; int normal = 0; -#define TEN_GIGA_BUFFER_SIZE 4112 -#define ONE_GIGA_BUFFER_SIZE 1040 -int initDetector(){ - int imod,i,n; - n = getNModBoard(1); - //#ifdef VERBOSE - printf("This Server is for 1 Eiger half module\n"); - //#endif +/* basic tests */ +void checkFirmwareCompatibility(){ + uint32_t ipadd = getDetectorIP(); + uint64_t macadd = getDetectorMAC(); + int64_t fwversion = getDetectorId(DETECTOR_FIRMWARE_VERSION); + int64_t swversion = getDetectorId(DETECTOR_SOFTWARE_VERSION); + int64_t sw_fw_apiversion = getDetectorId(SOFTWARE_FIRMWARE_API_VERSION); - //Allocation of memory - detectorModules=malloc(n*sizeof(sls_detector_module)); - detectorChips=malloc(n*NCHIP*sizeof(int)); + cprintf(BLUE,"\n\n" + "********************************************************\n" + "**********************EIGER Server**********************\n" + "********************************************************\n"); + cprintf(BLUE,"\n" + "Detector IP Addr:\t\t 0x%x\n" + "Detector MAC Addr:\t\t 0x%llx\n" - detectorChans=malloc(n*NCHIP*NCHAN*sizeof(int)); - detectorDacs=malloc(n*NDAC*sizeof(dacs_t)); - detectorAdcs=malloc(n*NADC*sizeof(dacs_t)); - detectorGain=malloc(n*NGAIN*sizeof(int)); - detectorOffset=malloc(n*NOFFSET*sizeof(int)); -#ifdef VERBOSE - printf("modules from 0x%x to 0x%x\n",detectorModules, detectorModules+n); - printf("chips from 0x%x to 0x%x\n",detectorChips, detectorChips+n*NCHIP); - printf("chans from 0x%x to 0x%x\n",detectorChans, detectorChans+n*NCHIP*NCHAN); - printf("dacs from 0x%x to 0x%x\n",detectorDacs, detectorDacs+n*NDAC); - printf("adcs from 0x%x to 0x%x\n",detectorAdcs, detectorAdcs+n*NADC); - printf("gains from 0x%x to 0x%x\n",detectorGain, detectorGain+n*NGAIN); - printf("offsets from 0x%x to 0x%x\n",detectorOffset, detectorOffset+n*NOFFSET); -#endif - for (imod=0; imoddacs=detectorDacs+imod*NDAC; - (detectorModules+imod)->adcs=detectorAdcs+imod*NADC; - (detectorModules+imod)->chipregs=detectorChips+imod*NCHIP; - (detectorModules+imod)->chanregs=detectorChans+imod*NCHIP*NCHAN; - (detectorModules+imod)->ndac=NDAC; - (detectorModules+imod)->nadc=NADC; - (detectorModules+imod)->nchip=NCHIP; - (detectorModules+imod)->nchan=NCHIP*NCHAN; - (detectorModules+imod)->module=imod; - (detectorModules+imod)->gain=0; - (detectorModules+imod)->offset=0; - (detectorModules+imod)->reg=0; - /* initialize registers, dacs, retrieve sn, adc values etc */ + "Firmware Version:\t\t %lld\n" + "Software Version:\t\t %llx\n" + "F/w-S/w API Version:\t\t %lld\n" + "Required Firmware Version:\t %d\n\n" + "********************************************************\n", + ipadd, macadd, + fwversion,swversion, + sw_fw_apiversion,REQUIRED_FIRMWARE_VERSION); + + //cant read versions + if(!fwversion || !sw_fw_apiversion){ + cprintf(RED,"FATAL ERROR: Cant read versions from FPGA. Please update firmware\n"); + cprintf(RED,"Exiting Server. Goodbye!\n\n"); + exit(-1); } - for(i=0;i REQUIRED_FIRMWARE_VERSION){ + cprintf(RED,"FATAL ERROR: This software version is incompatible.\n" + "Please update it to be compatible with this firmware\n\n"); + cprintf(RED,"Exiting Server. Goodbye!\n\n"); + exit(-1); } - printf("FEB Initialization done\n"); - Beb_Beb(); - printf("BEB Initialization done\n"); - //Get dac values - int retval[2]; - for(i=0;i<(detectorModules)->ndac;i++) - setDAC((enum detDacIndex)i,default_dac_values[i],(detectorModules)->module,0,retval); - - //setting default measurement parameters - setTimer(FRAME_NUMBER,1); - setTimer(ACQUISITION_TIME,1E9); - setTimer(SUBFRAME_ACQUISITION_TIME,DEFAULT_SUBFRAME_EXPOSURE_VAL); - setTimer(FRAME_PERIOD,1E9); - setDynamicRange(16); - eiger_photonenergy = -1; - setReadOutFlags(NONPARALLEL); - setSpeed(0,1);//clk_devider,half speed - setIODelay(650,0); - setTiming(AUTO_TIMING); - //SetPhotonEnergyCalibrationParameters(-5.8381e-5,1.838515,5.09948e-7,-4.32390e-11,1.32527e-15); - setRateCorrection(0); //deactivate rate correction - int enable[2] = {0,1}; - setExternalGating(enable);//disable external gating - Feb_Control_SetInTestModeVariable(0); - setHighVoltage(0,0); - Feb_Control_CheckSetup(); - - //print detector mac and ip - printf("mac read from detector: %llx\n",getDetectorMAC()); - printf("ip read from detector: %x\n",getDetectorIP()); - - - printf("\n"); - return 1; -} - -int initDetectorStop(){ - getModuleConfiguration(); - Feb_Interface_FebInterface(); - Feb_Control_FebControl(); - Feb_Control_Init(master,top,normal,getDetectorNumber()); - printf("FEB Initialization done\n"); - /* Beb_Beb(-1); - printf("BEB constructor done\n");*/ - - printf("\n"); - return 1; + //check for firmware compatibility - old firmware + if( REQUIRED_FIRMWARE_VERSION > fwversion){ + cprintf(RED,"FATAL ERROR: This firmware version is incompatible.\n" + "Please update it to v%d to be compatible with this server\n\n", REQUIRED_FIRMWARE_VERSION); + cprintf(RED,"Exiting Server. Goodbye!\n\n"); + exit(-1); + } } -void getModuleConfiguration(){ - int *m=&master; - int *t=⊤ - int *n=&normal; - /*if(getDetectorNumber() == 0xbeb015){ - master = 1; - top = 1; - }*/ - Beb_GetModuleConfiguration(m,t,n); - if(top) printf("*************** TOP ***************\n"); - else printf("*************** BOTTOM ***************\n"); - if(master) printf("*************** MASTER ***************\n"); - else printf("*************** SLAVE ***************\n"); - if(normal) printf("*************** NORMAL ***************\n"); - else printf("*************** SPECIAL ***************\n"); -} - - - -int setNMod(int nm, enum dimension dim){ - return 1; -} - - - -int getNModBoard(enum dimension arg){ - return 1; -} - - - -int64_t getModuleId(enum idMode arg, int imod){ - - /**/ - return -1; -} - +/* Ids */ int64_t getDetectorId(enum idMode arg){ int64_t retval = -1; @@ -249,7 +129,7 @@ int64_t getDetectorId(enum idMode arg){ retval = getDetectorNumber();/** to be implemented with mac? */ break; case DETECTOR_FIRMWARE_VERSION: - return (int64_t)Beb_GetFirmwareRevision(); + return (int64_t)getFirmwareVersion(); case SOFTWARE_FIRMWARE_API_VERSION: return (int64_t)Beb_GetFirmwareSoftwareAPIVersion(); case DETECTOR_SOFTWARE_VERSION: @@ -264,28 +144,21 @@ int64_t getDetectorId(enum idMode arg){ return retval; } +u_int64_t getFirmwareVersion() { + return Beb_GetFirmwareRevision(); +} -int getDetectorNumber(){ - int res=0; +u_int32_t getDetectorNumber(){ + u_int32_t res=0; //execute and get address char output[255]; FILE* sysFile = popen("more /home/root/executables/detid.txt", "r"); fgets(output, sizeof(output), sysFile); pclose(sysFile); - sscanf(output,"%d",&res); - printf("detector id: %d\n",res); - -/* - int res=0; - char hostname[100]; - if (gethostname(hostname, sizeof hostname) == 0) - puts(hostname); - else - perror("gethostname"); - sscanf(hostname,"%x",&res); -*/ + sscanf(output,"%u",&res); + printf("detector id: %u\n",res); return res; } @@ -318,10 +191,9 @@ u_int64_t getDetectorMAC() { } - -int getDetectorIP(){ +u_int32_t getDetectorIP(){ char temp[50]=""; - int res=0; + u_int32_t res=0; //execute and get address char output[255]; FILE* sysFile = popen("ifconfig | grep 'inet addr:'| grep -v '127.0.0.1' | cut -d: -f2", "r"); @@ -344,33 +216,126 @@ int getDetectorIP(){ -int moduleTest( enum digitalTestMode arg, int imod){ - //template testShiftIn from mcb_funcs.c - //CHIP_TEST - //testShiftIn - //testShiftOut - //testShiftStSel - //testDataInOutMux - //testExtPulseMux - //testOutMux - //testFpgaMux - return OK; +/* initialization */ + +void initControlServer(){ + //Feb and Beb Initializations + getModuleConfiguration(); + Feb_Interface_FebInterface(); + Feb_Control_FebControl(); + Feb_Control_Init(master,top,normal, getDetectorNumber()); + //master of 9M, check high voltage serial communication to blackfin + if(master && !normal){ + if(Feb_Control_OpenSerialCommunication()) + ;// Feb_Control_CloseSerialCommunication(); + } + printf("FEB Initialization done\n"); + Beb_Beb(); + printf("BEB Initialization done\n"); + + + setupDetector(); + + printf("\n"); +} + +void initStopServer(){ + getModuleConfiguration(); + Feb_Interface_FebInterface(); + Feb_Control_FebControl(); + Feb_Control_Init(master,top,normal,getDetectorNumber()); + printf("FEB Initialization done\n"); + + printf("\n"); +} + + +void getModuleConfiguration(){ + int *m=&master; + int *t=⊤ + int *n=&normal; + Beb_GetModuleConfiguration(m,t,n); + if(top) printf("*************** TOP ***************\n"); + else printf("*************** BOTTOM ***************\n"); + if(master) printf("*************** MASTER ***************\n"); + else printf("*************** SLAVE ***************\n"); + if(normal) printf("*************** NORMAL ***************\n"); + else printf("*************** SPECIAL ***************\n"); } +/* set up detector */ + +void allocateDetectorStructureMemory(){ + printf("This Server is for 1 Eiger half module (250k)\n"); + + //Allocation of memory + detectorModules=malloc(sizeof(sls_detector_module)); + detectorChips=malloc(NCHIP*sizeof(int)); + detectorChans=malloc(NCHIP*NCHAN*sizeof(int)); + detectorDacs=malloc(NDAC*sizeof(dacs_t)); + detectorAdcs=malloc(NADC*sizeof(dacs_t)); +#ifdef VERBOSE + printf("modules from 0x%x to 0x%x\n",detectorModules, detectorModules+n); + printf("chips from 0x%x to 0x%x\n",detectorChips, detectorChips+n*NCHIP); + printf("chans from 0x%x to 0x%x\n",detectorChans, detectorChans+n*NCHIP*NCHAN); + printf("dacs from 0x%x to 0x%x\n",detectorDacs, detectorDacs+n*NDAC); + printf("adcs from 0x%x to 0x%x\n",detectorAdcs, detectorAdcs+n*NADC); +#endif + (detectorModules)->dacs=detectorDacs; + (detectorModules)->adcs=detectorAdcs; + (detectorModules)->chipregs=detectorChips; + (detectorModules)->chanregs=detectorChans; + (detectorModules)->ndac=NDAC; + (detectorModules)->nadc=NADC; + (detectorModules)->nchip=NCHIP; + (detectorModules)->nchan=NCHIP*NCHAN; + (detectorModules)->module=0; + (detectorModules)->gain=0; + (detectorModules)->offset=0; + (detectorModules)->reg=0; + thisSettings = UNINITIALIZED; +} -int detectorTest( enum digitalTestMode arg){ - //templates from firmware_funcs.c - //DETECTOR_FIRMWARE_TEST:testFpga() - //DETECTOR_MEMORY_TEST:testRAM() - //DETECTOR_BUS_TEST:testBus() - //DETECTOR_SOFTWARE_TEST:testFpga() - return OK; +void setupDetector() { + + allocateDetectorStructureMemory(); + //set dacs + printf("Setting Default Dac values\n"); + { + int i = 0; + int retval[2]={-1,-1}; + const int defaultvals[NDAC] = DEFAULT_DAC_VALS; + for(i = 0; i < NDAC; ++i) { + setDAC((enum DACINDEX)i,defaultvals[i],0,0,retval); + if (retval[0] != defaultvals[i]) + cprintf(RED, "Warning: Setting dac %d failed, wrote %d, read %d\n",i ,defaultvals[i], retval[0]); + } + } + + //setting default measurement parameters + setTimer(FRAME_NUMBER, DEFAULT_NUM_FRAMES); + setTimer(ACQUISITION_TIME, DEFAULT_EXPTIME); + setTimer(SUBFRAME_ACQUISITION_TIME, DEFAULT_SUBFRAME_EXPOSURE_VAL); + setTimer(FRAME_PERIOD, DEFAULT_PERIOD); + setDynamicRange(DEFAULT_DYNAMIC_RANGE); + eiger_photonenergy = DEFAULT_PHOTON_ENERGY; + setReadOutFlags(DEFAULT_READOUT_FLAG); + setSpeed(CLOCK_DIVIDER, DEFAULT_CLK_SPEED);//clk_devider,half speed + setIODelay(DEFAULT_IO_DELAY, DEFAULT_MOD_INDEX); + setTiming(DEFAULT_TIMING_MODE); + //SetPhotonEnergyCalibrationParameters(-5.8381e-5,1.838515,5.09948e-7,-4.32390e-11,1.32527e-15); + setRateCorrection(DEFAULT_RATE_CORRECTION); + int enable[2] = {DEFAULT_EXT_GATING_ENABLE, DEFAULT_EXT_GATING_POLARITY}; + setExternalGating(enable);//disable external gating + Feb_Control_SetInTestModeVariable(DEFAULT_TEST_MODE); + setHighVoltage(DEFAULT_HIGH_VOLTAGE); + Feb_Control_CheckSetup(); } @@ -378,7 +343,306 @@ int detectorTest( enum digitalTestMode arg){ -void setDAC(enum detDacIndex ind, int val, int imod, int mV, int retval[]){ + +/* set parameters - nmod, dr, roi */ + +int setNMod(int nm, enum dimension dim){ + return NMOD; +} + + +int getNModBoard(enum dimension arg){ + return NMAXMOD; +} + +int setDynamicRange(int dr){ + if(dr > 0){ + printf(" Setting dynamic range: %d\n",dr); + if(Feb_Control_SetDynamicRange(dr)){ + + //EigerSetBitMode(dr); + on_dst = 0; + int i; + for(i=0;i<32;i++) dst_requested[i] = 0; //clear dst requested + if(Beb_SetUpTransferParameters(dr)) + eiger_dynamicrange = dr; + else printf("ERROR:Could not set bit mode in the back end\n"); + } + } + //make sure back end and front end have the same bit mode + dr= Feb_Control_GetDynamicRange(); + + return dr; +} + + + + +/* parameters - readout */ + +int setSpeed(enum speedVariable arg, int val){ + + if (arg != CLOCK_DIVIDER) + return -1; + + if(val != -1){ + printf(" Setting Read out Speed: %d\n",val); + if(Feb_Control_SetReadoutSpeed(val)) + eiger_readoutspeed = val; + } + return eiger_readoutspeed; +} + + +enum readOutFlags setReadOutFlags(enum readOutFlags val){ + + enum readOutFlags retval = GET_READOUT_FLAGS; + if(val!=GET_READOUT_FLAGS){ + + + if(val&0xF0000){ + switch(val){ + case PARALLEL: val=E_PARALLEL; printf(" Setting Read out Flag: Parallel\n"); break; + case NONPARALLEL: val=E_NON_PARALLEL; printf(" Setting Read out Flag: Non Parallel\n"); break; + case SAFE: val=E_SAFE; printf(" Setting Read out Flag: Safe\n"); break; + + default: + cprintf(RED,"Cannot set unknown readout flag. 0x%x\n", val); + return -1; + } + printf(" Setting Read out Flag: %d\n",val); + if(Feb_Control_SetReadoutMode(val)) + eiger_readoutmode = val; + else return -1; + + }else{ + switch(val){ + case STORE_IN_RAM: val=1; printf(" Setting Read out Flag: Store in Ram\n"); break; + case CONTINOUS_RO: val=0; printf(" Setting Read out Flag: Continuous Readout\n"); break; + + default: + cprintf(RED,"Cannot set unknown readout flag. 0x%x\n", val); + return -1; + } + printf(" Setting store in ram variable: %d\n",val); + eiger_storeinmem = val; + + } + } + + switch(eiger_readoutmode){ + case E_PARALLEL: retval=PARALLEL; break; + case E_NON_PARALLEL: retval=NONPARALLEL; break; + case E_SAFE: retval=SAFE; break; + } + + switch(eiger_storeinmem){ + case 0: retval|=CONTINOUS_RO; break; + case 1: retval|=STORE_IN_RAM; break; + } + printf("Read out Flag: 0x%x\n",retval); + return retval; +} + + + + + + + + +/* parameters - timer */ + +int64_t setTimer(enum timerIndex ind, int64_t val){ + + switch(ind){ + case FRAME_NUMBER: + if(val >= 0){ + printf(" Setting number of frames: %d * %d\n",(unsigned int)val,eiger_ncycles); + if(Feb_Control_SetNExposures((unsigned int)val*eiger_ncycles)){ + eiger_nexposures = val; + //SetDestinationParameters(EigerGetNumberOfExposures()*EigerGetNumberOfCycles()); + on_dst = 0; + int i; + for(i=0;i<32;i++) dst_requested[i] = 0; //clear dst requested + ndsts_in_use = 1; + nimages_per_request = eiger_nexposures * eiger_ncycles; + } + }return eiger_nexposures; + + case ACQUISITION_TIME: + if(val >= 0){ + printf(" Setting exp time: %fs\n",val/(1E9)); + Feb_Control_SetExposureTime(val/(1E9)); + } + return (Feb_Control_GetExposureTime()*(1E9)); + + case SUBFRAME_ACQUISITION_TIME: + if(val >= 0){ + printf(" Setting sub exp time: %lldns\n",(long long int)val/10); + Feb_Control_SetSubFrameExposureTime(val/10); + } + return (Feb_Control_GetSubFrameExposureTime()); + + + case FRAME_PERIOD: + if(val >= 0){ + printf(" Setting acq period: %fs\n",val/(1E9)); + Feb_Control_SetExposurePeriod(val/(1E9)); + } + return (Feb_Control_GetExposurePeriod()*(1E9)); + + case CYCLES_NUMBER: + if(val >= 0){ + printf(" Setting number of triggers: %d * %d\n",(unsigned int)val,eiger_nexposures); + if(Feb_Control_SetNExposures((unsigned int)val*eiger_nexposures)){ + eiger_ncycles = val; + //SetDestinationParameters(EigerGetNumberOfExposures()*EigerGetNumberOfCycles()); + on_dst = 0; + int i; + for(i=0;i<32;i++) dst_requested[i] = 0; //clear dst requested + nimages_per_request = eiger_nexposures * eiger_ncycles; + } + }return eiger_ncycles; + default: + cprintf(RED,"Warning: Timer Index not implemented for this detector: %d\n", ind); + break; + } + + return -1; +} + + + + + +/* parameters - channel, chip, module, settings */ + + +int setModule(sls_detector_module myMod, int delay){ + int retval[2]; + int i; + + //#ifdef VERBOSE + printf("Setting module with settings %d\n",myMod.reg); + //#endif + + setSettings( (enum detectorSettings)myMod.reg,-1); + + if(setIODelay(delay, -1)!= delay){ + cprintf(RED,"could not set iodelay %d\n",delay); + return FAIL; + } + + //copy module locally + if (detectorModules) + copyModule(detectorModules,&myMod); + + //set dac values + for(i=0;ichanregs[ich++]=tt[ip++]; + } + if (ichip<3) { + ip++; + ip++; + } + } + } + + //copy to local copy as well + if (detectorModules) + copyModule(myMod,detectorModules); + else + return FAIL; + return OK; +} + + + +enum detectorSettings setSettings(enum detectorSettings sett, int imod){ + if(sett == UNINITIALIZED){ + return thisSettings; + }if(sett != GET_SETTINGS) + thisSettings = sett; + printf(" Settings: %d\n", thisSettings); + return thisSettings; +} + +enum detectorSettings getSettings(){ + return thisSettings; +} + + + + + + +/* parameters - threshold */ + +int getThresholdEnergy(int imod){ + printf(" Getting Threshold energy\n"); + return eiger_photonenergy; +} + + +int setThresholdEnergy(int ev, int imod){ + printf(" Setting threshold energy:%d\n",ev); + if(ev >= 0) + eiger_photonenergy = ev; + return getThresholdEnergy(imod); +} + + + + + +/* parameters - dac, adc, hv */ + +void setDAC(enum DACINDEX ind, int val, int imod, int mV, int retval[]){ if(ind == VTHRESHOLD){ int ret[5]; @@ -438,27 +702,7 @@ void setDAC(enum detDacIndex ind, int val, int imod, int mV, int retval[]){ -int setHighVoltage(int val, int imod){ - if(val!=-1){ - eiger_highvoltage = val; - if(master){ - int ret = Feb_Control_SetHighVoltage(val); - if(!ret) //could not set - return -2; - else if (ret == -1) //outside range - return -1; - } - } - - if(master && !Feb_Control_GetHighVoltage(&eiger_highvoltage)){ - cprintf(RED,"Warning: Could not read high voltage\n"); - return -3; - } - return eiger_highvoltage; -} - - -int getADC(enum detAdcIndex ind, int imod){ +int getADC(enum ADCINDEX ind, int imod){ int retval = -1; char tempnames[6][20]={"FPGA EXT", "10GE","DCDC", "SODL", "SODR", "FPGA"}; char cstore[255]; @@ -494,6 +738,155 @@ int getADC(enum detAdcIndex ind, int imod){ } +int setHighVoltage(int val){ + if(val!=-1){ + eiger_highvoltage = val; + if(master){ + int ret = Feb_Control_SetHighVoltage(val); + if(!ret) //could not set + return -2; + else if (ret == -1) //outside range + return -1; + } + } + + if(master && !Feb_Control_GetHighVoltage(&eiger_highvoltage)){ + cprintf(RED,"Warning: Could not read high voltage\n"); + return -3; + } + return eiger_highvoltage; +} + + + + + + + +/* parameters - timing, extsig */ + +enum externalCommunicationMode setTiming( enum externalCommunicationMode arg){ + enum externalCommunicationMode ret=GET_EXTERNAL_COMMUNICATION_MODE; + if(arg != GET_EXTERNAL_COMMUNICATION_MODE){ + switch((int)arg){ + case AUTO_TIMING: ret = 0; break; + case TRIGGER_EXPOSURE: ret = 2; break; + case BURST_TRIGGER: ret = 1; break; + case GATE_FIX_NUMBER: ret = 3; break; + } + printf(" Setting Triggering Mode: %d\n",(int)ret); + if(Feb_Control_SetTriggerMode(ret,1)) + eiger_triggermode = ret; + } + + ret = eiger_triggermode; + switch((int)ret){ + case 0: ret = AUTO_TIMING; break; + case 2: ret = TRIGGER_EXPOSURE; break; + case 1: ret = BURST_TRIGGER; break; + case 3: ret = GATE_FIX_NUMBER; break; + default: + printf("Unknown trigger mode found %d\n",ret); + ret = 0; + } + return ret; +} + + + + + + +/* configure mac */ + +int configureMAC(uint32_t destip, uint64_t destmac, uint64_t sourcemac, uint32_t sourceip, uint32_t udpport, uint32_t udpport2, int ival) { + if (sourcemac != getDetectorMAC()){ + printf("*************************************************\n"); + printf("WARNING: actual detector mac address %llx does not match the one from client %llx\n",getDetectorMAC(),sourcemac); + sourcemac = getDetectorMAC(); + printf("WARNING: Matched detectormac to the hardware mac now\n"); + printf("*************************************************\n"); + } + //only for 1Gbe + if(!send_to_ten_gig){ + if (sourceip != getDetectorIP()){ + printf("*************************************************\n"); + printf("WARNING: actual detector ip address %x does not match the one from client %x\n",getDetectorIP(),sourceip); + sourceip = getDetectorIP(); + printf("WARNING: Matched detector ip to the hardware ip now\n"); + printf("*************************************************\n"); + } + } + + char src_mac[50], src_ip[50],dst_mac[50], dst_ip[50]; + int src_port = 0xE185; + sprintf(src_ip,"%d.%d.%d.%d",(sourceip>>24)&0xff,(sourceip>>16)&0xff,(sourceip>>8)&0xff,(sourceip)&0xff); + sprintf(dst_ip,"%d.%d.%d.%d",(destip>>24)&0xff,(destip>>16)&0xff,(destip>>8)&0xff,(destip)&0xff); + sprintf(src_mac,"%02x:%02x:%02x:%02x:%02x:%02x",(unsigned int)((sourcemac>>40)&0xFF), + (unsigned int)((sourcemac>>32)&0xFF), + (unsigned int)((sourcemac>>24)&0xFF), + (unsigned int)((sourcemac>>16)&0xFF), + (unsigned int)((sourcemac>>8)&0xFF), + (unsigned int)((sourcemac>>0)&0xFF)); + sprintf(dst_mac,"%02x:%02x:%02x:%02x:%02x:%02x",(unsigned int)((destmac>>40)&0xFF), + (unsigned int)((destmac>>32)&0xFF), + (unsigned int)((destmac>>24)&0xFF), + (unsigned int)((destmac>>16)&0xFF), + (unsigned int)((destmac>>8)&0xFF), + (unsigned int)((destmac>>0)&0xFF)); + + printf("src_port:%d\n",src_port); + printf("src_ip:%s\n",src_ip); + printf("dst_ip:%s\n",dst_ip); + printf("src_mac:%s\n",src_mac); + printf("dst_mac:%s\n",dst_mac); + + + int beb_num = BEB_NUM;//Feb_Control_GetModuleNumber(); + int header_number = 0; + int dst_port = udpport; + if(!top) + dst_port = udpport2; + + printf("dst_port:%d\n\n",dst_port); + + int i=0; + /* for(i=0;i<32;i++){ modified for Aldo*/ + if(Beb_SetBebSrcHeaderInfos(beb_num,send_to_ten_gig,src_mac,src_ip,src_port) && + Beb_SetUpUDPHeader(beb_num,send_to_ten_gig,header_number+i,dst_mac,dst_ip, dst_port)) + printf("set up left ok\n"); + else return -1; + /*}*/ + + header_number = 32; + dst_port = udpport2; + if(!top) + dst_port = udpport; + printf("dst_port:%d\n\n",dst_port); + + /*for(i=0;i<32;i++){*//** modified for Aldo*/ + if(Beb_SetBebSrcHeaderInfos(beb_num,send_to_ten_gig,src_mac,src_ip,src_port) && + Beb_SetUpUDPHeader(beb_num,send_to_ten_gig,header_number+i,dst_mac,dst_ip, dst_port)) + printf("set up right ok\n\n"); + else return -1; + /*}*/ + + on_dst = 0; + + for(i=0;i<32;i++) dst_requested[i] = 0; //clear dst requested + nimages_per_request=eiger_nexposures * eiger_ncycles; + + return 0; +} + + + + + + + +/* eiger specific - iodelay, 10g, pulse, rate, temp, activate, delay nw parameter */ + int setIODelay(int val, int imod){ if(val!=-1){ printf(" Setting IO Delay: %d\n",val); @@ -608,6 +1001,11 @@ int getDefaultSettingsTau_in_nsec(){ return default_tau_from_file; } +void setDefaultSettingsTau_in_nsec(int t){ + default_tau_from_file = t; + printf("Default tau set to %d\n",default_tau_from_file); +} + int64_t getCurrentTau(){ if(!getRateCorrectionEnable()) return 0; @@ -615,175 +1013,62 @@ int64_t getCurrentTau(){ return Feb_Control_Get_RateTable_Tau_in_nsec(); } -void setDefaultSettingsTau_in_nsec(int t){ - default_tau_from_file = t; +void setExternalGating(int enable[]){ + if(enable>=0){ + Feb_Control_SetExternalEnableMode(enable[0], enable[1]);//enable = 0 or 1, polarity = 0 or 1 , where 1 is positive + eiger_extgating = enable[0]; + eiger_extgatingpolarity = enable[1]; + } + enable[0] = eiger_extgating; + enable[1] = eiger_extgatingpolarity; } -int setModule(sls_detector_module myMod, int* gain, int* offset,int* delay){ - int retval[2]; - int i; - - //#ifdef VERBOSE - printf("Setting module with settings %d\n",myMod.reg); - //#endif - - //set the settings variable - setSettings( (enum detectorSettings)myMod.reg,-1); - - //set the gains and offset variables locally - for(i=0;i=0){ - detectorGain[i] = gain[i]; - printf("gain[%d]:%d\n",i,detectorGain[i]); - }else cprintf(RED,"gain not changed\n"); - } - for(i=0;i=0){ - detectorOffset[i] = offset[i]; - printf("offset[%d]:%d\n",i,detectorOffset[i]); - }else cprintf(RED,"offset not changed\n"); - } - - if(setIODelay(*delay, -1)!= (*delay)){ - cprintf(RED,"could not set iodelay %d\n",*delay); +int setAllTrimbits(int val){ + int ichan; + if(!Feb_Control_SaveAllTrimbitsTo(val)){ + cprintf(RED,"error in setting all trimbits to value\n"); return FAIL; - } - - //copy module locally - if (detectorModules) - copyModule(detectorModules,&myMod); - - //set dac values - for(i=0;ireg,val); +#endif + if (detectorModules){ + for (ichan=0; ichan<(detectorModules->nchan); ichan++) { + *((detectorModules->chanregs)+ichan)=val; } } } - - //set trimbits - if(!Feb_Control_SetTrimbits(Feb_Control_GetModuleNumber(),tt)){ - cprintf(BG_RED,"Could not set trimbits\n"); - return FAIL; - } - - return thisSettings; -} - - -int getModule(sls_detector_module *myMod, int* gain, int* offset){ - int i; - int retval[2]; - //printf("get gainval[0]:%d\n",detectorGain[0]); - - //dacs - for(i=0;ichanregs[ich++]=tt[ip++]; - } - if (ichip<3) { - ip++; - ip++; - } - } - } - - //copy to local copy as well - if (detectorModules) - copyModule(myMod,detectorModules); - else - return FAIL; return OK; } +int getAllTrimbits(){ + return *((detectorModules->chanregs)); +} +int getBebFPGATemp(){ + return Beb_GetBebFPGATemp(); +} +int activate(int enable){ + int ret = Beb_Activate(enable); + Feb_Control_activate(ret); + return ret; +} - - -int getThresholdEnergy(int imod){ - printf(" Getting Threshold energy\n"); - return eiger_photonenergy; +int setNetworkParameter(enum NETWORKINDEX mode, int value){ + return Beb_SetNetworkParameter(mode, value); } -int setThresholdEnergy(int ev, int imod){ - printf(" Setting threshold energy:%d\n",ev); - int retval[2],i; - int thrvalue[NGAIN]; - int average=0; - if(ev >= 0) { - enum detDacIndex ind[NGAIN]={VCMP_LL,VCMP_LR,VCMP_RL, VCMP_RR}; - const char* vcmp[4]={"vcmp_ll","vcmp_lr","vcmp_rl","vcmp_rr"}; - int valid=0; - - //calculate thrvalues for dacs - for(i=0;i=0 && thrvalue[i]<2001)valid++; - }//ngains - if( valid == NGAIN){ - eiger_photonenergy = ev; - for(i=0;i= 0){ - printf(" Setting number of frames: %d * %d\n",(unsigned int)val,eiger_ncycles); - if(Feb_Control_SetNExposures((unsigned int)val*eiger_ncycles)){ - eiger_nexposures = val; - //SetDestinationParameters(EigerGetNumberOfExposures()*EigerGetNumberOfCycles()); - on_dst = 0; - int i; - for(i=0;i<32;i++) dst_requested[i] = 0; //clear dst requested - ndsts_in_use = 1; - nimages_per_request = eiger_nexposures * eiger_ncycles; - } - }return eiger_nexposures; - - case ACQUISITION_TIME: - if(val >= 0){ - printf(" Setting exp time: %fs\n",val/(1E9)); - Feb_Control_SetExposureTime(val/(1E9)); - } - return (Feb_Control_GetExposureTime()*(1E9)); - - case SUBFRAME_ACQUISITION_TIME: - if(val >= 0){ - printf(" Setting sub exp time: %lldns\n",(long long int)val/10); - Feb_Control_SetSubFrameExposureTime(val/10); - } - return (Feb_Control_GetSubFrameExposureTime()); - - - case FRAME_PERIOD: - if(val >= 0){ - printf(" Setting acq period: %fs\n",val/(1E9)); - Feb_Control_SetExposurePeriod(val/(1E9)); - } - return (Feb_Control_GetExposurePeriod()*(1E9)); - /* case DELAY_AFTER_TRIGGER: - if(val >= 0) - EigerSetNumberOfExposures((unsigned int)val); - return EigerGetNumberOfExposures(); - - case GATES_NUMBER: - if(val >= 0) - EigerSetNumberOfGates((unsigned int)val); - return EigerGetNumberOfGates(); - - case PROBES_NUMBER: - if(val >= 0) - EigerSetNumberOfExposures((unsigned int)val); - return EigerGetNumberOfExposures();*/ - case CYCLES_NUMBER: - if(val >= 0){ - printf(" Setting number of triggers: %d * %d\n",(unsigned int)val,eiger_nexposures); - if(Feb_Control_SetNExposures((unsigned int)val*eiger_nexposures)){ - eiger_ncycles = val; - //SetDestinationParameters(EigerGetNumberOfExposures()*EigerGetNumberOfCycles()); - on_dst = 0; - int i; - for(i=0;i<32;i++) dst_requested[i] = 0; //clear dst requested - nimages_per_request = eiger_nexposures * eiger_ncycles; - } - }return eiger_ncycles; - default: - printf("unknown timer index: %d\n",ind); - break; - } - - return -1; -} - - - - -int64_t getTimeLeft(enum timerIndex ind){ - - return -1; -} - - - -int setDynamicRange(int dr){ - if(dr > 0){ - printf(" Setting dynamic range: %d\n",dr); - if(Feb_Control_SetDynamicRange(dr)){ - - //EigerSetBitMode(dr); - on_dst = 0; - int i; - for(i=0;i<32;i++) dst_requested[i] = 0; //clear dst requested - if(Beb_SetUpTransferParameters(dr)) - eiger_dynamicrange = dr; - else printf("ERROR:Could not set bit mode in the back end\n"); - } - } - //make sure back end and front end have the same bit mode - dr= Feb_Control_GetDynamicRange(); - - return dr; -} - - - -enum readOutFlags setReadOutFlags(enum readOutFlags val){ - - enum readOutFlags retval = GET_READOUT_FLAGS; - if(val!=GET_READOUT_FLAGS){ - - - if(val&0xF0000){ - switch(val){ - case PARALLEL: val=E_PARALLEL; printf(" Setting Read out Flag: Parallel\n"); break; - case NONPARALLEL: val=E_NON_PARALLEL; printf(" Setting Read out Flag: Non Parallel\n"); break; - case SAFE: val=E_SAFE; printf(" Setting Read out Flag: Safe\n"); break; - - default: - cprintf(RED,"Cannot set unknown readout flag. 0x%x\n", val); - return -1; - } - printf(" Setting Read out Flag: %d\n",val); - if(Feb_Control_SetReadoutMode(val)) - eiger_readoutmode = val; - else return -1; - - }else{ - switch(val){ - case STORE_IN_RAM: val=1; printf(" Setting Read out Flag: Store in Ram\n"); break; - case CONTINOUS_RO: val=0; printf(" Setting Read out Flag: Continuous Readout\n"); break; - - default: - cprintf(RED,"Cannot set unknown readout flag. 0x%x\n", val); - return -1; - } - printf(" Setting store in ram variable: %d\n",val); - eiger_storeinmem = val; - - } - } - - switch(eiger_readoutmode){ - case E_PARALLEL: retval=PARALLEL; break; - case E_NON_PARALLEL: retval=NONPARALLEL; break; - case E_SAFE: retval=SAFE; break; - } - - switch(eiger_storeinmem){ - case 0: retval|=CONTINOUS_RO; break; - case 1: retval|=STORE_IN_RAM; break; - } - printf("Read out Flag: 0x%x\n",retval); - return retval; -} - - - - -int setROI(int n, ROI arg[], int *retvalsize, int *ret){ - return FAIL; -} - - - -int setSpeed(enum speedVariable arg, int val){ - if(val != -1){ - printf(" Setting Read out Speed: %d\n",val); - if(Feb_Control_SetReadoutSpeed(val)) - eiger_readoutspeed = val; - } - return eiger_readoutspeed; -} - - - -int executeTrimming(enum trimMode mode, int par1, int par2, int imod){ - return FAIL; -} - - -int configureMAC(int ipad, long long int macad, long long int detectormacadd, int detipad, int udpport, int udpport2, int ival){ - if (detectormacadd != getDetectorMAC()){ - printf("*************************************************\n"); - printf("WARNING: actual detector mac address %llx does not match the one from client %llx\n",getDetectorMAC(),detectormacadd); - detectormacadd = getDetectorMAC(); - printf("WARNING: Matched detectormac to the hardware mac now\n"); - printf("*************************************************\n"); - } - //only for 1Gbe - if(!send_to_ten_gig){ - if (detipad != getDetectorIP()){ - printf("*************************************************\n"); - printf("WARNING: actual detector ip address %x does not match the one from client %x\n",getDetectorIP(),detipad); - detipad = getDetectorIP(); - printf("WARNING: Matched detector ip to the hardware ip now\n"); - printf("*************************************************\n"); - } - } - - char src_mac[50], src_ip[50],dst_mac[50], dst_ip[50]; - int src_port = 0xE185; - sprintf(src_ip,"%d.%d.%d.%d",(detipad>>24)&0xff,(detipad>>16)&0xff,(detipad>>8)&0xff,(detipad)&0xff); - sprintf(dst_ip,"%d.%d.%d.%d",(ipad>>24)&0xff,(ipad>>16)&0xff,(ipad>>8)&0xff,(ipad)&0xff); - sprintf(src_mac,"%02x:%02x:%02x:%02x:%02x:%02x",(unsigned int)((detectormacadd>>40)&0xFF), - (unsigned int)((detectormacadd>>32)&0xFF), - (unsigned int)((detectormacadd>>24)&0xFF), - (unsigned int)((detectormacadd>>16)&0xFF), - (unsigned int)((detectormacadd>>8)&0xFF), - (unsigned int)((detectormacadd>>0)&0xFF)); - sprintf(dst_mac,"%02x:%02x:%02x:%02x:%02x:%02x",(unsigned int)((macad>>40)&0xFF), - (unsigned int)((macad>>32)&0xFF), - (unsigned int)((macad>>24)&0xFF), - (unsigned int)((macad>>16)&0xFF), - (unsigned int)((macad>>8)&0xFF), - (unsigned int)((macad>>0)&0xFF)); - - printf("src_port:%d\n",src_port); - printf("src_ip:%s\n",src_ip); - printf("dst_ip:%s\n",dst_ip); - printf("src_mac:%s\n",src_mac); - printf("dst_mac:%s\n",dst_mac); - - - int beb_num = BEB_NUM;//Feb_Control_GetModuleNumber(); - int header_number = 0; - int dst_port = udpport; - if(!top) - dst_port = udpport2; - - printf("dst_port:%d\n\n",dst_port); - - int i=0; - /* for(i=0;i<32;i++){ modified for Aldo*/ - if(Beb_SetBebSrcHeaderInfos(beb_num,send_to_ten_gig,src_mac,src_ip,src_port) && - Beb_SetUpUDPHeader(beb_num,send_to_ten_gig,header_number+i,dst_mac,dst_ip, dst_port)) - printf("set up left ok\n"); - else return -1; - /*}*/ - - header_number = 32; - dst_port = udpport2; - if(!top) - dst_port = udpport; - printf("dst_port:%d\n\n",dst_port); - - /*for(i=0;i<32;i++){*//** modified for Aldo*/ - if(Beb_SetBebSrcHeaderInfos(beb_num,send_to_ten_gig,src_mac,src_ip,src_port) && - Beb_SetUpUDPHeader(beb_num,send_to_ten_gig,header_number+i,dst_mac,dst_ip, dst_port)) - printf("set up right ok\n\n"); - else return -1; - /*}*/ - - on_dst = 0; - - for(i=0;i<32;i++) dst_requested[i] = 0; //clear dst requested - nimages_per_request=eiger_nexposures * eiger_ncycles; - - return 0; -} - - -int calculateDataBytes(){ - if(send_to_ten_gig) - return setDynamicRange(-1)*16*TEN_GIGA_BUFFER_SIZE; - else - return setDynamicRange(-1)*16*ONE_GIGA_BUFFER_SIZE; -} +/* common */ int copyModule(sls_detector_module *destMod, sls_detector_module *srcMod){ @@ -1250,15 +1269,22 @@ int copyModule(sls_detector_module *destMod, sls_detector_module *srcMod){ } +int calculateDataBytes(){ + if(send_to_ten_gig) + return setDynamicRange(-1) * ONE_GIGA_CONSTANT * TEN_GIGA_BUFFER_SIZE; + else + return setDynamicRange(-1) * TEN_GIGA_CONSTANT * ONE_GIGA_BUFFER_SIZE; +} -int getTotalNumberOfChannels(){return getNumberOfChannelsPerModule();} -int getTotalNumberOfChips(){return NCHIP;} -int getTotalNumberOfModules(){return 1;} -int getNumberOfChannelsPerChip(){return NCHAN;} -int getNumberOfChannelsPerModule(){return getNumberOfChannelsPerChip() * getTotalNumberOfChips();} + +int getTotalNumberOfChannels(){return ((int)getNumberOfChannelsPerModule() * (int)getTotalNumberOfModules);} +int getTotalNumberOfChips(){return ((int)getNumberOfChipsPerModule * (int)getTotalNumberOfModules);} +int getTotalNumberOfModules(){return NMOD;} +int getNumberOfChannelsPerModule(){return ((int)getNumberOfChannelsPerChip() * (int)getTotalNumberOfChips());} int getNumberOfChipsPerModule(){return NCHIP;} int getNumberOfDACsPerModule(){return NDAC;} int getNumberOfADCsPerModule(){return NADC;} +int getNumberOfChannelsPerChip(){return NCHAN;} int getNumberOfGainsPerModule(){return NGAIN;} int getNumberOfOffsetsPerModule(){return NOFFSET;} @@ -1266,66 +1292,10 @@ int getNumberOfOffsetsPerModule(){return NOFFSET;} -enum externalSignalFlag getExtSignal(int signalindex){ - return GET_EXTERNAL_SIGNAL_FLAG; -} - - - - - -enum externalSignalFlag setExtSignal(int signalindex, enum externalSignalFlag flag){ - return getExtSignal(signalindex); -} - - - - - - -enum externalCommunicationMode setTiming( enum externalCommunicationMode arg){ - enum externalCommunicationMode ret=GET_EXTERNAL_COMMUNICATION_MODE; - if(arg != GET_EXTERNAL_COMMUNICATION_MODE){ - switch((int)arg){ - case AUTO_TIMING: ret = 0; break; - case TRIGGER_EXPOSURE: ret = 2; break; - case BURST_TRIGGER: ret = 1; break; - case GATE_FIX_NUMBER: ret = 3; break; - } - printf(" Setting Triggering Mode: %d\n",(int)ret); - if(Feb_Control_SetTriggerMode(ret,1)) - eiger_triggermode = ret; - } - - ret = eiger_triggermode; - switch((int)ret){ - case 0: ret = AUTO_TIMING; break; - case 2: ret = TRIGGER_EXPOSURE; break; - case 1: ret = BURST_TRIGGER; break; - case 3: ret = GATE_FIX_NUMBER; break; - default: - printf("Unknown trigger mode found %d\n",ret); - ret = 0; - } - return ret; -} - - -void setExternalGating(int enable[]){ - if(enable>=0){ - Feb_Control_SetExternalEnableMode(enable[0], enable[1]);//enable = 0 or 1, polarity = 0 or 1 , where 1 is positive - eiger_extgating = enable[0]; - eiger_extgatingpolarity = enable[1]; - } - enable[0] = eiger_extgating; - enable[1] = eiger_extgatingpolarity; -} +/* sync */ enum masterFlags setMaster(enum masterFlags arg){ - //if(arg != GET_MASTER) - // masterMode = arg; - return NO_MASTER; } @@ -1335,38 +1305,10 @@ enum synchronizationMode setSynchronization(enum synchronizationMode arg){ return NO_SYNCHRONIZATION; } -void setAllTrimbits(int val){ - int ichan; - if(Feb_Control_SaveAllTrimbitsTo(val)){ -#ifdef VERBOSE - printf("Copying register %x value %d\n",destMod->reg,val); -#endif - if (detectorModules){ - for (ichan=0; ichan<(detectorModules->nchan); ichan++) { - *((detectorModules->chanregs)+ichan)=val; - } - } - }else printf("error in setting all trimbits to value\n"); -} - -int getAllTrimbits(){ - return *((detectorModules->chanregs)); -} - -int getBebFPGATemp(){ - return Beb_GetBebFPGATemp(); -} -int activate(int enable){ - int ret = Beb_Activate(enable); - Feb_Control_activate(ret); - return ret; -} -int setNetworkParameter(enum detNetworkParameter mode, int value){ - return Beb_SetNetworkParameter(mode, value); -} + #endif diff --git a/slsDetectorSoftware/eigerDetectorServer/slsDetectorServer_defs.h b/slsDetectorSoftware/eigerDetectorServer/slsDetectorServer_defs.h index 9ddfea71b..1847b84d0 100644 --- a/slsDetectorSoftware/eigerDetectorServer/slsDetectorServer_defs.h +++ b/slsDetectorSoftware/eigerDetectorServer/slsDetectorServer_defs.h @@ -8,46 +8,81 @@ #ifndef SLSDETECTORSERVER_DEFS_H_ #define SLSDETECTORSERVER_DEFS_H_ -//#include "sls_detector_defs.h" +#include "sls_detector_defs.h" #include -#define GOODBYE -200 +#define GOODBYE (-200) +#define REQUIRED_FIRMWARE_VERSION (16) -#define FEB_PORT 43210 -#define BEB_PORT 43212 - -#define REQUIRED_FIRMWARE_VERSION 16 - -#define FIRMWAREREV 0xcaba //temporary should be in firmware +/* Enums */ +enum CLK_SPEED_INDEX {FULL_SPEED, HALF_SPEED, QUARTER_SPEED}; +enum DACINDEX {SVP,VTR,VRF,VRS,SVN,VTGSTV,VCMP_LL,VCMP_LR,CAL,VCMP_RL,RXB_RB,RXB_LB,VCMP_RR,VCP,VCN,VIS,VTHRESHOLD}; +#define DEFAULT_DAC_VALS { \ + 0, /* SvP */ \ + 2480, /* Vtr */ \ + 3300, /* Vrf */ \ + 1400, /* Vrs */ \ + 4000, /* SvN */ \ + 2556, /* Vtgstv */ \ + 1000, /* Vcmp_ll */ \ + 1000, /* Vcmp_lr */ \ + 4000, /* cal */ \ + 1000, /* Vcmp_rl */ \ + 1100, /* rxb_rb */ \ + 1100, /* rxb_lb */ \ + 1000, /* Vcmp_rr */ \ + 1000, /* Vcp */ \ + 2000, /* Vcn */ \ + 1550 /* Vis */ \ + }; +enum ADCINDEX {TEMP_FPGAEXT, TEMP_10GE, TEMP_DCDC, TEMP_SODL, TEMP_SODR, TEMP_FPGA, TEMP_FPGAFEBL, TEMP_FPGAFEBR}; +enum NETWORKINDEX {TXN_LEFT, TXN_RIGHT, TXN_FRAME,FLOWCTRL_10G}; -#define NCHAN 256*256 -#define NCHIP 4 -#define NDAC 16 -#define NADC 0 -#define NGAIN 4 -#define NOFFSET 4 - -#define NMAXMODX 1 -#define NMAXMODY 1 -#define NMAXMOD NMAXMODX*NMAXMODY -#define NCHANS NCHAN*NCHIP*NMAXMOD -#define NDACS NDAC*NMAXMOD +/* Hardware Definitions */ +#define NMAXMOD (1) +#define NMOD (1) +#define NCHAN (256 * 256) +#define NCHIP (4) +#define NADC (0) +#define NDAC (16) +#define NGAIN (0) +#define NOFFSET (0) -#define DYNAMIC_RANGE 16 +#define TEN_GIGA_BUFFER_SIZE (4112) +#define ONE_GIGA_BUFFER_SIZE (1040) +#define TEN_GIGA_CONSTANT (4) +#define ONE_GIGA_CONSTANT (16) +#define NORMAL_HIGHVOLTAGE_INPUTPORT "/sys/class/hwmon/hwmon5/device/in0_input" +#define NORMAL_HIGHVOLTAGE_OUTPUTPORT "/sys/class/hwmon/hwmon5/device/out0_output" +#define SPECIAL9M_HIGHVOLTAGE_PORT "/dev/ttyS1" +#define SPECIAL9M_HIGHVOLTAGE_BUFFERSIZE (16) + +/** Default Parameters */ +#define DEFAULT_MOD_INDEX (0) +#define DEFAULT_NUM_FRAMES (1) +#define DEFAULT_NUM_CYCLES (1) +#define DEFAULT_EXPTIME (1E9) //ns +#define DEFAULT_PERIOD (1E9) //ns +#define DEFAULT_DELAY (0) +#define DEFAULT_HIGH_VOLTAGE (0) +#define DEFAULT_SETTINGS (DYNAMICGAIN) +#define DEFAULT_SUBFRAME_EXPOSURE_VAL (2621440) // 2.6ms +#define DEFAULT_DYNAMIC_RANGE (16) +#define DEFAULT_READOUT_FLAG (NONPARALLEL) +#define DEFAULT_CLK_SPEED (HALF_SPEED) +#define DEFAULT_IO_DELAY (650) +#define DEFAULT_TIMING_MODE (AUTO_TIMING) +#define DEFAULT_PHOTON_ENERGY (-1) +#define DEFAULT_RATE_CORRECTION (0) +#define DEFAULT_EXT_GATING_ENABLE (0) +#define DEFAULT_EXT_GATING_POLARITY (1) //positive +#define DEFAULT_TEST_MODE (0) +#define DEFAULT_HIGH_VOLTAGE (0) -enum detDacIndex{SVP,VTR,VRF,VRS,SVN,VTGSTV,VCMP_LL,VCMP_LR,CAL,VCMP_RL,RXB_RB,RXB_LB,VCMP_RR,VCP,VCN,VIS,VTHRESHOLD}; - -enum detAdcIndex{TEMP_FPGAEXT, TEMP_10GE, TEMP_DCDC, TEMP_SODL, TEMP_SODR, TEMP_FPGA, TEMP_FPGAFEBL, TEMP_FPGAFEBR}; - -enum detNetworkParameter{TXN_LEFT, TXN_RIGHT, TXN_FRAME,FLOWCTRL_10G}; - -#define NORMAL_HIGHVOLTAGE_INPUTPORT "/sys/class/hwmon/hwmon5/device/in0_input" -#define NORMAL_HIGHVOLTAGE_OUTPUTPORT "/sys/class/hwmon/hwmon5/device/out0_output" -#define SPECIAL9M_HIGHVOLTAGE_PORT "/dev/ttyS1" -#define SPECIAL9M_HIGHVOLTAGE_BUFFERSIZE 16 +#define MAX_SUBFRAME_EXPOSURE_VAL_IN_10NS (0x1FFFFFFF) /** 29 bit register for max subframe exposure value */ diff --git a/slsDetectorSoftware/gitInfo.txt b/slsDetectorSoftware/gitInfo.txt index e0d45202f..c99343e29 100644 --- a/slsDetectorSoftware/gitInfo.txt +++ b/slsDetectorSoftware/gitInfo.txt @@ -1,9 +1,9 @@ Path: slsDetectorsPackage/slsDetectorSoftware URL: origin git@git.psi.ch:sls_detectors_software/sls_detector_software.git Repository Root: origin git@git.psi.ch:sls_detectors_software/sls_detector_software.git -Repsitory UUID: 230d6b36e9852214f4ba5ae7c92647f35000b24d -Revision: 1313 +Repsitory UUID: 6d38c0622a2936f70345e7d53aaf1c9e2de4cbd6 +Revision: 1401 Branch: developer Last Changed Author: Dhanya_Maliakal -Last Changed Rev: 1313 -Last Changed Date: 2016-11-30 10:36:34 +0100 +Last Changed Rev: 1401 +Last Changed Date: 2017-06-12 18:53:18 +0200 diff --git a/slsDetectorSoftware/gotthardDetectorServer/server_funcs.c b/slsDetectorSoftware/gotthardDetectorServer/server_funcs.c index 775cb9de1..b7ee31dd6 100755 --- a/slsDetectorSoftware/gotthardDetectorServer/server_funcs.c +++ b/slsDetectorSoftware/gotthardDetectorServer/server_funcs.c @@ -189,8 +189,8 @@ int function_table() { flist[F_SET_SYNCHRONIZATION_MODE]=&set_synchronization; flist[F_READ_COUNTER_BLOCK]=&read_counter_block; flist[F_RESET_COUNTER_BLOCK]=&reset_counter_block; - flist[F_START_RECEIVER]=&start_receiver; - flist[F_STOP_RECEIVER]=&stop_receiver; + flist[F_PREPARE_ACQUISITION]=&start_receiver; + flist[F_CLEANUP_ACQUISITION]=&stop_receiver; flist[F_CALIBRATE_PEDESTAL]=&calibrate_pedestal; return OK; } diff --git a/slsDetectorSoftware/jungfrauDetectorServer/.gitignore b/slsDetectorSoftware/jungfrauDetectorServer/.gitignore deleted file mode 100644 index 0173208ed..000000000 --- a/slsDetectorSoftware/jungfrauDetectorServer/.gitignore +++ /dev/null @@ -1 +0,0 @@ -*.gdb diff --git a/slsDetectorSoftware/jungfrauDetectorServer/.target-makefrag b/slsDetectorSoftware/jungfrauDetectorServer/.target-makefrag deleted file mode 100755 index ce093ecac..000000000 --- a/slsDetectorSoftware/jungfrauDetectorServer/.target-makefrag +++ /dev/null @@ -1 +0,0 @@ -AXIS_BUILDTYPE ?= cris-axis-linux-gnu diff --git a/slsDetectorSoftware/jungfrauDetectorServer/Makefile b/slsDetectorSoftware/jungfrauDetectorServer/Makefile index 7e7dd500a..8ff6779c8 100755 --- a/slsDetectorSoftware/jungfrauDetectorServer/Makefile +++ b/slsDetectorSoftware/jungfrauDetectorServer/Makefile @@ -1,57 +1,26 @@ -# $Id: Makefile,v 1.1.1.1 2006/02/04 03:35:01 freza Exp $ -# first compile -# make cris-axis-linux-gnu +CROSS = bfin-uclinux- +CC = $(CROSS)gcc +CFLAGS += -Wall -DJUNGFRAUD -DSLS_DETECTOR_FUNCTION_LIST -DDACS_INT -DSTOP_SERVER #-DVERBOSEI #-DVERBOSE +LDLIBS += -lm -lstdc++ +PROGS = jungfrauDetectorServer +DESTDIR ?= bin +INSTMODE = 0777 -CROSS = bfin-uclinux- -CC = $(CROSS)gcc +SRC_CLNT = communication_funcs.c slsDetectorServer.c slsDetectorServer_funcs.c slsDetectorFunctionList.c +OBJS = $(SRC_CLNT:.c=.o) + +all: clean $(PROGS) -CFLAGS += -Wall -DJUNGFRAUD -DMCB_FUNCS -DDACS_INT -DDEBUG -DV1 #-DVERBOSE #-DVERYVERBOSE #-DVIRTUAL +boot: $(OBJS) - -PROGS= jungfrauDetectorServer -INSTDIR= /tftpboot -INSTMODE= 0777 - - - -BINS = testlib_sharedlibc -SRCS = server.c server_funcs.c communication_funcs.c firmware_funcs.c mcb_funcs.c -OBJS = $(SRCS:%.c=%.o) - - - -all: clean $(PROGS) - -test: clean jungfrauADCTEst - -boot: $(OBJS) - -jungfrauDetectorServer: $(OBJS) - echo $(OBJS) - $(CC) $(CFLAGS) -o $@ $^ $(LDLIBS_$@) $(LDFLAGS_$@) - - -jungfrauADCTEst: $(OBJS) - echo $(OBJS) - $(CC) $(CFLAGS) -o $@ $^ $(LDLIBS_$@) $(LDFLAGS_$@) -DTESTADC - - - - -install: $(PROGS) - $(INSTALL) -d $(INSTDIR) - $(INSTALL) -m $(INSTMODE) $(PROGS) $(INSTDIR) - - -romfs: - $(ROMFSINST) /bin/$(PROGS) +$(PROGS): $(OBJS) + echo $(OBJS) + mkdir -p $(DESTDIR) + $(CC) -o $@ $^ $(CFLAGS) $(LDLIBS) + mv $(PROGS) $(DESTDIR) + rm *.gdb clean: - rm -rf $(PROGS) *.o *.gdb - - - - - - + rm -rf $(DESTDIR)/$(PROGS) *.o + diff --git a/slsDetectorSoftware/jungfrauDetectorServer/Makefile.virtual b/slsDetectorSoftware/jungfrauDetectorServer/Makefile.virtual old mode 100755 new mode 100644 index 38dd2537c..8ee348341 --- a/slsDetectorSoftware/jungfrauDetectorServer/Makefile.virtual +++ b/slsDetectorSoftware/jungfrauDetectorServer/Makefile.virtual @@ -1,30 +1,25 @@ +CC = gcc +CFLAGS += -Wall -DJUNGFRAUD -DSLS_DETECTOR_FUNCTION_LIST -DDACS_INT -DSTOP_SERVER #-DVERBOSEI #-DVERBOSE +LDLIBS += -lm -lstdc++ -DESTDIR ?= ./ +PROGS = jungfrauDetectorServer +DESTDIR ?= bin +INSTMODE = 0777 -CC = gcc -CFLAGS += -Wall -DMOENCHD -DMCB_FUNCS -DDACS_INT -DDEBUG -DVIRTUAL - - -PROGS= $(DESTDIR)/moenchVirtualServer - - -SRCS = server.c server_funcs.c communication_funcs.c firmware_funcs.c mcb_funcs.c trimming_funcs.c sharedmemory.c -OBJS = $(SRCS:%.c=%.o) - -moenchVirtualServer = $(PROGS) - -all: clean $(PROGS) +SRC_CLNT = communication_funcs.c slsDetectorServer.c slsDetectorServer_funcs.c slsDetectorFunctionList.c +OBJS = $(SRC_CLNT:.c=.o) + +all: clean $(PROGS) +boot: $(OBJS) $(PROGS): $(OBJS) - $(CC) $(CFLAGS) -o $@ $^ $(LDLIBS_$@) $(LDFLAGS_$@) - + echo $(OBJS) + mkdir -p $(DESTDIR) + $(CC) -o $@ $^ $(CFLAGS) $(LDLIBS) + mv $(PROGS) $(DESTDIR) + rm *.gdb clean: - rm -rf $(PROGS) *.o *.gdb - - - - - - + rm -rf $(DESTDIR)/$(PROGS) *.o + diff --git a/slsDetectorSoftware/jungfrauDetectorServer/README.txt b/slsDetectorSoftware/jungfrauDetectorServer/README.txt deleted file mode 100644 index 7785cee12..000000000 --- a/slsDetectorSoftware/jungfrauDetectorServer/README.txt +++ /dev/null @@ -1,11 +0,0 @@ -add the following to /etc/rc before using programfpga command before cat motd - - -#registering 7th and 9th pin to linux kernel -echo 7 > /sys/class/gpio/export -echo 9 > /sys/class/gpio/export -#define direction for the linux kernel -echo in > /sys/class/gpio/gpio7/direction -echo out > /sys/class/gpio/gpio9/direction -#needed, else all write errors when server starts up, because linux tries to take control fof gpio -echo 1 > /sys/class/gpio/gpio9/value diff --git a/slsDetectorSoftware/jungfrauDetectorServer/RegisterDefs.h b/slsDetectorSoftware/jungfrauDetectorServer/RegisterDefs.h new file mode 100644 index 000000000..50c1a3646 --- /dev/null +++ b/slsDetectorSoftware/jungfrauDetectorServer/RegisterDefs.h @@ -0,0 +1,338 @@ +#ifndef REGISTER_DEFS_H +#define REGISTER_DEFS_H + +/* Definitions for FPGA*/ +#define CSP0 0x20200000 +#define MEM_SIZE 0x100000 + +/* FPGA Version register */ +#define FPGA_VERSION_REG (0x00 << 11) + +#define BOARD_REVISION_OFST (0) +#define BOARD_REVISION_MSK (0x00FFFFFF << BOARD_REVISION_OFST) +#define DETECTOR_TYPE_OFST (24) +#define DETECTOR_TYPE_MSK (0x000000FF << DETECTOR_TYPE_OFST) + + + +/* Fix pattern register */ +#define FIX_PATT_REG (0x01 << 11) + +/* Status register */ +#define STATUS_REG (0x02 << 11) + +#define RUN_BUSY_OFST (0) +#define RUN_BUSY_MSK (0x00000001 << RUN_BUSY_OFST) +#define WAITING_FOR_TRIGGER_OFST (3) +#define WAITING_FOR_TRIGGER_MSK (0x00000001 << WAITING_FOR_TRIGGER_OFST) +#define DELAYBEFORE_OFST (4) //Not used in software +#define DELAYBEFORE_MSK (0x00000001 << DELAYBEFORE_OFST) //Not used in software +#define DELAYAFTER_OFST (5) //Not used in software +#define DELAYAFTER_MSK (0x00000001 << DELAYAFTER_OFST) //Not used in software +#define STOPPED_OFST (15) +#define STOPPED_MSK (0x00000001 << STOPPED_OFST) +#define RUNMACHINE_BUSY_OFST (17) +#define RUNMACHINE_BUSY_MSK (0x00000001 << RUNMACHINE_BUSY_OFST) + + +/* Look at me register */ +#define LOOK_AT_ME_REG (0x03 << 11) //Not used in firmware or software + +/* System Status register */ +#define SYSTEM_STATUS_REG (0x04 << 11) //Not used in software + +#define DDR3_CAL_DONE_OFST (0) //Not used in software +#define DDR3_CAL_DONE_MSK (0x00000001 << DDR3_CAL_DONE_OFST) //Not used in software +#define DDR3_CAL_FAIL_OFST (1) //Not used in software +#define DDR3_CAL_FAIL_MSK (0x00000001 << DDR3_CAL_FAIL_OFST) //Not used in software +#define DDR3_INIT_DONE_OFST (2) //Not used in software +#define DDR3_INIT_DONE_MSK (0x00000001 << DDR3_INIT_DONE_OFST) //Not used in software +#define RECONFIG_PLL_LCK_OFST (3) //Not used in software +#define RECONFIG_PLL_LCK_MSK (0x00000001 << RECONFIG_PLL_LCK_OFST) //Not used in software +#define PLL_A_LCK_OFST (4) //Not used in software +#define PLL_A_LCK_MSK (0x00000001 << PLL_A_LCK_OFST) //Not used in software +#define DD3_PLL_LCK_OFST (5) //Not used in software +#define DD3_PLL_LCK_MSK (0x00000001 << DD3_PLL_LCK_OFST) //Not used in software + + +/* Module Control Board Serial Number Register */ +#define MOD_SERIAL_NUM_REG (0x0A << 11) //Not used in software + +#define HARDWARE_SERIAL_NUM_OFST (0) //Not used in software +#define HARDWARE_SERIAL_NUM_MSK (0x000000FF << HARDWARE_SERIAL_NUM_OFST) //Not used in software +#define HARDWARE_VERSION_NUM_OFST (16) //Not used in software +#define HARDWARE_VERSION_NUM_MSK (0x0000003F << HARDWARE_VERSION_NUM_OFST) //Not used in software + + +/* Time from Start 64 bit register */ +#define TIME_FROM_START_LSB_REG (0x10 << 11) +#define TIME_FROM_START_MSB_REG (0x11 << 11) + +/* Get Delay 64 bit register */ +#define GET_DELAY_LSB_REG (0x12 << 11) +#define GET_DELAY_MSB_REG (0x13 << 11) + +/* Get Cycles 64 bit register */ +#define GET_CYCLES_LSB_REG (0x14 << 11) +#define GET_CYCLES_MSB_REG (0x15 << 11) + +/* Get Frames 64 bit register */ +#define GET_FRAMES_LSB_REG (0x16 << 11) +#define GET_FRAMES_MSB_REG (0x17 << 11) + +/* Get Period 64 bit register */ +#define GET_PERIOD_LSB_REG (0x18 << 11) +#define GET_PERIOD_MSB_REG (0x19 << 11) + +/** Get Temperature Carlos, incorrectl as get gates */ +#define GET_TEMPERATURE_TMP112_REG (0x1c << 11) // in 10ths of millidegrees of TMP112 + +/* Get Frames from Start 64 bit register (frames from start Run Control) */ +#define FRAMES_FROM_START_PG_LSB_REG (0x24 << 11) +#define FRAMES_FROM_START_PG_MSB_REG (0x25 << 11) + +/* Measurement Time 64 bit register (timestamp at a frame start until reset)*/ +#define START_FRAME_TIME_LSB_REG (0x26 << 11) +#define START_FRAME_TIME_MSB_REG (0x27 << 11) + +/* SPI (Serial Peripheral Interface) Register */ +#define SPI_REG (0x40 << 11) + +#define DAC_SERIAL_DIGITAL_OUT_OFST (0) +#define DAC_SERIAL_DIGITAL_OUT_MSK (0x00000001 << DAC_SERIAL_DIGITAL_OUT_OFST) +#define DAC_SERIAL_CLK_OUT_OFST (1) +#define DAC_SERIAL_CLK_OUT_MSK (0x00000001 << DAC_SERIAL_CLK_OUT_OFST) +#define DAC_SERIAL_CS_OUT_OFST (2) +#define DAC_SERIAL_CS_OUT_MSK (0x00000001 << DAC_SERIAL_CS_OUT_OFST) +#define HV_SERIAL_DIGITAL_OUT_OFST (8) +#define HV_SERIAL_DIGITAL_OUT_MSK (0x00000001 << HV_SERIAL_DIGITAL_OUT_OFST) +#define HV_SERIAL_CLK_OUT_OFST (9) +#define HV_SERIAL_CLK_OUT_MSK (0x00000001 << HV_SERIAL_CLK_OUT_OFST) +#define HV_SERIAL_CS_OUT_OFST (10) +#define HV_SERIAL_CS_OUT_MSK (0x00000001 << HV_SERIAL_CS_OUT_OFST) + + +/* ADC SPI (Serial Peripheral Interface) Register */ +#define ADC_SPI_REG (0x41 << 11) + +#define ADC_SERIAL_CLK_OUT_OFST (0) +#define ADC_SERIAL_CLK_OUT_MSK (0x00000001 << ADC_SERIAL_CLK_OUT_OFST) +#define ADC_SERIAL_DATA_OUT_OFST (1) +#define ADC_SERIAL_DATA_OUT_MSK (0x00000001 << ADC_SERIAL_DATA_OUT_OFST) +#define ADC_SERIAL_CS_OUT_OFST (2) +#define ADC_SERIAL_CS_OUT_MSK (0x0000000F << ADC_SERIAL_CS_OUT_OFST) + +/* ADC offset Register */ +#define ADC_OFST_REG (0x42 << 11) + +/* ADC Port Invert Register */ +#define ADC_PORT_INVERT_REG (0x43 << 11) + +/* Receiver IP Address Register */ +#define RX_IP_REG (0x45 << 11) + +/* UDP Port */ +#define UDP_PORT_REG (0x46 << 11) + +#define UDP_PORT_RX_OFST (0) +#define UDP_PORT_RX_MSK (0x0000FFFF << UDP_PORT_RX_OFST) +#define UDP_PORT_TX_OFST (16) +#define UDP_PORT_TX_MSK (0x0000FFFF << UDP_PORT_TX_OFST) + +/* Receiver Mac Address 64 bit Register */ +#define RX_MAC_LSB_REG (0x47 << 11) +#define RX_MAC_MSB_REG (0x48 << 11) + +#define RX_MAC_LSB_OFST (0) +#define RX_MAC_LSB_MSK (0xFFFFFFFF << RX_MAC_LSB_OFST) +#define RX_MAC_MSB_OFST (0) +#define RX_MAC_MSB_MSK (0x0000FFFF << RX_MAC_MSB_OFST) + +/* Detector/ Transmitter Mac Address 64 bit Register */ +#define TX_MAC_LSB_REG (0x49 << 11) +#define TX_MAC_MSB_REG (0x4A << 11) + +#define TX_MAC_LSB_OFST (0) +#define TX_MAC_LSB_MSK (0xFFFFFFFF << TX_MAC_LSB_OFST) +#define TX_MAC_MSB_OFST (0) +#define TX_MAC_MSB_MSK (0x0000FFFF << TX_MAC_MSB_OFST) + +/* Detector/ Transmitter IP Address Register */ +#define TX_IP_REG (0x4B << 11) + +/* Detector/ Transmitter IP Checksum Register */ +#define TX_IP_CHECKSUM_REG (0x4C << 11) + +#define TX_IP_CHECKSUM_OFST (0) +#define TX_IP_CHECKSUM_MSK (0x0000FFFF << TX_IP_CHECKSUM_OFST) + +/* Configuration Register */ +#define CONFIG_REG (0x4D << 11) + +#define CONFIG_OPERATION_MODE_OFST (16) +#define CONFIG_OPERATION_MODE_MSK (0x00000001 << CONFIG_OPERATION_MODE_OFST) +#define CONFIG_MODE_1_X_10GBE_VAL ((0x0 << CONFIG_OPERATION_MODE_OFST) & CONFIG_OPERATION_MODE_MSK) +#define CONFIG_MODE_2_X_10GBE_VAL ((0x1 << CONFIG_OPERATION_MODE_OFST) & CONFIG_OPERATION_MODE_MSK) +#define CONFIG_READOUT_SPEED_OFST (20) +#define CONFIG_READOUT_SPEED_MSK (0x00000003 << CONFIG_READOUT_SPEED_OFST) +#define CONFIG_QUARTER_SPEED_10MHZ_VAL ((0x0 << CONFIG_READOUT_SPEED_OFST) & CONFIG_READOUT_SPEED_MSK) +#define CONFIG_HALF_SPEED_20MHZ_VAL ((0x1 << CONFIG_READOUT_SPEED_OFST) & CONFIG_READOUT_SPEED_MSK) +#define CONFIG_FULL_SPEED_40MHZ_VAL ((0x2 << CONFIG_READOUT_SPEED_OFST) & CONFIG_READOUT_SPEED_MSK) +#define CONFIG_TDMA_OFST (24) +#define CONFIG_TDMA_MSK (0x00000001 << CONFIG_TDMA_OFST) +#define CONFIG_TDMA_DISABLE_VAL ((0x0 << CONFIG_TDMA_OFST) & CONFIG_TDMA_MSK) +#define CONFIG_TDMA_ENABLE_VAL ((0x1 << CONFIG_TDMA_OFST) & CONFIG_TDMA_MSK) +#define CONFIG_TDMA_TIMESLOT_OFST (25) +#define CONFIG_TDMA_TIMESLOT_MSK (0x0000001F << CONFIG_TDMA_TIMESLOT_OFST) +#define CONFIG_TDMA_TIMESLOT_0_VAL ((0x0 << CONFIG_TDMA_TIMESLOT_OFST) & CONFIG_TDMA_TIMESLOT_MSK) + +/* External Signal Register */ +#define EXT_SIGNAL_REG (0x4E << 11) + +#define EXT_SIGNAL_OFST (0) +#define EXT_SIGNAL_MSK (0x00000003 << EXT_SIGNAL_OFST) //enabled when both bits high + +/* Control Register */ +#define CONTROL_REG (0x4F << 11) + +#define CONTROL_START_ACQ_OFST (0) +#define CONTROL_START_ACQ_MSK (0x00000001 << CONTROL_START_ACQ_OFST) +#define CONTROL_STOP_ACQ_OFST (1) +#define CONTROL_STOP_ACQ_MSK (0x00000001 << CONTROL_STOP_ACQ_OFST) +#define CONTROL_CORE_RST_OFST (10) +#define CONTROL_CORE_RST_MSK (0x00000001 << CONTROL_CORE_RST_OFST) +#define CONTROL_PERIPHERAL_RST_OFST (11) //DDR3 HMem Ctrlr, GBE, Temp +#define CONTROL_PERIPHERAL_RST_MSK (0x00000001 << CONTROL_PERIPHERAL_RST_OFST) //DDR3 HMem Ctrlr, GBE, Temp +#define CONTROL_DDR3_MEM_RST_OFST (12) //only PHY, not DDR3 PLL ,Not used in software +#define CONTROL_DDR3_MEM_RST_MSK (0x00000001 << CONTROL_DDR3_MEM_RST_OFST) //only PHY, not DDR3 PLL ,Not used in software +#define CONTROL_ACQ_FIFO_CLR_OFST (14) +#define CONTROL_ACQ_FIFO_CLR_MSK (0x00000001 << CONTROL_ACQ_FIFO_CLR_OFST) + +/* Reconfiguratble PLL Paramater Register */ +#define PLL_PARAM_REG (0x50 << 11) + +/* Reconfiguratble PLL Control Regiser */ +#define PLL_CONTROL_REG (0x51 << 11) + +#define PLL_CTRL_RECONFIG_RST_OFST (0) //parameter reset +#define PLL_CTRL_RECONFIG_RST_MSK (0x00000001 << PLL_CTRL_RECONFIG_RST_OFST) //parameter reset +#define PLL_CTRL_WR_PARAMETER_OFST (2) +#define PLL_CTRL_WR_PARAMETER_MSK (0x00000001 << PLL_CTRL_WR_PARAMETER_OFST) +#define PLL_CTRL_RST_OFST (3) +#define PLL_CTRL_RST_MSK (0x00000001 << PLL_CTRL_RST_OFST) +#define PLL_CTRL_ADDR_OFST (16) +#define PLL_CTRL_ADDR_MSK (0x0000003F << PLL_CTRL_ADDR_OFST) + +/* Sample Register (Obsolete) */ +#define SAMPLE_REG (0x59 << 11) + +#define SAMPLE_ADC_SAMPLE_SEL_OFST (0) +#define SAMPLE_ADC_SAMPLE_SEL_MSK (0x00000007 << SAMPLE_ADC_SAMPLE_SEL_OFST) +#define SAMPLE_ADC_SAMPLE_0_VAL ((0x0 << SAMPLE_ADC_SAMPLE_SEL_OFST) & SAMPLE_ADC_SAMPLE_SEL_MSK) +#define SAMPLE_ADC_SAMPLE_1_VAL ((0x1 << SAMPLE_ADC_SAMPLE_SEL_OFST) & SAMPLE_ADC_SAMPLE_SEL_MSK) +#define SAMPLE_ADC_SAMPLE_2_VAL ((0x2 << SAMPLE_ADC_SAMPLE_SEL_OFST) & SAMPLE_ADC_SAMPLE_SEL_MSK) +#define SAMPLE_ADC_SAMPLE_3_VAL ((0x3 << SAMPLE_ADC_SAMPLE_SEL_OFST) & SAMPLE_ADC_SAMPLE_SEL_MSK) +#define SAMPLE_ADC_SAMPLE_4_VAL ((0x4 << SAMPLE_ADC_SAMPLE_SEL_OFST) & SAMPLE_ADC_SAMPLE_SEL_MSK) +#define SAMPLE_ADC_SAMPLE_5_VAL ((0x5 << SAMPLE_ADC_SAMPLE_SEL_OFST) & SAMPLE_ADC_SAMPLE_SEL_MSK) +#define SAMPLE_ADC_SAMPLE_6_VAL ((0x6 << SAMPLE_ADC_SAMPLE_SEL_OFST) & SAMPLE_ADC_SAMPLE_SEL_MSK) +#define SAMPLE_ADC_SAMPLE_7_VAL ((0x7 << SAMPLE_ADC_SAMPLE_SEL_OFST) & SAMPLE_ADC_SAMPLE_SEL_MSK) + +#define SAMPLE_ADC_DECMT_FACTOR_OFST (4) +#define SAMPLE_ADC_DECMT_FACTOR_MSK (0x00000007 << SAMPLE_ADC_DECMT_FACTOR_OFST) +#define SAMPLE_ADC_DECMT_FACTOR_0_VAL ((0x0 << SAMPLE_ADC_DECMT_FACTOR_OFST) & SAMPLE_ADC_DECMT_FACTOR_MSK) +#define SAMPLE_ADC_DECMT_FACTOR_1_VAL ((0x1 << SAMPLE_ADC_DECMT_FACTOR_OFST) & SAMPLE_ADC_DECMT_FACTOR_MSK) +#define SAMPLE_ADC_DECMT_FACTOR_2_VAL ((0x2 << SAMPLE_ADC_DECMT_FACTOR_OFST) & SAMPLE_ADC_DECMT_FACTOR_MSK) +#define SAMPLE_ADC_DECMT_FACTOR_3_VAL ((0x3 << SAMPLE_ADC_DECMT_FACTOR_OFST) & SAMPLE_ADC_DECMT_FACTOR_MSK) +#define SAMPLE_ADC_DECMT_FACTOR_4_VAL ((0x4 << SAMPLE_ADC_DECMT_FACTOR_OFST) & SAMPLE_ADC_DECMT_FACTOR_MSK) +#define SAMPLE_ADC_DECMT_FACTOR_5_VAL ((0x5 << SAMPLE_ADC_DECMT_FACTOR_OFST) & SAMPLE_ADC_DECMT_FACTOR_MSK) +#define SAMPLE_ADC_DECMT_FACTOR_6_VAL ((0x6 << SAMPLE_ADC_DECMT_FACTOR_OFST) & SAMPLE_ADC_DECMT_FACTOR_MSK) +#define SAMPLE_ADC_DECMT_FACTOR_7_VAL ((0x7 << SAMPLE_ADC_DECMT_FACTOR_OFST) & SAMPLE_ADC_DECMT_FACTOR_MSK) + +#define SAMPLE_DGTL_SAMPLE_SEL_OFST (8) +#define SAMPLE_DGTL_SAMPLE_SEL_MSK (0x0000000F << SAMPLE_DGTL_SAMPLE_SEL_OFST) +#define SAMPLE_DGTL_SAMPLE_0_VAL ((0x0 << SAMPLE_DGTL_SAMPLE_SEL_OFST) & SAMPLE_DGTL_SAMPLE_SEL_MSK) +#define SAMPLE_DGTL_SAMPLE_1_VAL ((0x1 << SAMPLE_DGTL_SAMPLE_SEL_OFST) & SAMPLE_DGTL_SAMPLE_SEL_MSK) +#define SAMPLE_DGTL_SAMPLE_2_VAL ((0x2 << SAMPLE_DGTL_SAMPLE_SEL_OFST) & SAMPLE_DGTL_SAMPLE_SEL_MSK) +#define SAMPLE_DGTL_SAMPLE_3_VAL ((0x3 << SAMPLE_DGTL_SAMPLE_SEL_OFST) & SAMPLE_DGTL_SAMPLE_SEL_MSK) +#define SAMPLE_DGTL_SAMPLE_4_VAL ((0x4 << SAMPLE_DGTL_SAMPLE_SEL_OFST) & SAMPLE_DGTL_SAMPLE_SEL_MSK) +#define SAMPLE_DGTL_SAMPLE_5_VAL ((0x5 << SAMPLE_DGTL_SAMPLE_SEL_OFST) & SAMPLE_DGTL_SAMPLE_SEL_MSK) +#define SAMPLE_DGTL_SAMPLE_6_VAL ((0x6 << SAMPLE_DGTL_SAMPLE_SEL_OFST) & SAMPLE_DGTL_SAMPLE_SEL_MSK) +#define SAMPLE_DGTL_SAMPLE_7_VAL ((0x7 << SAMPLE_DGTL_SAMPLE_SEL_OFST) & SAMPLE_DGTL_SAMPLE_SEL_MSK) +#define SAMPLE_DGTL_SAMPLE_8_VAL ((0x8 << SAMPLE_DGTL_SAMPLE_SEL_OFST) & SAMPLE_DGTL_SAMPLE_SEL_MSK) +#define SAMPLE_DGTL_SAMPLE_9_VAL ((0x9 << SAMPLE_DGTL_SAMPLE_SEL_OFST) & SAMPLE_DGTL_SAMPLE_SEL_MSK) +#define SAMPLE_DGTL_SAMPLE_10_VAL ((0xa << SAMPLE_DGTL_SAMPLE_SEL_OFST) & SAMPLE_DGTL_SAMPLE_SEL_MSK) +#define SAMPLE_DGTL_SAMPLE_11_VAL ((0xb << SAMPLE_DGTL_SAMPLE_SEL_OFST) & SAMPLE_DGTL_SAMPLE_SEL_MSK) +#define SAMPLE_DGTL_SAMPLE_12_VAL ((0xc << SAMPLE_DGTL_SAMPLE_SEL_OFST) & SAMPLE_DGTL_SAMPLE_SEL_MSK) +#define SAMPLE_DGTL_SAMPLE_13_VAL ((0xd << SAMPLE_DGTL_SAMPLE_SEL_OFST) & SAMPLE_DGTL_SAMPLE_SEL_MSK) +#define SAMPLE_DGTL_SAMPLE_14_VAL ((0xe << SAMPLE_DGTL_SAMPLE_SEL_OFST) & SAMPLE_DGTL_SAMPLE_SEL_MSK) +#define SAMPLE_DGTL_SAMPLE_15_VAL ((0xf << SAMPLE_DGTL_SAMPLE_SEL_OFST) & SAMPLE_DGTL_SAMPLE_SEL_MSK) + +#define SAMPLE_DGTL_DECMT_FACTOR_OFST (12) +#define SAMPLE_DGTL_DECMT_FACTOR_MSK (0x00000003 << SAMPLE_DGTL_DECMT_FACTOR_OFST) +#define SAMPLE_DECMT_FACTOR_1_VAL ((0x0 << SAMPLE_DGTL_DECMT_FACTOR_OFST) & SAMPLE_DGTL_DECMT_FACTOR_MSK) +#define SAMPLE_DECMT_FACTOR_2_VAL ((0x1 << SAMPLE_DGTL_DECMT_FACTOR_OFST) & SAMPLE_DGTL_DECMT_FACTOR_MSK) +#define SAMPLE_DECMT_FACTOR_4_VAL ((0x2 << SAMPLE_DGTL_DECMT_FACTOR_OFST) & SAMPLE_DGTL_DECMT_FACTOR_MSK) + +/** Vref Comp Mod Register */ +#define VREF_COMP_MOD_REG (0x5C << 11) //Not used in software, TBD in firmware + +/** DAQ Register */ +#define DAQ_REG (0x5D << 11) //TBD in firmware + +/** Chip Power Register */ +#define CHIP_POWER_REG (0x5E << 11) + +#define CHIP_POWER_ENABLE_OFST (0) +#define CHIP_POWER_ENABLE_MSK (0x00000001 << CHIP_POWER_ENABLE_OFST) + +/* Set Delay 64 bit register */ +#define SET_DELAY_LSB_REG (0x60 << 11) +#define SET_DELAY_MSB_REG (0x61 << 11) + +/* Set Cycles 64 bit register */ +#define SET_CYCLES_LSB_REG (0x62 << 11) +#define SET_CYCLES_MSB_REG (0x63 << 11) + +/* Set Frames 64 bit register */ +#define SET_FRAMES_LSB_REG (0x64 << 11) +#define SET_FRAMES_MSB_REG (0x65 << 11) + +/* Set Period 64 bit register */ +#define SET_PERIOD_LSB_REG (0x66 << 11) +#define SET_PERIOD_MSB_REG (0x67 << 11) + +/* Set Period 64 bit register */ +#define SET_EXPTIME_LSB_REG (0x68 << 11) +#define SET_EXPTIME_MSB_REG (0x69 << 11) + +/* Module Coordinates Register 0 */ +#define COORD_0 (0x7C << 11) + +#define COORD_0_Y_OFST (0) +#define COORD_0_Y_MSK (0x0000FFFF << COORD_0_Y_OFST) +#define COORD_0_X_OFST (16) +#define COORD_0_X_MSK (0x0000FFFF << COORD_0_X_OFST) + +/* Module Coordinates Register 1 */ +#define COORD_1 (0x7D << 11) + +#define COORD_0_Z_OFST (0) +#define COORD_0_Z_MSK (0x0000FFFF << COORD_0_Z_OFST) + + +#endif //REGISTERS_G_H + + + + + + + + + + + + + + + diff --git a/slsDetectorSoftware/jungfrauDetectorServer/ansi.h b/slsDetectorSoftware/jungfrauDetectorServer/ansi.h index c8131b6ec..a122db0ad 120000 --- a/slsDetectorSoftware/jungfrauDetectorServer/ansi.h +++ b/slsDetectorSoftware/jungfrauDetectorServer/ansi.h @@ -1 +1 @@ -/afs/psi.ch/project/sls_det_software/dhanya_softwareDevelopment/mySoft/slsDetectorsPackage/slsReceiverSoftware/include/ansi.h \ No newline at end of file +../../slsReceiverSoftware/include/ansi.h \ No newline at end of file diff --git a/slsDetectorSoftware/jungfrauDetectorServer/bin/jungfrauDetectorServerv3.0.0.1.1 b/slsDetectorSoftware/jungfrauDetectorServer/bin/jungfrauDetectorServerv3.0.0.1.1 new file mode 100755 index 000000000..68d58b3b2 Binary files /dev/null and b/slsDetectorSoftware/jungfrauDetectorServer/bin/jungfrauDetectorServerv3.0.0.1.1 differ diff --git a/slsDetectorSoftware/jungfrauDetectorServer/firmware_funcs.c b/slsDetectorSoftware/jungfrauDetectorServer/firmware_funcs.c deleted file mode 100755 index 20b9e97fb..000000000 --- a/slsDetectorSoftware/jungfrauDetectorServer/firmware_funcs.c +++ /dev/null @@ -1,3146 +0,0 @@ -//#define TESTADC -#define TESTADC1 - - -//#define TIMEDBG -#include "server_defs.h" -#include "firmware_funcs.h" -#include "mcb_funcs.h" -#include "registers_m.h" -#include "gitInfoJungfrau.h" - -//#define VERBOSE -//#define VERYVERBOSE - - -#ifdef SHAREDMEMORY -#include "sharedmemory.h" -#endif - -#include -#include -#include - -#include -#include -#include /* exit() */ -#include /* memset(), memcpy() */ -#include /* uname() */ -#include -#include /* socket(), bind(), - listen(), accept() */ -#include -#include -#include -#include -#include /* fork(), write(), close() */ -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include - - -extern enum detectorType myDetectorType; - -typedef struct ip_header_struct { - u_int16_t ip_len; - u_int8_t ip_tos; - u_int8_t ip_ihl:4 ,ip_ver:4; - u_int16_t ip_offset:13,ip_flag:3; - u_int16_t ip_ident; - u_int16_t ip_chksum; - u_int8_t ip_protocol; - u_int8_t ip_ttl; - u_int32_t ip_sourceip; - u_int32_t ip_destip; -} ip_header; - - -struct timeval tss,tse,tsss; //for timing - - - - -u_int32_t CSP0BASE; -FILE *debugfp, *datafp; -int fr; -int wait_time; -int *fifocntrl; -const int nModY=1; -int nModBoard; -int nModX=NMAXMOD; -int dynamicRange=16; -int nSamples=1; -size_t dataBytes=NMAXMOD*NCHIP*NCHAN*2; -int storeInRAM=0; -int ROI_flag=0; -int adcConfigured=-1; -int ram_size=0; - -int64_t totalTime=1; -u_int32_t progressMask=0; -int phase_shift=0;//DEFAULT_PHASE_SHIFT; -int ipPacketSize=DEFAULT_IP_PACKETSIZE; -int udpPacketSize=DEFAULT_UDP_PACKETSIZE; -int clockdivider_exptime = 40; -int clockdivider_fc = 20; -/* -#ifndef NEW_PLL_RECONFIG -u_int32_t clkDivider[2]={32,16}; -#else -u_int32_t clkDivider[2]={40,20}; -#endif - */ - -int32_t clkPhase[2]={0,0}; - -u_int32_t adcDisableMask=0; - -int ififostart, ififostop, ififostep, ififo; - -int masterMode=NO_MASTER, syncMode=NO_SYNCHRONIZATION, timingMode=AUTO_TIMING; - -enum externalSignalFlag signals[4]={EXT_SIG_OFF, EXT_SIG_OFF, EXT_SIG_OFF, EXT_SIG_OFF}; - -char mtdvalue[10]; - - - - - -int mapCSP0(void) { - printf("Mapping memory\n"); -#ifndef VIRTUAL - int fd; - fd = open("/dev/mem", O_RDWR | O_SYNC, 0); - if (fd == -1) { - printf("\nCan't find /dev/mem!\n"); - return FAIL; - } - //printf("/dev/mem opened\n"); - - CSP0BASE = (u_int32_t)mmap(0, MEM_SIZE, PROT_READ|PROT_WRITE, MAP_FILE|MAP_SHARED, fd, CSP0); - if (CSP0BASE == (u_int32_t)MAP_FAILED) { - printf("\nCan't map memmory area!!\n"); - return FAIL; - } - //printf("CSP0 mapped\n"); - -#endif -#ifdef VIRTUAL - CSP0BASE = malloc(MEM_SIZE); - printf("memory allocated\n"); -#endif -#ifdef SHAREDMEMORY - if ( (res=inism(SMSV))<0) { - printf("error attaching shared memory! %i",res); - return FAIL; - } -#endif - //printf("CSPObase is 0x%08x \n",CSP0BASE); - printf("CSPOBASE mapped from %08x to %08x\n",CSP0BASE,CSP0BASE+MEM_SIZE); - - printf("statusreg=%08x\n",bus_r(STATUS_REG)); - return OK; -} - - - -void defineGPIOpins(){ - //define the gpio pins - system("echo 7 > /sys/class/gpio/export"); - system("echo 9 > /sys/class/gpio/export"); - //define their direction - system("echo in > /sys/class/gpio/gpio7/direction"); - system("echo out > /sys/class/gpio/gpio9/direction"); -} - -void resetFPGA(){ - cprintf(BLUE,"\n*** Reseting FPGA ***\n"); - FPGAdontTouchFlash(); - FPGATouchFlash(); - usleep(250*1000); -} - -void FPGAdontTouchFlash(){ - //tell FPGA to not touch flash - system("echo 0 > /sys/class/gpio/gpio9/value"); - //usleep(100*1000); -} - -void FPGATouchFlash(){ - //tell FPGA to touch flash to program itself - system("echo 1 > /sys/class/gpio/gpio9/value"); -} - -int powerChip (int on){ - if(on != -1){ - if(on){ - printf("\nPowering on the chip\n"); - bus_w(POWER_ON_REG,0x1); - } - else{ - printf("\nPowering off the chip\n"); - bus_w(POWER_ON_REG,0x0); - } - } - - return bus_r(POWER_ON_REG); -} - - -void initializeDetector(){ - printf("Initializing Detector\n"); - - int i; - //printf("Bus test... "); - for (i=0; i<1000000; i++) { - bus_w(SET_DELAY_LSB_REG, i*100); - bus_r(FPGA_VERSION_REG); - if (i*100!=bus_r(SET_DELAY_LSB_REG)) - cprintf(RED,"Bus Test ERROR: wrote 0x%x, read 0x%x\n",i*100,bus_r(SET_DELAY_LSB_REG)); - } - //printf("Finished\n"); - - //confirm the detector type - if (((bus_r(PCB_REV_REG) & DETECTOR_TYPE_MASK)>>DETECTOR_TYPE_OFFSET) != JUNGFRAU_MODULE_ID){ - cprintf(BG_RED,"This is not a Jungfrau Server (enum:%d)\n",myDetectorType); - exit(-1); - } - cprintf(BLUE,"\n\n********************************************************\n" - "*********************Jungfrau Server********************\n" - "********************************************************\n"); - - //print version - cprintf(BLUE,"\n" - "Firmware Version:\t 0x%x\n" - "Software Version:\t %llx\n" - //"F/w-S/w API Version:\t\t %lld\n" - //"Required Firmware Version:\t %d\n" - "Fixed Pattern:\t\t 0x%x\n" - "Board Revision:\t\t 0x%x\n" - "\n********************************************************\n", - bus_r(FPGA_VERSION_REG),(long long unsigned int)(((int64_t)SVNREV <<32) | (int64_t)SVNDATE) - //,sw_fw_apiversion, REQUIRED_FIRMWARE_VERSION - ,bus_r(FIX_PATT_REG),(bus_r(PCB_REV_REG)&BOARD_REVISION_MASK) - ); - - - printf("Resetting PLL\n"); - resetPLL(); - bus_w16(CONTROL_REG, SYNC_RESET); - bus_w16(CONTROL_REG, 0); - bus_w16(CONTROL_REG, GB10_RESET_BIT); - bus_w16(CONTROL_REG, 0); - -#ifdef MCB_FUNCS - initDetector(); -#endif - /*some registers set, which is in common with jungfrau, please check */ - prepareADC(); - /*some registers set, which is in common with jungfrau, please check */ - initDac(0); initDac(8); //initializes the two dacs - - - //set dacs - printf("Setting Default Dac values\n"); - enum dacNames{VB_COMP,VDD_PROT,VIN_COM,VREF_PRECH,VB_PIXBUF,VB_DS,VREF_DS,VREF_COMP}; - int retval = -1; - int dacvalues[8][2]={ - {VB_COMP, 1220}, - {VDD_PROT, 3000}, - {VIN_COM, 1053}, - {VREF_PRECH,1450}, - {VB_PIXBUF, 750}, - {VB_DS, 1000}, - {VREF_DS, 480}, - {VREF_COMP, 420}, - }; - for(i=0;i<8;++i){ - retval=setDac(dacvalues[i][0], dacvalues[i][1]); - if(retval!=dacvalues[i][1]) - printf("Error: Setting dac %d failed, wrote %d, read %d\n",dacvalues[i][0],dacvalues[i][1],retval); - } - - - //done from config file - //printf("\nPowering on the chip\n"); - //bus_w(POWER_ON_REG,0x1); - - /* Only once */ - bus_w(CONFGAIN_REG,0x0); - - printf("Resetting ADC\n"); - writeADC(ADCREG1,0x3); writeADC(ADCREG1,0x0); - writeADC(ADCREG2,0x40); - writeADC(ADCREG3,0xf); - writeADC(ADCREG4,0x3f); - printf("Configuring Vrefs\n"); - writeADC(ADCREG_VREFS,0x2); - printf("Setting ADC Inversion\n");// (by trial and error) - bus_w(ADC_INVERSION_REG,0x453b2a9c); - - adcPipeline(HALFSPEED_ADC_PIPELINE); - dbitPipeline(HALFSPEED_DBIT_PIPELINE); - adcPhase(HALFSPEED_ADC_PHASE); //set adc_clock_phase in unit of 1/(52) clock period (by trial and error) - - printf("Reset mem machine fifos\n"); - bus_w(MEM_MACHINE_FIFOS_REG,0x4000); - bus_w(MEM_MACHINE_FIFOS_REG,0x0); - printf("Reset run control\n"); - bus_w(MEM_MACHINE_FIFOS_REG,0x0400); - bus_w(MEM_MACHINE_FIFOS_REG,0x0); - initSpeedConfGain(HALFSPEED_CONF); - setSettings(DYNAMICGAIN,-1); - - - - //Initialization of acquistion parameters - setFrames(1*1000*1000); - setTrains(-1); - setExposureTime(10*1000); - setPeriod(2*1000*1000); - setDelay(0); - setGates(0); - - - setTiming(GET_EXTERNAL_COMMUNICATION_MODE); - setMaster(GET_MASTER); - setSynchronization(GET_SYNCHRONIZATION_MODE); - -} - - -u_int16_t bus_r16(u_int32_t offset){ - volatile u_int16_t *ptr1; - ptr1=(u_int16_t*)(CSP0BASE+offset*2); - return *ptr1; -} - -u_int16_t bus_w16(u_int32_t offset, u_int16_t data) { - volatile u_int16_t *ptr1; - ptr1=(u_int16_t*)(CSP0BASE+offset*2); - *ptr1=data; - return OK; -} - -/** ramType is DARK_IMAGE_REG or GAIN_IMAGE_REG */ -u_int16_t ram_w16(u_int32_t ramType, int adc, int adcCh, int Ch, u_int16_t data) { - unsigned int adr = (ramType | adc << 8 | adcCh << 5 | Ch ); - // printf("Writing to addr:%x\n",adr); - return bus_w16(adr,data); -} - -/** ramType is DARK_IMAGE_REG or GAIN_IMAGE_REG */ -u_int16_t ram_r16(u_int32_t ramType, int adc, int adcCh, int Ch){ - unsigned int adr = (ramType | adc << 8 | adcCh << 5 | Ch ); - // printf("Reading from addr:%x\n",adr); - return bus_r16(adr); -} - -u_int32_t bus_w(u_int32_t offset, u_int32_t data) { - volatile u_int32_t *ptr1; - - ptr1=(u_int32_t*)(CSP0BASE+offset*2); - *ptr1=data; - - return OK; -} - - -u_int32_t bus_r(u_int32_t offset) { - volatile u_int32_t *ptr1; - ptr1=(u_int32_t*)(CSP0BASE+offset*2); - return *ptr1; -} - - -int setPhaseShiftOnce(){ - u_int32_t addr, reg; - int i; - addr=MULTI_PURPOSE_REG; - reg=bus_r(addr); -#ifdef VERBOSE - printf("Multipurpose reg:%x\n",reg); -#endif - - //Checking if it is power on(negative number) - // if(((reg&0xFFFF0000)>>16)>0){ - //bus_w(addr,0x0); //clear the reg - - if(reg==0){ - printf("\nImplementing phase shift of %d\n",phase_shift); - for (i=1;i2*l) { - h=l+1; - odd=1; - } - printf("Counter %d: Low is %d, High is %d\n",i, l,h); - val= (i<<18)| (odd<<17) | l | (h<<8); - printf("Counter %d, val: %08x\n", i, val); - setPllReconfigReg(PLL_C_COUNTER_REG, val,0); - // usleep(20); - //change sync at the same time as - if (i>0) { - val= (2<<18)| (odd<<17) | l | (h<<8); - printf("Counter %d, val: %08x\n", i, val); - setPllReconfigReg(PLL_C_COUNTER_REG, val,0); - } - - } else { - // if (mode==1) { - // } else { - printf("phase in %d\n",clkPhase[1]); - - if (clkPhase[1]>0) { - inv=0; - phase=clkPhase[1]; - } else { - inv=1; - phase=-1*clkPhase[1]; - } - - printf("phase out %d %08x\n",phase,phase); - if (inv) { - val=phase | (1<<16);// | (inv<<21); - printf("**************** phase word %08x\n",val); - - // printf("Phase, val: %08x\n", val); - setPllReconfigReg(PLL_PHASE_SHIFT_REG,val,0); //shifts counter 0 - } else { - - - val=phase ;// | (inv<<21); - printf("**************** phase word %08x\n",val); - - // printf("Phase, val: %08x\n", val); - setPllReconfigReg(PLL_PHASE_SHIFT_REG,val,0); //shifts counter 0 -#ifndef NEW_PLL_RECONFIG - printf("Start reconfig\n"); setPllReconfigReg(PLL_START_REG, 1,0); - - // bus_w(PLL_CNTRL_REG, 0); - printf("Status register\n"); getPllReconfigReg(PLL_STATUS_REG,0); - // sleep(1); - - printf("PLL mode\n"); setPllReconfigReg(PLL_MODE_REG,1,0); - // usleep(10000); - -#endif - printf("**************** phase word %08x\n",val); - - val=phase | (2<<16);// | (inv<<21); - // printf("Phase, val: %08x\n", val); - setPllReconfigReg(PLL_PHASE_SHIFT_REG,val,0); //shifts counter 0 - } - } -#ifndef NEW_PLL_RECONFIG - printf("Start reconfig\n"); setPllReconfigReg(PLL_START_REG, 1,0); - - // bus_w(PLL_CNTRL_REG, 0); - printf("Status register\n"); getPllReconfigReg(PLL_STATUS_REG,0); - // sleep(1); -#endif - // printf("PLL mode\n"); setPllReconfigReg(PLL_MODE_REG,0,0); - usleep(10000); - if (i<2) { - printf("reset pll\n"); - bus_w(PLL_CNTRL_REG,((1<65535 || st<-65535) - return clkPhase[0]; -#ifdef NEW_PLL_RECONFIG - printf("reset pll\n"); - bus_w(PLL_CNTRL_REG,((1<=0){ - printf("Setting ADC Pipeline to 0x%x\n",d); - bus_w(ADC_PIPELINE_REG, d); - } - return bus_r(ADC_PIPELINE_REG); - -} - - -u_int32_t dbitPipeline(int d){ - if (d>=0){ - printf("Setting DBIT Pipeline to 0x%x\n",d); - bus_w(DBIT_PIPELINE_REG, d); - } - return bus_r(DBIT_PIPELINE_REG); -} - -u_int32_t setSetLength(int d) { - return 0; -} - -u_int32_t getSetLength() { - return 0; -} - -u_int32_t setOversampling(int d) { - - if (d>=0 && d<=255) - bus_w(OVERSAMPLING_REG, d); - - return bus_r(OVERSAMPLING_REG); -} - - -u_int32_t setWaitStates(int d1) { - return 0; -} - -u_int32_t getWaitStates() { - return 0; -} - - -u_int32_t setTotClockDivider(int d) { - return 0; -} - -u_int32_t getTotClockDivider() { - return 0; -} - - -u_int32_t setTotDutyCycle(int d) { - return 0; -} - -u_int32_t getTotDutyCycle() { - return 0; -} - - -u_int32_t setExtSignal(int d, enum externalSignalFlag mode) { - - u_int32_t c; - c=bus_r(EXT_SIGNAL_REG); - - if (d>=0 && d<4) { - signals[d]=mode; -#ifdef VERBOSE - printf("settings signal variable number %d to value %04x\n", d, signals[d]); -#endif - - // if output signal, set it! - - switch (mode) { - case GATE_IN_ACTIVE_HIGH: - case GATE_IN_ACTIVE_LOW: - if (timingMode==GATE_FIX_NUMBER || timingMode==GATE_WITH_START_TRIGGER) - setFPGASignal(d,mode); - else - setFPGASignal(d,SIGNAL_OFF); - break; - case TRIGGER_IN_RISING_EDGE: - case TRIGGER_IN_FALLING_EDGE: - if (timingMode==TRIGGER_EXPOSURE || timingMode==GATE_WITH_START_TRIGGER) - setFPGASignal(d,mode); - else - setFPGASignal(d,SIGNAL_OFF); - break; - case RO_TRIGGER_IN_RISING_EDGE: - case RO_TRIGGER_IN_FALLING_EDGE: - if (timingMode==TRIGGER_READOUT) - setFPGASignal(d,mode); - else - setFPGASignal(d,SIGNAL_OFF); - break; - case MASTER_SLAVE_SYNCHRONIZATION: - setSynchronization(syncMode); - break; - default: - setFPGASignal(d,mode); - break; - } - - setTiming(GET_EXTERNAL_COMMUNICATION_MODE); - } - - return getExtSignal(d); -} - - - -u_int32_t setFPGASignal(int d, enum externalSignalFlag mode) { - - - int modes[]={EXT_SIG_OFF, EXT_GATE_IN_ACTIVEHIGH, EXT_GATE_IN_ACTIVELOW,EXT_TRIG_IN_RISING,EXT_TRIG_IN_FALLING,EXT_RO_TRIG_IN_RISING, EXT_RO_TRIG_IN_FALLING,EXT_GATE_OUT_ACTIVEHIGH, EXT_GATE_OUT_ACTIVELOW, EXT_TRIG_OUT_RISING, EXT_TRIG_OUT_FALLING, EXT_RO_TRIG_OUT_RISING, EXT_RO_TRIG_OUT_FALLING}; - - u_int32_t c; - int off=d*SIGNAL_OFFSET; - c=bus_r(EXT_SIGNAL_REG); - - - if (mode<=RO_TRIGGER_OUT_FALLING_EDGE && mode>=0) { -#ifdef VERBOSE - printf("writing signal register number %d mode %04x\n",d, modes[mode]); -#endif - bus_w(EXT_SIGNAL_REG,((modes[mode])<=0 && d<4) { -#ifdef VERBOSE - printf("gettings signal variable number %d value %04x\n", d, signals[d]); -#endif - return signals[d]; - } else - return -1; -} - - -int getFPGASignal(int d) { - - int modes[]={SIGNAL_OFF, GATE_IN_ACTIVE_HIGH, GATE_IN_ACTIVE_LOW,TRIGGER_IN_RISING_EDGE, TRIGGER_IN_FALLING_EDGE,RO_TRIGGER_IN_RISING_EDGE, RO_TRIGGER_IN_FALLING_EDGE, GATE_OUT_ACTIVE_HIGH, GATE_OUT_ACTIVE_LOW, TRIGGER_OUT_RISING_EDGE, TRIGGER_OUT_FALLING_EDGE, RO_TRIGGER_OUT_RISING_EDGE,RO_TRIGGER_OUT_FALLING_EDGE}; - - int off=d*SIGNAL_OFFSET; - int mode=((bus_r(EXT_SIGNAL_REG)&(SIGNAL_MASK<>off); - - if (mode<=RO_TRIGGER_OUT_FALLING_EDGE) { - if (modes[mode]!=SIGNAL_OFF && signals[d]!=MASTER_SLAVE_SYNCHRONIZATION) - signals[d]=modes[mode]; -#ifdef VERYVERBOSE - printf("gettings signal register number %d value %04x\n", d, modes[mode]); -#endif - return modes[mode]; - } else - return -1; - -} - - - - - -/* -enum externalCommunicationMode{ - GET_EXTERNAL_COMMUNICATION_MODE, - AUTO, - TRIGGER_EXPOSURE_SERIES, - TRIGGER_EXPOSURE_BURST, - TRIGGER_READOUT, - TRIGGER_COINCIDENCE_WITH_INTERNAL_ENABLE, - GATE_FIX_NUMBER, - GATE_FIX_DURATION, - GATE_WITH_START_TRIGGER, - GATE_COINCIDENCE_WITH_INTERNAL_ENABLE -}; - */ - - -int setTiming(int ti) { - - int ret=GET_EXTERNAL_COMMUNICATION_MODE; - - int g=-1, t=-1, rot=-1; - - int i; - - switch (ti) { - case AUTO_TIMING: - printf("\nSetting timing to auto\n"); - timingMode=ti; - // disable all gates/triggers in except if used for master/slave synchronization - for (i=0; i<4; i++) { - if (getFPGASignal(i)>0 && getFPGASignal(i)=0 && t>=0 && rot<0) { - ret=GATE_WITH_START_TRIGGER; - } else if (g<0 && t>=0 && rot<0) { - ret=TRIGGER_EXPOSURE; - } else if (g>=0 && t<0 && rot<0) { - ret=GATE_FIX_NUMBER; - } else if (g<0 && t<0 && rot>0) { - ret=TRIGGER_READOUT; - } else if (g<0 && t<0 && rot<0) { - ret=AUTO_TIMING; - } - - // timingMode=ret; - - return ret; - -} - - - -int setConfigurationRegister(int d) { -#ifdef VERBOSE - printf("Setting configuration register to %x",d); -#endif - if (d>=0) { - bus_w(CONFIG_REG,d); - } -#ifdef VERBOSE - printf("configuration register is %x", bus_r(CONFIG_REG)); -#endif - return bus_r(CONFIG_REG); -} - -int setToT(int d) { - //int ret=0; - int reg; -#ifdef VERBOSE - printf("Setting ToT to %d\n",d); -#endif - reg=bus_r(CONFIG_REG); -#ifdef VERBOSE - printf("Before: ToT is %x\n", reg); -#endif - if (d>0) { - bus_w(CONFIG_REG,reg|TOT_ENABLE_BIT); - } else if (d==0) { - bus_w(CONFIG_REG,reg&(~TOT_ENABLE_BIT)); - } - reg=bus_r(CONFIG_REG); -#ifdef VERBOSE - printf("ToT is %x\n", reg); -#endif - if (reg&TOT_ENABLE_BIT) - return 1; - else - return 0; -} - -int setContinousReadOut(int d) { - //int ret=0; - int reg; -#ifdef VERBOSE - printf("Setting Continous readout to %d\n",d); -#endif - reg=bus_r(CONFIG_REG); -#ifdef VERBOSE - printf("Before: Continous readout is %x\n", reg); -#endif - if (d>0) { - bus_w(CONFIG_REG,reg|CONT_RO_ENABLE_BIT); - } else if (d==0) { - bus_w(CONFIG_REG,reg&(~CONT_RO_ENABLE_BIT)); - } - reg=bus_r(CONFIG_REG); -#ifdef VERBOSE - printf("Continous readout is %x\n", reg); -#endif - if (reg&CONT_RO_ENABLE_BIT) - return 1; - else - return 0; -} - - -<<<<<<< HEAD -int startReceiver(int start) { - u_int32_t addr=CONFIG_REG; - //#ifdef VERBOSE - if(start) - printf("Setting up detector to send to Receiver\n"); - else - printf("Setting up detector to send to CPU\n"); - //#endif - int reg=bus_r(addr); - //for start recever, write 0 and for stop, write 1 - if (!start) - bus_w(CONFIG_REG,reg&(~GB10_NOT_CPU_BIT)); - else - bus_w(CONFIG_REG,reg|GB10_NOT_CPU_BIT); - - reg=bus_r(addr); -//#ifdef VERBOSE - printf("Config Reg %x\n", reg); -//#endif - int d =reg&GB10_NOT_CPU_BIT; - if(d!=0) d=1; - if(d!=start) - return OK; - else - return FAIL; -} -======= ->>>>>>> f24459bee05f373e2830bb24388e40f0b2983d5a - - -u_int64_t getDetectorNumber() { - char output[255],mac[255]=""; - u_int64_t res=0; - FILE* sysFile = popen("ifconfig eth0 | grep HWaddr | cut -d \" \" -f 11", "r"); - fgets(output, sizeof(output), sysFile); - pclose(sysFile); - //getting rid of ":" - char * pch; - pch = strtok (output,":"); - while (pch != NULL){ - strcat(mac,pch); - pch = strtok (NULL, ":"); - } - sscanf(mac,"%llx",&res); - return res; -} - -u_int32_t getFirmwareVersion() { - return bus_r(FPGA_VERSION_REG); -} - -u_int32_t getFirmwareSVNVersion(){ - return bus_r(FPGA_SVN_REG); -} - - -// for fpga test -u_int32_t testFpga(void) { - printf("Testing FPGA:\n"); - volatile u_int32_t val,addr,val2; - int result=OK,i; - //fixed pattern - val=bus_r(FIX_PATT_REG); - if (val==FIXED_PATT_VAL) { - printf("fixed pattern ok!! %08x\n",val); - } else { - printf("fixed pattern wrong!! %08x\n",val); - result=FAIL; - } - - //dummy register - addr = DUMMY_REG; - for(i=0;i<1000000;i++) - { - val=0x5A5A5A5A-i; - bus_w(addr, val); - val=bus_r(addr); - if (val!=0x5A5A5A5A-i) { - printf("ATTEMPT:%d:\tFPGA dummy register wrong!! %x instead of %x \n",i,val,0x5A5A5A5A-i); - result=FAIL; - } - val=(i+(i<<10)+(i<<20)); - bus_w(addr, val); - val2=bus_r(addr); - if (val2!=val) { - printf("ATTEMPT:%d:\tFPGA dummy register wrong!! read %x instead of %x.\n",i,val2,val); - result=FAIL; - } - val=0x0F0F0F0F; - bus_w(addr, val); - val=bus_r(addr); - if (val!=0x0F0F0F0F) { - printf("ATTEMPT:%d:\tFPGA dummy register wrong!! %x instead of 0x0F0F0F0F \n",i,val); - result=FAIL; - } - val=0xF0F0F0F0; - bus_w(addr, val); - val=bus_r(addr); - if (val!=0xF0F0F0F0) { - printf("ATTEMPT:%d:\tFPGA dummy register wrong!! %x instead of 0xF0F0F0F0 \n\n",i,val); - result=FAIL; - } - } - if(result==OK) - { - printf("----------------------------------------------------------------------------------------------"); - printf("\nATTEMPT 1000000: FPGA DUMMY REGISTER OK!!!\n"); - printf("----------------------------------------------------------------------------------------------"); - } - printf("\n"); - return result; -} - - -u_int32_t testRAM(void) { - int result=OK; - printf("TestRAM not implemented\n"); - return result; -} - - -int getNModBoard() { - return 1; -} - -int setNMod(int n) { - return 1; -} - -int getNMod() { - return 1; -} - - -// fifo test -int testFifos(void) { - printf("Fifo test not implemented!\n"); - bus_w16(CONTROL_REG, START_FIFOTEST_BIT); - bus_w16(CONTROL_REG, 0x0); - return OK; -} - - - -// program dacq settings - -int64_t set64BitReg(int64_t value, int aLSB, int aMSB){ - int64_t v64; - u_int32_t vLSB,vMSB; - if (value!=-1) { - vLSB=value&(0xffffffff); - bus_w(aLSB,vLSB); - v64=value>> 32; - vMSB=v64&(0xffffffff); - bus_w(aMSB,vMSB); - } - return get64BitReg(aLSB, aMSB); - -} - -int64_t get64BitReg(int aLSB, int aMSB){ - int64_t v64; - u_int32_t vLSB,vMSB; - vLSB=bus_r(aLSB); - vMSB=bus_r(aMSB); - v64=vMSB; - v64=(v64<<32) | vLSB; - - printf("reg64(%x,%x) %x %x %llx\n", aLSB, aMSB, vLSB, vMSB, v64); - - return v64; -} - -int64_t setFrames(int64_t value){ - if(value!=-1) - printf("\nSetting number of frames to %lld\n",(long long int)value); - - int64_t retval = set64BitReg(value, SET_FRAMES_LSB_REG, SET_FRAMES_MSB_REG); - printf("Getting number of frames: %lld\n",(long long int)retval); - return retval; -} - -int64_t getFrames(){ - return get64BitReg(GET_FRAMES_LSB_REG, GET_FRAMES_MSB_REG); -} - -int64_t setExposureTime(int64_t value){ - if (value!=-1){ - printf("\nSetting exptime to %lldns\n",(long long int)value); - value*=(1E-3*clockdivider_exptime); - } - int64_t retval = set64BitReg(value,SET_EXPTIME_LSB_REG, SET_EXPTIME_MSB_REG)/(1E-3*clockdivider_exptime);//(1E-9*CLK_FREQ); - printf("Getting exptime: %lldns\n",(long long int)retval); - return retval; -} - -int64_t getExposureTime(){ - return get64BitReg(GET_EXPTIME_LSB_REG, GET_EXPTIME_MSB_REG)/(1E-3*clockdivider_exptime);//(1E-9*CLK_FREQ); -} - -int64_t setGates(int64_t value){ - if(value!=-1) - printf("\nSetting number of gates to %lld\n",(long long int)value); - - int64_t retval = set64BitReg(value, SET_GATES_LSB_REG, SET_GATES_MSB_REG); - printf("Getting number of gates: %lld\n",(long long int)retval); - return retval; -} - -int64_t getGates(){ - return get64BitReg(GET_GATES_LSB_REG, GET_GATES_MSB_REG); -} - -int64_t setPeriod(int64_t value){ - if (value!=-1){ - printf("\nSetting period to %lldns\n",(long long int)value); - value*=(1E-3*clockdivider_fc); - } - - int64_t retval = set64BitReg(value,SET_PERIOD_LSB_REG, SET_PERIOD_MSB_REG)/(1E-3*clockdivider_fc);//(1E-9*CLK_FREQ); - printf("Getting period: %lldns\n",(long long int)retval); - return retval; -} - -int64_t getPeriod(){ - return get64BitReg(GET_PERIOD_LSB_REG, GET_PERIOD_MSB_REG)/(1E-3*clockdivider_fc);//(1E-9*CLK_FREQ); -} - -int64_t setDelay(int64_t value){ - if (value!=-1){ - printf("\nSetting delay to %lldns\n",(long long int)value); - value*=(1E-3*clockdivider_fc); - } - - int64_t retval = set64BitReg(value,SET_DELAY_LSB_REG, SET_DELAY_MSB_REG)/(1E-3*clockdivider_fc);//(1E-9*CLK_FREQ); - printf("Getting delay: %lldns\n",(long long int)retval); - return retval; -} - -int64_t getDelay(){ - return get64BitReg(GET_DELAY_LSB_REG, GET_DELAY_MSB_REG)/(1E-3*clockdivider_fc);//(1E-9*CLK_FREQ); -} - -int64_t setTrains(int64_t value){ - if(value!=-1) - printf("\nSetting number of cycles to %lld\n",(long long int)value); - - int64_t retval = set64BitReg(value, SET_CYCLES_LSB_REG, SET_CYCLES_MSB_REG); - printf("Getting number of cycles: %lld\n",(long long int)retval); - return retval; -} - -int64_t getTrains(){ - return get64BitReg(GET_CYCLES_LSB_REG, GET_CYCLES_MSB_REG); -} - - -int64_t setSamples(int64_t value){ - if (value>=0) - bus_w(NSAMPLES_REG,value); - return bus_r(NSAMPLES_REG); -} - -int64_t getSamples(){ - return bus_r(NSAMPLES_REG);//get64BitReg(GET_CYCLES_LSB_REG, GET_CYCLES_MSB_REG); -} - - -int64_t setProbes(int64_t value){ - return 0; -} - - -int64_t setProgress() { - return 0; - -} - - -int64_t getProgress() { - - - //should be done in firmware!!!! - - return 0; - -} - -int64_t getActualTime(){ - return get64BitReg(GET_ACTUAL_TIME_LSB_REG, GET_ACTUAL_TIME_MSB_REG)/(1E-9*CLK_FREQ); -} - -int64_t getMeasurementTime(){ - int64_t v=get64BitReg(GET_MEASUREMENT_TIME_LSB_REG, GET_MEASUREMENT_TIME_MSB_REG); - return v/(1E-9*CLK_FREQ); -} - -int64_t getFramesFromStart(){ - int64_t v=get64BitReg(FRAMES_FROM_START_LSB_REG, FRAMES_FROM_START_MSB_REG); - int64_t v1=get64BitReg(FRAMES_FROM_START_PG_LSB_REG, FRAMES_FROM_START_PG_MSB_REG); - - printf("Frames from start data streaming %lld\n",v); - printf("Frames from start run control %lld\n",v1); - - return v; -} - - -ROI *setROI(int nroi,ROI* arg,int *retvalsize, int *ret) { - cprintf(RED,"ROI Not implemented yet\n"); - return NULL; -} - - -int loadImage(int index, short int ImageVals[]){ - printf("loadImage Not implemented yet\n"); - return OK; -} - - - -int64_t getProbes(){ - return 0; -} - - -int setDACRegister(int idac, int val, int imod) { - u_int32_t addr, reg, mask; - int off; -#ifdef VERBOSE - if(val==-1) - printf("Getting dac register%d module %d\n",idac,imod); - else - printf("Setting dac register %d module %d to %d\n",idac,imod,val); -#endif - - switch(idac){ - case 0: - case 1: - case 2: - addr=MOD_DACS1_REG; - break; - case 3: - case 4: - case 5: - addr=MOD_DACS2_REG; - break; - case 6: - case 7: - addr=MOD_DACS3_REG; - break; - default: - printf("weird idac value %d\n",idac); - return -1; - break; - } - //saving only the msb - val=val>>2; - - off=(idac%3)*10; - mask=~((0x3ff)<=0 && val>off)&0x3ff; - //since we saved only the msb - val=val<<2; - - //val=(bus_r(addr)>>off)&0x3ff; - - -#ifdef VERBOSE - printf("Dac %d module %d register is %d\n\n",idac,imod,val); -#endif - return val; -} - - -int getTemperature(int tempSensor, int imod){ - int val; - imod=0;//ignoring more than 1 mod for now - int i,j,repeats=6; - u_int32_t tempVal=0; -#ifdef VERBOSE - char cTempSensor[2][100]={"ADCs/ASICs","VRs/FPGAs"}; - printf("Getting Temperature of module:%d for the %s for tempsensor:%d\n",imod,cTempSensor[tempSensor],tempSensor); -#endif - bus_w(TEMP_IN_REG,(T1_CLK_BIT)|(T1_CS_BIT)|(T2_CLK_BIT)|(T2_CS_BIT));//standby - bus_w(TEMP_IN_REG,((T1_CLK_BIT)&~(T1_CS_BIT))|(T2_CLK_BIT));//high clk low cs - - for(i=0;i<20;i++) { - //repeats is number of register writes for delay - for(j=0;j>1);//fpga - } - } - - bus_w(TEMP_IN_REG,(T1_CLK_BIT)|(T1_CS_BIT)|(T2_CLK_BIT)|(T2_CS_BIT));//standby - val=((int)tempVal)/4.0; - -#ifdef VERBOSE - printf("Temperature of module:%d for the %s is %.2fC\n",imod,cTempSensor[tempSensor],val); -#endif - return val; -} - - - -int initHighVoltage(int val, int imod){ - - - u_int32_t offw,codata; - u_int16_t valw, dacvalue; - int i,ddx,csdx,cdx; - float alpha=0.55; - - if (val>=0) { - if (val<60) { - dacvalue=0; - val=60; - } else if (val>=200) { - dacvalue=0x1; - val=200; - } else { - dacvalue=1.+(200.-val)/alpha; - val=200.-(dacvalue-1)*alpha; - } - printf ("****************************** setting val %d, dacval %d\n",val, dacvalue); - offw=DAC_REG; - - ddx=8; csdx=10; cdx=9; - codata=((dacvalue)&0xff); - - - - - valw=0xffff; bus_w(offw,(valw)); // start point - valw=((valw&(~(0x1<>(7-i))&0x1)<>SPEED_GAIN_OFFSET); - //#ifdef VERBOSE - printf("Value read from Speed of Gain reg is 0x%x\n",retval); - printf("Gain Reg Value is 0x%x\n",bus_r(addr)); - //#endif - return retval; -} - - -int setADC(int adc){ - int reg,nchips,mask,nchans; - - if(adc==-1) ROI_flag=0; - else ROI_flag=1; - - // setDAQRegister();//token timing - cleanFifo();//adc sync - - //with moench module all adc - //set packet size - ipPacketSize= DEFAULT_IP_PACKETSIZE; - udpPacketSize=DEFAULT_UDP_PACKETSIZE; - //set channel mask - nchips = NCHIP; - nchans = NCHANS; - mask = ACTIVE_ADC_MASK; - - //set channel mask - reg = (nchans*nchips)< 1 ) { - sum += *addr++; - count -= 2; - } - if( count > 0 ) sum += *addr; // Add left-over byte, if any - while (sum>>16) sum = (sum & 0xffff) + (sum >> 16);// Fold 32-bit sum to 16 bits - checksum = (~sum)&0xffff; - - printf("IP checksum is 0x%lx\n",checksum); - - return checksum; -} - - - -#ifdef NEW_GBE_INTERFACE -int writeGbeReg(int ivar, uint32_t val, int addr, int interface) { - /* #define GBE_CTRL_WSTROBE 0 */ - /* #define GBE_CTRL_VAR_OFFSET 16 */ - /* #define GBE_CTRL_VAR_MASK 0XF */ - /* #define GBE_CTRL_RAMADDR_OFFSET 24 */ - /* #define GBE_CTRL_RAMADDR_MASK 0X3F */ - /* #define GBE_CTRL_INTERFACE 23 */ - uint32_t ctrl=((ivar&GBE_CTRL_VAR_MASK)<>32)&0xFFFFFFFF; - vals[IPCHECKSUM_ADDR]=checksum; - vals[GBE_DELAY_ADDR]=0; - vals[GBE_RESERVED1_ADDR]=sourceport; - vals[GBE_RESERVED2_ADDR]=interface; - vals[DETECTOR_MAC_L_ADDR]=(sourcemac)&0xFFFFFFFF; - vals[DETECTOR_MAC_H_ADDR]=(sourcemac>>32)&0xFFFFFFFF; - vals[DETECTOR_IP_ADDR]=sourceip; - - for (ivar=0; ivar>32)&0xFFFFFFFF);//rx_udpmacH_AReg_c - bus_w(RX_UDPMACL_AREG,(destmac)&0xFFFFFFFF);//rx_udpmacL_AReg_c - bus_w(DETECTORMACH_AREG,(sourcemac>>32)&0xFFFFFFFF);//detectormacH_AReg_c - bus_w(DETECTORMACL_AREG,(sourcemac)&0xFFFFFFFF);//detectormacL_AReg_c - bus_w(UDPPORTS_AREG,((sourceport&0xFFFF)<<16)+(destport&0xFFFF));//udpports_AReg_c - bus_w(IPCHKSUM_AREG,(checksum&0xFFFF));//ipchksum_AReg_c - - -#endif - - //bus_w(CONTROL_REG,GB10_RESET_BIT); - //usleep(50 * 1000); - bus_w(CONTROL_REG,0); - //usleep(500* 1000); - //bus_w(CONFIG_REG,conf | GB10_NOT_CPU_BIT); - printf("System status register is %08x\n",bus_r(SYSTEM_STATUS_REG)); - - - /* - bus_w(CONTROL_REG,GB10_RESET_BIT); - bus_w(CONTROL_REG,0); - usleep(500 * 1000); - bus_w(CONFIG_REG,conf | GB10_NOT_CPU_BIT); - printf("System status register is %08x\n",bus_r(SYSTEM_STATUS_REG)); - */ - - printf("Reset mem machine fifos\n"); - bus_w(MEM_MACHINE_FIFOS_REG,0x4000); - bus_w(MEM_MACHINE_FIFOS_REG,0x0); - printf("Reset run control\n"); - bus_w(MEM_MACHINE_FIFOS_REG,0x0400); - bus_w(MEM_MACHINE_FIFOS_REG,0x0); - - usleep(500 * 1000); - - return 0; //any value doesnt matter - dhanya - -} - - - - - - - - - - - -int configureMAC(uint32_t destip,uint64_t destmac,uint64_t sourcemac,int sourceip,int ival,uint32_t destport) { - //int configureMAC(int ipad,long long int macad,long long int detectormacad, int detipad, int ival, int udpport){ - - - - - - /*volatile u_int32_t conf= bus_r(CONFIG_REG);*/ - uint32_t sourceport = 0x7e9a; // 0xE185; - int interface=0; - int ngb; - -#ifdef NEW_GBE_INTERFACE - ngb=2; - printf("--------- New XGB interface\n"); -#else - ngb=1; - printf("********* Old XGB interface\n"); -#endif - - for (interface=0; interface >((i)*2))==3) { *\/ */ -/* /\* i++; *\/ */ -/* /\* if (i>15) *\/ */ -/* /\* break; *\/ */ -/* /\* } *\/ */ -/* /\* if (i<16) { *\/ */ -/* bus_w16(DUMMY_REG,i); */ -/* } */ -/* val=*values; */ - - - // bus_w16(DUMMY_REG,0); // - for (i=0; i<32; i++) { - - - // bus_w16(DUMMY_REG,i); - // bus_r16(DUMMY_REG); -/* dum=(((u_int16_t*)(now_ptr))+i); */ -/* *dum=bus_r16(FIFO_DATA_REG); */ -/* a=bus_r16(FIFO_DATA_REG); */ - //dum=(((u_int32_t*)(now_ptr))+i); - - // a=*values;//bus_r(FIFO_DATA_REG); - // if ((adcDisableMask&(3<<(i*2)))==0) { - *((u_int32_t*)now_ptr)=*values;//bus_r(FIFO_DATA_REG); - - - if (i!=0 || ns!=0) { - a=0; - while (*((u_int32_t*)now_ptr)==*((u_int32_t*)(now_ptr)-1) && a++<10) { - - // printf("******************** %d: fifo %d: new %08x old %08x\n ",ns, i, *((u_int32_t*)now_ptr),*((u_int32_t*)(now_ptr)-1)); - *((u_int32_t*)now_ptr)=*values; - // printf("%d-",i); - - } - } - now_ptr+=4; - // } -/* while (((adcDisableMask&(3<<((i+1)*2)))>>((i+1)*2))==3) { */ -/* i++; */ -/* } */ - - // if (((adcDisableMask&(3<<((i+1)*2)))>>((i+1)*2))!=3) { - printf("sample %d fifo %d status %08x\n",ns,i,bus_r16(FIFO_STATUS_REG)); - bus_w16(DUMMY_REG,i+1); - // } - // *(((u_int16_t*)(now_ptr))+i)=bus_r16(FIFO_DATA_REG); - } - // bus_w16(DUMMY_REG,0); // -/* #ifdef TIMEDBG */ - -/* gettimeofday(&tss,NULL); */ -/* printf("read data loop = %ld usec\n",(tss.tv_usec) - (tse.tv_usec)); */ - -/* #endif */ -#ifdef VERBOSE - printf("*"); -#endif - return ram_values; -======= -u_int32_t fifo_full(void){ - return bus_r(STATUS_REG)&SOME_FIFO_FULL_BIT; ->>>>>>> f24459bee05f373e2830bb24388e40f0b2983d5a -} - - - -void waitForAcquisitionEnd(){ - while(runBusy()){ - usleep(500); - } -} - - - - - - - - - - -u_int32_t* decode_data(int *datain) -{ - u_int32_t *dataout; - // const char one=1; - const int bytesize=8; - char *ptr=(char*)datain; - //int nbits=dynamicRange; - int ipos=0, ichan=0;; - //int nch, boff=0; - int ibyte;//, ibit; - char iptr; - -#ifdef VERBOSE - printf("Decoding data for DR %d\n",dynamicRange); -#endif - dataout=malloc(NCHAN*NCHIP*nModX*4); - ichan=0; - switch (dynamicRange) { - case 1: - for (ibyte=0; ibyte>(ipos))&0x1; - ichan++; - } - } - break; - case 4: - for (ibyte=0; ibyte>(ipos*4))&0xf; - ichan++; - } - } - break; - case 8: - for (ichan=0; ichan0) { - dynamicRange=16; - // nSamples=dr/16; - // bus_w(NSAMPLES_REG,nSamples); - } - getDynamicRange(); - allocateRAM(); - printf("Setting dataBytes to %d: dr %d; samples %d\n",dataBytes, dynamicRange, nSamples); - return getDynamicRange(); -======= - return dynamicRange; ->>>>>>> f24459bee05f373e2830bb24388e40f0b2983d5a -} - - -int getDynamicRange() { -<<<<<<< HEAD - if(myDetectorType == JUNGFRAU){ - dynamicRange=16; - return dynamicRange; - } - - nSamples=bus_r(NSAMPLES_REG); - getChannels(); - dataBytes=nModX*N_CHIP*getChannels()*2*nSamples; - return dynamicRange;//*bus_r(NSAMPLES_REG);//nSamples; -======= - return dynamicRange; ->>>>>>> f24459bee05f373e2830bb24388e40f0b2983d5a -} - -int testBus() { - u_int32_t j; - u_int64_t i, n, nt; - // char cmd[100]; - u_int32_t val=0x0; - int ifail=OK; - // printf("%s\n",cmd); - // system(cmd); - i=0; - - n=1000000; - nt=n/100; - printf("testing bus %d times\n",(int)n); - while (i0) - storeInRAM=1; - else - storeInRAM=0; - return OK; -} - -int getChannels() { - int nch=32; - int i; - for (i=0; i>(23-i))&0x1)<-2) { - dataret=FAIL; - printf("no data and run stopped: %d frames left\n",(int)(getFrames()+2)); - } else { - dataret=FINISHED; - printf("acquisition successfully finished\n"); - } - } - - - - //double nf = (double)numberFrames; - for(i =0; i < 1280; i++){ - adc = i / 256; - adcCh = (i - adc * 256) / 32; - Ch = i - adc * 256 - adcCh * 32; - adc--; - double v2 = avg[i]; - avg[i] = avg[i]/ ((double)numberFrames/(double)frames); - unsigned short v = (unsigned short)avg[i]; - printf("setting avg for channel %i(%i,%i,%i): %i (double= %f (%f))\t", i,adc,adcCh,Ch, v,avg[i],v2); - v=i*100; - ram_w16(DARK_IMAGE_REG,adc,adcCh,Ch,v-4096); - if(ram_r16(DARK_IMAGE_REG,adc,adcCh,Ch) != v-4096){ - printf("value is wrong (%i,%i,%i): %i \n",adc,adcCh,Ch, ram_r16(DARK_IMAGE_REG,adc,adcCh,Ch)); - } - } - - - - printf("frames: %i\n",numberFrames); - printf("corrected avg by: %f\n",(double)numberFrames/(double)frames); - - printf("restoring previous condition\n"); - setFrames(framesBefore); - setPeriod(periodBefore); - - printf("---------------------------\n"); - return 0; -} - - - - -uint64_t readPatternWord(int addr) { - uint64_t word=0; - int cntrl=0; - - if (addr>=MAX_PATTERN_LENGTH) - return -1; - - - printf("read %x\n",addr); - cntrl= (addr&APATTERN_MASK) << PATTERN_CTRL_ADDR_OFFSET; - bus_w(PATTERN_CNTRL_REG, cntrl); - usleep(1000); - bus_w(PATTERN_CNTRL_REG, cntrl | (1<< PATTERN_CTRL_READ_BIT) ); - usleep(1000); - printf("reading\n"); - word=get64BitReg(PATTERN_OUT_LSB_REG,PATTERN_OUT_MSB_REG); - printf("read %llx\n", word); - usleep(1000); - bus_w(PATTERN_CNTRL_REG, cntrl); - printf("done\n"); - - return word; -} - -uint64_t writePatternWord(int addr, uint64_t word) { - - - int cntrl=0; - if (addr>=MAX_PATTERN_LENGTH) - return -1; - - printf("write %x %llx\n",addr, word); - if (word!=-1){ - - set64BitReg(word,PATTERN_IN_REG_LSB,PATTERN_IN_REG_MSB); - - - cntrl= (addr&APATTERN_MASK) << PATTERN_CTRL_ADDR_OFFSET; - bus_w(PATTERN_CNTRL_REG, cntrl); - usleep(1000); - bus_w(PATTERN_CNTRL_REG, cntrl | (1<< PATTERN_CTRL_WRITE_BIT) ); - usleep(1000); - bus_w(PATTERN_CNTRL_REG, cntrl); - return word; - } else - return readPatternWord(addr); -} - -uint64_t writePatternIOControl(uint64_t word) { - return FAIL; -} - -uint64_t writePatternClkControl(uint64_t word) { - return FAIL; -} - -int setPatternLoop(int level, int *start, int *stop, int *n) { - int ret=OK; - int lval=0; - - int nreg; - int areg; - - switch (level ) { - case 0: - nreg=PATTERN_N_LOOP0_REG; - areg=PATTERN_LOOP0_AREG; - break; - case 1: - nreg=PATTERN_N_LOOP1_REG; - areg=PATTERN_LOOP1_AREG; - break; - case 2: - nreg=PATTERN_N_LOOP2_REG; - areg=PATTERN_LOOP2_AREG; - break; - case -1: - nreg=-1; - areg=PATTERN_LIMITS_AREG; - break; - default: - return FAIL; - } - - printf("level %d start %x stop %x nl %d\n",level, *start, *stop, *n); - if (nreg>=0) { - if ((*n)>=0) bus_w(nreg, *n); - printf ("n %d\n",*n); - *n=bus_r(nreg); - printf ("n %d\n",*n); - - } - - printf("level %d start %x stop %x nl %d\n",level, *start, *stop, *n); - lval=bus_r(areg); - /* printf("l=%x\n",bus_r16(areg)); */ - /* printf("m=%x\n",bus_r16_m(areg)); */ - - - - - - printf("lval %x\n",lval); - if (*start==-1) *start=(lval>> ASTART_OFFSET) & APATTERN_MASK; - printf("start %x\n",*start); - - - if (*stop==-1) *stop=(lval>> ASTOP_OFFSET) & APATTERN_MASK; - printf("stop %x\n",*stop); - - lval= ((*start & APATTERN_MASK) << ASTART_OFFSET) | ((*stop & APATTERN_MASK) << ASTOP_OFFSET); - printf("lval %x\n",lval); - - bus_w(areg,lval); - printf("lval %x\n",lval); - - - return ret; -} - - -int setPatternWaitAddress(int level, int addr) { - int reg; - - switch (level) { - case 0: - reg=PATTERN_WAIT0_AREG; - break; - case 1: - reg=PATTERN_WAIT1_AREG; - break; - case 2: - reg=PATTERN_WAIT2_AREG; - break; - default: - return -1; - }; - // printf("BEFORE *********PATTERN IOCTRL IS %llx (%x)\n",writePatternIOControl(-1), PATTERN_IOCTRL_REG_MSB); - - // printf ("%d addr %x (%x)\n",level,addr,reg); - if (addr>=0) bus_w(reg, addr); - // printf ("%d addr %x %x (%x) \n",level,addr, bus_r(reg), reg); - - // printf("AFTER *********PATTERN IOCTRL IS %llx (%x)\n",writePatternIOControl(-1), PATTERN_IOCTRL_REG_MSB); - - return bus_r(reg); -} - - -uint64_t setPatternWaitTime(int level, uint64_t t) { - int reglsb; - int regmsb; - - - switch (level) { - case 0: - reglsb=PATTERN_WAIT0_TIME_REG_LSB; - regmsb=PATTERN_WAIT0_TIME_REG_MSB; - break; - case 1: - reglsb=PATTERN_WAIT1_TIME_REG_LSB; - regmsb=PATTERN_WAIT1_TIME_REG_MSB; - break; - case 2: - reglsb=PATTERN_WAIT2_TIME_REG_LSB; - regmsb=PATTERN_WAIT2_TIME_REG_MSB; - break; - default: - return -1; - } - - - if (t>=0) set64BitReg(t,reglsb,regmsb); - return get64BitReg(reglsb,regmsb); - -} - - -void initDac(int dacnum) { - printf("\nInitializing dac for %d\n",dacnum); - - u_int32_t offw,codata; - u_int16_t valw; - int i,ddx,csdx,cdx; - - - - //setting int reference - offw=DAC_REG; - - - ddx=0; cdx=1; - csdx=dacnum/8+2; - - - printf("data bit=%d, clkbit=%d, csbit=%d\n",ddx,cdx,csdx); - codata=(((0x6<<4)+(0xf<<16))+((0x0<<4)&0xfff0)); - - valw=0xffff; bus_w(offw,(valw)); // start point - valw=((valw&(~(0x1<>(24-i))&0x1)<>(24-i))&0x1)); - - - valw=((valw&(~(0x1<>16)&0xffff; - else - return retval&0xffff; - -} - - -int setDac(int dacnum,int dacvalue){ - printf("\nSetting of DAC %d with value %d\n",dacnum,dacvalue); - - u_int32_t offw,codata; - u_int16_t valw; - int i,ddx,csdx,cdx; - - int dacch=0; - - if (dacvalue>=0) { - - //setting int reference - offw=DAC_REG; - - - ddx=0; cdx=1; - csdx=dacnum/8+2; - - dacch=dacnum%8; - - printf("data bit=%d, clkbit=%d, csbit=%d\n",ddx,cdx,csdx); - //modified to power down single channels - // codata=((((0x2)<<4)+((dacch)&0xf))<<16)+((dacvalue<<4)&0xfff0); - codata=((((0x3)<<4)+((dacch)&0xf))<<16)+((dacvalue<<4)&0xfff0); - valw=0xffff; bus_w(offw,(valw)); // start point - valw=((valw&(~(0x1<>(24-i))&0x1)<>(24-i))&0x1)); - valw=((valw&(~(0x1<>(24-i))&0x1)<>(24-i))&0x1)); - valw=((valw&(~(0x1< -#include -#include -#include -#include -#include -#include -//#include -#include -#include -#include -#include -#include -#include - - -int mapCSP0(void); -void defineGPIOpins(); -void resetFPGA(); -void FPGAdontTouchFlash(); -void FPGATouchFlash(); -int powerChip (int on); -void initializeDetector(); - -u_int16_t bus_r16(u_int32_t offset); -u_int16_t bus_w16(u_int32_t offset, u_int16_t data);//aldos function -u_int32_t bus_w(u_int32_t offset, u_int32_t data); -u_int32_t bus_r(u_int32_t offset); - -int setPhaseShiftOnce(); -int adcPhase(int st); -int getPhase(); -int cleanFifo(); -int setDAQRegister(); - -u_int32_t putout(char *s, int modnum); -u_int32_t readin(int modnum); -u_int32_t setClockDivider(int d); -u_int32_t getClockDivider(); - -void resetPLL(); -u_int32_t setPllReconfigReg(u_int32_t reg, u_int32_t val, int trig); -u_int32_t getPllReconfigReg(u_int32_t reg, int trig); - -u_int32_t setSetLength(int d); -u_int32_t getSetLength(); -u_int32_t setWaitStates(int d); -u_int32_t getWaitStates(); -u_int32_t setTotClockDivider(int d); -u_int32_t getTotClockDivider(); -u_int32_t setTotDutyCycle(int d); -u_int32_t getTotDutyCycle(); -u_int32_t setOversampling(int d); -u_int32_t adcPipeline(int d); -u_int32_t dbitPipeline(int d); - -u_int32_t setExtSignal(int d, enum externalSignalFlag mode); -int getExtSignal(int d); - -u_int32_t setFPGASignal(int d, enum externalSignalFlag mode); -int getFPGASignal(int d); - -int setTiming(int t); - - -int setConfigurationRegister(int d); -int setToT(int d); -int setContinousReadOut(int d); - -int setDACRegister(int idac, int val, int imod); -int getDacRegister(int dacnum); - - -int getTemperature(int tempSensor,int imod); -int initHighVoltage(int val,int imod); -int initConfGain(int isettings,int val,int imod); -int initSpeedConfGain(int val); - -int setADC(int adc); -//int configureMAC(int ipad, long long int macad, long long int detectormacadd, int detipad, int ival, int udpport); -int configureMAC(uint32_t destip,uint64_t destmac,uint64_t sourcemac,int detipad,int ival,uint32_t destport); -int getAdcConfigured(); - - -u_int64_t getDetectorNumber(); -u_int32_t getFirmwareVersion(); -u_int32_t getFirmwareSVNVersion(); - -int testFifos(void); -u_int32_t testFpga(void); -u_int32_t testRAM(void); -int testBus(void); -int setDigitalTestBit(int ival); - -int64_t set64BitReg(int64_t value, int aLSB, int aMSB); -int64_t get64BitReg(int aLSB, int aMSB); - -int64_t setFrames(int64_t value); -int64_t getFrames(); - -int64_t setExposureTime(int64_t value); -int64_t getExposureTime(); - -int64_t setGates(int64_t value); -int64_t getGates(); - -int64_t setDelay(int64_t value); -int64_t getDelay(); - -int64_t setPeriod(int64_t value); -int64_t getPeriod(); - -int64_t setTrains(int64_t value); -int64_t getTrains(); - - -int64_t setProbes(int64_t value); -int64_t getProbes(); - -int64_t setSamples(int64_t value); -int64_t getSamples(); - -int64_t getProgress(); -int64_t setProgress(); - -int64_t getActualTime(); -int64_t getMeasurementTime(); -int64_t getFramesFromStart(); - -u_int32_t runBusy(void); -u_int32_t runState(void); -u_int32_t dataPresent(void); - - -int startStateMachine(); -int stopStateMachine(); -int startReadOut(); -u_int32_t fifoReset(void); -u_int32_t fifoReadCounter(int fifonum); -u_int32_t fifoReadStatus(); - - -u_int32_t fifo_full(void); - - -void waitForAcquisitionEnd(); -u_int32_t* decode_data(int* datain); -//u_int32_t move_data(u_int64_t* datain, u_int64_t* dataout); -int setDynamicRange(int dr); -int getDynamicRange(); -int getNModBoard(); -int setNMod(int n); -int getNMod(); - -int setStoreInRAM(int b); -int allocateRAM(); - - -int writeADC(int addr, int val); -int prepareADC(); - - -int clearRAM(); - - -int setMaster(int f); -int setSynchronization(int s); - -int loadImage(int index, short int ImageVals[]); -int readCounterBlock(int startACQ, short int CounterVals[]); -int resetCounterBlock(int startACQ); - -int calibratePedestal(int frames); - -uint64_t writePatternWord(int addr, uint64_t word); -uint64_t writePatternIOControl(uint64_t word); -uint64_t writePatternClkControl(uint64_t word); -int setPatternLoop(int level, int *start, int *stop, int *n); -int setPatternWaitAddress(int level, int addr); -uint64_t setPatternWaitTime(int level, uint64_t t); - - -void initDac(int dacnum); -int setDac(int dacnum,int dacvalue); - -ROI *setROI(int nroi,ROI* arg,int *retvalsize, int *ret); -int getChannels(); - -void eraseFlash(); -int startWritingFPGAprogram(FILE** filefp); -int stopWritingFPGAprogram(FILE* filefp); -int writeFPGAProgram(char* fpgasrc, size_t fsize, FILE* filefp); - -/* - -u_int32_t setNBits(u_int32_t); -u_int32_t getNBits(); -*/ - -/* -//move to mcb_funcs? - -int readOutChan(int *val); -u_int32_t getModuleNumber(int modnum); -int testShiftIn(int imod); -int testShiftOut(int imod); -int testShiftStSel(int imod); -int testDataInOut(int num, int imod); -int testExtPulse(int imod); -int testExtPulseMux(int imod, int ow); -int testDataInOutMux(int imod, int ow, int num); -int testOutMux(int imod); -int testFpgaMux(int imod); -int calibration_sensor(int num, int *values, int *dacs) ; -int calibration_chip(int num, int *values, int *dacs); -*/ - - -#endif diff --git a/slsDetectorSoftware/jungfrauDetectorServer/gitInfo.txt b/slsDetectorSoftware/jungfrauDetectorServer/gitInfo.txt index c64e4f71a..47883d08a 100644 --- a/slsDetectorSoftware/jungfrauDetectorServer/gitInfo.txt +++ b/slsDetectorSoftware/jungfrauDetectorServer/gitInfo.txt @@ -1,9 +1,9 @@ Path: slsDetectorsPackage/slsDetectorSoftware/jungfrauDetectorServer URL: origin git@git.psi.ch:sls_detectors_software/sls_detector_software.git/jungfrauDetectorServer Repository Root: origin git@git.psi.ch:sls_detectors_software/sls_detector_software.git -Repsitory UUID: 230d6b36e9852214f4ba5ae7c92647f35000b24d -Revision: 56 +Repsitory UUID: 6d38c0622a2936f70345e7d53aaf1c9e2de4cbd6 +Revision: 75 Branch: developer Last Changed Author: Dhanya_Maliakal -Last Changed Rev: 1313 -Last Changed Date: 2016-11-30 10:36:34 +0100 +Last Changed Rev: 1401 +Last Changed Date: 2017-06-12 18:53:18 +0200 diff --git a/slsDetectorSoftware/jungfrauDetectorServer/gitInfoJungfrau.h b/slsDetectorSoftware/jungfrauDetectorServer/gitInfoJungfrau.h index 633eb8933..5c0673ff4 100644 --- a/slsDetectorSoftware/jungfrauDetectorServer/gitInfoJungfrau.h +++ b/slsDetectorSoftware/jungfrauDetectorServer/gitInfoJungfrau.h @@ -1,11 +1,11 @@ //#define SVNPATH "" #define SVNURL "git@git.psi.ch:sls_detectors_software/sls_detector_software.git/jungfrauDetectorServer" //#define SVNREPPATH "" -#define SVNREPUUID "230d6b36e9852214f4ba5ae7c92647f35000b24d" -//#define SVNREV 0x1313 +#define SVNREPUUID "6d38c0622a2936f70345e7d53aaf1c9e2de4cbd6" +//#define SVNREV 0x1401 //#define SVNKIND "" //#define SVNSCHED "" #define SVNAUTH "Dhanya_Maliakal" -#define SVNREV 0x1313 -#define SVNDATE 0x20161130 +#define SVNREV 0x1401 +#define SVNDATE 0x20170612 // diff --git a/slsDetectorSoftware/jungfrauDetectorServer/jungfrauDetectorServerv2.2.1 b/slsDetectorSoftware/jungfrauDetectorServer/jungfrauDetectorServerv2.2.1 deleted file mode 100755 index 6014d803c..000000000 Binary files a/slsDetectorSoftware/jungfrauDetectorServer/jungfrauDetectorServerv2.2.1 and /dev/null differ diff --git a/slsDetectorSoftware/jungfrauDetectorServer/mcb_funcs.c b/slsDetectorSoftware/jungfrauDetectorServer/mcb_funcs.c deleted file mode 100755 index 2c22e1143..000000000 --- a/slsDetectorSoftware/jungfrauDetectorServer/mcb_funcs.c +++ /dev/null @@ -1,1933 +0,0 @@ -#ifdef MCB_FUNCS - -#include -#include -#include -#include -#include -#include "registers_m.h" - -#ifndef PICASSOD -#include "server_defs.h" -#else -#include "picasso_defs.h" -#endif -#include "firmware_funcs.h" -#include "mcb_funcs.h" - - -/* global variables */ -#undef DEBUG -#undef DEBUGOUT - -extern enum detectorType myDetectorType; -extern int nModX; -extern int dynamicRange; -enum detectorSettings thisSettings; - -int sChan, sChip, sMod, sDac, sAdc; -const int allSelected=-2; -const int noneSelected=-1; - -sls_detector_module *detectorModules=NULL; -int *detectorChips=NULL; -int *detectorChans=NULL; -int *detectorDacs=NULL; -int *detectorAdcs=NULL; - - - -int initDetector() { - int imod; - int n=getNModBoard(); - nModX=n; -#ifdef VERBOSE - printf("Board is for %d modules\n",n); -#endif - detectorModules=malloc(n*sizeof(sls_detector_module)); - detectorDacs=malloc(n*NDAC*sizeof(int)); - detectorAdcs=malloc(n*NADC*sizeof(int)); - detectorChips=NULL; - detectorChans=NULL; - detectorAdcs=NULL; -#ifdef VERBOSE - printf("modules from 0x%x to 0x%x\n",(unsigned int)(detectorModules), (unsigned int)(detectorModules+n)); - printf("dacs from 0x%x to 0x%x\n",(unsigned int)(detectorDacs), (unsigned int)(detectorDacs+n*NDAC)); - printf("adcs from 0x%x to 0x%x\n",(unsigned int)(detectorAdcs), (unsigned int)(detectorAdcs+n*NADC)); -#endif - - - for (imod=0; imoddacs=detectorDacs+imod*NDAC; - (detectorModules+imod)->adcs=detectorAdcs+imod*NADC; - (detectorModules+imod)->ndac=NDAC; - (detectorModules+imod)->nadc=NADC; - (detectorModules+imod)->nchip=NCHIP; - (detectorModules+imod)->nchan=NCHIP*NCHAN; - (detectorModules+imod)->module=imod; - (detectorModules+imod)->gain=0; - (detectorModules+imod)->offset=0; - (detectorModules+imod)->reg=0; - } - thisSettings=UNINITIALIZED; - sChan=noneSelected; - sChip=noneSelected; - sMod=noneSelected; - sDac=noneSelected; - sAdc=noneSelected; - - return OK; -} - - - - -int copyChannel(sls_detector_channel *destChan, sls_detector_channel *srcChan) { - destChan->chan=srcChan->chan; - destChan->chip=srcChan->chip; - destChan->module=srcChan->module; - destChan->reg=srcChan->reg; - return OK; -} - - -int copyChip(sls_detector_chip *destChip, sls_detector_chip *srcChip) { - - int ichan; - int ret=OK; - if ((srcChip->nchan)>(destChip->nchan)) { - printf("Number of channels of source is larger than number of channels of destination\n"); - return FAIL; - } - - destChip->nchan=srcChip->nchan; - destChip->reg=srcChip->reg; - destChip->chip=srcChip->chip; - destChip->module=srcChip->module; - for (ichan=0; ichan<(srcChip->nchan); ichan++) { - *((destChip->chanregs)+ichan)=*((srcChip->chanregs)+ichan); - } - return ret; -} - - -int copyModule(sls_detector_module *destMod, sls_detector_module *srcMod) { - - int idac, iadc; - - int ret=OK; - -#ifdef VERBOSE - printf("Copying module %x to module %x\n",(unsigned int)(srcMod),(unsigned int)(destMod)); -#endif - - if (srcMod->module>=0) { -#ifdef VERBOSE - printf("Copying module number %d to module number %d\n",srcMod->module,destMod->module); -#endif - destMod->module=srcMod->module; - } - if (srcMod->serialnumber>=0){ -/* #ifdef VERBOSE */ -/* printf("Copying module serial number %x to module serial number %x\n",srcMod->serialnumber,destMod->serialnumber); */ -/* #endif */ - destMod->serialnumber=srcMod->serialnumber; - } - - /* - if ((srcMod->nchip)>(destMod->nchip)) { - printf("Number of chip of source is larger than number of chips of destination\n"); - return FAIL; - } - if ((srcMod->nchan)>(destMod->nchan)) { - printf("Number of channels of source is larger than number of channels of destination\n"); - return FAIL; - } - */ - - if ((srcMod->ndac)>(destMod->ndac)) { - printf("Number of dacs of source is larger than number of dacs of destination\n"); - return FAIL; - } - if ((srcMod->nadc)>(destMod->nadc)) { - printf("Number of dacs of source is larger than number of dacs of destination\n"); - return FAIL; - } - -#ifdef VERBOSE - printf("DACs: src %d, dest %d\n",srcMod->ndac,destMod->ndac); - printf("ADCs: src %d, dest %d\n",srcMod->nadc,destMod->nadc); - //printf("Chips: src %d, dest %d\n",srcMod->nchip,destMod->nchip); - //printf("Chans: src %d, dest %d\n",srcMod->nchan,destMod->nchan); - -#endif - - - - destMod->ndac=srcMod->ndac; - destMod->nadc=srcMod->nadc; - // destMod->nchip=srcMod->nchip; - //destMod->nchan=srcMod->nchan; - if (srcMod->reg>=0) - destMod->reg=srcMod->reg; -#ifdef VERBOSE - printf("Copying register %x (%x)\n",destMod->reg,srcMod->reg ); -#endif - if (srcMod->gain>=0) - destMod->gain=srcMod->gain; - if (srcMod->offset>=0) - destMod->offset=srcMod->offset; - - // printf("copying gain and offset %f %f to %f %f\n",srcMod->gain,srcMod->offset,destMod->gain,destMod->offset); - - - for (idac=0; idac<(srcMod->ndac); idac++) { - if (*((srcMod->dacs)+idac)>=0) - *((destMod->dacs)+idac)=*((srcMod->dacs)+idac); - } - - for (iadc=0; iadc<(srcMod->nadc); iadc++) { - if (*((srcMod->adcs)+iadc)>=0) - *((destMod->adcs)+iadc)=*((srcMod->adcs)+iadc); - } - - return ret; -} - - - -int clearCSregister(int imod) { - - putout("0000000001000000",imod); - putout("0000100001000000",imod); - putout("0000100001000000",imod); - putout("0000000001000000",imod); -#ifdef DEBUG - fprintf(stdout, "Clearing CS shiftregister\n"); -#endif - /* - sChan=noneSelected; - sMod=noneSelected; - sDac=noneSelected; - sAdc=noneSelected; - */ - sChip=noneSelected; - sMod=imod; - if (imod==ALLMOD) - sMod=allSelected; - //putout("0000000000000000",imod); - return 0; -} - -int setCSregister(int imod){ - - putout("0000000001000000",imod); - putout("0001000001000000",imod); - putout("0001000001000000",imod); - putout("0000000001000000",imod); -#ifdef DEBUG - fprintf(stdout, "Setting CS shiftregister\n"); -#endif - putout("0000000000000000",imod); - sChip=allSelected; - sMod=imod; - if (imod==ALLMOD) - sMod=allSelected; - return 0; -} - -int nextChip(int imod){ - - putout("0000000001000000",imod); - putout("0010000001000000",imod); - putout("0000000001000000",imod); -#ifdef DEBUG - fprintf(stdout, "Next Chip\n"); -#endif - sChip++; - sMod=imod; - if (imod==ALLMOD) - sMod=allSelected; - return 0; -} - -int firstChip(int imod){ - - putout("0100000001000000",imod); - putout("0110000001000000",imod); - putout("0100000001000000",imod); -#ifdef DEBUG - fprintf(stdout, "First Chip\n"); -#endif - sChip=0; - sMod=imod; - if (imod==ALLMOD) - sMod=allSelected; - return 0; -} - -int clearSSregister(int imod){ - int i; - putout("0000011000000000",imod); - for (i=0; i<10; i++) - putout("0000111000000000",imod); - putout("0000011000000000",imod); -#ifdef DEBUG - fprintf(stdout,"Clearing SS shiftregister\n"); -#endif - putout("0000000000000000",imod); - sChan=noneSelected; - sMod=imod; - if (imod==ALLMOD) - sMod=allSelected; - return 0; -} - -int setSSregister(int imod){ - int i; - putout("0000011000000000",imod); - for (i=0; i<10; i++) - putout("0001011000000000",imod); - putout("0000011000000000",imod); -#ifdef DEBUG - fprintf(stdout,"Setting SS shiftregister\n"); -#endif - putout("0000000000000000",imod); - sChan=allSelected; - sMod=imod; - if (imod==ALLMOD) - sMod=allSelected; - return 0; -} - -int nextStrip(int imod){ - putout("0000011000000000",imod); - putout("0010011000000000",imod); - putout("0000011000000000",imod); -#ifdef DEBUG - fprintf(stdout,"|-"); -#endif - sChan++; - sMod=imod; - if (imod==ALLMOD) - sMod=allSelected; - return 0; -} - -int selChannel(const int strip,int imod) { - int istrip; - clearSSregister(imod); - nextStrip(imod); - for (istrip=0; istrip=0 && imod=0 && imod=0 && imod>(NTRIMBITS))&1; - int ae=(reg>>(NTRIMBITS+1))&1; - int coe=(reg>>(NTRIMBITS+2))&1; - int ocoe=(reg>>(NTRIMBITS+3))&1; - int counts=(reg>>(NTRIMBITS+4)); -#ifdef VERBOSE - printf("Initializing channel %d chip %d module %d reg %x\n",myChan.chan,myChan.chip,myChan.module, reg); - printf("trim %d, cae %d, ae %d, coe %d, ocoe %d, counts %d\n",ft, cae, ae, coe, ocoe, counts); -#endif - - if (myChan.chip<0) - setCSregister(myChan.module); - else - selChip(myChan.chip,myChan.module); - - if (myChan.chan<0) - setSSregister(myChan.module); - else - selChannel(myChan.chan,myChan.module); - - initChannel(ft,cae,ae, coe, ocoe, counts,myChan.module); - - setDynamicRange(dynamicRange); - - setCSregister(ALLMOD); - clearSSregister(ALLMOD); - putout("0000000000000000",ALLMOD); - - return myChan.reg; - -} - -int getChannelbyNumber(sls_detector_channel* myChan) { - int imod, ichip, ichan; - imod=myChan->module; - ichip=myChan->chip; - ichan=myChan->chan; - - if (detectorChans) { - if (imod=0) { - if (ichip<(detectorModules+imod)->nchip && ichan<(detectorModules+imod)->nchan/(detectorModules+imod)->nchip) - myChan->reg=detectorChans[imod*NCHAN*NCHIP+ichip*NCHAN+ichan]; - return OK; - } - } - return FAIL; - -} - -int getTrimbit(int imod, int ichip, int ichan) { - if (detectorChans) { - if (imod=0) - if (ichip<(detectorModules+imod)->nchip && ichan<(detectorModules+imod)->nchan/(detectorModules+imod)->nchip) - return (detectorChans[imod*NCHAN*NCHIP+ichip*NCHAN+ichan] & TRIM_DR); - } - - return -1; -} - -int initChannel(int ft,int cae, int ae, int coe, int ocoe, int counts, int imod){ - - int ibit, bit, i, im, ichip, ichan; - int chanmi, chanma, chipmi, chipma, modmi, modma; - - - - sMod=imod; - // printf("initializing module %d\n",sMod); - if (imod==ALLMOD) { - sMod=allSelected; - - // printf("initializing all modules\n"); - } - - if (sChan==allSelected) { - // printf("initializing all channels ft=%d coe=%d\n",ft,coe); - chanmi=0; - chanma=NCHAN; - } else if (sChan==noneSelected || sChan>NCHAN || sChan<0) { - // printf("initializing no channels ft=%d coe=%d\n",ft,coe); - chanmi=0; - chanma=-1; - } else { - // printf("initializing channel %d ft=%d coe=%d\n",sChan, ft,coe); - chanmi=sChan; - chanma=sChan+1; - } - - if (sChip==allSelected) { - // printf("initializing all chips\n"); - chipmi=0; - chipma=NCHIP; - } else if (sChip==noneSelected || sChip>NCHIP || sChip<0) { - // printf("initializing no chips\n"); - chipmi=0; - chipma=-1; - } else { - // printf("initializing chip %d\n",sChip); - chipmi=sChip; - chipma=sChip+1; - } - - - if (sMod==allSelected) { - modmi=0; - modma=nModX;//getNModBoard(); - } else if (sMod==noneSelected || sMod>nModX || sMod<0) {//(sMod==noneSelected || sMod>getNModBoard() || sMod<0) { - modmi=0; - modma=-1; - return 1; - } else { - modmi=sMod; - modma=sMod+1; - } - - if (detectorChans) { - for (im=modmi; im63 || ft<0) { - fprintf(stdout,"Fine Threshold is %d while should be between 0 and 63!",ft); - return 1; - } - /*cal_enable*/ - if (cae) { - putout("0100000000000000",imod); - putout("0110000000000000",imod); - } else { - putout("0000000000000000",imod); - putout("0010000000000000",imod); - } - /*n_an_enable*/ - if (ae) { - putout("0000000000000000",imod); - putout("0010000000000000",imod); - putout("0000000000000000",imod); - } else { - putout("0100000000000000",imod); - putout("0110000000000000",imod); - putout("0100000000000000",imod); - } - /*trb5*/ - ibit=5; - bit=ft & (1<>1; - int nchan, ichan; - int ft, cae, ae, coe, ocoe, counts, chanreg; - - - - nchan=myChip.nchan; - if (ichip<0) - setCSregister(imod); - else - selChip(ichip,imod); - - clearSSregister(imod); - for (ichan=0; ichan>(NTRIMBITS+1))&1; - ae=(chanreg>>(NTRIMBITS+2))&1; - coe=((chanreg)>>(NTRIMBITS+3))&1; - ocoe=((chanreg)>>(NTRIMBITS+4))&1; - counts=((chanreg)>>(NTRIMBITS+5)); - nextStrip(imod); - initChannel(ft,cae,ae, coe, ocoe, counts,imod); - } - initChip(obe,ow,imod); - return myChip.reg; - -} - -int getChipbyNumber(sls_detector_chip* myChip){ - int imod, ichip; - imod=myChip->module; - ichip=myChip->chip; - - if (detectorChips) { - if (imodnchip) { - myChip->reg=detectorChips[ichip+imod*NCHIP]; - myChip->nchan=NCHAN; - myChip->chanregs=detectorChans+imod*NCHAN*NCHIP+ichip*NCHIP; - return OK; - } - } - return FAIL; - -} - - - -int initChip(int obe, int ow,int imod){ - int i; - int im, ichip; - int chipmi, chipma, modmi, modma; - - -#ifdef DEBUGOUT - printf("Initializing chip\n"); -#endif - putout("0000000000000000",imod); -#ifdef DEBUGOUT - printf("Output mode= %d\n", ow); -#endif - - /* clearing shift in register */ - for (i=0; i<10; i++) - putout("0000100000000000",imod); - putout("0000000000000000",imod); - - if (ow>0) { - putout("0100000000000000",imod); - putout("0110000000000000",imod); - putout("0100000000000000",imod); - for (i=0; i<(OUTMUX_OFFSET-1); i++) { - putout("0000000000000000",imod); - putout("0010000000000000",imod); - putout("0000000000000000",imod); - } - if (ow>1) { - putout("0000000000000000",imod); - putout("0010000000000000",imod); - putout("0000000000000000",imod); - } - if (ow>2) { - putout("0000000000000000",imod); - putout("0010000000000000",imod); - putout("0000000000000000",imod); - } - if (ow>3) { - putout("0000000000000000",imod); - putout("0010000000000000",imod); - putout("0000000000000000",imod); - } - if (ow>4) { - putout("0000000000000000",imod); - putout("0010000000000000",imod); - putout("0000000000000000",imod); - } - } -#ifdef DEBUGOUT - printf("Output buffer enable= %d\n", obe); -#endif - if (obe) { - putout("0100000000000000",imod); - putout("0110000000000000",imod); - putout("0100000000000000",imod); - } else { - putout("0000000000000000",imod); - putout("0010000000000000",imod); - putout("0000000000000000",imod); - } - /*}*/ - putout("0000000000000000",imod); - - - - - - sMod=imod; - if (imod==ALLMOD) - sMod=allSelected; - - - if (sChip==allSelected) { - chipmi=0; - chipma=NCHIP; - } else if (sChip==noneSelected || sChip>NCHIP || sChip<0) { - chipmi=0; - chipma=-1; - } else { - chipmi=sChip; - chipma=sChip+1; - } - - - if (sMod==allSelected) { - modmi=0; - modma=nModX;//getNModBoard(); - } else if (sMod==noneSelected || sMod>nModX || sMod<0) {//(sMod==noneSelected || sMod>getNModBoard() || sMod<0) { - modmi=0; - modma=-1; - } else { - modmi=sMod; - modma=sMod+1; - } - - if (detectorChips) { - for (im=modmi; imNCHIP || sChip<0) { - chipmi=0; - chipma=-1; - } else { - chipmi=sChip; - chipma=sChip+1; - } - - - if (sMod==allSelected) { - modmi=0; - modma=nModX;//getNModBoard(); - } else if (sMod==noneSelected || sMod>nModX || sMod<0) {//(sMod==noneSelected || sMod>getNModBoard() || sMod<0) { - modmi=0; - modma=-1; - } else { - modmi=sMod; - modma=sMod+1; - } - - if (detectorChips) { - for (im=modmi; imnModX || sMod<0) {//(sMod==noneSelected || sMod>getNModBoard() || sMod<0) { - modmi=0; - modma=-1; - } else { - modmi=sMod; - modma=sMod+1; - } - - if (detectorModules) { - for (im=modmi; imreg)=cm; -#ifdef VERBOSE - printf("imod=%d reg=%d (%x)\n",im,(detectorModules+im)->reg,(unsigned int)((detectorModules+im))); -#endif - } - } - return 0; -} - -int initModulebyNumber(sls_detector_module myMod) { - printf("\nInitializing Module\n"); - int nchip,nchan;//int ichip, nchip, ichan, nchan; - int im, modmi,modma; - // int ft, cae, ae, coe, ocoe, counts, chanreg; - int imod; - // int obe; - // int ow; - /* int v[NDAC];*/ - int retval =-1, idac; - - - nchip=myMod.nchip; - nchan=(myMod.nchan)/nchip; - imod=myMod.module; - sMod=imod; - if (sMod==ALLMOD) - sMod=allSelected; - if (sMod==allSelected) { - modmi=0; - modma=nModX;//getNModBoard(); - } else if (sMod==noneSelected || sMod>nModX || sMod<0) {// (sMod==noneSelected || sMod>getNModBoard() || sMod<0) { - modmi=0; - modma=-1; - } else { - modmi=sMod; - modma=sMod+1; - } - - //printf("ndac:%d\n",NDAC); - - for (idac=0; idacmodule; -#ifdef VERBOSE - printf("Getting module %d\n",imod); -#endif - if (detectorModules) { - copyModule(myMod,detectorModules+imod); - ; - } else - return FAIL; - - return OK; -} - -/* To chips */ -int clearCounter(int imod){ - int i; -#ifdef DEBUG - printf("Clearing counter with contclear\n"); -#endif - putout("0000000000000000",imod); - for (i=0; i<10; i++) - putout("0000000000010000",imod); - putout("0000000000000000",imod); - - return 0; -} - -int clearOutReg(int imod){ - int i; -#ifdef DEBUG - printf("Clearing output register\n"); -#endif - putout("0000010000000000",imod); - for (i=0; i<10; i++) - putout("0000110000000000",imod); - putout("0000010000000000",imod); - return 0; -} -int setOutReg(int imod){ - int i; -#ifdef DEBUG - printf("Setting output register\n"); -#endif - putout("0000010000000000",imod); - for (i=0; i<10; i++) - putout("0001010000000000",imod); - putout("0000010000000000",imod); - return 0; -} - - -int extPulse(int ncal, int imod) { - int ical; -#ifdef DEBUG - printf("Giving a clock pulse to the counter\n"); -#endif - for (ical=0; ical0 && i%2==0) { - printf("Shift in: module %d chip %i bit %d read %d instead of %d \n",k,j,i,val & 1<< j, i%2); - result++; - } - if (i%2>0 && (val & 1<0 && (dum & (1<0) { - printf("Shift out: module %d chip %i bit %d read %d instead of %d \n",k,j,i,val & 1<< j, (dum &1<0 && i%2==0) { - printf("Shift stsel: module %d chip %i bit %d read %d instead of %d \n",k,j,i,val & 1<< j, i%2); - result++; - } - if (i%2>0 && (val & 1<> 1; - - - putout("0000000000000000",ALLMOD); - putout("0010000000000000",ALLMOD); //change mux setting - putout("0000000000000000",ALLMOD); - } - - printf("Test FpgaMux module %d : %d errors\n", imod,result); - if (result) - return 1; - else - return 0; -} - - - - - - - - - -int calibration_sensor(int num, int *v, int *dacs) { - int ich, ichip, imod; - int val[10]; - - - printf("calibrating sensor..."); - for (imod=0; imod -#include "communication_funcs.h" -#include "server_funcs.h" -#include - - - -extern int sockfd; -extern int phase_shift; - - - -void error(char *msg) -{ - perror(msg); -} - -int main(int argc, char *argv[]) -{ - int portno, b; - char cmd[500]; - int retval=OK; - int sd, fd; - int iarg; - - - for(iarg=1; iarg 2) && (!strcasecmp(argv[2],"stopserver"))){ - portno = DEFAULT_PORTNO+1; - if ( sscanf(argv[1],"%d",&portno) ==0) { - printf("could not open stop server: unknown port\n"); - return 1; - } - b=0; - printf("\n\nStop Server\nOpening stop server on port %d\n",portno); - } - - //control server - else { - portno = DEFAULT_PORTNO; - sprintf(cmd,"%s %d stopserver &",argv[0],DEFAULT_PORTNO+1); - printf("\n\nControl Server\nOpening control server on port %d\n",portno ); - //printf("\n\ncmd:%s\n",cmd); - system(cmd); - b=1; - } - - - - init_detector(b); - - - sd=bindSocket(portno); - sockfd=sd; - if (getServerError(sd)) { - printf("server error!\n"); - return -1; - } - - /* assign function table */ - function_table(); -#ifdef VERBOSE - printf("function table assigned \n"); -#endif - - - /* waits for connection */ - while(retval!=GOODBYE) { -#ifdef VERBOSE - printf("\n"); -#endif -#ifdef VERY_VERBOSE - printf("Waiting for client call\n"); -#endif - fd=acceptConnection(sockfd); -#ifdef VERY_VERBOSE - printf("Conenction accepted\n"); -#endif - retval=decode_function(fd); -#ifdef VERY_VERBOSE - printf("function executed\n"); -#endif - closeConnection(fd); -#ifdef VERY_VERBOSE - printf("connection closed\n"); -#endif - } - - exitServer(sockfd); - printf("Goodbye!\n"); - - return 0; -} - diff --git a/slsDetectorSoftware/jungfrauDetectorServer/server_defs.h b/slsDetectorSoftware/jungfrauDetectorServer/server_defs.h deleted file mode 100755 index 300fc7305..000000000 --- a/slsDetectorSoftware/jungfrauDetectorServer/server_defs.h +++ /dev/null @@ -1,61 +0,0 @@ -#ifndef SERVER_DEFS_H -#define SERVER_DEFS_H - -#include "sls_detector_defs.h" - -#include - - -// Hardware definitions -#define NMAXMODY 1 -#define NMAXMODX 1 -#define NMAXMOD (NMAXMODX*NMAXMODY) -#define NCHAN (256*256) -#define NCHIP 8 -#define NADC 0 -#define NDAC 16 -#define NCHANS (NCHAN*NCHIP*NMAXMOD) -#define NDACS (NDAC*NMAXMOD) - - -/**when moench readout tested with gotthard module*/ -#define GOTTHARDNCHAN 128 -#define GOTTHARDNCHIP 10 - - -#define NTRIMBITS 6 -#define NCOUNTBITS 24 - -#define NCHIPS_PER_ADC 2 - -//#define TRIM_DR ((2**NTRIMBITS)-1) -//#define COUNT_DR ((2**NCOUNTBITS)-1) -#define TRIM_DR (((int)pow(2,NTRIMBITS))-1) -#define COUNT_DR (((int)pow(2,NCOUNTBITS))-1) - - -#define ALLMOD 0xffff -#define ALLFIFO 0xffff - -#define GOTTHARD_ADCSYNC_VAL 0x32214 -#define ADCSYNC_VAL 0x02111 -#define TOKEN_RESTART_DELAY 0x88000000 -#define TOKEN_RESTART_DELAY_ROI 0x1b000000 -#define TOKEN_TIMING_REV1 0x1f16 -#define TOKEN_TIMING_REV2 0x1f0f - -#define DEFAULT_PHASE_SHIFT 0 // 120 -#define DEFAULT_IP_PACKETSIZE 0x0522 -#define DEFAULT_UDP_PACKETSIZE 0x050E -#define ADC1_IP_PACKETSIZE 256*2+14+20 -#define ADC1_UDP_PACKETSIZE 256*2+4+8+2 - -#ifdef VIRTUAL -#define DEBUGOUT -#endif - -#define CLK_FREQ 156.25E+6 -#define ADC_CLK_FREQ 32E+6 - - -#endif diff --git a/slsDetectorSoftware/jungfrauDetectorServer/server_funcs.c b/slsDetectorSoftware/jungfrauDetectorServer/server_funcs.c deleted file mode 100755 index 24eef1a62..000000000 --- a/slsDetectorSoftware/jungfrauDetectorServer/server_funcs.c +++ /dev/null @@ -1,3267 +0,0 @@ -#include "sls_detector_defs.h" -#include "sls_receiver_defs.h" -#include "server_funcs.h" -#include "server_defs.h" -#include "firmware_funcs.h" -#include "mcb_funcs.h" -#include "registers_m.h" -#include "gitInfoJungfrau.h" - - - -extern int nModX; -extern int nModY; -extern size_t dataBytes; -extern int nSamples; -extern int dynamicRange; -extern int storeInRAM; -extern int lockStatus; -extern char lastClientIP[INET_ADDRSTRLEN]; -extern char thisClientIP[INET_ADDRSTRLEN]; -extern int differentClients; -extern unsigned int *ram_values; - - -//defined in the detector specific file -#ifdef MYTHEND -const enum detectorType myDetectorType=MYTHEN; -#elif PROPIXD -const enum detectorType myDetectorType=PROPIX; -#elif GOTTHARDD -const enum detectorType myDetectorType=GOTTHARD; -#elif EIGERD -const enum detectorType myDetectorType=EIGER; -#elif PICASSOD -const enum detectorType myDetectorType=PICASSO; -#elif MOENCHD -const enum detectorType myDetectorType=MOENCH; -#elif JUNGFRAUD -const enum detectorType myDetectorType=JUNGFRAU; -#else -const enum detectorType myDetectorType=GENERIC; -#endif - - - - -// Global variables -int (*flist[256])(int); -char *dataretval=NULL; -int nframes, iframes, dataret; -char mess[MAX_STR_LENGTH]; - -int digitalTestBit = 0; -int adcvpp=0x4; - - -int init_detector(int b) { - if(b){ - defineGPIOpins(); - resetFPGA(); - }else - usleep(300*1000); - - if (mapCSP0()==FAIL) { - printf("Could not map memory\n"); - exit(1); - } - - if (b) - initializeDetector(); - - //common for both control and stop server - strcpy(mess,"dummy message"); - strcpy(lastClientIP,"none"); - strcpy(thisClientIP,"none1"); - lockStatus=0; - return OK; -} - - -int decode_function(int file_des) { - int fnum,n; - int retval=FAIL; -#ifdef VERBOSE - printf( "receive data\n"); -#endif - n = receiveDataOnly(file_des,&fnum,sizeof(fnum)); - if (n <= 0) { -#ifdef VERBOSE - printf("ERROR reading from socket %d, %d %d\n", n, fnum, file_des); -#endif - return FAIL; - } -#ifdef VERBOSE - else - printf("size of data received %d\n",n); -#endif - -#ifdef VERBOSE - printf( "calling function fnum = %d %x %x %x\n",fnum,(unsigned int)(flist[fnum]), (unsigned int)(flist[F_READ_REGISTER]),(unsigned int)(&read_register)); -#endif - if (fnum<0 || fnum>255) - fnum=255; - retval=(*flist[fnum])(file_des); - if (retval==FAIL) - printf( "Error executing the function = %d \n",fnum); - return retval; -} - - -int function_table() { - int i; - for (i=0;i<256;i++){ - flist[i]=&M_nofunc; - } - flist[F_EXIT_SERVER]=&exit_server; - flist[F_EXEC_COMMAND]=&exec_command; - flist[F_GET_DETECTOR_TYPE]=&get_detector_type; - flist[F_SET_NUMBER_OF_MODULES]=&set_number_of_modules; - flist[F_GET_MAX_NUMBER_OF_MODULES]=&get_max_number_of_modules; - flist[F_SET_EXTERNAL_SIGNAL_FLAG]=&set_external_signal_flag; - flist[F_SET_EXTERNAL_COMMUNICATION_MODE]=&set_external_communication_mode; - flist[F_GET_ID]=&get_id; - flist[F_DIGITAL_TEST]=&digital_test; - flist[F_WRITE_REGISTER]=&write_register; - flist[F_READ_REGISTER]=&read_register; - flist[F_SET_DAC]=&set_dac; - flist[F_GET_ADC]=&get_adc; - flist[F_SET_CHANNEL]=&set_channel; - flist[F_SET_CHIP]=&set_chip; - flist[F_SET_MODULE]=&set_module; - flist[F_GET_CHANNEL]=&get_channel; - flist[F_GET_CHIP]=&get_chip; - flist[F_GET_MODULE]=&get_module; - flist[F_GET_THRESHOLD_ENERGY]=&get_threshold_energy; - flist[F_SET_THRESHOLD_ENERGY]=&set_threshold_energy; - flist[F_SET_SETTINGS]=&set_settings; - flist[F_START_ACQUISITION]=&start_acquisition; - flist[F_STOP_ACQUISITION]=&stop_acquisition; - flist[F_START_READOUT]=&start_readout; - flist[F_GET_RUN_STATUS]=&get_run_status; - flist[F_READ_FRAME]=&read_frame; - flist[F_READ_ALL]=&read_all; - flist[F_START_AND_READ_ALL]=&start_and_read_all; - flist[F_SET_TIMER]=&set_timer; - flist[F_GET_TIME_LEFT]=&get_time_left; - flist[F_SET_DYNAMIC_RANGE]=&set_dynamic_range; - flist[F_SET_ROI]=&set_roi; - flist[F_SET_SPEED]=&set_speed; - flist[F_SET_READOUT_FLAGS]=&set_readout_flags; - flist[F_EXECUTE_TRIMMING]=&execute_trimming; - flist[F_LOCK_SERVER]=&lock_server; - flist[F_SET_PORT]=&set_port; - flist[F_GET_LAST_CLIENT_IP]=&get_last_client_ip; - flist[F_UPDATE_CLIENT]=&update_client; - flist[F_CONFIGURE_MAC]=&configure_mac; - flist[F_LOAD_IMAGE]=&load_image; - flist[F_SET_MASTER]=&set_master; - flist[F_SET_SYNCHRONIZATION_MODE]=&set_synchronization; - flist[F_READ_COUNTER_BLOCK]=&read_counter_block; - flist[F_RESET_COUNTER_BLOCK]=&reset_counter_block; - flist[F_START_RECEIVER]=&start_receiver; - flist[F_STOP_RECEIVER]=&stop_receiver; - flist[F_CALIBRATE_PEDESTAL]=&calibrate_pedestal; - flist[F_SET_CTB_PATTERN]=&set_ctb_pattern; - flist[F_WRITE_ADC_REG]=&write_adc_register; - flist[F_PROGRAM_FPGA]=&program_fpga; - flist[F_RESET_FPGA]=&reset_fpga; - flist[F_POWER_CHIP]=&power_chip; - - return OK; -} - - -int M_nofunc(int file_des){ - - int ret=FAIL; - sprintf(mess,"Unrecognized Function\n"); - printf(mess); - - sendDataOnly(file_des,&ret,sizeof(ret)); - sendDataOnly(file_des,mess,sizeof(mess)); - return GOODBYE; -} - - -int exit_server(int file_des) { - int retval=FAIL; - sendDataOnly(file_des,&retval,sizeof(retval)); - printf("closing server."); - sprintf(mess,"closing server"); - sendDataOnly(file_des,mess,sizeof(mess)); - return GOODBYE; -} - -int exec_command(int file_des) { - char cmd[MAX_STR_LENGTH]; - char answer[MAX_STR_LENGTH]; - int retval=OK; - int sysret=0; - int n=0; - - /* receive arguments */ - n = receiveDataOnly(file_des,cmd,MAX_STR_LENGTH); - if (n < 0) { - sprintf(mess,"Error reading from socket\n"); - retval=FAIL; - } - - /* execute action if the arguments correctly arrived*/ - if (retval==OK) { -#ifdef VERBOSE - printf("executing command %s\n", cmd); -#endif - if (lockStatus==0 || differentClients==0) - sysret=system(cmd); - - //should be replaced by popen - if (sysret==0) { - sprintf(answer,"Succeeded\n"); - if (lockStatus==1 && differentClients==1) - sprintf(answer,"Detector locked by %s\n", lastClientIP); - } else { - sprintf(answer,"Failed\n"); - retval=FAIL; - } - } else { - sprintf(answer,"Could not receive the command\n"); - } - - /* send answer */ - n = sendDataOnly(file_des,&retval,sizeof(retval)); - n = sendDataOnly(file_des,answer,MAX_STR_LENGTH); - if (n < 0) { - sprintf(mess,"Error writing to socket"); - retval=FAIL; - } - - - /*return ok/fail*/ - return retval; - -} - - - -int get_detector_type(int file_des) { - int n=0; - enum detectorType ret; - int retval=OK; - - sprintf(mess,"Can't return detector type\n"); - - - /* receive arguments */ - /* execute action */ - ret=myDetectorType; - -#ifdef VERBOSE - printf("Returning detector type %d\n",ret); -#endif - - /* send answer */ - /* send OK/failed */ - if (differentClients==1) - retval=FORCE_UPDATE; - - n += sendDataOnly(file_des,&retval,sizeof(retval)); - if (retval!=FAIL) { - /* send return argument */ - n += sendDataOnly(file_des,&ret,sizeof(ret)); - } else { - n += sendDataOnly(file_des,mess,sizeof(mess)); - } - /*return ok/fail*/ - return retval; - - -} - - -int set_number_of_modules(int file_des) { - int n; - int arg[2], ret=0; - int retval=OK; - int dim, nm; - - sprintf(mess,"Can't set number of modules\n"); - - /* receive arguments */ - n = receiveDataOnly(file_des,&arg,sizeof(arg)); - if (n < 0) { - sprintf(mess,"Error reading from socket %d", n); - retval=GOODBYE; - } - if (retval==OK) { - dim=arg[0]; - nm=arg[1]; - - /* execute action */ -#ifdef VERBOSE - printf("Setting the number of modules in dimension %d to %d\n",dim,nm ); -#endif - - //if (nm!=GET_FLAG) { - if (dim!=X && nm!=GET_FLAG) { - retval=FAIL; - sprintf(mess,"Can't change module number in dimension %d\n",dim); - } else { - if (lockStatus==1 && differentClients==1 && nm!=GET_FLAG) { - sprintf(mess,"Detector locked by %s\n", lastClientIP); - retval=FAIL; - } else { - ret=setNMod(nm); - if (nModX==nm || nm==GET_FLAG) { - retval=OK; - if (differentClients==1) - retval=FORCE_UPDATE; - } else - retval=FAIL; - } - } - } - - /* send answer */ - /* send OK/failed */ - n = sendDataOnly(file_des,&retval,sizeof(retval)); - if (retval!=FAIL) { - /* send return argument */ - n += sendDataOnly(file_des,&ret,sizeof(ret)); - } else { - n += sendDataOnly(file_des,mess,sizeof(mess)); - } - /*return ok/fail*/ - return retval; - -} - - -int get_max_number_of_modules(int file_des) { - int n; - int ret; - int retval=OK; - enum dimension arg; - - sprintf(mess,"Can't get max number of modules\n"); - /* receive arguments */ - n = receiveDataOnly(file_des,&arg,sizeof(arg)); - if (n < 0) { - sprintf(mess,"Error reading from socket\n"); - retval=FAIL; - } - /* execute action */ -#ifdef VERBOSE - printf("Getting the max number of modules in dimension %d \n",arg); -#endif - - - switch (arg) { - case X: - ret=getNModBoard(); - break; - case Y: - ret=NMAXMODY; - break; - default: - ret=FAIL; - retval=FAIL; - break; - } -#ifdef VERBOSE - printf("Max number of module in dimension %d is %d\n",arg,ret ); -#endif - - - - if (differentClients==1 && retval==OK) { - retval=FORCE_UPDATE; - } - - /* send answer */ - /* send OK/failed */ - n = sendDataOnly(file_des,&retval,sizeof(retval)); - if (retval!=FAIL) { - /* send return argument */ - n += sendDataOnly(file_des,&ret,sizeof(ret)); - } else { - n += sendDataOnly(file_des,mess,sizeof(mess)); - } - - - - /*return ok/fail*/ - return retval; -} - - -//index 0 is in gate -//index 1 is in trigger -//index 2 is out gate -//index 3 is out trigger - -int set_external_signal_flag(int file_des) { - int n; - int arg[2]; - int ret=OK; - int signalindex; - enum externalSignalFlag flag, retval; - - sprintf(mess,"Can't set external signal flag\n"); - - /* receive arguments */ - n = receiveDataOnly(file_des,&arg,sizeof(arg)); - if (n < 0) { - sprintf(mess,"Error reading from socket\n"); - ret=FAIL; - } - retval=SIGNAL_OFF; - if (ret==OK) { - signalindex=arg[0]; - flag=arg[1]; - /* execute action */ - switch (flag) { - case GET_EXTERNAL_SIGNAL_FLAG: - retval=getExtSignal(signalindex); - break; - - default: - if (differentClients==0 || lockStatus==0) { - retval=setExtSignal(signalindex,flag); - } else { - if (lockStatus!=0) { - ret=FAIL; - sprintf(mess,"Detector locked by %s\n", lastClientIP); - } - } - } -#ifdef VERBOSE - printf("Setting external signal %d to flag %d\n",signalindex,flag ); - printf("Set to flag %d\n",retval); -#endif - } else - ret=FAIL; - - - if (ret==OK && differentClients!=0) - ret=FORCE_UPDATE; - - - /* send answer */ - /* send OK/failed */ - n = sendDataOnly(file_des,&ret,sizeof(ret)); - if (ret!=FAIL) { - /* send return argument */ - n += sendDataOnly(file_des,&retval,sizeof(retval)); - } else { - n += sendDataOnly(file_des,mess,sizeof(mess)); - } - - - /*return ok/fail*/ - return ret; - -} - - -int set_external_communication_mode(int file_des) { - int n; - enum externalCommunicationMode arg, ret=GET_EXTERNAL_COMMUNICATION_MODE; - int retval=OK; - - sprintf(mess,"Can't set external communication mode\n"); - - /* receive arguments */ - n = receiveDataOnly(file_des,&arg,sizeof(arg)); - if (n < 0) { - sprintf(mess,"Error reading from socket\n"); - retval=FAIL; - } - /* - enum externalCommunicationMode{ - GET_EXTERNAL_COMMUNICATION_MODE, - AUTO, - TRIGGER_EXPOSURE_SERIES, - TRIGGER_EXPOSURE_BURST, - TRIGGER_READOUT, - TRIGGER_COINCIDENCE_WITH_INTERNAL_ENABLE, - GATE_FIX_NUMBER, - GATE_FIX_DURATION, - GATE_WITH_START_TRIGGER, - GATE_COINCIDENCE_WITH_INTERNAL_ENABLE - }; - */ - if (retval==OK) { - /* execute action */ - ret=setTiming(arg); -#ifdef VERBOSE - printf("Setting external communication mode to %d\n", arg); -#endif - } else - ret=FAIL; - - /* send answer */ - /* send OK/failed */ - n = sendDataOnly(file_des,&retval,sizeof(retval)); - if (retval!=FAIL) { - /* send return argument */ - n += sendDataOnly(file_des,&ret,sizeof(ret)); - } else { - n += sendDataOnly(file_des,mess,sizeof(mess)); - } - - /*return ok/fail*/ - return retval; -} - - - -int get_id(int file_des) { - // sends back 64 bits! - int64_t retval=-1; - int ret=OK; - int n=0; - enum idMode arg; - - sprintf(mess,"Can't return id\n"); - - /* receive arguments */ - n = receiveDataOnly(file_des,&arg,sizeof(arg)); - if (n < 0) { - sprintf(mess,"Error reading from socket\n"); - ret=FAIL; - } - -#ifdef VERBOSE - printf("Getting id %d\n", arg); -#endif - - switch (arg) { - case DETECTOR_SERIAL_NUMBER: - retval=getDetectorNumber(); - break; - case DETECTOR_FIRMWARE_VERSION: - retval=getFirmwareSVNVersion(); - retval=(retval <<32) | getFirmwareVersion(); - break; - case DETECTOR_SOFTWARE_VERSION: - retval= SVNREV; - retval= (retval <<32) | SVNDATE; - break; - default: - printf("Required unknown id %d \n", arg); - ret=FAIL; - retval=FAIL; - break; - } - -#ifdef VERBOSE - printf("Id is %llx\n", retval); -#endif - - if (differentClients==1) - ret=FORCE_UPDATE; - - /* send answer */ - /* send OK/failed */ - n = sendDataOnly(file_des,&ret,sizeof(ret)); - if (ret!=FAIL) { - /* send return argument */ - n += sendDataOnly(file_des,&retval,sizeof(retval)); - } else { - n += sendDataOnly(file_des,mess,sizeof(mess)); - } - - /*return ok/fail*/ - return ret; - -} - -int digital_test(int file_des) { - - int retval; - int ret=OK; - int imod=-1; - int n=0; - int ibit=0; - int ow; - int ival; - enum digitalTestMode arg; - - sprintf(mess,"Can't send digital test\n"); - - n = receiveDataOnly(file_des,&arg,sizeof(arg)); - if (n < 0) { - sprintf(mess,"Error reading from socket\n"); - ret=FAIL; - } - -#ifdef VERBOSE - printf("Digital test mode %d\n",arg ); -#endif - - switch (arg) { - case CHIP_TEST: - n = receiveDataOnly(file_des,&imod,sizeof(imod)); - if (n < 0) { - sprintf(mess,"Error reading from socket\n"); - retval=FAIL; - } -#ifdef VERBOSE - printf("of module %d\n", imod); -#endif - retval=0; -#ifdef MCB_FUNCS - if (differentClients==1 && lockStatus==1) { - ret=FAIL; - sprintf(mess,"Detector locked by %s\n",lastClientIP); - break; - } - if (imod >= nModX) { - ret=FAIL; - sprintf(mess,"Module %d disabled\n",imod); - break; - } - if (testShiftIn(imod)) retval|=(1<<(ibit)); - ibit++; - if (testShiftOut(imod)) retval|=(1<<(ibit)); - ibit++; - if (testShiftStSel(imod)) retval|=(1<<(ibit)); - ibit++; - //if ( testDataInOut(0x123456, imod)) retval|=(1<<(ibit++)); - //if ( testExtPulse(imod)) retval|=(1<<(ibit++)); - // for (ow=0; ow<6; ow++) - // ow=1; - //#ifndef PICASSOD - for (ow=0; ow<5; ow++) { - //#endif - if (testDataInOutMux(imod, ow, 0x789abc)) retval|=(1<=getNModBoard()) - ret=FAIL; - if (imod<0) - imod=ALLMOD; - - - - -#ifdef MCB_FUNCS - - if (ret==OK) { - if (differentClients==1 && lockStatus==1) { - ret=FAIL; - sprintf(mess,"Detector locked by %s\n",lastClientIP); - } else{ - if (ind<16) { - - if (mV) { - if (val>2500) - val=-1; - printf("%d mV is ",val); - if (val>0) - val=4095*val/2500; - printf("%d DACu\n", val); - } else if (val>4095) - val=-1; - - - retval=setDac(ind,val); - /* if(idac==HIGH_VOLTAGE) */ - /* retval=initHighVoltageByModule(val,imod); */ - /* else */ - /* retval=initDACbyIndexDACU(idac,val,imod); */ - } - else if (ind==ADC_VPP) { - printf("Setting ADC VPP to %d\n",val); - if (val>4 || val<0) - printf("Cannot set ADC VPP to %d\n",val); - else { - writeADC(0x18,val); - adcvpp=val; - } - retval=adcvpp;; - - } else if (ind==HV_NEW ) - retval=initHighVoltageByModule(val,imod); - else - printf("**********No dac with index %d\n",ind); - } - } - if(ret==OK){ - if (ind<16) { - if (mV) { - - printf("%d DACu is ",retval); - retval1=2500*retval/16535; - printf("%d mV \n",retval1); - } else - retval1=retval; - } else - retval1=retval; - } -#endif - -#ifdef VERBOSE - printf("DAC set to %d V\n", retval); -#endif - - if(ret==FAIL) - printf("Setting dac %d of module %d: wrote %d but read %d\n", ind, imod, val, retval); - else{ - if (differentClients) - ret=FORCE_UPDATE; - } - - - /* send answer */ - /* send OK/failed */ - n = sendDataOnly(file_des,&ret,sizeof(ret)); - if (ret!=FAIL) { - /* send return argument */ - n += sendDataOnly(file_des,&retval,sizeof(retval)); - n += sendDataOnly(file_des,&retval1,sizeof(retval1)); - } else { - n += sendDataOnly(file_des,mess,sizeof(mess)); - } - - - /*return ok/fail*/ - return ret; - -} - - - -int get_adc(int file_des) { - //default: mod 0 - int retval; - int ret=OK; - int arg[2]; - enum dacIndex ind; - int imod; - int n; - int idac=0; - - sprintf(mess,"Can't read ADC\n"); - - - n = receiveDataOnly(file_des,arg,sizeof(arg)); - if (n < 0) { - sprintf(mess,"Error reading from socket\n"); - ret=FAIL; - } - ind=arg[0]; - imod=arg[1]; - -#ifdef VERBOSE - printf("Getting ADC %d of module %d\n", ind, imod); -#endif - - if (imod>=getNModBoard() || imod<0) - ret=FAIL; - -#ifdef MCB_FUNCS - switch (ind) { - case TEMPERATURE_FPGA: - idac=TEMP_FPGA; - break; - case TEMPERATURE_ADC: - idac=TEMP_ADC; - break; - default: - printf("Unknown DAC index %d\n",ind); - sprintf(mess,"Unknown DAC index %d\n",ind); - ret=FAIL; - break; - } - - if (ret==OK) - retval=getTemperatureByModule(idac,imod); -#endif - -#ifdef VERBOSE - printf("ADC is %d V\n", retval); -#endif - if (ret==FAIL) { - printf("Getting adc %d of module %d failed\n", ind, imod); - } - - if (differentClients) - ret=FORCE_UPDATE; - - /* send answer */ - /* send OK/failed */ - n = sendDataOnly(file_des,&ret,sizeof(ret)); - if (ret!=FAIL) { - /* send return argument */ - n += sendDataOnly(file_des,&retval,sizeof(retval)); - } else { - n += sendDataOnly(file_des,mess,sizeof(mess)); - } - - /*return ok/fail*/ - return ret; - -} - -int set_channel(int file_des) { - int ret=OK; - sls_detector_channel myChan; - int retval; - int n; - - - sprintf(mess,"Can't set channel\n"); - -#ifdef VERBOSE - printf("Setting channel\n"); -#endif - ret=receiveChannel(file_des, &myChan); - if (ret>=0) - ret=OK; - else - ret=FAIL; -#ifdef VERBOSE - printf("channel number is %d, chip number is %d, module number is %d, register is %lld\n", myChan.chan,myChan.chip, myChan.module, myChan.reg); -#endif - - if (ret==OK) { - if (myChan.module>=getNModBoard()) - ret=FAIL; - if (myChan.chip>=NCHIP) - ret=FAIL; - if (myChan.chan>=NCHAN) - ret=FAIL; - if (myChan.module<0) - myChan.module=ALLMOD; - } - - - if (ret==OK) { - if (differentClients==1 && lockStatus==1) { - ret=FAIL; - sprintf(mess,"Detector locked by %s\n",lastClientIP); - } else { -#ifdef MCB_FUNCS - retval=initChannelbyNumber(myChan); -#endif - } - } - /* Maybe this is done inside the initialization funcs */ - //copyChannel(detectorChans[myChan.module][myChan.chip]+(myChan.chan), &myChan); - - - - if (differentClients==1 && ret==OK) - ret=FORCE_UPDATE; - - /* send answer */ - /* send OK/failed */ - n = sendDataOnly(file_des,&ret,sizeof(ret)); - if (ret!=FAIL) { - /* send return argument */ - n += sendDataOnly(file_des,&retval,sizeof(retval)); - } else { - n += sendDataOnly(file_des,mess,sizeof(mess)); - } - - - /*return ok/fail*/ - return ret; - -} - - - - -int get_channel(int file_des) { - - int ret=OK; - sls_detector_channel retval; - - int arg[3]; - int ichan, ichip, imod; - int n; - - sprintf(mess,"Can't get channel\n"); - - - - n = receiveDataOnly(file_des,arg,sizeof(arg)); - if (n < 0) { - sprintf(mess,"Error reading from socket\n"); - ret=FAIL; - } - ichan=arg[0]; - ichip=arg[1]; - imod=arg[2]; - - if (ret==OK) { - ret=FAIL; - if (imod>=0 && imod=0 && ichip=0 && ichan=0) - ret=OK; - else - ret=FAIL; -#ifdef VERBOSE - printf("chip number is %d, module number is %d, register is %d, nchan %d\n",myChip.chip, myChip.module, myChip.reg, myChip.nchan); -#endif - - if (ret==OK) { - if (myChip.module>=getNModBoard()) - ret=FAIL; - if (myChip.module<0) - myChip.module=ALLMOD; - if (myChip.chip>=NCHIP) - ret=FAIL; - } - if (differentClients==1 && lockStatus==1) { - ret=FAIL; - sprintf(mess,"Detector locked by %s\n",lastClientIP); - } else { -#ifdef MCB_FUNCS - retval=initChipbyNumber(myChip); -#endif - } - /* Maybe this is done inside the initialization funcs */ - //copyChip(detectorChips[myChip.module]+(myChip.chip), &myChip); - - if (differentClients && ret==OK) - ret=FORCE_UPDATE; - /* send answer */ - /* send OK/failed */ - n = sendDataOnly(file_des,&ret,sizeof(ret)); - if (ret!=FAIL) { - /* send return argument */ - n += sendDataOnly(file_des,&retval,sizeof(retval)); - } else { - n += sendDataOnly(file_des,mess,sizeof(mess)); - } - - return ret; -} - - -int get_chip(int file_des) { - - - int ret=OK; - sls_detector_chip retval; - int arg[2]; - int ichip, imod; - int n; - - - - n = receiveDataOnly(file_des,arg,sizeof(arg)); - if (n < 0) { - sprintf(mess,"Error reading from socket\n"); - ret=FAIL; - } - ichip=arg[0]; - imod=arg[1]; - if (ret==OK) { - ret=FAIL; - if (imod>=0 && imod=0 && ichip=0) - ret=OK; - else - ret=FAIL; - - -//#ifdef VERBOSE - printf("module number is %d,register is %d, nchan %d, nchip %d, ndac %d, nadc %d, gain %f, offset %f\n",myModule.module, myModule.reg, myModule.nchan, myModule.nchip, myModule.ndac, myModule.nadc, myModule.gain,myModule.offset); -//#endif - - if (ret==OK) { - if (myModule.module>=getNModBoard()) { - ret=FAIL; - printf("Module number is too large %d\n",myModule.module); - } - if (myModule.module<0) - myModule.module=ALLMOD; - } - - if (ret==OK) { - if (differentClients==1 && lockStatus==1) { - ret=FAIL; - sprintf(mess,"Detector locked by %s\n",lastClientIP); - } else { -#ifdef MCB_FUNCS - retval=initModulebyNumber(myModule); - if(retval != myModule.reg) - ret = FAIL; -#endif - } - } - - if (differentClients==1 && ret==OK) - ret=FORCE_UPDATE; - - /* Maybe this is done inside the initialization funcs */ - //copyChip(detectorChips[myChip.module]+(myChip.chip), &myChip); - - /* send answer */ - /* send OK/failed */ - n = sendDataOnly(file_des,&ret,sizeof(ret)); - if (ret!=FAIL) { - /* send return argument */ - n += sendDataOnly(file_des,&retval,sizeof(retval)); - } else { - n += sendDataOnly(file_des,mess,sizeof(mess)); - } - - free(myDac); - if(myAdc != NULL) free(myAdc); - if(myChip != NULL) free(myChip); - if(myChan != NULL) free(myChan); - - - //setDynamicRange(dr); always 16 commented out - - return ret; -} - - - - -int get_module(int file_des) { - - int ret=OK; - int arg; - int imod; - int n; - sls_detector_module myModule; - int *myDac=malloc(NDAC*sizeof(int)); - int *myChip=NULL; - int *myChan=NULL; - int *myAdc=NULL; - //not allocating mychip,mychan for jungfrau to sace memory - - if (myDac) - myModule.dacs=myDac; - else { - sprintf(mess,"could not allocate dacs\n"); - ret=FAIL; - } - - - myModule.adcs=NULL; - myModule.chipregs=NULL; - myModule.chanregs=NULL; - myModule.ndac=NDAC; - myModule.nchip=NCHIP; - myModule.nchan=NCHAN*NCHIP; - myModule.nadc=NADC; - - - - n = receiveDataOnly(file_des,&arg,sizeof(arg)); - if (n < 0) { - sprintf(mess,"Error reading from socket\n"); - ret=FAIL; - } - imod=arg; - - if (ret==OK) { - ret=FAIL; - if (imod>=0 && imod0) { - dataret=FAIL; - sprintf(mess,"no data and run stopped: %d frames left\n",(int)(getFrames()+1)); - cprintf(RED,"%s\n",mess); - } else { - dataret=FINISHED; - sprintf(mess,"acquisition successfully finished\n"); - printf("%s",mess); - if (differentClients) - dataret=FORCE_UPDATE; - } -#endif - sendDataOnly(file_des,&dataret,sizeof(dataret)); - sendDataOnly(file_des,mess,sizeof(mess)); - return dataret; -} - - - - -int read_all(int file_des) { - while(read_frame(file_des)==OK) { -#ifdef VERBOSE - printf("frame read\n"); -#endif - ; - } -#ifdef VERBOSE - printf("Frames finished\n"); -#endif - return OK; -} - - - -int start_and_read_all(int file_des) { -#ifdef VERBOSE - printf("Starting and reading all frames\n"); -#endif - if (differentClients==1 && lockStatus==1) { - dataret=FAIL; - sprintf(mess,"Detector locked by %s\n",lastClientIP); - sendDataOnly(file_des,&dataret,sizeof(dataret)); - sendDataOnly(file_des,mess,sizeof(mess)); - return dataret; - - } - startStateMachine(); - read_all(file_des); -#ifdef VERBOSE - printf("Frames finished\n"); -#endif - return OK; -} - -int set_timer(int file_des) { - enum timerIndex ind; - int64_t tns; - int n; - int64_t retval; - int ret=OK; - - sprintf(mess,"can't set timer\n"); - - n = receiveDataOnly(file_des,&ind,sizeof(ind)); - if (n < 0) { - sprintf(mess,"Error reading from socket\n"); - ret=FAIL; - } - - n = receiveDataOnly(file_des,&tns,sizeof(tns)); - if (n < 0) { - sprintf(mess,"Error reading from socket\n"); - ret=FAIL; - } - -int set_timer(int file_des) { - enum timerIndex ind; - int64_t tns; - int n; - int64_t retval; - int ret=OK; - - - printf("set\n"); - sprintf(mess,"can't set timer\n"); - - n = receiveDataOnly(file_des,&ind,sizeof(ind)); - if (n < 0) { - sprintf(mess,"Error reading from socket\n"); - ret=FAIL; - } - - n = receiveDataOnly(file_des,&tns,sizeof(tns)); - if (n < 0) { - sprintf(mess,"Error reading from socket\n"); - ret=FAIL; - } - - if (ret!=OK) { - printf(mess); - } - - -#ifdef VERBOSE - printf("setting timer %d to %lld ns\n",ind,tns); -#endif - - if (ret==OK) { - - if (differentClients==1 && lockStatus==1 && tns!=-1) { - ret=FAIL; - sprintf(mess,"Detector locked by %s\n",lastClientIP); - } else { - switch(ind) { - case FRAME_NUMBER: - retval=setFrames(tns); - break; - case ACQUISITION_TIME: - retval=setExposureTime(tns); - break; - case FRAME_PERIOD: - retval=setPeriod(tns); - break; - case DELAY_AFTER_TRIGGER: - retval=setDelay(tns); - break; - case GATES_NUMBER: - retval=setGates(tns); - break; - case PROBES_NUMBER: - sprintf(mess,"can't set timer for this detector\n"); - ret=FAIL; - break; - case CYCLES_NUMBER: - retval=setTrains(tns); - break; - default: - ret=FAIL; - sprintf(mess,"timer index unknown %d\n",ind); - break; - } - } - } - - if(ret == OK && (retval!=tns) && (tns != -1)){ - ret = FAIL; - sprintf(mess,"Setting timer %d of failed: wrote %lld but read %lld\n", ind, (long long int)tns, (long long int)retval); - cprintf(RED,"%s",mess); - }else if (ret!=OK) { - cprintf(RED,"%s",mess); - cprintf(RED,"set timer failed\n"); - } - - if (ret==OK && differentClients) - ret=FORCE_UPDATE; - - - n = sendDataOnly(file_des,&ret,sizeof(ret)); - if (ret==FAIL) { - n = sendDataOnly(file_des,mess,sizeof(mess)); - } else { -#ifdef VERBOSE - printf("returning ok %d\n",(int)(sizeof(retval))); -#endif - - n = sendDataOnly(file_des,&retval,sizeof(retval)); - } - - return ret; - -} - - - - - - - - -int get_time_left(int file_des) { - - enum timerIndex ind; - int n; - int64_t retval; - int ret=OK; - - sprintf(mess,"can't get timer\n"); - n = receiveDataOnly(file_des,&ind,sizeof(ind)); - if (n < 0) { - sprintf(mess,"Error reading from socket\n"); - ret=FAIL; - } - - - //#ifdef VERBOSE - - printf("getting time left on timer %d \n",ind); - //#endif - - if (ret==OK) { - switch(ind) { - case FRAME_NUMBER: - printf("getting frames \n"); - retval=getFrames(); - break; - case ACQUISITION_TIME: - retval=getExposureTime(); - break; - case FRAME_PERIOD: - retval=getPeriod(); - break; - case DELAY_AFTER_TRIGGER: - retval=getDelay(); - break; - case GATES_NUMBER: - retval=getGates(); - break; - case PROBES_NUMBER: - retval=getProbes(); - break; - case CYCLES_NUMBER: - retval=getTrains(); - break; - case PROGRESS: - retval=getProgress(); - break; - case ACTUAL_TIME: - retval=getActualTime(); - break; - case MEASUREMENT_TIME: - retval=getMeasurementTime(); - break; - case FRAMES_FROM_START: - case FRAMES_FROM_START_PG: - retval=getFramesFromStart(); - break; - default: - ret=FAIL; - sprintf(mess,"timer index unknown %d\n",ind); - break; - } - } - - - if (ret!=OK) { - printf("get time left failed\n"); - } else if (differentClients) - ret=FORCE_UPDATE; - - //#ifdef VERBOSE - - printf("time left on timer %d is %lld\n",ind, retval); - //#endif - - n = sendDataOnly(file_des,&ret,sizeof(ret)); - if (ret==FAIL) { - n += sendDataOnly(file_des,mess,sizeof(mess)); - } else - n = sendDataOnly(file_des,&retval,sizeof(retval)); - -#ifdef VERBOSE - - printf("data sent\n"); -#endif - - return ret; - - -} - -int set_dynamic_range(int file_des) { - - - - int dr; - int n; - int retval; - int ret=OK; - - sprintf(mess,"can't set dynamic range\n"); - - - n = receiveDataOnly(file_des,&dr,sizeof(dr)); - if (n < 0) { - sprintf(mess,"Error reading from socket\n"); - ret=FAIL; - } - - - if (differentClients==1 && lockStatus==1 && dr>=0) { - ret=FAIL; - sprintf(mess,"Detector locked by %s\n",lastClientIP); - } else { - retval=setDynamicRange(dr); - } - - //if (dr>=0 && retval!=dr) ret=FAIL; - if (ret!=OK) { - sprintf(mess,"set dynamic range failed\n"); - } else { - if (differentClients) - ret=FORCE_UPDATE; - } - - n = sendDataOnly(file_des,&ret,sizeof(ret)); - if (ret==FAIL) { - n = sendDataOnly(file_des,mess,sizeof(mess)); - } else { - n = sendDataOnly(file_des,&retval,sizeof(retval)); - } - return ret; -} - -int set_roi(int file_des) { - - int ret=OK; - int nroi=-1; - int n=0; - strcpy(mess,"Could not set/get roi\n"); - - n = receiveDataOnly(file_des,&nroi,sizeof(nroi)); - if (n < 0) { - sprintf(mess,"Error reading from socket\n"); - ret=FAIL; - } - - ret = FAIL; - strcpy(mess,"Not applicable/implemented for this detector\n"); - printf("Error:Set ROI-%s",mess); - - - if(ret==OK && differentClients){ - printf("Force update\n"); - ret=FORCE_UPDATE; - } - - /* send answer */ - n = sendDataOnly(file_des,&ret,sizeof(ret)); - n = sendDataOnly(file_des,mess,sizeof(mess)); - /*return ok/fail*/ - return ret; -} - -int get_roi(int file_des) { - return FAIL; -} - -int set_speed(int file_des) { - - enum speedVariable arg; - int val,n; - int ret=OK; - int retval=-1; - - n=receiveDataOnly(file_des,&arg,sizeof(arg)); - if (n < 0) { - sprintf(mess,"Error reading from socket\n"); - ret=FAIL; - } - n=receiveDataOnly(file_des,&val,sizeof(val)); - if (n < 0) { - sprintf(mess,"Error reading from socket\n"); - ret=FAIL; - } - - if (ret==OK) { - - - if (val!=-1) { - if (differentClients==1 && lockStatus==1 && val>=0) { - ret=FAIL; - sprintf(mess,"Detector locked by %s\n",lastClientIP); - } else { - switch (arg) { - case CLOCK_DIVIDER: - switch(val){ - case 0: - ret=FAIL; - sprintf(mess,"Full speed not implemented yet. Available options: 1 for half speed and 2 for quarter speed"); - break; - case 1: - case 2: - break; - default: - ret=FAIL; - sprintf(mess,"Unknown clock options %d. Available options: 1 for half speed and 2 for quarter speed",arg); - break; - } - setClockDivider(val); - break; - - case ADC_PHASE: - adcPhase(val); - break; - - default: - ret=FAIL; - sprintf(mess,"Unknown speed parameter %d",arg); - } - } - } - } - - - - if (ret==OK) { - switch (arg) { - case CLOCK_DIVIDER: - retval=getClockDivider(); - break; - - case ADC_PHASE: - retval=getPhase(); - break; - - default: - ret=FAIL; - sprintf(mess,"Unknown speed parameter %d",arg); - } - } - - - n = sendDataOnly(file_des,&ret,sizeof(ret)); - if (ret==FAIL) { - n = sendDataOnly(file_des,mess,sizeof(mess)); - } else { - n = sendDataOnly(file_des,&retval,sizeof(retval)); - } - return ret; -} - - - -int set_readout_flags(int file_des) { - - enum readOutFlags arg; - int ret=FAIL; - - - receiveDataOnly(file_des,&arg,sizeof(arg)); - - sprintf(mess,"can't set readout flags for this detector\n"); - - sendDataOnly(file_des,&ret,sizeof(ret)); - sendDataOnly(file_des,mess,sizeof(mess)); - - return ret; -} - - - - - -int execute_trimming(int file_des) { - - int arg[3]; - int ret=FAIL; - enum trimMode mode; - - sprintf(mess,"can't set execute trimming for this detector\n"); - - receiveDataOnly(file_des,&mode,sizeof(mode)); - receiveDataOnly(file_des,arg,sizeof(arg)); - - - sendDataOnly(file_des,&ret,sizeof(ret)); - sendDataOnly(file_des,mess,sizeof(mess)); - - return ret; -} - - -int lock_server(int file_des) { - - - int n; - int ret=OK; - - int lock; - n = receiveDataOnly(file_des,&lock,sizeof(lock)); - if (n < 0) { - sprintf(mess,"Error reading from socket\n"); - printf("Error reading from socket (lock)\n"); - ret=FAIL; - } - if (lock>=0) { - if (lockStatus==0 || strcmp(lastClientIP,thisClientIP)==0 || strcmp(lastClientIP,"none")==0) - lockStatus=lock; - else { - ret=FAIL; - sprintf(mess,"Server already locked by %s\n", lastClientIP); - } - } - if (differentClients && ret==OK) - ret=FORCE_UPDATE; - - n = sendDataOnly(file_des,&ret,sizeof(ret)); - if (ret==FAIL) { - n = sendDataOnly(file_des,mess,sizeof(mess)); - } else - n = sendDataOnly(file_des,&lockStatus,sizeof(lockStatus)); - - return ret; - -} - -int set_port(int file_des) { - int n; - int ret=OK; - int sd=-1; - - enum portType p_type; /** data? control? stop? Unused! */ - int p_number; /** new port number */ - - n = receiveDataOnly(file_des,&p_type,sizeof(p_type)); - if (n < 0) { - sprintf(mess,"Error reading from socket\n"); - printf("Error reading from socket (ptype)\n"); - ret=FAIL; - } - - n = receiveDataOnly(file_des,&p_number,sizeof(p_number)); - if (n < 0) { - sprintf(mess,"Error reading from socket\n"); - printf("Error reading from socket (pnum)\n"); - ret=FAIL; - } - if (differentClients==1 && lockStatus==1 ) { - ret=FAIL; - sprintf(mess,"Detector locked by %s\n",lastClientIP); - } else { - if (p_number<1024) { - sprintf(mess,"Too low port number %d\n", p_number); - printf("\n"); - ret=FAIL; - } - - printf("set port %d to %d\n",p_type, p_number); - - sd=bindSocket(p_number); - } - if (sd>=0) { - ret=OK; - if (differentClients ) - ret=FORCE_UPDATE; - } else { - ret=FAIL; - sprintf(mess,"Could not bind port %d\n", p_number); - printf("Could not bind port %d\n", p_number); - if (sd==-10) { - sprintf(mess,"Port %d already set\n", p_number); - printf("Port %d already set\n", p_number); - - } - } - - n = sendDataOnly(file_des,&ret,sizeof(ret)); - if (ret==FAIL) { - n = sendDataOnly(file_des,mess,sizeof(mess)); - } else { - n = sendDataOnly(file_des,&p_number,sizeof(p_number)); - closeConnection(file_des); - exitServer(sockfd); - sockfd=sd; - - } - - return ret; - -} - -int get_last_client_ip(int file_des) { - int ret=OK; - int n; - if (differentClients ) - ret=FORCE_UPDATE; - n = sendDataOnly(file_des,&ret,sizeof(ret)); - n = sendDataOnly(file_des,lastClientIP,sizeof(lastClientIP)); - - return ret; - -} - - -int send_update(int file_des) { - - int ret=OK; - enum detectorSettings t; - int n;//int thr, n; - //int it; - int64_t retval, tns=-1; - n = sendDataOnly(file_des,lastClientIP,sizeof(lastClientIP)); - n = sendDataOnly(file_des,&nModX,sizeof(nModX)); - n = sendDataOnly(file_des,&nModY,sizeof(nModY)); - n = sendDataOnly(file_des,&dynamicRange,sizeof(dynamicRange)); - n = sendDataOnly(file_des,&dataBytes,sizeof(dataBytes)); - t=setSettings(GET_SETTINGS,-1); - n = sendDataOnly(file_des,&t,sizeof(t)); - /* thr=getThresholdEnergy(); - n = sendDataOnly(file_des,&thr,sizeof(thr));*/ - retval=setFrames(tns); - n = sendDataOnly(file_des,&retval,sizeof(int64_t)); - retval=setExposureTime(tns); - n = sendDataOnly(file_des,&retval,sizeof(int64_t)); - retval=setPeriod(tns); - n = sendDataOnly(file_des,&retval,sizeof(int64_t)); - retval=setDelay(tns); - n = sendDataOnly(file_des,&retval,sizeof(int64_t)); - retval=setGates(tns); - n = sendDataOnly(file_des,&retval,sizeof(int64_t)); - /* retval=setProbes(tns); - n = sendDataOnly(file_des,&retval,sizeof(int64_t));*/ - retval=setTrains(tns); - n = sendDataOnly(file_des,&retval,sizeof(int64_t)); - - if (lockStatus==0) { - strcpy(lastClientIP,thisClientIP); - } - - return ret; - - -} -int update_client(int file_des) { - - int ret=OK; - - sendDataOnly(file_des,&ret,sizeof(ret)); - return send_update(file_des); - - - -} - - -int configure_mac(int file_des) { - - int ret=OK; - char arg[5][50]; - int n; - - int imod=0;//should be in future sent from client as -1, arg[2] - int ipad; - long long int imacadd; - long long int idetectormacadd; - int udpport; - int detipad; - int retval=-100; - - sprintf(mess,"Can't configure MAC\n"); - - - n = receiveDataOnly(file_des,arg,sizeof(arg)); - if (n < 0) { - sprintf(mess,"Error reading from socket\n"); - ret=FAIL; - } - - sscanf(arg[0], "%x", &ipad); - sscanf(arg[1], "%llx", &imacadd); - sscanf(arg[2], "%x", &udpport); - sscanf(arg[3], "%llx", &idetectormacadd); - sscanf(arg[4], "%x", &detipad); - - //#ifdef VERBOSE - int i; - printf("\ndigital_test_bit in server %d\t",digitalTestBit); - printf("\nipadd %x\t",ipad); - printf("destination ip is %d.%d.%d.%d = 0x%x \n",(ipad>>24)&0xff,(ipad>>16)&0xff,(ipad>>8)&0xff,(ipad)&0xff,ipad); - printf("macad:%llx\n",imacadd); - for (i=0;i<6;i++) - printf("mac adress %d is 0x%x \n",6-i,(unsigned int)(((imacadd>>(8*i))&0xFF))); - printf("udp port:0x%x\n",udpport); - printf("detector macad:%llx\n",idetectormacadd); - for (i=0;i<6;i++) - printf("detector mac adress %d is 0x%x \n",6-i,(unsigned int)(((idetectormacadd>>(8*i))&0xFF))); - printf("detipad %x\n",detipad); - printf("\n"); - //#endif - - - - if (imod>=getNModBoard()) - ret=FAIL; - if (imod<0) - imod=ALLMOD; - - //#ifdef VERBOSE - printf("Configuring MAC of module %d at port %x\n", imod, udpport); - //#endif -#ifdef MCB_FUNCS - if (ret==OK){ - if(runBusy()){ - ret=stopStateMachine(); - if(ret==FAIL) - strcpy(mess,"could not stop detector acquisition to configure mac"); - } - - if(ret==OK) - configureMAC(ipad,imacadd,idetectormacadd,detipad,digitalTestBit,udpport); - retval=getAdcConfigured(); - } -#endif - if (ret==FAIL) - printf("configuring MAC of mod %d failed\n", imod); - else - printf("Configuremac successful of mod %d and adc %d\n",imod,retval); - - if (differentClients) - ret=FORCE_UPDATE; - - /* send answer */ - /* send OK/failed */ - n = sendDataOnly(file_des,&ret,sizeof(ret)); - if (ret==FAIL) - n += sendDataOnly(file_des,mess,sizeof(mess)); - else - n += sendDataOnly(file_des,&retval,sizeof(retval)); - /*return ok/fail*/ - return ret; - -} - - - -int load_image(int file_des) { - int retval; - int ret=OK; - int n; - enum imageType index; - short int ImageVals[NCHAN*NCHIP]; - - sprintf(mess,"Loading image failed\n"); - - n = receiveDataOnly(file_des,&index,sizeof(index)); - if (n < 0) { - sprintf(mess,"Error reading from socket\n"); - ret=FAIL; - } - - n = receiveDataOnly(file_des,ImageVals,dataBytes); - if (n < 0) { - sprintf(mess,"Error reading from socket\n"); - ret=FAIL; - } - - switch (index) { - case DARK_IMAGE : -#ifdef VERBOSE - printf("Loading Dark image\n"); -#endif - break; - case GAIN_IMAGE : -#ifdef VERBOSE - printf("Loading Gain image\n"); -#endif - break; - default: - printf("Unknown index %d\n",index); - sprintf(mess,"Unknown index %d\n",index); - ret=FAIL; - break; - } - - if (ret==OK) { - if (differentClients==1 && lockStatus==1) { - ret=FAIL; - sprintf(mess,"Detector locked by %s\n",lastClientIP); - } else{ - retval=loadImage(index,ImageVals); - if (retval==-1) - ret = FAIL; - } - } - - if(ret==OK){ - if (differentClients) - ret=FORCE_UPDATE; - } - - /* send answer */ - /* send OK/failed */ - n = sendDataOnly(file_des,&ret,sizeof(ret)); - if (ret!=FAIL) { - /* send return argument */ - n += sendDataOnly(file_des,&retval,sizeof(retval)); - } else { - n += sendDataOnly(file_des,mess,sizeof(mess)); - } - - /*return ok/fail*/ - return ret; -} - - - -int set_master(int file_des) { - - enum masterFlags retval=GET_MASTER; - enum masterFlags arg; - int n; - int ret=OK; - // int regret=OK; - - - sprintf(mess,"can't set master flags\n"); - - - n = receiveDataOnly(file_des,&arg,sizeof(arg)); - if (n < 0) { - sprintf(mess,"Error reading from socket\n"); - ret=FAIL; - } - - -#ifdef VERBOSE - printf("setting master flags to %d\n",arg); -#endif - - if (differentClients==1 && lockStatus==1 && arg!=GET_READOUT_FLAGS) { - ret=FAIL; - sprintf(mess,"Detector locked by %s\n",lastClientIP); - } else { - retval=setMaster(arg); - - } - if (retval==GET_MASTER) { - ret=FAIL; - } - n = sendDataOnly(file_des,&ret,sizeof(ret)); - if (ret==FAIL) { - n = sendDataOnly(file_des,mess,sizeof(mess)); - } else { - n = sendDataOnly(file_des,&retval,sizeof(retval)); - } - return ret; -} - - - - - - -int set_synchronization(int file_des) { - - enum synchronizationMode retval=GET_MASTER; - enum synchronizationMode arg; - int n; - int ret=OK; - //int regret=OK; - - - sprintf(mess,"can't set synchronization mode\n"); - - - n = receiveDataOnly(file_des,&arg,sizeof(arg)); - if (n < 0) { - sprintf(mess,"Error reading from socket\n"); - ret=FAIL; - } -#ifdef VERBOSE - printf("setting master flags to %d\n",arg); -#endif - - if (differentClients==1 && lockStatus==1 && arg!=GET_READOUT_FLAGS) { - ret=FAIL; - sprintf(mess,"Detector locked by %s\n",lastClientIP); - } else { - //ret=setStoreInRAM(0); - // initChipWithProbes(0,0,0, ALLMOD); - retval=setSynchronization(arg); - } - if (retval==GET_SYNCHRONIZATION_MODE) { - ret=FAIL; - } - n = sendDataOnly(file_des,&ret,sizeof(ret)); - if (ret==FAIL) { - n = sendDataOnly(file_des,mess,sizeof(mess)); - } else { - n = sendDataOnly(file_des,&retval,sizeof(retval)); - } - return ret; -} - - - - - - -int read_counter_block(int file_des) { - - int ret=OK; - int n; - int startACQ; - //char *retval=NULL; - short int CounterVals[NCHAN*NCHIP]; - - sprintf(mess,"Read counter block failed\n"); - - n = receiveDataOnly(file_des,&startACQ,sizeof(startACQ)); - if (n < 0) { - sprintf(mess,"Error reading from socket\n"); - ret=FAIL; - } - - if (ret==OK) { - if (differentClients==1 && lockStatus==1) { - ret=FAIL; - sprintf(mess,"Detector locked by %s\n",lastClientIP); - } else{ - ret=readCounterBlock(startACQ,CounterVals); -#ifdef VERBOSE - int i; - for(i=0;i<6;i++) - printf("%d:%d\t",i,CounterVals[i]); -#endif - } - } - - if(ret!=FAIL){ - if (differentClients) - ret=FORCE_UPDATE; - } - - /* send answer */ - /* send OK/failed */ - n = sendDataOnly(file_des,&ret,sizeof(ret)); - if (ret!=FAIL) { - /* send return argument */ - n += sendDataOnly(file_des,CounterVals,dataBytes);//1280*2 - } else { - n += sendDataOnly(file_des,mess,sizeof(mess)); - } - - /*return ok/fail*/ - return ret; -} - - - - - -int reset_counter_block(int file_des) { - - int ret=OK; - int n; - int startACQ; - - sprintf(mess,"Reset counter block failed\n"); - - n = receiveDataOnly(file_des,&startACQ,sizeof(startACQ)); - if (n < 0) { - sprintf(mess,"Error reading from socket\n"); - ret=FAIL; - } - - if (ret==OK) { - if (differentClients==1 && lockStatus==1) { - ret=FAIL; - sprintf(mess,"Detector locked by %s\n",lastClientIP); - } else - ret=resetCounterBlock(startACQ); - } - - if(ret==OK){ - if (differentClients) - ret=FORCE_UPDATE; - } - - /* send answer */ - /* send OK/failed */ - n = sendDataOnly(file_des,&ret,sizeof(ret)); - if (ret==FAIL) - n += sendDataOnly(file_des,mess,sizeof(mess)); - - /*return ok/fail*/ - return ret; -} - - - - - - -int start_receiver(int file_des) { - int ret=FAIL; - int n; - strcpy(mess,"Not implemented for this detector\n"); - - /* send answer */ - n = sendDataOnly(file_des,&ret,sizeof(ret)); - n = sendDataOnly(file_des,mess,sizeof(mess)); - /*return ok/fail*/ - return ret; -} - - - - - - -int stop_receiver(int file_des) { - int ret = FAIL; - int n; - strcpy(mess,"Not implemented for this detector\n"); - - /* send answer */ - n = sendDataOnly(file_des,&ret,sizeof(ret)); - n = sendDataOnly(file_des,mess,sizeof(mess)); - /*return ok/fail*/ - return ret; -} - - - - - -int calibrate_pedestal(int file_des){ - - int ret=OK; - int retval=-1; - int n; - int frames; - - sprintf(mess,"Could not calibrate pedestal\n"); - - n = receiveDataOnly(file_des,&frames,sizeof(frames)); - if (n < 0) { - sprintf(mess,"Error reading from socket\n"); - ret=FAIL; - } - - if (ret==OK) { - if (differentClients==1 && lockStatus==1) { - ret=FAIL; - sprintf(mess,"Detector locked by %s\n",lastClientIP); - } else - ret=calibratePedestal(frames); - } - - if(ret==OK){ - if (differentClients) - ret=FORCE_UPDATE; - } - - /* send answer */ - /* send OK/failed */ - n = sendDataOnly(file_des,&ret,sizeof(ret)); - if (ret==FAIL) - n += sendDataOnly(file_des,mess,sizeof(mess)); - else - n += sendDataOnly(file_des,&retval,sizeof(retval)); - - /*return ok/fail*/ - return ret; -} - - -int set_ctb_pattern(int file_des){ - - int ret=OK;//FAIL; - int retval=-1; - int n; - int mode; - uint64_t word, retval64, t; - int addr; - int level, start, stop, nl; - uint64_t pat[1024]; - - sprintf(mess,"Could not set pattern\n"); - - n = receiveDataOnly(file_des,&mode,sizeof(mode)); - printf("pattern mode is %d\n",mode); - switch (mode) { - - case 0: //sets word - n = receiveDataOnly(file_des,&addr,sizeof(addr)); - n = receiveDataOnly(file_des,&word,sizeof(word)); - ret=OK; - - switch (addr) { - case -1: - retval64=writePatternIOControl(word); - break; - case -2: - retval64=writePatternClkControl(word); - break; - default: - retval64=writePatternWord(addr,word); - }; - - - //write word; - //@param addr address of the word, -1 is I/O control register, -2 is clk control register - //@param word 64bit word to be written, -1 gets - - n = sendDataOnly(file_des,&ret,sizeof(ret)); - if (ret==FAIL) - n += sendDataOnly(file_des,mess,sizeof(mess)); - else - n += sendDataOnly(file_des,&retval64,sizeof(retval64)); - break; - - case 1: //pattern loop - n = receiveDataOnly(file_des,&level,sizeof(level)); - n = receiveDataOnly(file_des,&start,sizeof(start)); - n = receiveDataOnly(file_des,&stop,sizeof(stop)); - n = receiveDataOnly(file_des,&nl,sizeof(nl)); - - - - printf("level %d start %x stop %x nl %d\n",level, start, stop, nl); - /** Sets the pattern or loop limits in the CTB - @param level -1 complete pattern, 0,1,2, loop level - @param start start address if >=0 - @param stop stop address if >=0 - @param n number of loops (if level >=0) - @returns OK/FAIL - */ - ret=setPatternLoop(level, &start, &stop, &nl); - - n = sendDataOnly(file_des,&ret,sizeof(ret)); - if (ret==FAIL) - n += sendDataOnly(file_des,mess,sizeof(mess)); - else { - n += sendDataOnly(file_des,&start,sizeof(start)); - n += sendDataOnly(file_des,&stop,sizeof(stop)); - n += sendDataOnly(file_des,&nl,sizeof(nl)); - } - break; - - - - case 2: //wait address - n = receiveDataOnly(file_des,&level,sizeof(level)); - n = receiveDataOnly(file_des,&addr,sizeof(addr)); - - - - /** Sets the wait address in the CTB - @param level 0,1,2, wait level - @param addr wait address, -1 gets - @returns actual value - */ - printf("wait addr %d %x\n",level, addr); - retval=setPatternWaitAddress(level,addr); - printf("ret: wait addr %d %x\n",level, retval); - ret=OK; - n = sendDataOnly(file_des,&ret,sizeof(ret)); - if (ret==FAIL) - n += sendDataOnly(file_des,mess,sizeof(mess)); - else { - n += sendDataOnly(file_des,&retval,sizeof(retval)); - - } - - - break; - - - case 3: //wait time - n = receiveDataOnly(file_des,&level,sizeof(level)); - n = receiveDataOnly(file_des,&t,sizeof(t)); - - - /** Sets the wait time in the CTB - @param level 0,1,2, wait level - @param t wait time, -1 gets - @returns actual value - */ - - ret=OK; - - retval64=setPatternWaitTime(level,t); - - n = sendDataOnly(file_des,&ret,sizeof(ret)); - if (ret==FAIL) - n += sendDataOnly(file_des,mess,sizeof(mess)); - else - n += sendDataOnly(file_des,&retval64,sizeof(retval64)); - - break; - - - - case 4: - n = receiveDataOnly(file_des,pat,sizeof(pat)); - for (addr=0; addr<1024; addr++) - writePatternWord(addr,word); - ret=OK; - retval=0; - n = sendDataOnly(file_des,&ret,sizeof(ret)); - if (ret==FAIL) - n += sendDataOnly(file_des,mess,sizeof(mess)); - else - n += sendDataOnly(file_des,&retval64,sizeof(retval64)); - - break; - - - - - - default: - ret=FAIL; - printf(mess); - sprintf(mess,"%s - wrong mode %d\n",mess, mode); - n = sendDataOnly(file_des,&ret,sizeof(ret)); - n += sendDataOnly(file_des,mess,sizeof(mess)); - - - - } - - - /*return ok/fail*/ - return ret; -} - - -int write_adc_register(int file_des) { - - int retval; - int ret=OK; - int arg[2]; - int addr, val; - int n; - - sprintf(mess,"Can't write to register\n"); - - n = receiveDataOnly(file_des,arg,sizeof(arg)); - if (n < 0) { - sprintf(mess,"Error reading from socket\n"); - ret=FAIL; - } - addr=arg[0]; - val=arg[1]; - -#ifdef VERBOSE - printf("writing to register 0x%x data 0x%x\n", addr, val); -#endif - - if (differentClients==1 && lockStatus==1) { - ret=FAIL; - sprintf(mess,"Detector locked by %s\n",lastClientIP); - } - - - if(ret!=FAIL){ - ret=writeADC(addr,val); - if (ret==OK) - retval=val; - } - - -#ifdef VERBOSE - printf("Data set to 0x%x\n", retval); -#endif - if (retval==val) { - ret=OK; - if (differentClients) - ret=FORCE_UPDATE; - } else { - ret=FAIL; - sprintf(mess,"Writing to register 0x%x failed: wrote 0x%x but read 0x%x\n", addr, val, retval); - } - - /* send answer */ - /* send OK/failed */ - n = sendDataOnly(file_des,&ret,sizeof(ret)); - if (ret!=FAIL) { - /* send return argument */ - n += sendDataOnly(file_des,&retval,sizeof(retval)); - } else { - n += sendDataOnly(file_des,mess,sizeof(mess)); - } - - /*return ok/fail*/ - return ret; - -} - - - - - -int program_fpga(int file_des) { - int ret=OK; - int n; - sprintf(mess,"Program FPGA unsuccessful\n"); - char* fpgasrc = NULL; - FILE* fp = NULL; - size_t filesize = 0; - size_t unitprogramsize = 0; - size_t totalsize = 0; - - - //filesize - n = receiveDataOnly(file_des,&filesize,sizeof(filesize)); - if (n < 0) { - sprintf(mess,"Error reading from socket\n"); - ret=FAIL; - } - totalsize = filesize; -#ifdef VERY_VERBOSE - printf("\n\n Total size is:%d\n",totalsize); -#endif - - //lock - if (ret==OK && differentClients==1 && lockStatus==1) { - ret=FAIL; - sprintf(mess,"Detector locked by %s\n",lastClientIP); - filesize = 0; - } - - //opening file pointer to flash and telling FPGA to not touch flash - if(ret == OK && startWritingFPGAprogram(&fp) != OK){ - sprintf(mess,"Could not write to flash. Error at startup.\n"); - cprintf(RED,"%s",mess); - ret=FAIL; - filesize = 0; - } - - //---------------- first ret ---------------- - n = sendDataOnly(file_des,&ret,sizeof(ret)); - if (ret==FAIL) - n += sendDataOnly(file_des,mess,sizeof(mess)); - //---------------- first ret ---------------- - - - //erasing flash - if(ret != FAIL){ - eraseFlash(); - fpgasrc = (char*)malloc(MAX_FPGAPROGRAMSIZE); - } - - - - //writing to flash part by part - while(ret != FAIL && filesize){ - - unitprogramsize = MAX_FPGAPROGRAMSIZE; //2mb - if(unitprogramsize > filesize) //less than 2mb - unitprogramsize = filesize; -#ifdef VERY_VERBOSE - printf("unit size to receive is:%d\n",unitprogramsize); - printf("filesize:%d currentpointer:%d\n",filesize,currentPointer); -#endif - - - //receive - n = receiveDataOnly(file_des,fpgasrc,unitprogramsize); - if (n < 0) { - sprintf(mess,"Error reading from socket\n"); - ret=FAIL; - } - - - if (ret==OK) { - if(!(unitprogramsize - filesize)){ - fpgasrc[unitprogramsize]='\0'; - filesize-=unitprogramsize; - unitprogramsize++; - }else - filesize-=unitprogramsize; - - ret = writeFPGAProgram(fpgasrc,unitprogramsize,fp); - } - - - //---------------- middle rets ---------------- - n = sendDataOnly(file_des,&ret,sizeof(ret)); - if (ret==FAIL) { - n += sendDataOnly(file_des,mess,sizeof(mess)); - cprintf(RED,"Failure: Breaking out of program receiving\n"); - } - //---------------- middle rets ---------------- - - - if(ret != FAIL){ - //print progress - printf("Writing to Flash:%d%%\r",(int) (((double)(totalsize-filesize)/totalsize)*100) ); - fflush(stdout); - } - - } - - - - printf("\n"); - - //closing file pointer to flash and informing FPGA - if(stopWritingFPGAprogram(fp) == FAIL){ - sprintf(mess,"Could not write to flash. Error at end.\n"); - cprintf(RED,"%s",mess); - ret=FAIL; - } - - if(ret!=FAIL){ - ret=FORCE_UPDATE; - } - - - //---------------- last ret ---------------- - n = sendDataOnly(file_des,&ret,sizeof(ret)); - if (ret==FAIL) - n += sendDataOnly(file_des,mess,sizeof(mess)); - //---------------- last ret ---------------- - - - //free resources - if(fpgasrc != NULL) - free(fpgasrc); - if(fp!=NULL) - fclose(fp); -#ifdef VERY_VERBOSE - printf("Done with program receiving command\n"); -#endif - /*return ok/fail*/ - return ret; -} - - - -int reset_fpga(int file_des) { - int ret=OK; - int n; - sprintf(mess,"Reset FPGA unsuccessful\n"); - - resetFPGA(); - initializeDetector(); - - ret = FORCE_UPDATE; - n = sendDataOnly(file_des,&ret,sizeof(ret)); - if (ret==FAIL) - n += sendDataOnly(file_des,mess,sizeof(mess)); - - /*return ok/fail*/ - return ret; -} - - - -int power_chip(int file_des) { - - int retval=-1; - int ret=OK; - int arg=-1; - int n; - - n = receiveDataOnly(file_des,&arg,sizeof(arg)); - if (n < 0) { - sprintf(mess,"Error reading from socket\n"); - ret=FAIL; - } - - -#ifdef VERBOSE - printf("Power chip to %d\n", arg); -#endif - - if (differentClients==1 && lockStatus==1 && arg!=-1) { - ret=FAIL; - sprintf(mess,"Detector locked by %s\n",lastClientIP); - } else { - retval=powerChip(arg); -#ifdef VERBOSE - printf("Chip powered: %d\n",retval); -#endif - - if (retval==arg || arg<0) { - ret=OK; - } else { - ret=FAIL; - printf("Powering chip failed, wrote %d but read %d\n", arg, retval); - } - - } - if (ret==OK && differentClients==1) - ret=FORCE_UPDATE; - - /* send answer */ - n = sendDataOnly(file_des,&ret,sizeof(ret)); - if (ret==FAIL) { - n += sendDataOnly(file_des,mess,sizeof(mess)); - } else - n += sendDataOnly(file_des,&retval,sizeof(retval)); - - return ret; -} diff --git a/slsDetectorSoftware/jungfrauDetectorServer/server_funcs.h b/slsDetectorSoftware/jungfrauDetectorServer/server_funcs.h deleted file mode 100755 index 0cbdd052b..000000000 --- a/slsDetectorSoftware/jungfrauDetectorServer/server_funcs.h +++ /dev/null @@ -1,102 +0,0 @@ -#ifndef SERVER_FUNCS_H -#define SERVER_FUNCS_H - - -#include "sls_detector_defs.h" - - -#include -/* -#include -#include -#include -*/ -#include "communication_funcs.h" - - - - -#define GOODBYE -200 - -int sockfd; - -int function_table(); - -int decode_function(int); -int init_detector(int); - -int M_nofunc(int); -int exit_server(int); - - - - -// General purpose functions -int get_detector_type(int); -int set_number_of_modules(int); -int get_max_number_of_modules(int); - - -int exec_command(int); -int set_external_signal_flag(int); -int set_external_communication_mode(int); -int get_id(int); -int digital_test(int); -int write_register(int); -int read_register(int); -int set_dac(int); -int get_adc(int); -int set_channel(int); -int set_chip(int); -int set_module(int); -int get_channel(int); -int get_chip(int); -int get_module(int); - -int get_threshold_energy(int); -int set_threshold_energy(int); -int set_settings(int); -int start_acquisition(int); -int stop_acquisition(int); -int start_readout(int); -int get_run_status(int); -int read_frame(int); -int read_all(int); -int start_and_read_all(int); -int set_timer(int); -int get_time_left(int); -int set_dynamic_range(int); -int set_roi(int); -int get_roi(int); -int set_speed(int); -int set_readout_flags(int); -int execute_trimming(int); -int lock_server(int); -int set_port(int); -int get_last_client_ip(int); -int set_master(int); -int set_synchronization(int); - -int update_client(int); -int send_update(int); -int configure_mac(int); - -int load_image(int); -int read_counter_block(int); -int reset_counter_block(int); - -int start_receiver(int); -int stop_receiver(int); - - -int calibrate_pedestal(int); - -int set_roi(int); -int set_ctb_pattern(int); - -int write_adc_register(int);; - -int program_fpga(int); -int reset_fpga(int); -int power_chip(int); -#endif diff --git a/slsDetectorSoftware/jungfrauDetectorServer/slsDetectorFunctionList.c b/slsDetectorSoftware/jungfrauDetectorServer/slsDetectorFunctionList.c new file mode 100644 index 000000000..be4a86f08 --- /dev/null +++ b/slsDetectorSoftware/jungfrauDetectorServer/slsDetectorFunctionList.c @@ -0,0 +1,1691 @@ +//#ifdef SLS_DETECTOR_FUNCTION_LIST + + +#include "slsDetectorFunctionList.h" +#include "gitInfoJungfrau.h" +#include "slsDetectorServer_defs.h" // also include RegisterDefs.h + +#include +#include // usleep +#include +#include // open +#include // mmap +/* global variables */ + +sls_detector_module *detectorModules=NULL; +int *detectorChips=NULL; +int *detectorChans=NULL; +dacs_t *detectorDacs=NULL; +dacs_t *detectorAdcs=NULL; + +int gpioDefined=0; +enum detectorSettings thisSettings; +enum masterFlags masterMode = NO_MASTER; +int highvoltage = 0; +int dacValues[NDAC]; + +u_int32_t CSP0BASE = 0; +int32_t clkPhase[2] = {0, 0}; +char mtdvalue[10]; + + + + + +/* basic tests */ + +void checkFirmwareCompatibility(){ + + defineGPIOpins(); + resetFPGA(); + if ((mapCSP0() == FAIL) || (checkType() == FAIL) || (testFpga() == FAIL) || (testBus() == FAIL) ) { + cprintf(BG_RED, "Dangerous to continue. Goodbye!\n"); + exit(EXIT_FAILURE); + } + + uint16_t hversion = getHardwareVersionNumber(); + uint16_t hsnumber = getHardwareSerialNumber(); + uint32_t ipadd = getDetectorIP(); + uint64_t macadd = getDetectorMAC(); + int64_t fwversion = getDetectorId(DETECTOR_FIRMWARE_VERSION); + int64_t swversion = getDetectorId(DETECTOR_SOFTWARE_VERSION); + //int64_t sw_fw_apiversion = getDetectorId(SOFTWARE_FIRMWARE_API_VERSION); + cprintf(BLUE,"\n\n" + "********************************************************\n" + "****************** Jungfrau Server *********************\n" + "********************************************************\n\n" + "Hardware Version:\t\t 0x%x\n" + "Hardware Serial Nr:\t\t 0x%x\n" + + "Detector IP Addr:\t\t 0x%x\n" + "Detector MAC Addr:\t\t 0x%llx\n" + + "Firmware Version:\t\t 0x%llx\n" + "Software Version:\t\t 0x%llx\n" + //"F/w-S/w API Version:\t\t 0x%llx\n" + //"Required Firmware Version:\t 0x%x\n" + "\n" + "********************************************************\n", + hversion, hsnumber, + ipadd, macadd, + fwversion, swversion + //, sw_fw_apiversion, REQUIRED_FIRMWARE_VERSION + ); + + +/* + * printf("Testing firmware capability... "); + //cant read versions + if(!fwversion || !sw_fw_apiversion){ + cprintf(RED,"FATAL ERROR: Cant read versions from FPGA. Please update firmware\n"); + cprintf(RED,"Exiting Server. Goodbye!\n\n"); + exit(-1); + } + + //check for API compatibility - old server + if(sw_fw_apiversion > REQUIRED_FIRMWARE_VERSION){ + cprintf(RED,"FATAL ERROR: This software version is incompatible.\n" + "Please update it to be compatible with this firmware\n\n"); + cprintf(RED,"Exiting Server. Goodbye!\n\n"); + exit(-1); + } + + //check for firmware compatibility - old firmware + if( REQUIRED_FIRMWARE_VERSION > fwversion){ + cprintf(RED,"FATAL ERROR: This firmware version is incompatible.\n" + "Please update it to v%d to be compatible with this server\n\n", REQUIRED_FIRMWARE_VERSION); + cprintf(RED,"Exiting Server. Goodbye!\n\n"); + exit(-1); + } +*/ +} + + +int checkType() { + volatile u_int32_t type = ((bus_r(FPGA_VERSION_REG) & DETECTOR_TYPE_MSK) >> DETECTOR_TYPE_OFST); + if (type != JUNGFRAU){ + cprintf(BG_RED,"This is not a Jungfrau Server (read %d, expected %d)\n",type, JUNGFRAU); + return FAIL; + } + + return OK; +} + + + +u_int32_t testFpga(void) { + printf("\nTesting FPGA...\n"); + + //fixed pattern + int ret = OK; + volatile u_int32_t val = bus_r(FIX_PATT_REG); + if (val == FIX_PATT_VAL) { + printf("Fixed pattern: successful match 0x%08x\n",val); + } else { + cprintf(RED,"Fixed pattern does not match! Read 0x%08x, expected 0x%08x\n", val, FIX_PATT_VAL); + ret = FAIL; + } + return ret; +} + + +int testBus() { + printf("\nTesting Bus...\n"); + + int ret = OK; + u_int32_t addr = SET_DELAY_LSB_REG; + int times = 1000 * 1000; + int i = 0; + + for (i = 0; i < times; ++i) { + bus_w(addr, i * 100); + if (i * 100 != bus_r(SET_DELAY_LSB_REG)) { + cprintf(RED,"ERROR: Mismatch! Wrote 0x%x, read 0x%x\n", i * 100, bus_r(SET_DELAY_LSB_REG)); + ret = FAIL; + } + } + + if (ret == OK) + printf("Successfully tested bus %d times\n", times); + return ret; +} + + +int moduleTest( enum digitalTestMode arg, int imod){ + return OK; +} + +int detectorTest( enum digitalTestMode arg){ + switch(arg){ + case DETECTOR_FIRMWARE_TEST: return testFpga(); + case DETECTOR_BUS_TEST: return testBus(); + //DETECTOR_MEMORY_TEST:testRAM + //DETECTOR_SOFTWARE_TEST: + default: + cprintf(RED,"Warning: Test not implemented for this detector %d\n", (int)arg); + break; + } + return OK; +} + + + + + +/* Ids */ + +int64_t getDetectorId(enum idMode arg){ + int64_t retval = -1; + + switch(arg){ + case DETECTOR_SERIAL_NUMBER: + retval = getDetectorNumber();// or getDetectorMAC() + break; + case DETECTOR_FIRMWARE_VERSION: + retval = getFirmwareVersion(); + break; + //case SOFTWARE_FIRMWARE_API_VERSION: + //return GetFirmwareSoftwareAPIVersion(); + case DETECTOR_SOFTWARE_VERSION: + retval= SVNREV; + retval= (retval <<32) | SVNDATE; + break; + default: + break; + } + + return retval; +} + +u_int64_t getFirmwareVersion() { + return ((bus_r(FPGA_VERSION_REG) & BOARD_REVISION_MSK) >> BOARD_REVISION_OFST); +} + +u_int16_t getHardwareVersionNumber() { + return ((bus_r(MOD_SERIAL_NUM_REG) & HARDWARE_VERSION_NUM_MSK) >> HARDWARE_VERSION_NUM_OFST); +} + +u_int16_t getHardwareSerialNumber() { + return ((bus_r(MOD_SERIAL_NUM_REG) & HARDWARE_SERIAL_NUM_MSK) >> HARDWARE_SERIAL_NUM_OFST); +} + +u_int32_t getDetectorNumber(){ + return bus_r(MOD_SERIAL_NUM_REG); +} + +u_int64_t getDetectorMAC() { + char output[255],mac[255]=""; + u_int64_t res=0; + FILE* sysFile = popen("ifconfig eth0 | grep HWaddr | cut -d \" \" -f 11", "r"); + fgets(output, sizeof(output), sysFile); + pclose(sysFile); + //getting rid of ":" + char * pch; + pch = strtok (output,":"); + while (pch != NULL){ + strcat(mac,pch); + pch = strtok (NULL, ":"); + } + sscanf(mac,"%llx",&res); + return res; +} + +u_int32_t getDetectorIP(){ + char temp[50]=""; + u_int32_t res=0; + //execute and get address + char output[255]; + FILE* sysFile = popen("ifconfig | grep 'inet addr:'| grep -v '127.0.0.1' | cut -d: -f2", "r"); + fgets(output, sizeof(output), sysFile); + pclose(sysFile); + + //converting IPaddress to hex. + char* pcword = strtok (output,"."); + while (pcword != NULL) { + sprintf(output,"%02x",atoi(pcword)); + strcat(temp,output); + pcword = strtok (NULL, "."); + } + strcpy(output,temp); + sscanf(output, "%x", &res); + //printf("ip:%x\n",res); + + return res; +} + + + + + + + + +/* initialization */ + +void initControlServer(){ + + setupDetector(); + printf("\n"); +} + + + +void initStopServer() { + + usleep(CTRL_SRVR_INIT_TIME_US); + if (mapCSP0() == FAIL) { + cprintf(BG_RED, "Stop Server: Map Fail. Dangerous to continue. Goodbye!\n"); + exit(EXIT_FAILURE); + } +} + + +int mapCSP0(void) { + // if not mapped + if (!CSP0BASE) { + printf("Mapping memory\n"); +#ifdef VIRTUAL + CSP0BASE = malloc(MEM_SIZE); + printf("memory allocated\n"); +#else + int fd; + fd = open("/dev/mem", O_RDWR | O_SYNC, 0); + if (fd == -1) { + cprintf(BG_RED, "Error: Can't find /dev/mem\n"); + return FAIL; + } +#ifdef VERBOSE + printf("/dev/mem opened\n"); +#endif + CSP0BASE = (u_int32_t)mmap(0, MEM_SIZE, PROT_READ|PROT_WRITE, MAP_FILE|MAP_SHARED, fd, CSP0); + if (CSP0BASE == (u_int32_t)MAP_FAILED) { + cprintf(BG_RED, "Error: Can't map memmory area\n"); + return FAIL; + } + printf("CSPOBASE mapped from %08x to %08x\n",CSP0BASE,CSP0BASE+MEM_SIZE); +#endif + printf("Status Register: %08x\n",bus_r(STATUS_REG)); + }else + printf("Memory already mapped before\n"); + return OK; +} + + +void bus_w16(u_int32_t offset, u_int16_t data) { + volatile u_int16_t *ptr1; + ptr1=(u_int16_t*)(CSP0BASE+offset*2); + *ptr1=data; +} + +u_int16_t bus_r16(u_int32_t offset){ + volatile u_int16_t *ptr1; + ptr1=(u_int16_t*)(CSP0BASE+offset*2); + return *ptr1; +} + +void bus_w(u_int32_t offset, u_int32_t data) { + volatile u_int32_t *ptr1; + ptr1=(u_int32_t*)(CSP0BASE+offset*2); + *ptr1=data; +} + +u_int32_t bus_r(u_int32_t offset) { + volatile u_int32_t *ptr1; + ptr1=(u_int32_t*)(CSP0BASE+offset*2); + return *ptr1; +} + +int64_t set64BitReg(int64_t value, int aLSB, int aMSB){ + int64_t v64; + u_int32_t vLSB,vMSB; + if (value!=-1) { + vLSB=value&(0xffffffff); + bus_w(aLSB,vLSB); + v64=value>> 32; + vMSB=v64&(0xffffffff); + bus_w(aMSB,vMSB); + } + return get64BitReg(aLSB, aMSB); + +} + +int64_t get64BitReg(int aLSB, int aMSB){ + int64_t v64; + u_int32_t vLSB,vMSB; + vLSB=bus_r(aLSB); + vMSB=bus_r(aMSB); + v64=vMSB; + v64=(v64<<32) | vLSB; + printf(" reg64(%x,%x) %x %x %llx\n", aLSB, aMSB, vLSB, vMSB, v64); + return v64; +} + + +void defineGPIOpins(){ + if (!gpioDefined) { + //define the gpio pins + system("echo 7 > /sys/class/gpio/export"); + system("echo 9 > /sys/class/gpio/export"); + //define their direction + system("echo in > /sys/class/gpio/gpio7/direction"); + system("echo out > /sys/class/gpio/gpio9/direction"); + printf("gpio pins defined\n"); + gpioDefined = 1; + }else printf("gpio pins already defined earlier\n"); +} + +void resetFPGA(){ + cprintf(BLUE,"\n*** Reseting FPGA ***\n"); + FPGAdontTouchFlash(); + FPGATouchFlash(); + usleep(250*1000); +} + +void FPGAdontTouchFlash(){ + //tell FPGA to not touch flash + system("echo 0 > /sys/class/gpio/gpio9/value"); + //usleep(100*1000); +} + +void FPGATouchFlash(){ + //tell FPGA to touch flash to program itself + system("echo 1 > /sys/class/gpio/gpio9/value"); +} + + + + + + +/* set up detector */ + +void allocateDetectorStructureMemory(){ + printf("This Server is for 1 Jungfrau module (500k)\n"); + + //Allocation of memory + if (detectorModules!=NULL) free(detectorModules); + if (detectorChips!=NULL) free(detectorChips); + if (detectorChans!=NULL) free(detectorChans); + if (detectorDacs!=NULL) free(detectorDacs); + if (detectorAdcs!=NULL) free(detectorAdcs); + detectorModules=malloc(sizeof(sls_detector_module)); + detectorChips=malloc(NCHIP*sizeof(int)); + detectorChans=malloc(NCHIP*NCHAN*sizeof(int)); + detectorDacs=malloc(NDAC*sizeof(dacs_t)); + detectorAdcs=malloc(NADC*sizeof(dacs_t)); +#ifdef VERBOSE + printf("modules from 0x%x to 0x%x\n",detectorModules, detectorModules+n); + printf("chips from 0x%x to 0x%x\n",detectorChips, detectorChips+n*NCHIP); + printf("chans from 0x%x to 0x%x\n",detectorChans, detectorChans+n*NCHIP*NCHAN); + printf("dacs from 0x%x to 0x%x\n",detectorDacs, detectorDacs+n*NDAC); + printf("adcs from 0x%x to 0x%x\n",detectorAdcs, detectorAdcs+n*NADC); +#endif + (detectorModules)->dacs=detectorDacs; + (detectorModules)->adcs=detectorAdcs; + (detectorModules)->chipregs=detectorChips; + (detectorModules)->chanregs=detectorChans; + (detectorModules)->ndac=NDAC; + (detectorModules)->nadc=NADC; + (detectorModules)->nchip=NCHIP; + (detectorModules)->nchan=NCHIP*NCHAN; + (detectorModules)->module=0; + (detectorModules)->gain=0; + (detectorModules)->offset=0; + (detectorModules)->reg=0; + thisSettings = UNINITIALIZED; +} + + + +void setupDetector() { + + allocateDetectorStructureMemory(); + + printf("Resetting PLL\n"); + resetPLL(); + resetCore(); + resetPeripheral(); + cleanFifos(); + + prepareADC(); + + // initialize dac series + initDac(0); /* todo might work without */ + initDac(8); //only for old board compatibility + + //set dacs + printf("Setting Default Dac values\n"); + { + int i = 0; + int retval[2]={-1,-1}; + const int defaultvals[NDAC] = DEFAULT_DAC_VALS; + for(i = 0; i < NDAC; ++i) { + setDAC((enum DACINDEX)i,defaultvals[i],0,0,retval); + if (retval[0] != defaultvals[i]) + cprintf(RED, "Warning: Setting dac %d failed, wrote %d, read %d\n",i ,defaultvals[i], retval[0]); + } + } + + bus_w(DAQ_REG, 0x0); /* Only once at server startup */ + setSpeed(CLOCK_DIVIDER, HALF_SPEED); + cleanFifos(); /* todo might work without */ + resetCore(); /* todo might work without */ + + + //Initialization of acquistion parameters + setSettings(DEFAULT_SETTINGS,-1); + + setTimer(FRAME_NUMBER, DEFAULT_NUM_FRAMES); + setTimer(CYCLES_NUMBER, DEFAULT_NUM_CYCLES); + setTimer(ACQUISITION_TIME, DEFAULT_PERIOD); + setTimer(FRAME_PERIOD, DEFAULT_PERIOD); + setTimer(DELAY_AFTER_TRIGGER, DEFAULT_DELAY); + /*setSpeed(CLOCK_DIVIDER, HALF_SPEED); depends if all the previous stuff works*/ + setTiming(DEFAULT_TIMING_MODE); + setHighVoltage(DEFAULT_HIGH_VOLTAGE); +} + + + + + +/* advanced read/write reg */ + +u_int32_t writeRegister(u_int32_t offset, u_int32_t data) { + bus_w(offset << 11, data); + return readRegister(offset); +} + +u_int32_t readRegister(u_int32_t offset) { + return bus_r(offset << 11); +} + + + + +/* firmware functions (resets) */ + +int powerChip (int on){ + if(on != -1){ + if(on){ + cprintf(BLUE, "\n*** Powering on the chip ***\n"); + bus_w(CHIP_POWER_REG, bus_r(CHIP_POWER_REG) | CHIP_POWER_ENABLE_MSK); + } + else{ + cprintf(BLUE, "\n*** Powering off the chip*** \n"); + bus_w(CHIP_POWER_REG, bus_r(CHIP_POWER_REG) & ~CHIP_POWER_ENABLE_MSK); + } + } + return bus_r(CHIP_POWER_REG); +} + +void cleanFifos() { + printf("\nClearing Acquisition Fifos\n"); + bus_w(CONTROL_REG, bus_r(CONTROL_REG) | CONTROL_ACQ_FIFO_CLR_MSK); + bus_w(CONTROL_REG, bus_r(CONTROL_REG) & ~CONTROL_ACQ_FIFO_CLR_MSK); +} + +void resetCore() { + printf("\nResetting Core\n"); + bus_w(CONTROL_REG, bus_r(CONTROL_REG) | CONTROL_CORE_RST_MSK); + bus_w(CONTROL_REG, bus_r(CONTROL_REG) & ~CONTROL_CORE_RST_MSK); +} + +void resetPeripheral() { + printf("\nResetting Peripheral\n"); + bus_w(CONTROL_REG, bus_r(CONTROL_REG) | CONTROL_PERIPHERAL_RST_MSK); + bus_w(CONTROL_REG, bus_r(CONTROL_REG) & ~CONTROL_PERIPHERAL_RST_MSK); +} + +int adcPhase(int st){ /**carlos needed clkphase 1 and 2? cehck with Aldo */ + printf("Setting ADC Phase to %d\n",st); + if (st > 65535 || st < -65535) + return clkPhase[0]; + clkPhase[1] = st - clkPhase[0]; + + printf(" phase %d\n", clkPhase[1] ); + configurePll(); + clkPhase[0] = st; + return clkPhase[0]; +} + +int getPhase() { + return clkPhase[0]; +} + + + + + + + + + + +/* set parameters - nmod, dr, roi */ + +int setNMod(int nm, enum dimension dim){ + return NMOD; +} + + +int getNModBoard(enum dimension arg){ + return NMAXMOD; +} + + +int setDynamicRange(int dr){ + return DYNAMIC_RANGE; +} + + + + +/* parameters - readout */ + +int setSpeed(enum speedVariable arg, int val) { + + if (arg != CLOCK_DIVIDER) + return -1; + + // setting + if(val >= 0) { + + switch(val){ + + // stop state machine if running + if(runBusy()) + stopStateMachine(); + + // todo in firmware, for now setting half speed + case FULL_SPEED://40 + printf("\nSetting Half Speed (20 MHz):\n"); + printf("Setting Sample Reg to 0x%x\n", SAMPLE_ADC_HALF_SPEED); bus_w(SAMPLE_REG, SAMPLE_ADC_HALF_SPEED); + printf("Setting Config Reg to 0x%x\n", CONFIG_HALF_SPEED); bus_w(CONFIG_REG, CONFIG_HALF_SPEED); + printf("Setting ADC Ofst Reg to 0x%x\n", ADC_OFST_HALF_SPEED_VAL); bus_w(ADC_OFST_REG, ADC_OFST_HALF_SPEED_VAL); + printf("Setting ADC Phase Reg to 0x%x\n", ADC_PHASE_HALF_SPEED); adcPhase(ADC_PHASE_HALF_SPEED); + break; + case HALF_SPEED: + printf("\nSetting Half Speed (20 MHz):\n"); + printf("Setting Sample Reg to 0x%x\n", SAMPLE_ADC_HALF_SPEED); bus_w(SAMPLE_REG, SAMPLE_ADC_HALF_SPEED); + printf("Setting Config Reg to 0x%x\n", CONFIG_HALF_SPEED); bus_w(CONFIG_REG, CONFIG_HALF_SPEED); + printf("Setting ADC Ofst Reg to 0x%x\n", ADC_OFST_HALF_SPEED_VAL); bus_w(ADC_OFST_REG, ADC_OFST_HALF_SPEED_VAL); + printf("Setting ADC Phase Reg to 0x%x\n", ADC_PHASE_HALF_SPEED); adcPhase(ADC_PHASE_HALF_SPEED); + break; + case QUARTER_SPEED: + printf("\nSetting Half Speed (10 MHz):\n"); + printf("Setting Sample Reg to 0x%x\n", SAMPLE_ADC_QUARTER_SPEED); bus_w(SAMPLE_REG, SAMPLE_ADC_QUARTER_SPEED); + printf("Setting Config Reg to 0x%x\n", CONFIG_QUARTER_SPEED); bus_w(CONFIG_REG, CONFIG_QUARTER_SPEED); + printf("Setting ADC Ofst Reg to 0x%x\n", ADC_OFST_QUARTER_SPEED_VAL); bus_w(ADC_OFST_REG, ADC_OFST_QUARTER_SPEED_VAL); + printf("Setting ADC Phase Reg to 0x%x\n", ADC_PHASE_QUARTER_SPEED); adcPhase(ADC_PHASE_QUARTER_SPEED); + break; + } + printf("\n"); + } + + //getting + u_int32_t speed = bus_r(CONFIG_REG) & CONFIG_READOUT_SPEED_MSK; + switch(speed){ + case CONFIG_FULL_SPEED_40MHZ_VAL: + return FULL_SPEED; + case CONFIG_HALF_SPEED_20MHZ_VAL: + return HALF_SPEED; + case CONFIG_QUARTER_SPEED_10MHZ_VAL: + return QUARTER_SPEED; + default: + return -1; + } +} + + + + + + +/* parameters - timer */ + +int64_t setTimer(enum timerIndex ind, int64_t val) { + + int64_t retval = -1; + switch(ind){ + + case FRAME_NUMBER: + if(val >= 0) + printf("\nSetting #frames: %lld\n",(long long int)val); + retval = set64BitReg(val, SET_FRAMES_LSB_REG, SET_FRAMES_MSB_REG); + printf("Getting #frames: %lld\n",(long long int)retval); + break; + + case ACQUISITION_TIME: + if(val >= 0){ + printf("\nSetting exptime: %lldns\n", (long long int)val); + val *= (1E-3 * CLK_RUN); + } + retval = set64BitReg(val, SET_EXPTIME_LSB_REG, SET_EXPTIME_MSB_REG) / (1E-3 * CLK_RUN); + printf("Getting exptime: %lldns\n", (long long int)retval); + break; + + case FRAME_PERIOD: + if(val >= 0){ + printf("\nSetting period to %lldns\n",(long long int)val); + val *= (1E-3 * CLK_SYNC); + } + retval = set64BitReg(val, SET_PERIOD_LSB_REG, SET_PERIOD_MSB_REG )/ (1E-3 * CLK_SYNC); + printf("Getting period: %lldns\n", (long long int)retval); + break; + + case DELAY_AFTER_TRIGGER: + if(val >= 0){ + printf("\nSetting delay to %lldns\n", (long long int)val); + val *= (1E-3 * CLK_SYNC); + } + retval = set64BitReg(val, SET_DELAY_LSB_REG, SET_DELAY_MSB_REG) / (1E-3 * CLK_SYNC); + printf("Getting delay: %lldns\n", (long long int)retval); + break; + + case CYCLES_NUMBER: + if(val >= 0) + printf("\nSetting #cycles to %lld\n", (long long int)val); + retval = set64BitReg(val, SET_CYCLES_LSB_REG, SET_CYCLES_MSB_REG); + printf("Getting #cycles: %lld\n", (long long int)retval); + break; + + default: + cprintf(RED,"Warning: Timer Index not implemented for this detector: %d\n", ind); + break; + } + + return retval; + +} + + + +int64_t getTimeLeft(enum timerIndex ind){ + int64_t retval = -1; + switch(ind){ + + case FRAME_NUMBER: + retval = get64BitReg(GET_FRAMES_LSB_REG, GET_FRAMES_MSB_REG); + printf("Getting number of frames left: %lld\n",(long long int)retval); + break; + + case FRAME_PERIOD: + retval = get64BitReg(GET_PERIOD_LSB_REG, GET_PERIOD_MSB_REG) / (1E-3 * CLK_SYNC); + printf("Getting period left: %lldns\n", (long long int)retval); + break; + + case DELAY_AFTER_TRIGGER: + retval = get64BitReg(GET_DELAY_LSB_REG, GET_DELAY_MSB_REG) / (1E-3 * CLK_SYNC); + printf("Getting delay left: %lldns\n", (long long int)retval); + break; + + case CYCLES_NUMBER: + retval = get64BitReg(GET_CYCLES_LSB_REG, GET_CYCLES_MSB_REG); + printf("Getting number of cycles left: %lld\n", (long long int)retval); + break; + + case ACTUAL_TIME: + retval = get64BitReg(TIME_FROM_START_LSB_REG, TIME_FROM_START_MSB_REG) / (1E-9 * CLK_SYNC); + printf("Getting actual time (time from start): %lld\n", (long long int)retval); + break; + + case MEASUREMENT_TIME: + retval = get64BitReg(START_FRAME_TIME_LSB_REG, START_FRAME_TIME_MSB_REG) / (1E-9 * CLK_SYNC); + printf("Getting measurement time (timestamp/ start frame time): %lld\n", (long long int)retval); + break; + + case FRAMES_FROM_START: + case FRAMES_FROM_START_PG: + retval = get64BitReg(FRAMES_FROM_START_PG_LSB_REG, FRAMES_FROM_START_PG_MSB_REG); + printf("Getting frames from start run control %lld\n", (long long int)retval); + break; + + default: + cprintf(RED, "Warning: Remaining Timer index not implemented for this detector: %d\n", ind); + break; + } + + return retval; +} + + + + + + +/* parameters - channel, chip, module, settings */ + + +int setModule(sls_detector_module myMod){ + int retval[2]; + int i; + + //#ifdef VERBOSE + printf("Setting module with settings %d\n",myMod.reg); + //#endif + + setSettings( (enum detectorSettings)myMod.reg,-1); + + //copy module locally + if (detectorModules) + copyModule(detectorModules,&myMod); + + //set dac values + for(i=0;i> (numbitstosend - 1 - i)) & 0x1) << digofset)); // each bit from val starting from msb + bus_w16 (addr, valw); + + // clk up + valw |= clkmask ; + bus_w16 (addr, valw); + } + } + + // chip sel bar up + valw |= csmask; /* todo with test: not done for spi */ + bus_w16 (addr, valw); + + //clk down + valw &= ~clkmask; + bus_w16 (addr, valw); + + // stop point = start point of course + valw = 0xffff; /**todo testwith old board 0xff for adc_spi */ // old board compatibility (not using specific bits) + bus_w16 (addr, valw); +} + + + +void initDac(int dacnum) { + printf("\nInitializing dac for %d to \n",dacnum); + + u_int32_t codata; + int csdx = dacnum / NDAC + DAC_SERIAL_CS_OUT_OFST; // old board (16 dacs),so can be DAC_SERIAL_CS_OUT_OFST or +1 + int dacchannel = 0xf; // all channels + int dacvalue = 0x6; // can be any random value (just writing to power up) + printf(" Write to Input Register\n" + " Chip select bit:%d\n" + " Dac Channel:0x%x\n" + " Dac Value:0x%x\n", + csdx, dacchannel, dacvalue); + + codata = LTC2620_DAC_CMD_WRITE + // command to write to input register + ((dacchannel << LTC2620_DAC_ADDR_OFST) & LTC2620_DAC_ADDR_MSK) + // all channels + ((dacvalue << LTC2620_DAC_DATA_OFST) & LTC2620_DAC_DATA_MSK); // any random value + serializeToSPI(SPI_REG, codata, (0x1 << csdx), LTC2620_DAC_NUMBITS, + DAC_SERIAL_CLK_OUT_MSK, DAC_SERIAL_DIGITAL_OUT_MSK, DAC_SERIAL_DIGITAL_OUT_OFST); +} + + + +void prepareADC(){ + printf("\n\nPreparing ADC ... \n"); + + //power mode reset + printf("power mode reset:\n"); + setAdc(AD9257_POWER_MODE_REG, + (AD9257_INT_RESET_VAL << AD9257_POWER_INTERNAL_OFST) & AD9257_POWER_INTERNAL_MSK); + + //power mode chip run + printf("power mode chip run:\n"); + setAdc(AD9257_POWER_MODE_REG, + (AD9257_INT_CHIP_RUN_VAL << AD9257_POWER_INTERNAL_OFST) & AD9257_POWER_INTERNAL_MSK); + + //output clock phase + printf("output clock phase:\n"); + setAdc(AD9257_OUT_PHASE_REG, + (AD9257_OUT_CLK_60_VAL << AD9257_OUT_CLK_OFST) & AD9257_OUT_CLK_MSK); + + // lvds-iee reduced , binary offset + printf("lvds-iee reduced, binary offset:\n"); + setAdc(AD9257_OUT_MODE_REG, + (AD9257_OUT_LVDS_IEEE_VAL << AD9257_OUT_LVDS_OPT_OFST) & AD9257_OUT_LVDS_OPT_MSK); + + // all devices on chip to receive next command + printf("all devices on chip to receive next command:\n"); + setAdc(AD9257_DEV_IND_2_REG, + AD9257_CHAN_H_MSK | AD9257_CHAN_G_MSK | AD9257_CHAN_F_MSK | AD9257_CHAN_E_MSK); + setAdc(AD9257_DEV_IND_1_REG, + AD9257_CHAN_D_MSK | AD9257_CHAN_C_MSK | AD9257_CHAN_B_MSK | AD9257_CHAN_A_MSK | + AD9257_CLK_CH_DCO_MSK | AD9257_CLK_CH_IFCO_MSK); + + // vref 1.33 + printf("vref 1.33:\n"); + setAdc(AD9257_VREF_REG, + (AD9257_VREF_1_33_VAL << AD9257_VREF_OFST) & AD9257_VREF_MSK); + + // no test mode + printf("no test mode:\n"); + setAdc(AD9257_TEST_MODE_REG, + (AD9257_NONE_VAL << AD9257_OUT_TEST_OFST) & AD9257_OUT_TEST_MSK); + +#ifdef TESTADC + printf("***************************************** *******\n"); + printf("******* PUTTING ADC IN TEST MODE!!!!!!!!! *******\n"); + printf("***************************************** *******\n"); + // mixed bit frequency test mode + printf("mixed bit frequency test mode:\n"); + setAdc(AD9257_TEST_MODE_REG, + (AD9257_MIXED_BIT_FREQ_VAL << AD9257_OUT_TEST_OFST) & AD9257_OUT_TEST_MSK); +#endif +} + + + +void setAdc(int addr, int val) { + + u_int32_t codata; + codata = val + (addr << 8); + printf(" Setting ADC SPI Register. Wrote 0x%04x at 0x%04x\n", val, addr); + serializeToSPI(ADC_SPI_REG, codata, ADC_SERIAL_CS_OUT_MSK, AD9257_ADC_NUMBITS, + ADC_SERIAL_CLK_OUT_MSK, ADC_SERIAL_DATA_OUT_MSK, ADC_SERIAL_DATA_OUT_OFST); +} + + +int voltageToDac(int value){ + int vmin = 0; + int vmax = 2500; + int nsteps = 4096; + if ((value < vmin) || (value > vmax)) { + cprintf(RED,"Voltage value (to convert to dac value) is outside bounds: %d\n", value); + return -1; + } + return (int)(((value - vmin) / (vmax - vmin)) * (nsteps - 1) + 0.5); +} + +int dacToVoltage(unsigned int digital){ + int vmin = 0; + int vmax = 2500; + int nsteps = 4096; + int v = vmin + (vmax - vmin) * digital / (nsteps - 1); + if((v < 0) || (v > nsteps - 1)) { + cprintf(RED,"Voltage value (converted from dac value) is outside bounds: %d\n", v); + return -1; + } + return v; +} + + + +void setDAC(enum DACINDEX ind, int val, int imod, int mV, int retval[]){ + int dacval = val; + + //if set and mv, convert to dac + if (val > 0 && mV) { + val = voltageToDac(val); //gives -1 on error + } + + if ( (val >= 0) || (val == -100)) { + u_int32_t codata; + int csdx = ind / NDAC + DAC_SERIAL_CS_OUT_OFST; // old board (16 dacs),so can be DAC_SERIAL_CS_OUT_OFST or +1 + int dacchannel = ind % NDAC; // 0-8, dac channel number (also for dacnum 9-15 in old board) + + printf("\nSetting of DAC %d : %d dac units (%d mV)\n",ind, dacval, val); + // command + if (val >= 0) { + printf(" Write to Input Register and Update\n"); + codata = LTC2620_DAC_CMD_SET; + + } else if (val == -100) { + printf(" POWER DOWN\n"); + codata = LTC2620_DAC_CMD_POWER_DOWN; + } + // address + printf(" Chip select bit:%d\n" + " Dac Channel:0x%x\n" + " Dac Value:0x%x\n", + csdx, dacchannel, val); + codata += ((dacchannel << LTC2620_DAC_ADDR_OFST) & LTC2620_DAC_ADDR_MSK) + + ((val << LTC2620_DAC_DATA_OFST) & LTC2620_DAC_DATA_MSK); + // to spi + serializeToSPI(SPI_REG, codata, (0x1 << csdx), LTC2620_DAC_NUMBITS, + DAC_SERIAL_CLK_OUT_MSK, DAC_SERIAL_DIGITAL_OUT_MSK, DAC_SERIAL_DIGITAL_OUT_OFST); + + dacValues[ind] = dacval; + } + + printf("Getting DAC %d : ",ind); + retval[0] = dacValues[ind]; printf("%d dac units ", retval[0]); + retval[1] = dacToVoltage(retval[0]);printf("(%d mV)\n", retval[1]); +} + + +int getADC(enum ADCINDEX ind, int imod){ + + char tempnames[2][40]={"VRs/FPGAs Temperature", "ADCs/ASICs Temperature"}; + printf("Getting Temperature for %s\n",tempnames[ind]); + u_int32_t addr = GET_TEMPERATURE_TMP112_REG; + int retval = -1; +/* + u_int32_t val = 0; + { + int i; + for(i = 0; i < 10; i++) { + switch((int)ind){ + + case TEMP_FPGA: + val = (val<<1) + ((bus_r(addr) & (2)) >> 1); + break; + case TEMP_ADC: + val= (val<<1) + (bus_r(addr) & (1)); + break; + } + } + } + // or just read it + retval = ((int)val) / 4.0; + + printf("Temperature %s: %d °C\n",tempnames[ind],retval);*/ + printf("\nReal Temperature %s: %d °C\n",tempnames[ind],bus_r(addr)); + + + return retval; +} + + + +int setHighVoltage(int val){ + u_int32_t dacvalue; + float alpha = 0.55; + // setting hv + if (val >= 0) { + // limit values + if (val < 60) { + dacvalue = 0; + val = 60; + } else if (val >= 200) { + dacvalue = 0x1; + val = 200; + } else { + dacvalue = 1. + (200.-val) / alpha; + val=200.-(dacvalue-1)*alpha; + } + printf ("\nSetting High voltage to %d (dacval %d)\n",val, dacvalue); + dacvalue &= MAX1932_HV_DATA_MSK; + serializeToSPI(SPI_REG, dacvalue, HV_SERIAL_CS_OUT_MSK, MAX1932_HV_NUMBITS, + HV_SERIAL_CLK_OUT_MSK, HV_SERIAL_DIGITAL_OUT_MSK, HV_SERIAL_DIGITAL_OUT_OFST); + highvoltage = val; + } + return highvoltage; +} + + + + + + +/* parameters - timing, extsig */ + + +enum externalCommunicationMode setTiming( enum externalCommunicationMode arg){ + + if(arg != GET_EXTERNAL_COMMUNICATION_MODE){ + switch((int)arg){ + case AUTO_TIMING: bus_w(EXT_SIGNAL_REG, bus_r(EXT_SIGNAL_REG) & ~EXT_SIGNAL_MSK); break; + case TRIGGER_EXPOSURE: bus_w(EXT_SIGNAL_REG, bus_r(EXT_SIGNAL_REG) | EXT_SIGNAL_MSK); break; + default: + cprintf(RED,"Unknown timing mode %d\n", arg); + return GET_EXTERNAL_COMMUNICATION_MODE; + } + } + if (bus_r(EXT_SIGNAL_REG) == EXT_SIGNAL_MSK) + return TRIGGER_EXPOSURE; + return AUTO_TIMING; +} + + + + + +/* configure mac */ + + +long int calcChecksum(int sourceip, int destip) { + + ip_header ip; + int count; + unsigned short *addr; + long int sum = 0; + long int checksum; + ip.ip_ver = 0x4; + ip.ip_ihl = 0x5; + ip.ip_tos = 0x0; + ip.ip_len = IP_PACKETSIZE; + ip.ip_ident = 0x0000; + ip.ip_flag = 0x2; //not nibble aligned (flag& offset + ip.ip_offset = 0x000; + ip.ip_ttl = 0x40; + ip.ip_protocol = 0x11; + ip.ip_chksum = 0x0000 ; // pseudo + ip.ip_sourceip = sourceip; + ip.ip_destip = destip; + + count = sizeof(ip); + addr =& (ip); /* warning: assignment from incompatible pointer type */ + while( count > 1 ) { + sum += *addr++; + count -= 2; + } + if (count > 0) sum += *addr; // Add left-over byte, if any + while (sum>>16) sum = (sum & 0xffff) + (sum >> 16);// Fold 32-bit sum to 16 bits + checksum = (~sum) & 0xffff; + + printf("IP checksum is 0x%lx\n",checksum); + + return checksum; +} + + + +int configureMAC(uint32_t destip, uint64_t destmac, uint64_t sourcemac, uint32_t sourceip, uint32_t udpport, uint32_t udpport2, int ival){ + cprintf(BLUE, "\n*** Configuring MAC ***\n"); + uint32_t sourceport = DEFAULT_TX_UDP_PORT; + + printf("Source IP : %d.%d.%d.%d \t\t(0x%08x)\n",(sourceip>>24)&0xff,(sourceip>>16)&0xff,(sourceip>>8)&0xff,(sourceip)&0xff, sourceip); + printf("Source MAC : %02x:%02x:%02x:%02x:%02x:%02x \t(0x%010llx)\n", + (unsigned int)((sourcemac>>40)&0xFF), + (unsigned int)((sourcemac>>32)&0xFF), + (unsigned int)((sourcemac>>24)&0xFF), + (unsigned int)((sourcemac>>16)&0xFF), + (unsigned int)((sourcemac>>8)&0xFF), + (unsigned int)((sourcemac>>0)&0xFF), + sourcemac); + printf("Source Port : %d \t\t\t(0x%08x)\n",sourceport, sourceport); + + printf("Dest. IP : %d.%d.%d.%d \t\t(0x%08x)\n",(destip>>24)&0xff,(destip>>16)&0xff,(destip>>8)&0xff,(destip)&0xff, destip); + printf("Dest. MAC : %02x:%02x:%02x:%02x:%02x:%02x \t(0x%010llx)\n", + (unsigned int)((destmac>>40)&0xFF), + (unsigned int)((destmac>>32)&0xFF), + (unsigned int)((destmac>>24)&0xFF), + (unsigned int)((destmac>>16)&0xFF), + (unsigned int)((destmac>>8)&0xFF), + (unsigned int)((destmac>>0)&0xFF), + destmac); + printf("Dest. Port : %d \t\t\t(0x%08x)\n",udpport, udpport); + + long int checksum=calcChecksum(sourceip, destip); + bus_w(TX_IP_REG, sourceip); + bus_w(RX_IP_REG, destip); + +/* + bus_w(TX_MAC_LSB_REG,(destmac>>32)&0xFFFFFFFF);//rx_udpmacH_AReg_c + bus_w(TX_MAC_MSB_REG,(destmac)&0xFFFFFFFF);//rx_udpmacL_AReg_c + bus_w(RX_MAC_MSB_REG,(sourcemac>>32)&0xFFFFFFFF);//detectormacH_AReg_c + bus_w(RX_MAC_LSB_REG,(sourcemac)&0xFFFFFFFF);//detectormacL_AReg_c + bus_w(UDP_PORT_REG,((sourceport&0xFFFF)<<16)+(udpport&0xFFFF));//udpports_AReg_c +*/ + uint32_t val = 0; + + val = ((sourcemac >> LSB_OF_64_BIT_REG_OFST) & BIT_32_MSK); + bus_w(TX_MAC_LSB_REG, val); +#ifdef VERBOSE + printf("Read from TX_MAC_LSB_REG: 0x%08x\n", bus_r(TX_MAC_LSB_REG)); +#endif + + val = ((sourcemac >> MSB_OF_64_BIT_REG_OFST) & BIT_32_MSK); + bus_w(TX_MAC_MSB_REG,val); +#ifdef VERBOSE + printf("Read from TX_MAC_MSB_REG: 0x%08x\n", bus_r(TX_MAC_MSB_REG)); +#endif + + val = ((destmac >> LSB_OF_64_BIT_REG_OFST) & BIT_32_MSK); + bus_w(RX_MAC_LSB_REG, val); +#ifdef VERBOSE + printf("Read from RX_MAC_LSB_REG: 0x%08x\n", bus_r(RX_MAC_LSB_REG)); +#endif + + val = ((destmac >> MSB_OF_64_BIT_REG_OFST) & BIT_32_MSK); + bus_w(RX_MAC_MSB_REG, val); +#ifdef VERBOSE + printf("Read from RX_MAC_MSB_REG: 0x%08x\n", bus_r(RX_MAC_MSB_REG)); +#endif + + val = (((sourceport << UDP_PORT_TX_OFST) & UDP_PORT_TX_MSK) | + ((udpport << UDP_PORT_RX_OFST) & UDP_PORT_RX_MSK)); + bus_w(UDP_PORT_REG, val); +#ifdef VERBOSE + printf("Read from UDP_PORT_REG: 0x%08x\n", bus_r(UDP_PORT_REG)); +#endif + + bus_w(TX_IP_CHECKSUM_REG,(checksum << TX_IP_CHECKSUM_OFST) & TX_IP_CHECKSUM_MSK); +#ifdef VERBOSE + printf("Read from TX_IP_CHECKSUM_REG: 0x%08x\n", bus_r(TX_IP_CHECKSUM_REG)); +#endif + cleanFifos(); + resetCore(); + + usleep(500 * 1000); /* todo maybe without */ + return 0; +} + + + + + + +/* jungfrau specific - pll, flashing fpga */ + + + +void resetPLL() { + // reset PLL Reconfiguration and PLL + bus_w(PLL_CONTROL_REG, bus_r(PLL_CONTROL_REG) | PLL_CTRL_RECONFIG_RST_MSK | PLL_CTRL_RST_MSK); + usleep(100); + bus_w(PLL_CONTROL_REG, bus_r(PLL_CONTROL_REG) & ~PLL_CTRL_RECONFIG_RST_MSK & ~PLL_CTRL_RST_MSK); +} + + +u_int32_t setPllReconfigReg(u_int32_t reg, u_int32_t val) { + + // set parameter + bus_w(PLL_PARAM_REG, val); + + // set address + bus_w(PLL_CONTROL_REG, (reg << PLL_CTRL_ADDR_OFST) & PLL_CTRL_ADDR_MSK); + usleep(10*1000); + + //write parameter + bus_w(PLL_CONTROL_REG, bus_r(PLL_CONTROL_REG) | PLL_CTRL_WR_PARAMETER_MSK); + bus_w(PLL_CONTROL_REG, bus_r(PLL_CONTROL_REG) & ~PLL_CTRL_WR_PARAMETER_MSK); + usleep(10*1000); + + return val; +} + + + + +void configurePll() { + u_int32_t val; + int32_t phase=0, inv=0; + + printf(" phase in %d\n", clkPhase[1]); + if (clkPhase[1]>0) { + inv=0; + phase=clkPhase[1]; + } else { + inv=1; + phase=-1*clkPhase[1]; + } + printf(" phase out %d (0x%08x)\n", phase, phase); + + if (inv) { + val = ((phase << PLL_SHIFT_NUM_SHIFTS_OFST) & PLL_SHIFT_NUM_SHIFTS_MSK) + PLL_SHIFT_CNT_SLCT_C1_VAL + PLL_SHIFT_UP_DOWN_NEG_VAL; + printf(" phase word 0x%08x\n", val); + setPllReconfigReg(PLL_PHASE_SHIFT_REG, val); + } else { + val = ((phase << PLL_SHIFT_NUM_SHIFTS_OFST) & PLL_SHIFT_NUM_SHIFTS_MSK) + PLL_SHIFT_CNT_SLCT_C0_VAL + PLL_SHIFT_UP_DOWN_NEG_VAL; + printf(" phase word 0x%08x\n", val); + setPllReconfigReg(PLL_PHASE_SHIFT_REG, val); + + printf(" phase word 0x%08x\n", val); + val = ((phase << PLL_SHIFT_NUM_SHIFTS_OFST) & PLL_SHIFT_NUM_SHIFTS_MSK) + PLL_SHIFT_CNT_SLCT_C2_VAL; + setPllReconfigReg(PLL_PHASE_SHIFT_REG, val); + } + usleep(10000); +} + + + +void eraseFlash(){ +#ifdef VERY_VERBOSE + printf("\nErasing Flash\n"); +#endif + char command[255]; + sprintf(command,"flash_eraseall %s",mtdvalue); + system(command); + printf("flash erased\n"); +} + + +int startWritingFPGAprogram(FILE** filefp){ +#ifdef VERY_VERBOSE + printf("\nStart Writing of FPGA program\n"); +#endif + + //getting the drive + char output[255]; + FILE* fp = popen("awk \'$4== \"\\\"bitfile(spi)\\\"\" {print $1}\' /proc/mtd", "r"); + fgets(output, sizeof(output), fp); + pclose(fp); + strcpy(mtdvalue,"/dev/"); + char* pch = strtok(output,":"); + if(pch == NULL){ + cprintf(RED,"Could not get mtd value\n"); + return FAIL; + } + strcat(mtdvalue,pch); + printf ("\nFlash drive found: %s\n",mtdvalue); + + FPGAdontTouchFlash(); + + //writing the program to flash + *filefp = fopen(mtdvalue, "w"); + if(*filefp == NULL){ + cprintf(RED,"Unable to open %s in write mode\n",mtdvalue); + return FAIL; + } + printf("flash ready for writing\n"); + + return OK; +} + +int stopWritingFPGAprogram(FILE* filefp){ +#ifdef VERY_VERBOSE + printf("\nStopping of writing FPGA program\n"); +#endif + + int wait = 0; + if(filefp!= NULL){ + fclose(filefp); + wait = 1; + } + + //touch and program + FPGATouchFlash(); + + if(wait){ +#ifdef VERY_VERBOSE + printf("Waiting for FPGA to program from flash\n"); +#endif + //waiting for success or done + char output[255]; + int res=0; + while(res == 0){ + FILE* sysFile = popen("cat /sys/class/gpio/gpio7/value", "r"); + fgets(output, sizeof(output), sysFile); + pclose(sysFile); + sscanf(output,"%d",&res); +#ifdef VERY_VERBOSE + printf("gpi07 returned %d\n",res); +#endif + } + } + printf("FPGA has picked up the program from flash\n\n"); + + return OK; +} + +int writeFPGAProgram(char* fpgasrc, size_t fsize, FILE* filefp){ +#ifdef VERY_VERBOSE + printf("\nWriting of FPGA Program\n"); + cprintf(BLUE,"address of fpgasrc:%p\n",(void *)fpgasrc); + cprintf(BLUE,"fsize:%d\n",fsize); + cprintf(BLUE,"pointer:%p\n",(void*)filefp); +#endif + + if(fwrite((void*)fpgasrc , sizeof(char) , fsize , filefp )!= fsize){ + cprintf(RED,"Could not write FPGA source to flash\n"); + return FAIL; + } +#ifdef VERY_VERBOSE + cprintf(BLUE, "program written to flash\n"); +#endif + return OK; +} + + + + +/* aquisition */ + +int startStateMachine(){ + printf("*******Starting State Machine*******\n"); + + cleanFifos(); + + //start state machine + bus_w(CONTROL_REG, bus_r(CONTROL_REG) | CONTROL_START_ACQ_MSK); + bus_w(CONTROL_REG, bus_r(CONTROL_REG) & ~CONTROL_START_ACQ_MSK); + + printf("Status Register: %08x\n",bus_r(STATUS_REG)); + return OK; +} + + +int stopStateMachine(){ + cprintf(BG_RED,"*******Stopping State Machine*******\n"); + + //stop state machine + bus_w(CONTROL_REG, bus_r(CONTROL_REG) | CONTROL_STOP_ACQ_MSK); + usleep(100); + bus_w(CONTROL_REG, bus_r(CONTROL_REG) & ~CONTROL_STOP_ACQ_MSK); + + printf("Status Register: %08x\n",bus_r(STATUS_REG)); + return OK; +} + + + + + +enum runStatus getRunStatus(){ +#ifdef VERBOSE + printf("Getting status\n"); +#endif + + enum runStatus s; + u_int32_t retval = bus_r(STATUS_REG); + printf("Status Register: %08x\n",retval); + + //running + if(((retval & RUN_BUSY_MSK) >> RUN_BUSY_OFST)) { + if ((retval & WAITING_FOR_TRIGGER_MSK) >> WAITING_FOR_TRIGGER_OFST) { + printf("-----------------------------------WAITING-----------------------------------\n"); + s=WAITING; + } + else{ + printf("-----------------------------------RUNNING-----------------------------------\n"); + s=RUNNING; + } + } + + //not running + else { + if ((retval & STOPPED_MSK) >> STOPPED_OFST) { + printf("-----------------------------------STOPPED--------------------------\n"); + s=STOPPED; + } else if ((retval & RUNMACHINE_BUSY_MSK) >> RUNMACHINE_BUSY_OFST) { + printf("-----------------------------------READ MACHINE BUSY--------------------------\n"); + s=TRANSMITTING; + } else if (!retval) { + printf("-----------------------------------IDLE--------------------------------------\n"); + s=IDLE; + } else { + printf("-----------------------------------Unknown status %08x--------------------------------------\n", retval); + s=ERROR; + } + } + + return s; +} + + + +void readFrame(int *ret, char *mess){ + + // wait for status to be done + while(runBusy()){ + usleep(500); + } + + // frames left to give status + int64_t retval = getTimeLeft(FRAME_NUMBER) + 1; + if ( retval > 0) { + *ret = (int)FAIL; + sprintf(mess,"no data and run stopped: %lld frames left\n",retval); + cprintf(RED,"%s\n",mess); + } else { + *ret = (int)FINISHED; + sprintf(mess,"acquisition successfully finished\n"); + printf("%s",mess); + } +} + + + +u_int32_t runBusy(void) { + u_int32_t s = ((bus_r(STATUS_REG) & RUN_BUSY_MSK) >> RUN_BUSY_OFST); +#ifdef VERBOSE + printf("Status Register: %08x\n", s); +#endif + return s; +} + + + + + + + + + + +/* common */ + + + + +int copyModule(sls_detector_module *destMod, sls_detector_module *srcMod){ + + int ichip, idac, ichan, iadc; + int ret=OK; + +#ifdef VERBOSE + printf("Copying module %x to module %x\n",srcMod,destMod); +#endif + + if (srcMod->module>=0) { +#ifdef VERBOSE + printf("Copying module number %d to module number %d\n",srcMod->module,destMod->module); +#endif + destMod->module=srcMod->module; + } + if (srcMod->serialnumber>=0){ + + destMod->serialnumber=srcMod->serialnumber; + } + if ((srcMod->nchip)>(destMod->nchip)) { + printf("Number of chip of source is larger than number of chips of destination\n"); + return FAIL; + } + if ((srcMod->nchan)>(destMod->nchan)) { + printf("Number of channels of source is larger than number of channels of destination\n"); + return FAIL; + } + if ((srcMod->ndac)>(destMod->ndac)) { + printf("Number of dacs of source is larger than number of dacs of destination\n"); + return FAIL; + } + if ((srcMod->nadc)>(destMod->nadc)) { + printf("Number of dacs of source is larger than number of dacs of destination\n"); + return FAIL; + } + +#ifdef VERBOSE + printf("DACs: src %d, dest %d\n",srcMod->ndac,destMod->ndac); + printf("ADCs: src %d, dest %d\n",srcMod->nadc,destMod->nadc); + printf("Chips: src %d, dest %d\n",srcMod->nchip,destMod->nchip); + printf("Chans: src %d, dest %d\n",srcMod->nchan,destMod->nchan); + +#endif + destMod->ndac=srcMod->ndac; + destMod->nadc=srcMod->nadc; + destMod->nchip=srcMod->nchip; + destMod->nchan=srcMod->nchan; + if (srcMod->reg>=0) + destMod->reg=srcMod->reg; +#ifdef VERBOSE + printf("Copying register %x (%x)\n",destMod->reg,srcMod->reg ); +#endif + if (srcMod->gain>=0) + destMod->gain=srcMod->gain; + if (srcMod->offset>=0) + destMod->offset=srcMod->offset; + + for (ichip=0; ichip<(srcMod->nchip); ichip++) { + if (*((srcMod->chipregs)+ichip)>=0) + *((destMod->chipregs)+ichip)=*((srcMod->chipregs)+ichip); + } + for (ichan=0; ichan<(srcMod->nchan); ichan++) { + if (*((srcMod->chanregs)+ichan)>=0) + *((destMod->chanregs)+ichan)=*((srcMod->chanregs)+ichan); + } + for (idac=0; idac<(srcMod->ndac); idac++) { + if (*((srcMod->dacs)+idac)>=0) + *((destMod->dacs)+idac)=*((srcMod->dacs)+idac); + } + for (iadc=0; iadc<(srcMod->nadc); iadc++) { + if (*((srcMod->adcs)+iadc)>=0) + *((destMod->adcs)+iadc)=*((srcMod->adcs)+iadc); + } + return ret; +} + + +int calculateDataBytes(){ + return DATA_BYTES; +} + +int getTotalNumberOfChannels(){return ((int)getNumberOfChannelsPerModule() * (int)getTotalNumberOfModules);} +int getTotalNumberOfChips(){return ((int)getNumberOfChipsPerModule * (int)getTotalNumberOfModules);} +int getTotalNumberOfModules(){return NMOD;} +int getNumberOfChannelsPerModule(){return ((int)getNumberOfChannelsPerChip() * (int)getTotalNumberOfChips());} +int getNumberOfChipsPerModule(){return NCHIP;} +int getNumberOfDACsPerModule(){return NDAC;} +int getNumberOfADCsPerModule(){return NADC;} +int getNumberOfChannelsPerChip(){return NCHAN;} + + + +/* sync */ + +enum masterFlags setMaster(enum masterFlags arg){ + return NO_MASTER; +} + +enum synchronizationMode setSynchronization(enum synchronizationMode arg){ + return NO_SYNCHRONIZATION; +} + + + + + + +//#endif diff --git a/slsDetectorSoftware/jungfrauDetectorServer/slsDetectorFunctionList.h b/slsDetectorSoftware/jungfrauDetectorServer/slsDetectorFunctionList.h new file mode 120000 index 000000000..345b8c029 --- /dev/null +++ b/slsDetectorSoftware/jungfrauDetectorServer/slsDetectorFunctionList.h @@ -0,0 +1 @@ +../slsDetectorServer/slsDetectorFunctionList.h \ No newline at end of file diff --git a/slsDetectorSoftware/jungfrauDetectorServer/slsDetectorServer.c b/slsDetectorSoftware/jungfrauDetectorServer/slsDetectorServer.c new file mode 120000 index 000000000..a7eb59acb --- /dev/null +++ b/slsDetectorSoftware/jungfrauDetectorServer/slsDetectorServer.c @@ -0,0 +1 @@ +../slsDetectorServer/slsDetectorServer.c \ No newline at end of file diff --git a/slsDetectorSoftware/jungfrauDetectorServer/slsDetectorServer_defs.h b/slsDetectorSoftware/jungfrauDetectorServer/slsDetectorServer_defs.h new file mode 100644 index 000000000..afb4b2ba1 --- /dev/null +++ b/slsDetectorSoftware/jungfrauDetectorServer/slsDetectorServer_defs.h @@ -0,0 +1,252 @@ +#ifndef SLSDETECTORSERVER_DEFS_H +#define SLSDETECTORSERVER_DEFS_H + +#include "sls_detector_defs.h" //default dynamicgain in settings +#include "RegisterDefs.h" +#include + + + +#define GOODBYE (-200) +#define CTRL_SRVR_INIT_TIME_US (300 * 1000) +//#define REQUIRED_FIRMWARE_VERSION 16 + + +/* Struct Definitions */ +typedef struct ip_header_struct { + uint16_t ip_len; + uint8_t ip_tos; + uint8_t ip_ihl:4 ,ip_ver:4; + uint16_t ip_offset:13,ip_flag:3; + uint16_t ip_ident; + uint16_t ip_chksum; + uint8_t ip_protocol; + uint8_t ip_ttl; + uint32_t ip_sourceip; + uint32_t ip_destip; +} ip_header; + +/* Enums */ +enum CLK_SPEED_INDEX {FULL_SPEED, HALF_SPEED, QUARTER_SPEED}; +enum ADCINDEX {TEMP_FPGA, TEMP_ADC}; +enum DACINDEX {VB_COMP, VDD_PROT, VIN_COM, VREF_PRECH, VB_PIXBUF, VB_DS, VREF_DS, VREF_COMP }; +#define DEFAULT_DAC_VALS { 1220, /* VB_COMP */ \ + 3000, /* VDD_PROT */ \ + 1053, /* VIN_COM */ \ + 1450, /* VREF_PRECH */ \ + 750, /* VB_PIXBUF */ \ + 1000, /* VB_DS */ \ + 480, /* VREF_DS */ \ + 420 /* VREF_COMP */ \ + }; + +#define NUM_SETTINGS 6 +#define DEFAULT_SETT_INDX {DYNAMICGAIN, DYNAMICHG0, FIXGAIN1, FIXGAIN2, FORCESWITCHG1, FORCESWITCHG2}; +#define DEFAULT_SETT_VALS { 0x0f00, /* DYNAMICGAIN */ \ + 0x0f01, /* DYNAMICHG0 */ \ + 0x0f02, /* FIXGAIN1 */ \ + 0x0f06, /* FIXGAIN2 */ \ + 0x1f00, /* FORCESWITCHG1 */ \ + 0x3f00 /* FORCESWITCHG2 */ \ + }; +#define DEFAULT_SETT_NAMES { "Dynamic Gain", /* DYNAMICGAIN */ \ + "Dynamic High Gain 0", /* DYNAMICHG0 */ \ + "Fix Gain 1", /* FIXGAIN1 */ \ + "Fix Gain 2", /* FIXGAIN2 */ \ + "Force Switch Gain 1", /* FORCESWITCHG1*/ \ + "Force Switch Gain 2" /* FORCESWITCHG2*/ \ + }; + + + +/* Hardware Definitions */ +#define NMAXMOD (1) +#define NMOD (1) +#define NCHAN (256 * 256) +#define NCHIP (8) +#define NADC (0) +#define NDAC (8) +#define NDAC_OLDBOARD (16) +#define DYNAMIC_RANGE (16) +#define NUM_BITS_PER_PIXEL (DYNAMIC_RANGE / 8) +#define DATA_BYTES (NCHIP * NCHAN * NUM_BITS_PER_PIXEL) +#define IP_PACKETSIZE (0x2052) +#define CLK_RUN (40) /* MHz */ +#define CLK_SYNC (20) /* MHz */ + + +/** Default Parameters */ +#define DEFAULT_NUM_FRAMES (100*1000*1000) +#define DEFAULT_NUM_CYCLES (1) +#define DEFAULT_EXPTIME (10*1000) //ns +#define DEFAULT_PERIOD (2*1000*1000) //ns +#define DEFAULT_DELAY (0) +#define DEFAULT_HIGH_VOLTAGE (0) +#define DEFAULT_TIMING_MODE (AUTO_TIMING) +#define DEFAULT_SETTINGS (DYNAMICGAIN) +#define DEFAULT_TX_UDP_PORT (0x7e9a) + +/* Defines in the Firmware */ +#define FIX_PATT_VAL (0xACDC2014) +#define ADC_PORT_INVERT_VAL (0x453b2a9c) + + +#define SAMPLE_ADC_HALF_SPEED (SAMPLE_DECMT_FACTOR_2_VAL + SAMPLE_DGTL_SAMPLE_0_VAL + SAMPLE_ADC_DECMT_FACTOR_0_VAL + SAMPLE_ADC_SAMPLE_0_VAL) /* 0x1000 */ +#define SAMPLE_ADC_QUARTER_SPEED (SAMPLE_DECMT_FACTOR_4_VAL + SAMPLE_DGTL_SAMPLE_8_VAL + SAMPLE_ADC_DECMT_FACTOR_1_VAL + SAMPLE_ADC_SAMPLE_0_VAL) /* 0x2810 */ +#define CONFIG_HALF_SPEED (CONFIG_TDMA_TIMESLOT_0_VAL + CONFIG_TDMA_DISABLE_VAL + CONFIG_HALF_SPEED_20MHZ_VAL + CONFIG_MODE_1_X_10GBE_VAL) +#define CONFIG_QUARTER_SPEED (CONFIG_TDMA_TIMESLOT_0_VAL + CONFIG_TDMA_DISABLE_VAL + CONFIG_QUARTER_SPEED_10MHZ_VAL + CONFIG_MODE_1_X_10GBE_VAL) +#define ADC_OFST_HALF_SPEED_VAL (0x20) //adc pipeline +#define ADC_OFST_QUARTER_SPEED_VAL (0x0f) +#define ADC_PHASE_HALF_SPEED (0x41) +#define ADC_PHASE_QUARTER_SPEED (0x19) + +/* Maybe not required for jungfrau */ +#define NTRIMBITS (6) +#define NCOUNTBITS (24) +#define NCHIPS_PER_ADC (2) +#define TRIM_DR (((int)pow(2,NTRIMBITS))-1) +#define COUNT_DR (((int)pow(2,NCOUNTBITS))-1) +#define ALLMOD (0xffff) +#define ALLFIFO (0xffff) + +/* MSB & LSB DEFINES */ +#define MSB_OF_64_BIT_REG_OFST (32) +#define LSB_OF_64_BIT_REG_OFST (0) +#define BIT_32_MSK (0xFFFFFFFF) + +/* LTC2620 DAC DEFINES */ +#define LTC2620_DAC_CMD_OFST (20) +#define LTC2620_DAC_CMD_MSK (0x0000000F << LTC2620_DAC_CMD_OFST) +#define LTC2620_DAC_ADDR_OFST (16) +#define LTC2620_DAC_ADDR_MSK (0x0000000F << LTC2620_DAC_ADDR_OFST) +#define LTC2620_DAC_DATA_OFST (4) +#define LTC2620_DAC_DATA_MSK (0x00000FFF << LTC2620_DAC_DATA_OFST) + +#define LTC2620_DAC_CMD_WRITE (0x00000000 << LTC2620_DAC_CMD_OFST) +#define LTC2620_DAC_CMD_SET (0x00000003 << LTC2620_DAC_CMD_OFST) +#define LTC2620_DAC_CMD_POWER_DOWN (0x00000004 << LTC2620_DAC_CMD_OFST) +#define LTC2620_DAC_NUMBITS (24) + + +/* MAX1932 HV DEFINES */ +#define MAX1932_HV_NUMBITS (8) +#define MAX1932_HV_DATA_OFST (0) +#define MAX1932_HV_DATA_MSK (0x000000FF << MAX1932_HV_DATA_OFST) + +/* AD9257 ADC DEFINES */ +#define AD9257_ADC_NUMBITS (24) + +#define AD9257_DEV_IND_2_REG (0x04) +#define AD9257_CHAN_H_OFST (0) +#define AD9257_CHAN_H_MSK (0x00000001 << AD9257_CHAN_H_OFST) +#define AD9257_CHAN_G_OFST (1) +#define AD9257_CHAN_G_MSK (0x00000001 << AD9257_CHAN_G_OFST) +#define AD9257_CHAN_F_OFST (2) +#define AD9257_CHAN_F_MSK (0x00000001 << AD9257_CHAN_F_OFST) +#define AD9257_CHAN_E_OFST (3) +#define AD9257_CHAN_E_MSK (0x00000001 << AD9257_CHAN_E_OFST) + +#define AD9257_DEV_IND_1_REG (0x05) +#define AD9257_CHAN_D_OFST (0) +#define AD9257_CHAN_D_MSK (0x00000001 << AD9257_CHAN_D_OFST) +#define AD9257_CHAN_C_OFST (1) +#define AD9257_CHAN_C_MSK (0x00000001 << AD9257_CHAN_C_OFST) +#define AD9257_CHAN_B_OFST (2) +#define AD9257_CHAN_B_MSK (0x00000001 << AD9257_CHAN_B_OFST) +#define AD9257_CHAN_A_OFST (3) +#define AD9257_CHAN_A_MSK (0x00000001 << AD9257_CHAN_A_OFST) +#define AD9257_CLK_CH_DCO_OFST (4) +#define AD9257_CLK_CH_DCO_MSK (0x00000001 << AD9257_CLK_CH_DCO_OFST) +#define AD9257_CLK_CH_IFCO_OFST (5) +#define AD9257_CLK_CH_IFCO_MSK (0x00000001 << AD9257_CLK_CH_IFCO_OFST) + +#define AD9257_POWER_MODE_REG (0x08) +#define AD9257_POWER_INTERNAL_OFST (0) +#define AD9257_POWER_INTERNAL_MSK (0x00000003 << AD9257_POWER_INTERNAL_OFST) +#define AD9257_INT_RESET_VAL (0x3) +#define AD9257_INT_CHIP_RUN_VAL (0x0) +#define AD9257_POWER_EXTERNAL_OFST (5) +#define AD9257_POWER_EXTERNAL_MSK (0x00000001 << AD9257_POWER_EXTERNAL_OFST) +#define AD9257_EXT_FULL_POWER_VAL (0x0) +#define AD9257_EXT_STANDBY_VAL (0x1) + +#define AD9257_OUT_MODE_REG (0x14) +#define AD9257_OUT_FORMAT_OFST (0) +#define AD9257_OUT_FORMAT_MSK (0x00000001 << AD9257_OUT_FORMAT_OFST) +#define AD9257_OUT_BINARY_OFST_VAL (0) +#define AD9257_OUT_TWOS_COMPL_VAL (1) +#define AD9257_OUT_LVDS_OPT_OFST (6) +#define AD9257_OUT_LVDS_OPT_MSK (0x00000001 << AD9257_OUT_LVDS_OPT_OFST) +#define AD9257_OUT_LVDS_ANSI_VAL (0) +#define AD9257_OUT_LVDS_IEEE_VAL (1) + +#define AD9257_OUT_PHASE_REG (0x16) +#define AD9257_OUT_CLK_OFST (0) +#define AD9257_OUT_CLK_MSK (0x0000000F << AD9257_OUT_CLK_OFST) +#define AD9257_OUT_CLK_60_VAL (0x1) +#define AD9257_IN_CLK_OFST (4) +#define AD9257_IN_CLK_MSK (0x00000007 << AD9257_IN_CLK_OFST) +#define AD9257_IN_CLK_0_VAL (0x0) + +#define AD9257_VREF_REG (0x18) +#define AD9257_VREF_OFST (0) +#define AD9257_VREF_MSK (0x00000003 << AD9257_VREF_OFST) +#define AD9257_VREF_1_33_VAL (0x2) + +#define AD9257_TEST_MODE_REG (0x0D) +#define AD9257_OUT_TEST_OFST (0) +#define AD9257_OUT_TEST_MSK (0x0000000F << AD9257_OUT_TEST_OFST) +#define AD9257_NONE_VAL (0x0) +#define AD9257_MIXED_BIT_FREQ_VAL (0xC) +#define AD9257_TEST_RESET_SHORT_GEN (4) +#define AD9257_TEST_RESET_LONG_GEN (5) +#define AD9257_USER_IN_MODE_OFST (6) +#define AD9257_USER_IN_MODE_MSK (0x00000003 << AD9257_USER_IN_MODE_OFST) + +/** PLL Reconfiguration Registers */ +//https://www.altera.com/documentation/mcn1424769382940.html +#define PLL_MODE_REG (0x00) +#define PLL_STATUS_REG (0x01) +#define PLL_START_REG (0x02) +#define PLL_N_COUNTER_REG (0x03) +#define PLL_M_COUNTER_REG (0x04) +#define PLL_C_COUNTER_REG (0x05) +#define PLL_PHASE_SHIFT_REG (0x06) + +#define PLL_SHIFT_NUM_SHIFTS_OFST (0) +#define PLL_SHIFT_NUM_SHIFTS_MSK (0x0000FFFF << PLL_SHIFT_NUM_SHIFTS_OFST) + +#define PLL_SHIFT_CNT_SELECT_OFST (16) +#define PLL_SHIFT_CNT_SELECT_MSK (0x0000001F << PLL_SHIFT_CNT_SELECT_OFST) +#define PLL_SHIFT_CNT_SLCT_C0_VAL ((0x0 << PLL_SHIFT_CNT_SELECT_OFST) & PLL_SHIFT_CNT_SELECT_MSK) +#define PLL_SHIFT_CNT_SLCT_C1_VAL ((0x1 << PLL_SHIFT_CNT_SELECT_OFST) & PLL_SHIFT_CNT_SELECT_MSK) +#define PLL_SHIFT_CNT_SLCT_C2_VAL ((0x2 << PLL_SHIFT_CNT_SELECT_OFST) & PLL_SHIFT_CNT_SELECT_MSK) +#define PLL_SHIFT_CNT_SLCT_C3_VAL ((0x3 << PLL_SHIFT_CNT_SELECT_OFST) & PLL_SHIFT_CNT_SELECT_MSK) +#define PLL_SHIFT_CNT_SLCT_C4_VAL ((0x4 << PLL_SHIFT_CNT_SELECT_OFST) & PLL_SHIFT_CNT_SELECT_MSK) +#define PLL_SHIFT_CNT_SLCT_C5_VAL ((0x5 << PLL_SHIFT_CNT_SELECT_OFST) & PLL_SHIFT_CNT_SELECT_MSK) +#define PLL_SHIFT_CNT_SLCT_C6_VAL ((0x6 << PLL_SHIFT_CNT_SELECT_OFST) & PLL_SHIFT_CNT_SELECT_MSK) +#define PLL_SHIFT_CNT_SLCT_C7_VAL ((0x7 << PLL_SHIFT_CNT_SELECT_OFST) & PLL_SHIFT_CNT_SELECT_MSK) +#define PLL_SHIFT_CNT_SLCT_C8_VAL ((0x8 << PLL_SHIFT_CNT_SELECT_OFST) & PLL_SHIFT_CNT_SELECT_MSK) +#define PLL_SHIFT_CNT_SLCT_C9_VAL ((0x9 << PLL_SHIFT_CNT_SELECT_OFST) & PLL_SHIFT_CNT_SELECT_MSK) +#define PLL_SHIFT_CNT_SLCT_C10_VAL ((0x10 << PLL_SHIFT_CNT_SELECT_OFST) & PLL_SHIFT_CNT_SELECT_MSK) +#define PLL_SHIFT_CNT_SLCT_C11_VAL ((0x11 << PLL_SHIFT_CNT_SELECT_OFST) & PLL_SHIFT_CNT_SELECT_MSK) +#define PLL_SHIFT_CNT_SLCT_C12_VAL ((0x12 << PLL_SHIFT_CNT_SELECT_OFST) & PLL_SHIFT_CNT_SELECT_MSK) +#define PLL_SHIFT_CNT_SLCT_C13_VAL ((0x13 << PLL_SHIFT_CNT_SELECT_OFST) & PLL_SHIFT_CNT_SELECT_MSK) +#define PLL_SHIFT_CNT_SLCT_C14_VAL ((0x14 << PLL_SHIFT_CNT_SELECT_OFST) & PLL_SHIFT_CNT_SELECT_MSK) +#define PLL_SHIFT_CNT_SLCT_C15_VAL ((0x15 << PLL_SHIFT_CNT_SELECT_OFST) & PLL_SHIFT_CNT_SELECT_MSK) +#define PLL_SHIFT_CNT_SLCT_C16_VAL ((0x16 << PLL_SHIFT_CNT_SELECT_OFST) & PLL_SHIFT_CNT_SELECT_MSK) +#define PLL_SHIFT_CNT_SLCT_C17_VAL ((0x17 << PLL_SHIFT_CNT_SELECT_OFST) & PLL_SHIFT_CNT_SELECT_MSK) + +#define PLL_SHIFT_UP_DOWN_OFST (21) +#define PLL_SHIFT_UP_DOWN_MSK (0x00000001 << PLL_SHIFT_UP_DOWN_OFST) +#define PLL_SHIFT_UP_DOWN_NEG_VAL ((0x0 << PLL_SHIFT_UP_DOWN_OFST) & PLL_SHIFT_UP_DOWN_MSK) +#define PLL_SHIFT_UP_DOWN_POS_VAL ((0x1 << PLL_SHIFT_UP_DOWN_OFST) & PLL_SHIFT_UP_DOWN_MSK) + +#define PLL_K_COUNTER_REG (0x07) +#define PLL_BANDWIDTH_REG (0x08) +#define PLL_CHARGEPUMP_REG (0x09) +#define PLL_VCO_DIV_REG (0x1c) +#define PLL_MIF_REG (0x1f) + + +#endif /* SLSDETECTORSERVER_DEFS_H */ diff --git a/slsDetectorSoftware/jungfrauDetectorServer/slsDetectorServer_funcs.c b/slsDetectorSoftware/jungfrauDetectorServer/slsDetectorServer_funcs.c new file mode 120000 index 000000000..a7532ccd4 --- /dev/null +++ b/slsDetectorSoftware/jungfrauDetectorServer/slsDetectorServer_funcs.c @@ -0,0 +1 @@ +../slsDetectorServer/slsDetectorServer_funcs.c \ No newline at end of file diff --git a/slsDetectorSoftware/jungfrauDetectorServer/slsDetectorServer_funcs.h b/slsDetectorSoftware/jungfrauDetectorServer/slsDetectorServer_funcs.h new file mode 120000 index 000000000..7569daf47 --- /dev/null +++ b/slsDetectorSoftware/jungfrauDetectorServer/slsDetectorServer_funcs.h @@ -0,0 +1 @@ +../slsDetectorServer/slsDetectorServer_funcs.h \ No newline at end of file diff --git a/slsDetectorSoftware/jungfrauDetectorServer/stop_server.c b/slsDetectorSoftware/jungfrauDetectorServer/stop_server.c deleted file mode 100755 index e3c8ff7e1..000000000 --- a/slsDetectorSoftware/jungfrauDetectorServer/stop_server.c +++ /dev/null @@ -1,46 +0,0 @@ -/* A simple server in the internet domain using TCP - The port number is passed as an argument */ - - -#include "sls_detector_defs.h" - - -#include "communication_funcs.h" -#include "firmware_funcs.h" - - -int sockfd; - -int main(int argc, char *argv[]) -{ - int portno; - int retval=0; - - portno = DEFAULT_PORTNO; - - - bindSocket(portno); - if (getServerError()) - return -1; - - - - /* waits for connection */ - while(retval!=GOODBYE) { -#ifdef VERBOSE - printf("\n"); -#endif -#ifdef VERY_VERBOSE - printf("Stop server: waiting for client call\n"); -#endif - acceptConnection(); - retval=stopStateMachine(); - closeConnection(); - } - - exitServer(); - printf("Goodbye!\n"); - - return 0; -} - diff --git a/slsDetectorSoftware/multiSlsDetector/multiSlsDetector.cpp b/slsDetectorSoftware/multiSlsDetector/multiSlsDetector.cpp index 865310c6e..8db4925bd 100644 --- a/slsDetectorSoftware/multiSlsDetector/multiSlsDetector.cpp +++ b/slsDetectorSoftware/multiSlsDetector/multiSlsDetector.cpp @@ -17,14 +17,13 @@ ID: $Id$ #include "postProcessingFuncs.h" #include "usersFunctions.h" #include "ThreadPool.h" +#include "ZmqSocket.h" #include #include #include #include #include -#include -#include //to scan json header in zmq stream using namespace std; @@ -140,6 +139,8 @@ multiSlsDetector::multiSlsDetector(int id) : slsDetectorUtils(), shmId(-1) thisMultiDetector->fileIndex=0; /** set frames per file to default to 1*/ thisMultiDetector->framesPerFile=1; + /** set fileFormat to default to ascii*/ + thisMultiDetector->fileFormatType=ASCII; /** set progress Index to default to 0*/ thisMultiDetector->progressIndex=0; @@ -245,6 +246,7 @@ multiSlsDetector::multiSlsDetector(int id) : slsDetectorUtils(), shmId(-1) fileName=thisMultiDetector->fileName; fileIndex=&thisMultiDetector->fileIndex; framesPerFile=&thisMultiDetector->framesPerFile; + fileFormatType=&thisMultiDetector->fileFormatType; for (int i=0; inumberOfDetectors; i++) { @@ -269,11 +271,8 @@ multiSlsDetector::multiSlsDetector(int id) : slsDetectorUtils(), shmId(-1) getNMods(); getMaxMods(); dataSocketsStarted = false; - for(int i=0;idestroy_threadpool(); - threadpool=0; } if(thisMultiDetector->numberOfDetectors < 1){ cout << "No detectors attached to create threadpool" << endl; @@ -317,6 +320,7 @@ int multiSlsDetector::createThreadPool(){ void multiSlsDetector::destroyThreadPool(){ if(threadpool){ threadpool->destroy_threadpool(); + delete threadpool; threadpool=0; #ifdef VERBOSE cout<<"Destroyed Threadpool "<< threadpool << endl; @@ -773,7 +777,21 @@ int multiSlsDetector::addSlsDetector(detectorType t, int pos) { +void multiSlsDetector::getNumberOfDetectors(int& nx, int& ny) { + nx = 0; ny = 0; + int offsetx = -1, offsety = -1; + for (int i = 0; i < thisMultiDetector->numberOfDetectors; ++i) { + if (thisMultiDetector->offsetX[i] > offsetx) { + nx++; + offsetx = thisMultiDetector->offsetX[i]; + } + if (thisMultiDetector->offsetY[i] > offsety) { + ny++; + offsety = thisMultiDetector->offsetY[i]; + } + } +} @@ -1141,44 +1159,57 @@ int multiSlsDetector::getThresholdEnergy(int pos) { int multiSlsDetector::setThresholdEnergy(int e_eV, int pos, detectorSettings isettings) { - int i, posmin, posmax; - int ret1=-100, ret; + int posmin, posmax; + int ret=-100; + if (pos<0) { + posmin=0; + posmax=thisMultiDetector->numberOfDetectors; + } else { + posmin=pos; + posmax=pos+1; + } - if (pos<0) { - posmin=0; - posmax=thisMultiDetector->numberOfDetectors; - } else { - posmin=pos; - posmax=pos+1; - } - - for (i=posmin; isetThresholdEnergy(e_eV,-1,isettings); - if(detectors[i]->getErrorMask()) - setErrorMask(getErrorMask()|(1<(ret1+200)) - ret1=FAIL; - -#ifdef VERBOSE - cout << "return value " << ret1 << endl; -#endif - } - - } - thisMultiDetector->currentThresholdEV=ret1; - return ret1; + if(!threadpool){ + cout << "Error in creating threadpool. Exiting" << endl; + return -1; + }else{ + //return storage values + int* iret[posmax-posmin]; + for(int idet=posmin; idet(&slsDetector::setThresholdEnergy, + detectors[idet],e_eV,-1,isettings,iret[idet])); + threadpool->add_task(task); + } + } + threadpool->startExecuting(); + threadpool->wait_for_tasks_to_complete(); + for(int idet=posmin; idet(*iret[idet]+200)) + ret=-1; + }else ret=-1; + if(detectors[idet]->getErrorMask()) + setErrorMask(getErrorMask()|(1<currentThresholdEV=ret; + return ret; } + + + slsDetectorDefs::detectorSettings multiSlsDetector::getSettings(int pos) { - int i, posmin, posmax; + int posmin, posmax; int ret=-100; if (pos<0) { @@ -1212,10 +1243,10 @@ slsDetectorDefs::detectorSettings multiSlsDetector::getSettings(int pos) { ret=*iret[idet]; else if (ret!=*iret[idet]) ret=GET_SETTINGS; - delete iret[idet]; }else ret=GET_SETTINGS; if(detectors[idet]->getErrorMask()) setErrorMask(getErrorMask()|(1<getErrorMask()) setErrorMask(getErrorMask()|(1<getDataBytes(); - if (retdet) { - nodata=0; + if (retdet) {; #ifdef VERBOSE cout << "Detector " << id << " returned " << n << " bytes " << endl; #endif @@ -1650,10 +1680,10 @@ int multiSlsDetector::startAndReadAllNoWait(){ if(iret[idet] != NULL){ if(*iret[idet] != OK) ret = FAIL; - delete iret[idet]; }else ret = FAIL; if(detectors[idet]->getErrorMask()) setErrorMask(getErrorMask()|(1<numberOfDetectors; - int nroi[ndet]; int maxroi = ndet*MAX_ROIS; ROI temproi; ROI roiLimits[maxroi]; @@ -2110,7 +2139,6 @@ slsDetectorDefs::ROI* multiSlsDetector::getROI(int &n){ if(detectors[i]->getErrorMask()) setErrorMask(getErrorMask()|(1<flatFieldFile); @@ -2605,7 +2633,7 @@ int multiSlsDetector::setRateCorrection(double t){ ret=detectors[idet]->setRateCorrection(t); if(detectors[idet]->getErrorMask()) setErrorMask(getErrorMask()|(1<numberOfDetectors; - if(!threadpool){ cout << "Error in creating threadpool. Exiting" << endl; return getNetworkParameter(p); @@ -4002,10 +4028,10 @@ int multiSlsDetector::executeTrimming(trimMode mode, int par1, int par2, int imo ret=*iret[idet]; else if (ret!=*iret[idet]) ret=-1; - delete iret[idet]; }else ret=-1; if(detectors[idet]->getErrorMask()) setErrorMask(getErrorMask()|(1<getErrorMask()) setErrorMask(getErrorMask()|(1<getErrorMask()) setErrorMask(getErrorMask()|(1<getErrorMask()) setErrorMask(getErrorMask()|(1<executeLine(1,args,GET_ACTION) << std::endl; - + iline++; // single detector configuration for (int i=0; inumberOfDetectors; i++) { // sprintf(ext,".det%d",i); @@ -4546,6 +4570,7 @@ int multiSlsDetector::writeConfigurationFile(string const fname){ cout << iv << " " << names[iv] << endl; strcpy(args[0],names[iv].c_str()); outfile << names[iv] << " " << cmd->executeLine(1,args,GET_ACTION) << std::endl; + iline++; } @@ -4557,7 +4582,7 @@ int multiSlsDetector::writeConfigurationFile(string const fname){ return FAIL; } #ifdef VERBOSE - std::cout<< "wrote " <numberOfDetectors; idet++) { + if (detectors[idet]) { + ret1=(int)detectors[idet]->setFileFormat(f); + if(detectors[idet]->getErrorMask()) + setErrorMask(getErrorMask()|(1<getErrorMask()) setErrorMask(getErrorMask()|(1<getErrorMask()) setErrorMask(getErrorMask()|(1<getReceiver()); - cout<<"rx_hostname:"<h_addr)); + uint32_t portnum = DEFAULT_ZMQ_PORTNO + + (i/numSocketsPerDetector)*numSocketsPerDetector + (i%numSocketsPerDetector); + zmqSocket[i] = new ZmqSocket(detectors[i/numSocketsPerDetector]->getReceiver(), portnum); + if (zmqSocket[i]->IsError()) { + cprintf(RED, "Error: Could not create Zmq socket on port %d\n", portnum); + createReceivingDataSockets(true); + return FAIL; } - //add port - sprintf(dataSocketServerDetails[i],"%s:%d",dataSocketServerDetails[i],DEFAULT_ZMQ_PORTNO + - (i/numSocketsPerDetector)*numSocketsPerDetector + (i%numSocketsPerDetector));//using this instead of i in the offchance, detid doesnt start at 0 (shmget error) - - //create context - context[i] = zmq_ctx_new(); - //create socket - zmqsocket[i] = zmq_socket(context[i], ZMQ_PULL); - //connect socket - zmq_connect(zmqsocket[i], dataSocketServerDetails[i]); - //int hwmval = 10; - //zmq_setsockopt(zmqsocket[i],ZMQ_RCVHWM,&hwmval,sizeof(hwmval)); //set receive HIGH WATER MARK (8-9ms slower//should not drop last packets) - cout << "ZMQ Client[" << i << "] from " << dataSocketServerDetails[i] << endl; + printf("Zmq Client[%d] at %s\n",i, zmqSocket[i]->GetZmqServerAddress()); } dataSocketsStarted = true; @@ -5164,91 +5182,24 @@ int multiSlsDetector::createReceivingDataSockets(const bool destroy){ -int multiSlsDetector::getData(const int isocket, const bool masking, int* image, const int size, int &acqIndex, int &frameIndex, int &subframeIndex, string &filename){ +int multiSlsDetector::getData(const int isocket, const bool masking, int* image, const int size, + uint64_t &acqIndex, uint64_t &frameIndex, uint32_t &subframeIndex, string &filename) { - zmq_msg_t message; - - //scan header------------------------------------------------------------------- - zmq_msg_init (&message); - int len = zmq_msg_recv(&message, zmqsocket[isocket], 0); - if (len == -1) { - cprintf(BG_RED,"Could not read header for socket %d\n",isocket); - zmq_msg_close(&message); - cprintf(RED, "%d message null\n",isocket); + //fail is on parse error or end of acquisition + if (!zmqSocket[isocket]->ReceiveHeader(isocket, acqIndex, frameIndex, subframeIndex, filename)) return FAIL; - } + //receiving incorrect size is replaced by 0xFF + zmqSocket[isocket]->ReceiveData(isocket, image, size); - // error if you print it - // cout << isocket << " header len:"<getDataBytes(); slsmaxchannels = detectors[0]->getMaxNumberOfChannels(); - bytesperchannel = slsdatabytes/slsmaxchannels; + bytesperchannel = (double)slsdatabytes/(double)slsmaxchannels; slsmaxX = detectors[0]->getTotalNumberOfChannels(X); slsmaxY = detectors[0]->getTotalNumberOfChannels(Y); } @@ -5355,17 +5307,17 @@ void multiSlsDetector::readFrameFromReceiver(){ if(bottom[isocket]){ //if((((isocket/numSocketsPerSLSDetector)+1)%2) == 0){ for(int i=0;igetErrorMask(); #ifdef VERYVERBOSE //append sls det error mask - sprintf(sNumber,"0x%x",slsMask); + sprintf(sNumber,"0x%lx",slsMask); retval.append("Error Mask " + string(sNumber)+string("\n")); #endif //get the error critical level @@ -5800,10 +5752,10 @@ uint64_t multiSlsDetector::setCTBWord(int addr,uint64_t word) { ret1=detectors[idet]->setCTBWord(addr, word); if(detectors[idet]->getErrorMask()) setErrorMask(getErrorMask()|(1<getErrorMask()) setErrorMask(getErrorMask()|(1<getErrorMask()) setErrorMask(getErrorMask()|(1<getErrorMask()) setErrorMask(getErrorMask()|(1<numberOfDetectors;}; + /** returns the number of detectors in each direction + \param nx number of detectors in x direction + \param ny number of detectors in y direction + */ + void getNumberOfDetectors(int& nx, int& ny); + int getMaxMods(); int getNMods(); int getMaxMod(dimension d); @@ -1149,6 +1158,13 @@ class multiSlsDetector : public slsDetectorUtils { */ string setFileName(string s=""); + /** + Sets up the file format + @param f file format + \returns file format + */ + fileFormat setFileFormat(fileFormat f=GET_FILE_FORMAT); + /** Sets up the file index @param i file index @@ -1166,6 +1182,11 @@ class multiSlsDetector : public slsDetectorUtils { */ string getFileName(){return setFileName();}; + /** + \returns file name + */ + fileFormat getFileFormat(){return setFileFormat();}; + /** \returns file index */ @@ -1408,14 +1429,23 @@ private: /** * Gets data from socket + * @param isocket socket index + * @param masking if masking required (jungfrau) + * @param image image buffer + * @param size size of image + * @param acqIndex address of acquisition index + * @param frameIndex address of frame index + * @param subframeIndex address of subframe index + * @param filename address of file name */ - int getData(const int isocket, const bool masking, int* image, const int size, int &acqIndex, int &frameIndex, int &subframeIndex, string &filename); + int getData(const int isocket, const bool masking, int* image, const int size, uint64_t &acqIndex, uint64_t &frameIndex, uint32_t &subframeIndex, string &filename); + /** Ensures if sockets created successfully */ bool dataSocketsStarted; - void *context[MAXDET]; - void *zmqsocket[MAXDET]; - char dataSocketServerDetails[MAXDET][100]; + + /** ZMQ Socket - Receiver to Client */ + ZmqSocket* zmqSocket[MAXDET]; protected: diff --git a/slsDetectorSoftware/slsDetector/gitInfoLib.h b/slsDetectorSoftware/slsDetector/gitInfoLib.h index a7e8cf690..08e58b43a 100644 --- a/slsDetectorSoftware/slsDetector/gitInfoLib.h +++ b/slsDetectorSoftware/slsDetector/gitInfoLib.h @@ -1,11 +1,11 @@ //#define SVNPATH "" #define SVNURLLIB "git@git.psi.ch:sls_detectors_software/sls_detector_software.git" //#define SVNREPPATH "" -#define SVNREPUUIDLIB "230d6b36e9852214f4ba5ae7c92647f35000b24d" -//#define SVNREV 0x1313 +#define SVNREPUUIDLIB "6d38c0622a2936f70345e7d53aaf1c9e2de4cbd6" +//#define SVNREV 0x1401 //#define SVNKIND "" //#define SVNSCHED "" #define SVNAUTHLIB "Dhanya_Maliakal" -#define SVNREVLIB 0x1313 -#define SVNDATELIB 0x20161130 +#define SVNREVLIB 0x1401 +#define SVNDATELIB 0x20170612 // diff --git a/slsDetectorSoftware/slsDetector/slsDetector.cpp b/slsDetectorSoftware/slsDetector/slsDetector.cpp index 7f6a26e20..09e8eb514 100644 --- a/slsDetectorSoftware/slsDetector/slsDetector.cpp +++ b/slsDetectorSoftware/slsDetector/slsDetector.cpp @@ -660,8 +660,8 @@ int slsDetector::initializeDetectorSize(detectorType type) { thisDetector->nChip[Y]=1; thisDetector->nDacs=16; thisDetector->nAdcs=0; - thisDetector->nGain=4; - thisDetector->nOffset=4; + thisDetector->nGain=0; + thisDetector->nOffset=0; thisDetector->nModMax[X]=1; thisDetector->nModMax[Y]=1; thisDetector->dynamicRange=16; @@ -882,15 +882,32 @@ int slsDetector::initializeDetectorSize(detectorType type) { fileName=parentDet->fileName; fileIndex=parentDet->fileIndex; framesPerFile=parentDet->framesPerFile; - if((thisDetector->myDetectorType==GOTTHARD)||(thisDetector->myDetectorType==PROPIX)) - setFramesPerFile(MAX_FRAMES_PER_FILE); - if (thisDetector->myDetectorType==MOENCH) - setFramesPerFile(MOENCH_MAX_FRAMES_PER_FILE); - if (thisDetector->myDetectorType==JUNGFRAU) - setFramesPerFile(JFRAU_MAX_FRAMES_PER_FILE); - if (thisDetector->myDetectorType==JUNGFRAUCTB) + fileFormatType=parentDet->fileFormatType; + if((thisDetector->myDetectorType==GOTTHARD)||(thisDetector->myDetectorType==PROPIX)){ + fileIO::setFramesPerFile(MAX_FRAMES_PER_FILE); + pthread_mutex_unlock(&ms); + setFileFormat(BINARY); + }else if (thisDetector->myDetectorType==EIGER){ + fileIO::setFramesPerFile(EIGER_MAX_FRAMES_PER_FILE); + pthread_mutex_unlock(&ms); + setFileFormat(BINARY); + }else if (thisDetector->myDetectorType==MOENCH){ + fileIO::setFramesPerFile(MOENCH_MAX_FRAMES_PER_FILE); + pthread_mutex_unlock(&ms); + setFileFormat(BINARY); + }else if (thisDetector->myDetectorType==JUNGFRAU){ + fileIO::setFramesPerFile(JFRAU_MAX_FRAMES_PER_FILE); + pthread_mutex_unlock(&ms); + setFileFormat(BINARY); + }else if (thisDetector->myDetectorType==JUNGFRAUCTB){ setFramesPerFile(JFCTB_MAX_FRAMES_PER_FILE); - pthread_mutex_unlock(&ms); + fileIO::setFramesPerFile(JFRAU_MAX_FRAMES_PER_FILE); + pthread_mutex_unlock(&ms); + setFileFormat(BINARY); + }else + pthread_mutex_unlock(&ms); + if (thisReceiver != NULL) + delete thisReceiver; thisReceiver = new receiverInterface(dataSocket); // setAngularConversionPointer(thisDetector->angOff,&thisDetector->nMods, thisDetector->nChans*thisDetector->nChips); @@ -912,8 +929,8 @@ int slsDetector::initializeDetectorSize(detectorType type) { int slsDetector::initializeDetectorStructure() { sls_detector_module *thisMod; - char *p2; - p2=(char*)thisDetector; + //char *p2; + //p2=(char*)thisDetector; /** for each of the detector modules up to the maximum number which can be installed initlialize the sls_detector_module structure \sa ::sls_detector_module*/ for (int imod=0; imodnModsMax; imod++) { @@ -981,66 +998,67 @@ slsDetectorDefs::sls_detector_module* slsDetector::createModule(detectorType t) sls_detector_module *myMod=(sls_detector_module*)malloc(sizeof(sls_detector_module)); - int nch, nm, nc, nd, na=0; + int nch, nc, nd, na=0; + // int nm = 0; switch(t) { case MYTHEN: nch=128; // complete mythen system - nm=24; +// nm=24; nc=10; nd=6; // dacs break; case PICASSO: nch=128; // complete mythen system - nm=24; + // nm=24; nc=12; nd=6; // dacs+adcs break; case GOTTHARD: nch=128; - nm=1; +// nm=1; nc=10; nd=8; // dacs+adcs na=5; break; case PROPIX: nch=22*22; - nm=1; +// nm=1; nc=1; nd=8; // dacs+adcs na=5; break; case EIGER: nch=256*256; // one EIGER half module - nm=1; //modules/detector +// nm=1; //modules/detector nc=4*1; //chips nd=16; //dacs na=0; break; case MOENCH: nch=160*160; - nm=1; //modules/detector +// nm=1; //modules/detector nc=1; //chips nd=8; //dacs na=1; break; case JUNGFRAU: nch=256*256;//32; - nm=1; + // nm=1; nc=4*2; nd=16; // dacs+adcs na=0; break; case JUNGFRAUCTB: nch=36; - nm=1; +// nm=1; nc=1; nd=8; // dacs+adcs na=1; break; default: nch=0; // dum! - nm=0; //modules/detector +// nm=0; //modules/detector nc=0; //chips nd=0; //dacs+adcs na=0; @@ -1286,6 +1304,7 @@ string slsDetector::checkOnline() { int slsDetector::activate(int const enable){ int fnum = F_ACTIVATE; + int fnum2 = F_RECEIVER_ACTIVATE; int retval = -1; int arg = enable; char mess[MAX_STR_LENGTH]=""; @@ -1337,7 +1356,7 @@ int slsDetector::activate(int const enable){ std::cout << "Activating/Deactivating Receiver: " << retval << std::endl; #endif if (connectData() == OK){ - ret=thisReceiver->sendInt(fnum,retval,retval); + ret=thisReceiver->sendInt(fnum2,retval,retval); disconnectData(); } if(ret==FAIL) @@ -1684,8 +1703,10 @@ slsDetectorDefs::detectorType slsDetector::getDetectorsType(int pos){ // readOutFlags roFlags; -int slsDetector::getTotalNumberOfChannels() { - cout << "total number of channels" << endl; +int slsDetector::getTotalNumberOfChannels() { +#ifdef VERBOSE + cout << "total number of channels" << endl; +#endif if(thisDetector->myDetectorType==JUNGFRAUCTB){ if (thisDetector->roFlags&DIGITAL_ONLY) thisDetector->nChan[X]=4; @@ -1703,11 +1724,15 @@ int slsDetector::getTotalNumberOfChannels() { } thisDetector->nChans=thisDetector->nChan[X]; thisDetector->dataBytes=thisDetector->nChans*thisDetector->nChips*thisDetector->nMods*2*thisDetector->timerValue[SAMPLES_JCTB]; - } else + } else { +#ifdef VERBOSE cout << "det type is "<< thisDetector->myDetectorType << endl; cout << "Total number of channels is "<< thisDetector->nChans*thisDetector->nChips*thisDetector->nMods << " data bytes is " << thisDetector->dataBytes << endl; +#endif + ; + } return thisDetector->nChans*thisDetector->nChips*thisDetector->nMods; -}; +} int slsDetector::getTotalNumberOfChannels(dimension d) { getTotalNumberOfChannels(); @@ -1722,7 +1747,10 @@ int slsDetector::getMaxNumberOfChannels(){ }; int slsDetector::getMaxNumberOfChannels(dimension d){ - if(thisDetector->myDetectorType==JUNGFRAUCTB) if (d==X) return 36*thisDetector->nChip[d]*thisDetector->nModMax[d]; else return 1*thisDetector->nChip[d]*thisDetector->nModMax[d]; + if(thisDetector->myDetectorType==JUNGFRAUCTB) { + if (d==X) return 36*thisDetector->nChip[d]*thisDetector->nModMax[d]; + else return 1*thisDetector->nChip[d]*thisDetector->nModMax[d]; + } return thisDetector->nChan[d]*thisDetector->nChip[d]*thisDetector->nModMax[d]; }; @@ -1735,7 +1763,6 @@ int slsDetector::setNumberOfModules(int n, dimension d){ int ret=FAIL; char mess[MAX_STR_LENGTH]="dummy"; int connect; - int num; arg[0]=d; arg[1]=n; @@ -1756,11 +1783,11 @@ int slsDetector::setNumberOfModules(int n, dimension d){ if (connect == UNDEFINED) cout << "no control socket?" << endl; else if (connect == OK){ - num = controlSocket->SendDataOnly(&fnum,sizeof(fnum)); - num = controlSocket->SendDataOnly(&arg,sizeof(arg)); - num = controlSocket->ReceiveDataOnly(&ret,sizeof(ret)); + controlSocket->SendDataOnly(&fnum,sizeof(fnum)); + controlSocket->SendDataOnly(&arg,sizeof(arg)); + controlSocket->ReceiveDataOnly(&ret,sizeof(ret)); if (ret!=FAIL) { - num = controlSocket->ReceiveDataOnly(&retval,sizeof(retval)); + controlSocket->ReceiveDataOnly(&retval,sizeof(retval)); } else { controlSocket->ReceiveDataOnly(mess,sizeof(mess)); std::cout<< "Detector returned error: " << mess << std::endl; @@ -1894,7 +1921,6 @@ int slsDetector::setFlippedData(dimension d, int value){ int retval=-1; int fnum=F_SET_FLIPPED_DATA_RECEIVER; int ret=FAIL; - char mess[MAX_STR_LENGTH]=""; int args[2]={X,-1}; @@ -2424,7 +2450,7 @@ dacs_t slsDetector::setDAC(dacs_t val, dacIndex index, int mV, int imod){ int arg[3]; - if ( (thisDetector->myDetectorType == GOTTHARD) || (thisDetector->myDetectorType == PROPIX) && index==HV_NEW) + if ( (index==HV_NEW) &&((thisDetector->myDetectorType == GOTTHARD) || (thisDetector->myDetectorType == PROPIX))) index=HV_POT; arg[0]=index; @@ -2868,12 +2894,8 @@ slsDetectorDefs::sls_detector_chip slsDetector::getChip(int ichip, int imod){ int slsDetector::setModule(int reg, int imod){ sls_detector_module myModule; - int* g=0; - int* o=0; - int* iod=0; - int64_t tau=-1; -#ifdef VERBOSE + #ifdef VERBOSE std::cout << "slsDetector set module " << std::endl; #endif int charegs[thisDetector->nChans*thisDetector->nChips]; @@ -2940,14 +2962,14 @@ int slsDetector::setModule(int reg, int imod){ ads[i]=-1; myModule.adcs=ads; } - ret=setModule(myModule,g,o,iod,tau); + ret=setModule(myModule,-1,-1,-1,0,0); } return ret; }; -int slsDetector::setModule(sls_detector_module module, int* gainval, int* offsetval, int* iodelay, int64_t tau){ +int slsDetector::setModule(sls_detector_module module, int iodelay, int tau, int e_eV, int* gainval, int* offsetval){ int fnum=F_SET_MODULE; int retval; @@ -2966,16 +2988,18 @@ int slsDetector::setModule(sls_detector_module module, int* gainval, int* offset controlSocket->SendDataOnly(&fnum,sizeof(fnum)); sendModule(&module); - //extra gain and offset - eiger - if((thisDetector->nGain) && (gainval)) + //not included in module + if(gainval && (thisDetector->nGain)) controlSocket->SendDataOnly(gainval,sizeof(int)*thisDetector->nGain); - if((thisDetector->nOffset) && (offsetval)) + if(offsetval && (thisDetector->nOffset)) controlSocket->SendDataOnly(offsetval,sizeof(int)*thisDetector->nOffset); - if(thisDetector->myDetectorType == EIGER){ - controlSocket->SendDataOnly(iodelay,sizeof(int)); + if(thisDetector->myDetectorType == EIGER) { + controlSocket->SendDataOnly(&iodelay,sizeof(iodelay)); controlSocket->SendDataOnly(&tau,sizeof(tau)); + controlSocket->SendDataOnly(&e_eV,sizeof(e_eV)); } + controlSocket->ReceiveDataOnly(&ret,sizeof(ret)); if (ret!=FAIL) controlSocket->ReceiveDataOnly(&retval,sizeof(retval)); @@ -3172,13 +3196,14 @@ slsDetectorDefs::sls_detector_module *slsDetector::getModule(int imod){ offset[i+imod*thisDetector->nOffset]=offsetval[i]; } - if(gainval) delete[]gainval; - if(offsetval) delete[]offsetval; - } else { deleteModule(myMod); myMod=NULL; } + + if(gainval) delete[]gainval; + if(offsetval) delete[]offsetval; + return myMod; } @@ -3243,41 +3268,201 @@ int slsDetector::getThresholdEnergy(int imod){ int slsDetector::setThresholdEnergy(int e_eV, int imod, detectorSettings isettings){ - int fnum= F_SET_THRESHOLD_ENERGY; - int retval; - int ret=FAIL; - char mess[MAX_STR_LENGTH]=""; + //currently only for eiger + if (thisDetector->myDetectorType == EIGER) { + setThresholdEnergyAndSettings(e_eV,isettings); + return thisDetector->currentThresholdEV; + } + + int fnum= F_SET_THRESHOLD_ENERGY; + int retval; + int ret=FAIL; + char mess[MAX_STR_LENGTH]=""; #ifdef VERBOSE - std::cout<< "Setting threshold energy "<< std::endl; + std::cout<< "Setting threshold energy "<< std::endl; #endif - if (thisDetector->onlineFlag==ONLINE_FLAG) { - if (connectControl() == OK){ - controlSocket->SendDataOnly(&fnum,sizeof(fnum)); - controlSocket->SendDataOnly(&e_eV,sizeof(e_eV)); - controlSocket->SendDataOnly(&imod,sizeof(imod)); - controlSocket->SendDataOnly(&isettings,sizeof(isettings)); - controlSocket->ReceiveDataOnly(&ret,sizeof(ret)); - if (ret==FAIL) { - std::cout<< "Detector returned error: "<< std::endl; - controlSocket->ReceiveDataOnly(mess,sizeof(mess)); - std::cout<< mess << std::endl; - } else { + if (thisDetector->onlineFlag==ONLINE_FLAG) { + if (connectControl() == OK){ + controlSocket->SendDataOnly(&fnum,sizeof(fnum)); + controlSocket->SendDataOnly(&e_eV,sizeof(e_eV)); + controlSocket->SendDataOnly(&imod,sizeof(imod)); + controlSocket->SendDataOnly(&isettings,sizeof(isettings)); + controlSocket->ReceiveDataOnly(&ret,sizeof(ret)); + if (ret==FAIL) { + std::cout<< "Detector returned error: "<< std::endl; + controlSocket->ReceiveDataOnly(mess,sizeof(mess)); + std::cout<< mess << std::endl; + } else { #ifdef VERBOSE - std::cout<< "Detector returned OK "<< std::endl; + std::cout<< "Detector returned OK "<< std::endl; #endif - controlSocket->ReceiveDataOnly(&retval,sizeof(retval)); - thisDetector->currentThresholdEV=retval; - } - disconnectControl(); - if (ret==FORCE_UPDATE) - updateDetector(); - } - } else { - thisDetector->currentThresholdEV=e_eV; - } - return thisDetector->currentThresholdEV; + controlSocket->ReceiveDataOnly(&retval,sizeof(retval)); + thisDetector->currentThresholdEV=retval; + } + disconnectControl(); + if (ret==FORCE_UPDATE) + updateDetector(); + } + } else { + thisDetector->currentThresholdEV=e_eV; + } + return thisDetector->currentThresholdEV; }; + + +int slsDetector::setThresholdEnergyAndSettings(int e_eV, detectorSettings isettings) { + + //if settings provided, use that, else use the shared memory variable + detectorSettings is = ((isettings != GET_SETTINGS) ? isettings: thisDetector->currentSettings); + string ssettings; + switch (is) { + case STANDARD: + ssettings="/standard"; + thisDetector->currentSettings=STANDARD; + break; + case HIGHGAIN: + ssettings="/highgain"; + thisDetector->currentSettings=HIGHGAIN; + break; + case LOWGAIN: + ssettings="/lowgain"; + thisDetector->currentSettings=LOWGAIN; + break; + case VERYHIGHGAIN: + ssettings="/veryhighgain"; + thisDetector->currentSettings=VERYHIGHGAIN; + break; + case VERYLOWGAIN: + ssettings="/verylowgain"; + thisDetector->currentSettings=VERYLOWGAIN; + break; + default: + printf("Error: Unknown settings %s for this detector!\n", getDetectorSettings(is).c_str()); + setErrorMask((getErrorMask())|(SETTINGS_NOT_SET)); + return FAIL; + } + + //verify e_eV exists in trimEneregies[] + if (!thisDetector->nTrimEn || + (e_eV < thisDetector->trimEnergies[0]) || + (e_eV > thisDetector->trimEnergies[thisDetector->nTrimEn-1]) ) { + printf("Error: This energy %d not defined for this module!\n", e_eV); + setErrorMask((getErrorMask())|(SETTINGS_NOT_SET)); + return FAIL; + } + + //find if interpolation required + bool interpolate = true; + for (int i = 0; i < thisDetector->nTrimEn; ++i) { + if (thisDetector->trimEnergies[i] == e_eV) { + interpolate = false; + break; + } + } + + //fill detector module structure + sls_detector_module *myMod = NULL; + int iodelay = -1; //not included in the module + int tau = -1; //not included in the module + + //normal + if(!interpolate) { + //find their directory names + ostringstream ostfn; + ostfn << thisDetector->settingsDir << ssettings << "/" << e_eV << "eV" << "/noise.sn" << setfill('0') << setw(3) << dec << getId(DETECTOR_SERIAL_NUMBER) << setbase(10); + string settingsfname = ostfn.str(); +#ifdef VERBOSE + printf("Settings File is %s\n", settingsfname.c_str()); +#endif + //read the files + myMod=createModule(); + if (NULL == readSettingsFile(settingsfname,thisDetector->myDetectorType, iodelay, tau, myMod)) { + if(myMod)deleteModule(myMod); + return FAIL; + } + } + + + //interpolate + else { + //find the trim values + int trim1 = -1, trim2 = -1; + for (int i = 0; i < thisDetector->nTrimEn; ++i) { + if (e_eV < thisDetector->trimEnergies[i]) { + trim2 = thisDetector->trimEnergies[i]; + trim1 = thisDetector->trimEnergies[i-1]; + break; + } + } + //find their directory names + ostringstream ostfn; + ostfn << thisDetector->settingsDir << ssettings << "/" << trim1 << "eV" << "/noise.sn" << setfill('0') << setw(3) << dec << getId(DETECTOR_SERIAL_NUMBER) << setbase(10); + string settingsfname1 = ostfn.str(); + ostfn.str(""); ostfn.clear(); + ostfn << thisDetector->settingsDir << ssettings << "/" << trim2 << "eV" << "/noise.sn" << setfill('0') << setw(3) << dec << getId(DETECTOR_SERIAL_NUMBER) << setbase(10); + string settingsfname2 = ostfn.str(); + //read the files +#ifdef VERBOSE + printf("Settings Files are %s and %s\n",settingsfname1.c_str(), settingsfname2.c_str()); +#endif + sls_detector_module *myMod1=createModule(); + sls_detector_module *myMod2=createModule(); + int iodelay1 = -1; //not included in the module + int tau1 = -1; //not included in the module + int iodelay2 = -1; //not included in the module + int tau2 = -1; //not included in the module + if (NULL == readSettingsFile(settingsfname1,thisDetector->myDetectorType, iodelay1, tau1, myMod1)) { + setErrorMask((getErrorMask())|(SETTINGS_FILE_NOT_OPEN)); + deleteModule(myMod1); + deleteModule(myMod2); + return FAIL; + } + if (NULL == readSettingsFile(settingsfname2,thisDetector->myDetectorType, iodelay2, tau2, myMod2)) { + setErrorMask((getErrorMask())|(SETTINGS_FILE_NOT_OPEN)); + deleteModule(myMod1); + deleteModule(myMod2); + return FAIL; + } + if (iodelay1 != iodelay2) { + printf("iodelays do not match between files\n"); + setErrorMask((getErrorMask())|(SETTINGS_NOT_SET)); + deleteModule(myMod1); + deleteModule(myMod2); + return FAIL; + } + iodelay = iodelay1; + + //interpolate module + myMod = interpolateTrim(thisDetector->myDetectorType, myMod1, myMod2, e_eV, trim1, trim2); + if (myMod == NULL) { + printf("Could not interpolate, different dac values in files\n"); + setErrorMask((getErrorMask())|(SETTINGS_NOT_SET)); + } + //interpolate tau + tau = linearInterpolation(e_eV, trim1, trim2, tau1, tau2); + printf("new tau:%d\n",tau); + + deleteModule(myMod1); + deleteModule(myMod2); + } + + + myMod->module=0; + myMod->reg=thisDetector->currentSettings; + setModule(*myMod, iodelay, tau, e_eV, 0, 0); + deleteModule(myMod); + if (getSettings(-1) != is){ + std::cout << "Could not set settings in detector" << endl; + setErrorMask((getErrorMask())|(SETTINGS_NOT_SET)); + return FAIL; + } + + return OK; +} + + + /* select detector settings */ @@ -3324,20 +3509,36 @@ slsDetectorDefs::detectorSettings slsDetector::setSettings( detectorSettings ise #ifdef VERBOSE std::cout<< "slsDetector setSettings "<< std::endl; #endif + + //only set client shared memory variable for Eiger, settings threshold loads the module data (trimbits, dacs etc.) + if (thisDetector->myDetectorType == EIGER) { + switch(isettings) { + case STANDARD: + case HIGHGAIN: + case LOWGAIN: + case VERYHIGHGAIN: + case VERYLOWGAIN: + thisDetector->currentSettings = isettings; + break; + default: + printf("Unknown settings %s for this detector!\n", getDetectorSettings(isettings).c_str()); + } + return thisDetector->currentSettings; + } + sls_detector_module *myMod=createModule(); int modmi=imod, modma=imod+1, im=imod; string settingsfname, calfname; string ssettings; + //not included in module structure + int iodelay = -1; + int tau = -1; int* gainval=0, *offsetval=0; - int* iodelay=0; if(thisDetector->nGain) gainval=new int[thisDetector->nGain]; if(thisDetector->nOffset) offsetval=new int[thisDetector->nOffset]; - if(thisDetector->myDetectorType == EIGER) - iodelay = new int; - int64_t tau=-1; int ret=0; @@ -3495,7 +3696,7 @@ slsDetectorDefs::detectorSettings slsDetector::setSettings( detectorSettings ise #ifdef VERBOSE cout << "the settings file name is "<myDetectorType, myMod,iodelay)) { + if (NULL == readSettingsFile(settingsfname,thisDetector->myDetectorType, iodelay, tau, myMod)) { //if it didnt open, try default settings file ostringstream ostfn_default; switch(thisDetector->myDetectorType){ @@ -3515,7 +3716,7 @@ slsDetectorDefs::detectorSettings slsDetector::setSettings( detectorSettings ise #ifdef VERBOSE cout << settingsfname << endl; #endif - if (!readSettingsFile(settingsfname,thisDetector->myDetectorType, myMod,iodelay)) { + if (NULL == readSettingsFile(settingsfname,thisDetector->myDetectorType, iodelay, tau, myMod)) { //if default doesnt work, return error std::cout << "Could not open settings file" << endl; setErrorMask((getErrorMask())|(SETTINGS_FILE_NOT_OPEN)); @@ -3526,41 +3727,43 @@ slsDetectorDefs::detectorSettings slsDetector::setSettings( detectorSettings ise //calibration file**** - calfname=oscfn.str(); + if(thisDetector->myDetectorType != EIGER) { + calfname=oscfn.str(); #ifdef VERBOSE - cout << "Specific file:"<< calfname << endl; -#endif - //extra gain and offset - if(thisDetector->nGain) - ret = readCalibrationFile(calfname,gainval, offsetval, tau, thisDetector->myDetectorType ); - //normal gain and offset inside sls_detector_module - else - ret = readCalibrationFile(calfname,myMod->gain, myMod->offset); - - //if it didnt open, try default - if(ret != OK){ - ostringstream oscfn_default; - oscfn_default << thisDetector->calDir << ssettings << ssettings << ".cal"; - calfname=oscfn_default.str(); -#ifdef VERBOSE - cout << "Default file:" << calfname << endl; + cout << "Specific file:"<< calfname << endl; #endif //extra gain and offset if(thisDetector->nGain) - ret = readCalibrationFile(calfname,gainval, offsetval, tau, thisDetector->myDetectorType ); + ret = readCalibrationFile(calfname,gainval, offsetval); //normal gain and offset inside sls_detector_module else ret = readCalibrationFile(calfname,myMod->gain, myMod->offset); - } - //if default doesnt work, return error - if(ret != OK){ - std::cout << "Could not open calibration file" << calfname << endl; - setErrorMask((getErrorMask())|(SETTINGS_FILE_NOT_OPEN)); - return thisDetector->currentSettings; + + //if it didnt open, try default + if(ret != OK){ + ostringstream oscfn_default; + oscfn_default << thisDetector->calDir << ssettings << ssettings << ".cal"; + calfname=oscfn_default.str(); +#ifdef VERBOSE + cout << "Default file:" << calfname << endl; +#endif + //extra gain and offset + if(thisDetector->nGain) + ret = readCalibrationFile(calfname,gainval, offsetval); + //normal gain and offset inside sls_detector_module + else + ret = readCalibrationFile(calfname,myMod->gain, myMod->offset); + } + //if default doesnt work, return error + if(ret != OK){ + std::cout << "Could not open calibration file" << calfname << endl; + setErrorMask((getErrorMask())|(SETTINGS_FILE_NOT_OPEN)); + return thisDetector->currentSettings; + } } //if everything worked, set module**** - setModule(*myMod,gainval,offsetval,iodelay, tau); + setModule(*myMod,iodelay,tau,-1,gainval,offsetval); } } @@ -3611,18 +3814,18 @@ int slsDetector::updateDetectorNoWait() { enum readOutFlags ro; // int ret=OK; enum detectorSettings t; - int thr, n, nm; + int thr, n = 0, nm; // int it; int64_t retval;// tns=-1; char lastClientIP[INET_ADDRSTRLEN]; - n = controlSocket->ReceiveDataOnly(lastClientIP,sizeof(lastClientIP)); + n += controlSocket->ReceiveDataOnly(lastClientIP,sizeof(lastClientIP)); #ifdef VERBOSE cout << "Updating detector last modified by " << lastClientIP << std::endl; #endif - n = controlSocket->ReceiveDataOnly(&nm,sizeof(nm)); + n += controlSocket->ReceiveDataOnly(&nm,sizeof(nm)); thisDetector->nMod[X]=nm; - n = controlSocket->ReceiveDataOnly( &nm,sizeof(nm)); + n += controlSocket->ReceiveDataOnly( &nm,sizeof(nm)); /// Should be overcome at a certain point! if (thisDetector->myDetectorType==MYTHEN) { @@ -3644,72 +3847,80 @@ int slsDetector::updateDetectorNoWait() { if (thisDetector->nModMax[Y]nMod[Y]) thisDetector->nModMax[Y]=thisDetector->nMod[Y]; - n = controlSocket->ReceiveDataOnly( &nm,sizeof(nm)); + n += controlSocket->ReceiveDataOnly( &nm,sizeof(nm)); thisDetector->dynamicRange=nm; - n = controlSocket->ReceiveDataOnly( &nm,sizeof(nm)); + n += controlSocket->ReceiveDataOnly( &nm,sizeof(nm)); thisDetector->dataBytes=nm; + //t=setSettings(GET_SETTINGS); - n = controlSocket->ReceiveDataOnly( &t,sizeof(t)); + n += controlSocket->ReceiveDataOnly( &t,sizeof(t)); thisDetector->currentSettings=t; - if((thisDetector->myDetectorType!= GOTTHARD)&& - (thisDetector->myDetectorType!= PROPIX)&& - (thisDetector->myDetectorType!= JUNGFRAU)&& - (thisDetector->myDetectorType!= MOENCH) && (thisDetector->myDetectorType!= JUNGFRAUCTB)){ + if((thisDetector->myDetectorType == EIGER) || (thisDetector->myDetectorType == MYTHEN)){ //thr=getThresholdEnergy(); - n = controlSocket->ReceiveDataOnly( &thr,sizeof(thr)); + n += controlSocket->ReceiveDataOnly( &thr,sizeof(thr)); thisDetector->currentThresholdEV=thr; } //retval=setFrames(tns); - n = controlSocket->ReceiveDataOnly( &retval,sizeof(int64_t)); + n += controlSocket->ReceiveDataOnly( &retval,sizeof(int64_t)); thisDetector->timerValue[FRAME_NUMBER]=retval; + // retval=setExposureTime(tns); - n = controlSocket->ReceiveDataOnly( &retval,sizeof(int64_t)); + n += controlSocket->ReceiveDataOnly( &retval,sizeof(int64_t)); thisDetector->timerValue[ACQUISITION_TIME]=retval; if(thisDetector->myDetectorType == EIGER){ //retval=setSubFrameExposureTime(tns); - n = controlSocket->ReceiveDataOnly( &retval,sizeof(int64_t)); + n += controlSocket->ReceiveDataOnly( &retval,sizeof(int64_t)); thisDetector->timerValue[SUBFRAME_ACQUISITION_TIME]=retval; } + //retval=setPeriod(tns); - n = controlSocket->ReceiveDataOnly( &retval,sizeof(int64_t)); + n += controlSocket->ReceiveDataOnly( &retval,sizeof(int64_t)); thisDetector->timerValue[FRAME_PERIOD]=retval; - //retval=setDelay(tns); - n = controlSocket->ReceiveDataOnly( &retval,sizeof(int64_t)); - thisDetector->timerValue[DELAY_AFTER_TRIGGER]=retval; + + if(thisDetector->myDetectorType != EIGER) { + //retval=setDelay(tns); + n += controlSocket->ReceiveDataOnly( &retval,sizeof(int64_t)); + thisDetector->timerValue[DELAY_AFTER_TRIGGER]=retval; + } + // retval=setGates(tns); - n = controlSocket->ReceiveDataOnly( &retval,sizeof(int64_t)); + if ((thisDetector->myDetectorType != JUNGFRAU) && (thisDetector->myDetectorType != EIGER)){ + n += controlSocket->ReceiveDataOnly( &retval,sizeof(int64_t)); thisDetector->timerValue[GATES_NUMBER]=retval; + } //retval=setProbes(tns); if (thisDetector->myDetectorType == MYTHEN){ - n = controlSocket->ReceiveDataOnly( &retval,sizeof(int64_t)); + n += controlSocket->ReceiveDataOnly( &retval,sizeof(int64_t)); thisDetector->timerValue[PROBES_NUMBER]=retval; } - //retval=setTrains(tns); - n = controlSocket->ReceiveDataOnly( &retval,sizeof(int64_t)); + n += controlSocket->ReceiveDataOnly( &retval,sizeof(int64_t)); thisDetector->timerValue[CYCLES_NUMBER]=retval; //retval=setProbes(tns); if (thisDetector->myDetectorType == JUNGFRAUCTB){ - n = controlSocket->ReceiveDataOnly( &retval,sizeof(int64_t)); + n += controlSocket->ReceiveDataOnly( &retval,sizeof(int64_t)); if (retval>=0) thisDetector->timerValue[SAMPLES_JCTB]=retval; - n = controlSocket->ReceiveDataOnly( &ro,sizeof(ro)); + n += controlSocket->ReceiveDataOnly( &ro,sizeof(ro)); thisDetector->roFlags=ro; //retval=setProbes(tns); getTotalNumberOfChannels(); - // thisDetector->dataBytes=getTotalNumberOfChannels()*thisDetector->dynamicRange/8*thisDetector->timerValue[SAMPLES_JCTB]; - } + + + if (!n) + printf("n: %d\n", n); + return OK; } @@ -4120,7 +4331,6 @@ int64_t slsDetector::setTimer(timerIndex index, int64_t t){ int64_t retval = -1; char mess[MAX_STR_LENGTH]=""; int ret=OK; - int n=0; if (index!=MEASUREMENTS_NUMBER) { @@ -4132,7 +4342,7 @@ int64_t slsDetector::setTimer(timerIndex index, int64_t t){ if (connectControl() == OK){ controlSocket->SendDataOnly(&fnum,sizeof(fnum)); controlSocket->SendDataOnly(&index,sizeof(index)); - n=controlSocket->SendDataOnly(&t,sizeof(t)); + controlSocket->SendDataOnly(&t,sizeof(t)); controlSocket->ReceiveDataOnly(&ret,sizeof(ret)); if (ret==FAIL) { controlSocket->ReceiveDataOnly(mess,sizeof(mess)); @@ -4628,7 +4838,7 @@ int slsDetector::setSpeed(speedVariable sp, int value) { int retval=-1; char mess[MAX_STR_LENGTH]=""; int ret=OK; - int n=0; + #ifdef VERBOSE std::cout<< "Setting speed variable"<< sp << " to " << value << std::endl; #endif @@ -4636,7 +4846,7 @@ int slsDetector::setSpeed(speedVariable sp, int value) { if (connectControl() == OK){ controlSocket->SendDataOnly(&fnum,sizeof(fnum)); controlSocket->SendDataOnly(&sp,sizeof(sp)); - n=controlSocket->SendDataOnly(&value,sizeof(value)); + controlSocket->SendDataOnly(&value,sizeof(value)); #ifdef VERBOSE std::cout<< "Sent "<< n << " bytes " << std::endl; #endif @@ -4883,7 +5093,7 @@ int slsDetector::sendROI(int n,ROI roiLimits[]){ if (ret!=FAIL){ controlSocket->ReceiveDataOnly(&retvalsize,sizeof(retvalsize)); nrec = controlSocket->ReceiveDataOnly(retval,retvalsize*sizeof(ROI)); - if(nrec!=(retvalsize*sizeof(ROI))){ + if(nrec!=(retvalsize*(int)sizeof(ROI))){ ret=FAIL; std::cout << " wrong size received: received " << nrec << "but expected " << retvalsize*sizeof(ROI) << endl; } @@ -5035,6 +5245,7 @@ double* slsDetector::decodeData(int *datain, int &nn, double *fdata) { double *dataout; if (fdata) { dataout=fdata; + nn=thisDetector->nChans*thisDetector->nChips*thisDetector->nMods; // printf("not allocating fdata!\n"); if (thisDetector->myDetectorType==JUNGFRAUCTB) nn=thisDetector->dataBytes/2; } else { @@ -5050,7 +5261,7 @@ double* slsDetector::decodeData(int *datain, int &nn, double *fdata) { // printf("allocating fdata!\n"); } - const int bytesize=8; + // const int bytesize=8; int ival=0; char *ptr=(char*)datain; @@ -5313,7 +5524,7 @@ int slsDetector::setRateCorrection(double t){ int ret=FAIL; char mess[MAX_STR_LENGTH]=""; int64_t arg = t; - int64_t retval = -1; + #ifdef VERBOSE std::cout<< "Setting Rate Correction to " << arg << endl; #endif @@ -5738,6 +5949,7 @@ char* slsDetector::setReceiver(string receiverIP){ #ifdef VERBOSE std::cout << "Setting up receiver with" << endl; std::cout << "detector type:" << slsDetectorBase::getDetectorType(thisDetector->myDetectorType) << endl; + std::cout << "detector id:" << posId << endl; std::cout << "detector hostname:" << thisDetector->hostname << endl; std::cout << "file path:" << fileIO::getFilePath() << endl; std::cout << "file name:" << fileIO::getFileName() << endl; @@ -5755,10 +5967,14 @@ char* slsDetector::setReceiver(string receiverIP){ /** enable compresison, */ #endif if(setDetectorType()!= GENERIC){ + if(!posId) + sendMultiDetectorSize(); + setDetectorId(); setDetectorHostname(); setFilePath(fileIO::getFilePath()); setFileName(fileIO::getFileName()); setFileIndex(fileIO::getFileIndex()); + setFileFormat(fileIO::getFileFormat()); pthread_mutex_lock(&ms); int imask = parentDet->enableWriteToFileMask(); pthread_mutex_unlock(&ms); @@ -5980,151 +6196,173 @@ int slsDetector::setUDPConnection(){ int slsDetector::configureMAC(){ - int i; - int ret=FAIL; - int fnum=F_CONFIGURE_MAC,fnum2=F_RECEIVER_SHORT_FRAME; - char mess[MAX_STR_LENGTH]=""; - char arg[6][50]={"","","","","",""}; - char cword[50]="", *pcword; - string sword; - int retval=-1; + int i; + int ret=FAIL; + int fnum=F_CONFIGURE_MAC,fnum2=F_RECEIVER_SHORT_FRAME; + char mess[MAX_STR_LENGTH]=""; + char arg[6][50]={"","","","","",""}; + int retval=-1; - //if udpip wasnt initialized in config file - if(!(strcmp(thisDetector->receiverUDPIP,"none"))){ - //hostname is an ip address - if(strchr(thisDetector->receiver_hostname,'.')!=NULL) - strcpy(thisDetector->receiverUDPIP,thisDetector->receiver_hostname); - //if hostname not ip, convert it to ip - else{ - struct hostent *he = gethostbyname(thisDetector->receiver_hostname); - if (he != NULL) - strcpy(thisDetector->receiverUDPIP,inet_ntoa(*(struct in_addr*)he->h_addr)); - else{ - std::cout << "configure mac failed. no rx_udpip given and invalid receiver hostname" << endl; - setErrorMask((getErrorMask())|(COULD_NOT_CONFIGURE_MAC)); - return FAIL; - } - } - } - strcpy(arg[0],thisDetector->receiverUDPIP); - strcpy(arg[1],thisDetector->receiverUDPMAC); - sprintf(arg[2],"%x",thisDetector->receiverUDPPort); - strcpy(arg[3],thisDetector->detectorMAC); - strcpy(arg[4],thisDetector->detectorIP); - sprintf(arg[5],"%x",thisDetector->receiverUDPPort2); - -#ifdef VERBOSE - std::cout<< "Configuring MAC"<< std::endl; -#endif - - - for(i=0;i<2;i++){ - if(!strcmp(arg[i],"none")){ - std::cout<< "Configure MAC Error. IP/MAC Addresses not set"<< std::endl; - setErrorMask((getErrorMask())|(COULD_NOT_CONFIGURE_MAC)); - return FAIL; - } - } - -#ifdef VERBOSE - std::cout<< "IP/MAC Addresses valid "<< std::endl; -#endif - - //converting IPaddress to hex. - pcword = strtok (arg[0],"."); - while (pcword != NULL) { - sprintf(arg[0],"%02x",atoi(pcword)); - strcat(cword,arg[0]); - pcword = strtok (NULL, "."); - } - strcpy(arg[0],cword); -#ifdef VERBOSE - std::cout<<"receiver udp ip:"<onlineFlag==ONLINE_FLAG) { - if (connectControl() == OK){ - controlSocket->SendDataOnly(&fnum,sizeof(fnum)); - controlSocket->SendDataOnly(arg,sizeof(arg)); - controlSocket->ReceiveDataOnly(&ret,sizeof(ret)); - if (ret==FAIL){ - controlSocket->ReceiveDataOnly(mess,sizeof(mess)); - std::cout<< "Detector returned error: " << mess << std::endl; - setErrorMask((getErrorMask())|(COULD_NOT_CONFIGURE_MAC)); - } - else - controlSocket->ReceiveDataOnly(&retval,sizeof(retval)); - disconnectControl(); - if (ret==FORCE_UPDATE) - updateDetector(); - } - } - if (ret==FAIL) { - ret=FAIL; - std::cout<< "Configuring MAC failed " << std::endl; - setErrorMask((getErrorMask())|(COULD_NOT_CONFIGURE_MAC)); - } - else if (thisDetector->myDetectorType==GOTTHARD){ - //set frames per file - only for gotthard - pthread_mutex_lock(&ms); - if(retval==-1) - setFramesPerFile(MAX_FRAMES_PER_FILE); - else - setFramesPerFile(SHORT_MAX_FRAMES_PER_FILE); - pthread_mutex_unlock(&ms); - //connect to receiver - if(thisDetector->receiverOnlineFlag==ONLINE_FLAG){ -#ifdef VERBOSE - std::cout << "Sending adc val to receiver " << retval << std::endl; -#endif - if (connectData() == OK){ - ret=thisReceiver->sendInt(fnum2,retval,retval); - disconnectData(); + //if udpip wasnt initialized in config file + if(!(strcmp(thisDetector->receiverUDPIP,"none"))){ + //hostname is an ip address + if(strchr(thisDetector->receiver_hostname,'.')!=NULL) + strcpy(thisDetector->receiverUDPIP,thisDetector->receiver_hostname); + //if hostname not ip, convert it to ip + else{ + struct hostent *he = gethostbyname(thisDetector->receiver_hostname); + if (he != NULL) + strcpy(thisDetector->receiverUDPIP,inet_ntoa(*(struct in_addr*)he->h_addr)); + else{ + std::cout << "configure mac failed. no rx_udpip given and invalid receiver hostname" << endl; + setErrorMask((getErrorMask())|(COULD_NOT_CONFIGURE_MAC)); + return FAIL; + } + } } - if(ret==FAIL) - setErrorMask((getErrorMask())|(COULD_NOT_CONFIGURE_MAC)); - } - } + strcpy(arg[0],thisDetector->receiverUDPIP); + strcpy(arg[1],thisDetector->receiverUDPMAC); + sprintf(arg[2],"%x",thisDetector->receiverUDPPort); + strcpy(arg[3],thisDetector->detectorMAC); + strcpy(arg[4],thisDetector->detectorIP); + sprintf(arg[5],"%x",thisDetector->receiverUDPPort2); - return ret; +#ifdef VERBOSE + std::cout<< "Configuring MAC"<< std::endl; +#endif + + + for(i=0;i<2;i++){ + if(!strcmp(arg[i],"none")){ + std::cout<< "Configure MAC Error. IP/MAC Addresses not set"<< std::endl; + setErrorMask((getErrorMask())|(COULD_NOT_CONFIGURE_MAC)); + return FAIL; + } + } + +#ifdef VERBOSE + std::cout<< "IP/MAC Addresses valid "<< std::endl; +#endif + + + { + //converting IPaddress to hex + stringstream ss(arg[0]); + char cword[50]=""; + bzero(cword, 50); + string s; + while (getline(ss, s, '.')) { + sprintf(cword,"%s%02x",cword,atoi(s.c_str())); + } + bzero(arg[0], 50); + strcpy(arg[0],cword); +#ifdef VERBOSE + std::cout<<"receiver udp ip:"<onlineFlag==ONLINE_FLAG) { + if (connectControl() == OK){ + controlSocket->SendDataOnly(&fnum,sizeof(fnum)); + controlSocket->SendDataOnly(arg,sizeof(arg)); + controlSocket->ReceiveDataOnly(&ret,sizeof(ret)); + if (ret==FAIL){ + controlSocket->ReceiveDataOnly(mess,sizeof(mess)); + std::cout<< "Detector returned error: " << mess << std::endl; + setErrorMask((getErrorMask())|(COULD_NOT_CONFIGURE_MAC)); + } + else + controlSocket->ReceiveDataOnly(&retval,sizeof(retval)); + disconnectControl(); + if (ret==FORCE_UPDATE) + updateDetector(); + } + } + if (ret==FAIL) { + ret=FAIL; + std::cout<< "Configuring MAC failed " << std::endl; + setErrorMask((getErrorMask())|(COULD_NOT_CONFIGURE_MAC)); + } + else if (thisDetector->myDetectorType==GOTTHARD){ + //set frames per file - only for gotthard + pthread_mutex_lock(&ms); + if(retval==-1) + setFramesPerFile(MAX_FRAMES_PER_FILE); + else + setFramesPerFile(SHORT_MAX_FRAMES_PER_FILE); + pthread_mutex_unlock(&ms); + //connect to receiver + if(thisDetector->receiverOnlineFlag==ONLINE_FLAG){ +#ifdef VERBOSE + std::cout << "Sending adc val to receiver " << retval << std::endl; +#endif + if (connectData() == OK){ + ret=thisReceiver->sendInt(fnum2,retval,retval); + disconnectData(); + } + if(ret==FAIL) + setErrorMask((getErrorMask())|(COULD_NOT_CONFIGURE_MAC)); + } + } + + return ret; } @@ -6394,13 +6632,17 @@ int slsDetector::readConfigurationFile(string const fname){ //char *args[1000]; string sargname, sargval; - int iline=0; #ifdef VERBOSE + int iline=0; std::cout<< "config file name "<< fname << std::endl; #endif infile.open(fname.c_str(), ios_base::in); if (infile.is_open()) { +#ifdef VERBOSE iline=readConfigurationFile(infile); +#else + readConfigurationFile(infile); +#endif infile.close(); } else { std::cout<< "Error opening configuration file " << fname << " for reading" << std::endl; @@ -6488,11 +6730,16 @@ int slsDetector::writeConfigurationFile(string const fname){ ofstream outfile; +#ifdef VERBOSE int ret; - +#endif outfile.open(fname.c_str(),ios_base::out); if (outfile.is_open()) { - ret=writeConfigurationFile(outfile); +#ifdef VERBOSE + ret=writeConfigurationFile(outfile); +#else + writeConfigurationFile(outfile); +#endif outfile.close(); } else { @@ -6608,9 +6855,9 @@ int slsDetector::writeConfigurationFile(ofstream &outfile, int id){ -int slsDetector::writeSettingsFile(string fname, int imod, int* iodelay){ +int slsDetector::writeSettingsFile(string fname, int imod, int iodelay, int tau){ - return writeSettingsFile(fname,thisDetector->myDetectorType, detectorModules[imod], iodelay); + return writeSettingsFile(fname,thisDetector->myDetectorType, detectorModules[imod], iodelay, tau); }; @@ -6621,7 +6868,6 @@ int slsDetector::programFPGA(string fname){ int ret=FAIL; int fnum=F_PROGRAM_FPGA; char mess[MAX_STR_LENGTH]=""; - int64_t retval = -1; size_t filesize=0; char* fpgasrc = NULL; @@ -6722,7 +6968,7 @@ int slsDetector::programFPGA(string fname){ #endif if (thisDetector->onlineFlag==ONLINE_FLAG) { if (connectControl() == OK){ - controlSocket->SendDataOnly(&fnum,sizeof(fnum)); + controlSocket->SendDataOnly(&fnum,sizeof(fnum));cprintf(BG_RED,"size of filesize:%lu\n",sizeof(filesize)); controlSocket->SendDataOnly(&filesize,sizeof(filesize)); //check opening error controlSocket->ReceiveDataOnly(&ret,sizeof(ret)); @@ -6875,22 +7121,9 @@ int slsDetector::loadSettingsFile(string fname, int imod) { sls_detector_module *myMod=NULL; - //tau set to -2 to not affect in any way (-1 for set settings) - int64_t tau =-2; - int* gainval=0; int* offsetval=0; - int *iodelay=0; - if(thisDetector->nGain){ - gainval=new int[thisDetector->nGain]; - for(int i=0;inGain;i++) - gainval[i] = -1; - } - if(thisDetector->nOffset){ - offsetval=new int[thisDetector->nOffset]; - for(int i=0;inOffset;i++) - offsetval[i] = -1; - } - if(thisDetector->myDetectorType == EIGER) - iodelay = new int;*iodelay=0; + int iodelay = -1; + int tau = -1; + string fn=fname; fn=fname; int mmin=0, mmax=setNumberOfModules(); @@ -6910,17 +7143,15 @@ int slsDetector::loadSettingsFile(string fname, int imod) { ostfn << ".sn" << setfill('0') << setw(3) << dec << getId(DETECTOR_SERIAL_NUMBER, im); fn=ostfn.str(); } - myMod=readSettingsFile(fn, thisDetector->myDetectorType,myMod,iodelay); + myMod=readSettingsFile(fn, thisDetector->myDetectorType,iodelay, tau, myMod); if (myMod) { myMod->module=im; //settings is saved in myMod.reg for all except mythen if(thisDetector->myDetectorType!=MYTHEN) - myMod->reg=thisDetector->currentSettings; - setModule(*myMod,gainval,offsetval,iodelay,tau); + myMod->reg=-1; + setModule(*myMod,iodelay,tau,-1,0,0); deleteModule(myMod); - if(gainval) delete[] gainval; - if(offsetval) delete[] offsetval; } else return FAIL; } @@ -6932,7 +7163,8 @@ int slsDetector::saveSettingsFile(string fname, int imod) { sls_detector_module *myMod=NULL; int ret=FAIL; - int *iod = 0; + int iodelay = -1; + int tau = -1; int mmin=0, mmax=setNumberOfModules(); if (imod>=0) { @@ -6948,10 +7180,10 @@ int slsDetector::saveSettingsFile(string fname, int imod) { if ((myMod=getModule(im))) { if(thisDetector->myDetectorType == EIGER){ - iod = new int; - *iod = (int)setDAC((dacs_t)-1,IO_DELAY,0,-1); + iodelay = (int)setDAC((dacs_t)-1,IO_DELAY,0,-1); + tau = (int64_t)getRateCorrectionTau(); } - ret=writeSettingsFile(ostfn.str(), thisDetector->myDetectorType, *myMod,iod); + ret=writeSettingsFile(ostfn.str(), thisDetector->myDetectorType, *myMod, iodelay, tau); deleteModule(myMod); } } @@ -6999,12 +7231,15 @@ int slsDetector::setAllTrimbits(int val, int imod){ int slsDetector::loadCalibrationFile(string fname, int imod) { + if(thisDetector->myDetectorType == EIGER) { + std::cout << "Not required for this detector!" << std::endl; + return FAIL; + } + sls_detector_module *myMod=NULL; string fn=fname; - int64_t tau = -1; int* gainval=0; int* offsetval=0; - int* iodelay=0; if(thisDetector->nGain){ gainval=new int[thisDetector->nGain]; for(int i=0;inGain;i++) @@ -7036,18 +7271,16 @@ int slsDetector::loadCalibrationFile(string fname, int imod) { } fn=ostfn.str(); if((myMod=getModule(im))){ - iodelay = new int; - *iodelay = (int)setDAC(-1,IO_DELAY,0); //extra gain and offset if(thisDetector->nGain){ - if(readCalibrationFile(fn,gainval, offsetval,tau, thisDetector->myDetectorType)==FAIL) + if(readCalibrationFile(fn, gainval, offsetval)==FAIL) return FAIL; } //normal gain and offset inside sls_detector_module else{ if(readCalibrationFile(fn,myMod->gain, myMod->offset)==FAIL) return FAIL; } - setModule(*myMod,gainval,offsetval,iodelay,tau); + setModule(*myMod,-1,-1,-1,gainval,offsetval); deleteModule(myMod); if(gainval) delete[]gainval; @@ -7079,7 +7312,7 @@ int slsDetector::saveCalibrationFile(string fname, int imod) { if ((myMod=getModule(im))) { //extra gain and offset if(thisDetector->nGain) - ret=writeCalibrationFile(ostfn.str(),gain, offset,(int64_t)thisDetector->tDead, thisDetector->myDetectorType); + ret=writeCalibrationFile(ostfn.str(),gain, offset); //normal gain and offset inside sls_detector_module else ret=writeCalibrationFile(ostfn.str(),myMod->gain, myMod->offset); @@ -7239,6 +7472,7 @@ string slsDetector::checkReceiverOnline() { return string(""); } } + return retval; } @@ -7349,7 +7583,7 @@ string slsDetector::setFilePath(string s) { pthread_mutex_unlock(&ms); } else if(!s.empty()){ - std::cout << "path does not exist" << endl; + std::cout << "file path does not exist" << endl; setErrorMask((getErrorMask())|(FILE_PATH_DOES_NOT_EXIST)); } if(ret==FORCE_UPDATE) @@ -7374,10 +7608,10 @@ string slsDetector::setFileName(string s) { if(!s.empty()){ pthread_mutex_lock(&ms); fileIO::setFileName(s); - if(thisDetector->myDetectorType == EIGER) + /*if(thisDetector->myDetectorType == EIGER) parentDet->setDetectorIndex(posId); else if(parentDet->getNumberOfDetectors()>1) - parentDet->setDetectorIndex(posId); + parentDet->setDetectorIndex(-1);*/ s=parentDet->createReceiverFilePrefix(); pthread_mutex_unlock(&ms); } @@ -7414,6 +7648,48 @@ string slsDetector::setFileName(string s) { +slsReceiverDefs::fileFormat slsDetector::setFileFormat(fileFormat f){ + int fnum=F_SET_RECEIVER_FILE_FORMAT; + int ret = FAIL; + int arg = -1; + int retval = -1; + + + + if(thisDetector->receiverOnlineFlag==OFFLINE_FLAG){ + if(f>=0){ + pthread_mutex_lock(&ms); + fileIO::setFileFormat(f); + pthread_mutex_unlock(&ms); + } + } + + else{ + arg = (int)f; +#ifdef VERBOSE + std::cout << "Sending file format to receiver " << arg << std::endl; +#endif + if (connectData() == OK){ + ret=thisReceiver->sendInt(fnum,retval,arg); + disconnectData(); + } + if(ret == FAIL) + setErrorMask((getErrorMask())|(RECEIVER_FILE_FORMAT)); + else{ + pthread_mutex_lock(&ms); + fileIO::setFileFormat(retval); + pthread_mutex_unlock(&ms); + if(ret==FORCE_UPDATE) + updateReceiver(); + } + } + + return fileIO::getFileFormat(); +} + + + + int slsDetector::setFileIndex(int i) { int fnum=F_SET_RECEIVER_FILE_INDEX; @@ -7478,9 +7754,13 @@ int slsDetector::startReceiver(){ setErrorMask((getErrorMask())|(COULDNOT_START_RECEIVER)); } } - //let detector prepare anyway even if receiver didnt work - if((thisDetector->myDetectorType !=JUNGFRAU)) - ret=detectorSendToReceiver(true); + + //let detector prepare anyway even if receiver didnt work (for those not using the receiver) + if((thisDetector->myDetectorType != JUNGFRAU)) { + int ret1 = detectorSendToReceiver(true); + if (ret != FAIL) + ret = ret1; + } return ret; } @@ -7542,8 +7822,8 @@ slsDetectorDefs::runStatus slsDetector::startReceiverReadout(){ int slsDetector::detectorSendToReceiver(bool set){ int fnum; - if(set) fnum=F_START_RECEIVER; - else fnum=F_STOP_RECEIVER; + if(set) fnum=F_PREPARE_ACQUISITION; + else fnum=F_CLEANUP_ACQUISITION; int ret = FAIL; char mess[MAX_STR_LENGTH]=""; @@ -7770,30 +8050,32 @@ string slsDetector::getReceiverLastClientIP(){ int slsDetector::updateReceiverNoWait() { - int n,ind; + int n = 0,ind; char path[MAX_STR_LENGTH]; char lastClientIP[INET_ADDRSTRLEN]; - n = dataSocket->ReceiveDataOnly(lastClientIP,sizeof(lastClientIP)); + n += dataSocket->ReceiveDataOnly(lastClientIP,sizeof(lastClientIP)); #ifdef VERBOSE cout << "Updating receiver last modified by " << lastClientIP << std::endl; #endif - n = dataSocket->ReceiveDataOnly(&ind,sizeof(ind)); + n += dataSocket->ReceiveDataOnly(&ind,sizeof(ind)); pthread_mutex_lock(&ms); fileIO::setFileIndex(ind); pthread_mutex_unlock(&ms); - n = dataSocket->ReceiveDataOnly(path,MAX_STR_LENGTH); + n += dataSocket->ReceiveDataOnly(path,MAX_STR_LENGTH); pthread_mutex_lock(&ms); fileIO::setFilePath(path); pthread_mutex_unlock(&ms); - n = dataSocket->ReceiveDataOnly(path,MAX_STR_LENGTH); + n += dataSocket->ReceiveDataOnly(path,MAX_STR_LENGTH); pthread_mutex_lock(&ms); fileIO::setFileName(path); pthread_mutex_unlock(&ms); + if (!n) printf("n: %d\n", n); + return OK; } @@ -8133,6 +8415,54 @@ int slsDetector::enableReceiverCompression(int i){ +void slsDetector::sendMultiDetectorSize(){ + int fnum=F_SEND_RECEIVER_MULTIDETSIZE; + int ret = FAIL; + int retval = -1; + int arg[2]; + + pthread_mutex_lock(&ms); + parentDet->getNumberOfDetectors(arg[0],arg[1]); + pthread_mutex_unlock(&ms); + + if(thisDetector->receiverOnlineFlag==ONLINE_FLAG){ +#ifdef VERBOSE + std::cout << "Sending multi detector size to Receiver (" << arg[0] << "," << arg[1] << ")" << std::endl; +#endif + if (connectData() == OK){ + ret=thisReceiver->sendIntArray(fnum,retval,arg); + disconnectData(); + } + if((ret==FAIL)){ + std::cout << "Could not set position Id" << std::endl; + setErrorMask((getErrorMask())|(RECEIVER_MULTI_DET_SIZE_NOT_SET)); + } + } +} + + +void slsDetector::setDetectorId(){ + int fnum=F_SEND_RECEIVER_DETPOSID; + int ret = FAIL; + int retval = -1; + int arg = posId; + + if(thisDetector->receiverOnlineFlag==ONLINE_FLAG){ +#ifdef VERBOSE + std::cout << "Sending detector pos id to Receiver " << posId << std::endl; +#endif + if (connectData() == OK){ + ret=thisReceiver->sendInt(fnum,retval,arg); + disconnectData(); + } + if((ret==FAIL) || (retval != arg)){ + std::cout << "Could not set position Id" << std::endl; + setErrorMask((getErrorMask())|(RECEIVER_DET_POSID_NOT_SET)); + } + } +} + + void slsDetector::setDetectorHostname(){ int fnum=F_SEND_RECEIVER_DETHOSTNAME; int ret = FAIL; @@ -8246,9 +8576,9 @@ int slsDetector::setReceiverFifoDepth(int i){ int slsDetector::setCTBPattern(string fname) { - int fnum=F_SET_CTB_PATTERN; - int ret = FAIL; - char retval[MAX_STR_LENGTH]=""; + //int fnum=F_SET_CTB_PATTERN; + //int ret = FAIL; + //char retval[MAX_STR_LENGTH]=""; // if(thisDetector->receiverOnlineFlag==ONLINE_FLAG){ diff --git a/slsDetectorSoftware/slsDetector/slsDetector.h b/slsDetectorSoftware/slsDetector/slsDetector.h index 9d22e51a5..951a70eb4 100644 --- a/slsDetectorSoftware/slsDetector/slsDetector.h +++ b/slsDetectorSoftware/slsDetector/slsDetector.h @@ -270,6 +270,7 @@ class slsDetector : public slsDetectorUtils, public energyConversion { /** flipped data across x or y axis */ int flippedData[2]; + } sharedSlsDetector; @@ -506,11 +507,12 @@ class slsDetector : public slsDetectorUtils, public energyConversion { \param fname name of the file to be written \param imod module number \param iodelay io delay (detector specific) + \param tau tau (detector specific) \returns OK or FAIL if the file could not be written \sa ::sls_detector_module sharedSlsDetector mythenDetector::writeSettingsFile(string, int) */ using energyConversion::writeSettingsFile; - int writeSettingsFile(string fname, int imod, int* iodelay=0); + int writeSettingsFile(string fname, int imod, int iodelay, int tau); /** @@ -958,14 +960,15 @@ class slsDetector : public slsDetectorUtils, public energyConversion { /** configure chip \param module module to be set - must contain correct module number and also channel and chip registers - \param gainval pointer to extra gain values - \param offsetval pointer to extra offset values \param iodelay iodelay (detector specific) \param tau tau (detector specific) + \param e_eV threashold in eV (detector specific) + \param gainval pointer to extra gain values + \param offsetval pointer to extra offset values \returns current register value \sa ::sls_detector_module */ - int setModule(sls_detector_module module, int* gainval, int* offsetval,int* iodelay, int64_t tau); + int setModule(sls_detector_module module, int iodelay, int tau, int e_eV, int* gainval=0, int* offsetval=0); //virtual int setModule(sls_detector_module module); /** @@ -999,6 +1002,14 @@ class slsDetector : public slsDetectorUtils, public energyConversion { \returns current threshold value for imod in ev (-1 failed) */ int setThresholdEnergy(int e_eV, int imod=-1, detectorSettings isettings=GET_SETTINGS); + + /** + set threshold energy + \param e_eV threshold in eV + \param isettings ev. change settings + \returns OK if successful, else FAIL + */ + int setThresholdEnergyAndSettings(int e_eV, detectorSettings isettings); /** get detector settings @@ -1548,6 +1559,13 @@ class slsDetector : public slsDetectorUtils, public energyConversion { */ string setFileName(string s=""); + /** + Sets up the file format + @param f file format + \returns file format + */ + fileFormat setFileFormat(fileFormat f=GET_FILE_FORMAT); + /** Sets up the file index @param i file index @@ -1565,6 +1583,11 @@ class slsDetector : public slsDetectorUtils, public energyConversion { */ string getFileName(){return setFileName();}; + /** + \returns file name + */ + fileFormat getFileFormat(){return setFileFormat();}; + /** \returns file index */ @@ -1742,7 +1765,17 @@ class slsDetector : public slsDetectorUtils, public energyConversion { */ int enableReceiverCompression(int i = -1); - /** send the detector host name to the eiger receiver + /** + * Send the multi detector size to the detector + */ + void sendMultiDetectorSize(); + + /** send the detector pos id to the receiver + * for various file naming conventions for multi detectors in receiver + */ + void setDetectorId(); + + /** send the detector host name to the receiver * for various handshaking required with the detector */ void setDetectorHostname(); diff --git a/slsDetectorSoftware/slsDetector/slsDetectorActions.cpp b/slsDetectorSoftware/slsDetector/slsDetectorActions.cpp index a9c3616a8..bdcc6cebd 100644 --- a/slsDetectorSoftware/slsDetector/slsDetectorActions.cpp +++ b/slsDetectorSoftware/slsDetector/slsDetectorActions.cpp @@ -75,10 +75,10 @@ int slsDetectorActions::setActionScript(int iaction, string fname) { int slsDetectorActions::setActionParameter(int iaction, string par) { - int am; + //int am; if (iaction>=0 && iactionsetFileName(string(args[1])); return string(myDet->getFileName()); - } else + } else if(cmd=="fileformat") { + if (action==PUT_ACTION){ + if (string(args[1])=="binary") + myDet->setFileFormat(BINARY); + else if (string(args[1])=="ascii") + myDet->setFileFormat(ASCII); + else if (string(args[1])=="hdf5") + myDet->setFileFormat(HDF5); + else return string("could not scan file format mode\n"); + } + return myDet->fileFormats(myDet->getFileFormat()); + } return string(myDet->getCurrentFileName()); } @@ -1968,10 +1983,14 @@ string slsDetectorCommand::cmdFileName(int narg, char *args[], int action){ string slsDetectorCommand::helpFileName(int narg, char *args[], int action){ ostringstream os; - if (action==GET_ACTION || action==HELP_ACTION) + if (action==GET_ACTION || action==HELP_ACTION){ os << string("fname \t gets the filename for the data without index and extension\n"); - if (action==PUT_ACTION || action==HELP_ACTION) + os << string("fileformat \t gets the file format for data\n"); + } + if (action==PUT_ACTION || action==HELP_ACTION){ os << string("fname s \t sets the filename for the data (index and extension will be automatically appended)\n"); + os << string("fname s \t sets the file format for the data (binary, ascii, hdf5)\n"); + } return os.str(); } @@ -2002,9 +2021,9 @@ string slsDetectorCommand::cmdEnablefwrite(int narg, char *args[], int action){ string slsDetectorCommand::helpEnablefwrite(int narg, char *args[], int action){ ostringstream os; if (action==GET_ACTION || action==HELP_ACTION) - os << string("When Enabled writes the data into the file\n"); + os << string("enablefwrite \t When Enabled writes the data into the file\n"); if (action==PUT_ACTION || action==HELP_ACTION) - os << string(" i \t should be 1 or 0 or -1\n"); + os << string("enablefwrite i \t should be 1 or 0 or -1\n"); return os.str(); } @@ -2034,9 +2053,9 @@ string slsDetectorCommand::cmdOverwrite(int narg, char *args[], int action){ string slsDetectorCommand::helpOverwrite(int narg, char *args[], int action){ ostringstream os; if (action==GET_ACTION || action==HELP_ACTION) - os << string("When Enabled overwrites files\n"); + os << string("overwrite \t When Enabled overwrites files\n"); if (action==PUT_ACTION || action==HELP_ACTION) - os << string(" i \t should be 1 or 0 or -1\n"); + os << string("overwrite i \t should be 1 or 0 or -1\n"); return os.str(); } @@ -2066,7 +2085,7 @@ string slsDetectorCommand::helpFileIndex(int narg, char *args[], int action){ if (action==GET_ACTION || action==HELP_ACTION) os << string("index \t gets the file index for the next the data file\n"); if (action==PUT_ACTION || action==HELP_ACTION) - os << string("fname i \t sets the fileindex for the next data file\n"); + os << string("index i \t sets the fileindex for the next data file\n"); return os.str(); } @@ -2942,7 +2961,7 @@ string slsDetectorCommand::helpNetworkParameter(int narg, char *args[], int acti os << "txndelay_left \n gets detector transmission delay of the left port"<< std::endl; os << "txndelay_right \n gets detector transmission delay of the right port"<< std::endl; os << "txndelay_frame \n gets detector transmission delay of the entire frame"<< std::endl; - os << "flowcontrol_10g \n sets flow control for 10g for eiger"<< std::endl; + os << "flowcontrol_10g \n gets flow control for 10g for eiger"<< std::endl; } return os.str(); @@ -3354,15 +3373,28 @@ string slsDetectorCommand::cmdSettings(int narg, char *args[], int action) { myDet->setOnline(ONLINE_FLAG); if (cmd=="settings") { - if (action==PUT_ACTION) - myDet->setSettings(myDet->getDetectorSettings(string(args[1]))); + detectorSettings sett = GET_SETTINGS; + if (action==PUT_ACTION) { + sett = myDet->setSettings(myDet->getDetectorSettings(string(args[1]))); + if (myDet->getDetectorsType() == EIGER) { + return myDet->getDetectorSettings(sett); + } + } return myDet->getDetectorSettings(myDet->getSettings()); } else if (cmd=="threshold") { if (action==PUT_ACTION) { - if (sscanf(args[1],"%d",&val)) - myDet->setThresholdEnergy(val); - else - return string("invalid threshold value ")+cmd; + detectorType type = myDet->getDetectorsType(); + if (!sscanf(args[1],"%d",&val)) { + return string("invalid threshold value"); + } + if (type != EIGER || (type == EIGER && narg<=2)) { + myDet->setThresholdEnergy(val); + } else { + detectorSettings sett= myDet->getDetectorSettings(string(args[2])); + if(sett == -1) + return string("invalid settings value"); + myDet->setThresholdEnergy(val, -1, sett); + } } sprintf(ans,"%d",myDet->getThresholdEnergy()); return string(ans); @@ -3489,7 +3521,11 @@ string slsDetectorCommand::cmdSN(int narg, char *args[], int action) { if (cmd=="thisversion"){ - sprintf(answer,"%llx",myDet->getId(THIS_SOFTWARE_VERSION)); + int64_t retval = myDet->getId(THIS_SOFTWARE_VERSION); + if (retval < 0) + sprintf(answer, "%d", -1); + else + sprintf(answer,"%lx", retval); return string(answer); } @@ -3499,37 +3535,61 @@ string slsDetectorCommand::cmdSN(int narg, char *args[], int action) { if (cmd=="moduleversion") { int ival=-1; if (sscanf(args[0],"moduleversion:%d",&ival)) { - sprintf(answer,"%llx",myDet->getId(MODULE_FIRMWARE_VERSION,ival)); + int64_t retval = myDet->getId(MODULE_FIRMWARE_VERSION, ival); + if (retval < 0) + sprintf(answer, "%d", -1); + else + sprintf(answer,"%lx", retval); return string(answer); } else return string("undefined module number"); } if (cmd=="detectornumber") { - sprintf(answer,"%llx",myDet->getId(DETECTOR_SERIAL_NUMBER)); + int64_t retval = myDet->getId(DETECTOR_SERIAL_NUMBER); + if (retval < 0) + sprintf(answer, "%d", -1); + else + sprintf(answer,"%lx", retval); return string(answer); } if (cmd.find("modulenumber")!=string::npos) { int ival=-1; if (sscanf(args[0],"modulenumber:%d",&ival)) { - sprintf(answer,"%llx",myDet->getId(MODULE_SERIAL_NUMBER,ival)); + int64_t retval = myDet->getId(MODULE_SERIAL_NUMBER, ival); + if (retval < 0) + sprintf(answer, "%d", -1); + else + sprintf(answer,"%lx", retval); return string(answer); } else return string("undefined module number"); } if (cmd=="detectorversion") { - sprintf(answer,"%llx",myDet->getId(DETECTOR_FIRMWARE_VERSION)); + int64_t retval = myDet->getId(DETECTOR_FIRMWARE_VERSION); + if (retval < 0) + sprintf(answer, "%d", -1); + else + sprintf(answer,"%lx", retval); return string(answer); } if (cmd=="softwareversion") { - sprintf(answer,"%llx",myDet->getId(DETECTOR_SOFTWARE_VERSION)); + int64_t retval = myDet->getId(DETECTOR_SOFTWARE_VERSION); + if (retval < 0) + sprintf(answer, "%d", -1); + else + sprintf(answer,"%lx", retval); return string(answer); } if (cmd=="receiverversion") { myDet->setReceiverOnline(ONLINE_FLAG); - sprintf(answer,"%llx",myDet->getId(RECEIVER_VERSION)); + int64_t retval = myDet->getId(RECEIVER_VERSION); + if (retval < 0) + sprintf(answer, "%d", -1); + else + sprintf(answer,"%lx", retval); return string(answer); } return string("unknown id mode ")+cmd; @@ -4022,13 +4082,13 @@ string slsDetectorCommand::helpDAC(int narg, char *args[], int action) { os << "dac0 " << "\t gets dac 0" << std::endl; - os << "dac1 " << "\t gets dac 0" << std::endl; - os << "dac2 " << "\t gets dac 0" << std::endl; - os << "dac3 " << "\t gets dac 0" << std::endl; - os << "dac4 " << "\t gets dac 0" << std::endl; - os << "dac5 " << "\t gets dac 0" << std::endl; - os << "dac6 " << "\t gets dac 0" << std::endl; - os << "dac7 " << "\t gets dac 0" << std::endl; + os << "dac1 " << "\t gets dac 1" << std::endl; + os << "dac2 " << "\t gets dac 2" << std::endl; + os << "dac3 " << "\t gets dac 3" << std::endl; + os << "dac4 " << "\t gets dac 4" << std::endl; + os << "dac5 " << "\t gets dac 5" << std::endl; + os << "dac6 " << "\t gets dac 6" << std::endl; + os << "dac7 " << "\t gets dac 7" << std::endl; os << "vsvp" << "dacu\t gets vsvp" << std::endl; os << "vsvn" << "dacu\t gets vsvn" << std::endl; @@ -4221,12 +4281,16 @@ string slsDetectorCommand::cmdTimer(int narg, char *args[], int action) { if (action==PUT_ACTION) { if (sscanf(args[1],"%lf", &val)) - ; + ;//printf("value:%0.9lf\n",val); else return string("cannot scan timer value ")+string(args[1]); - if (index==ACQUISITION_TIME || index==SUBFRAME_ACQUISITION_TIME || index==FRAME_PERIOD || index==DELAY_AFTER_TRIGGER) - t=(int64_t)(val*1E+9); - else t=(int64_t)val; + if (index==ACQUISITION_TIME || index==SUBFRAME_ACQUISITION_TIME || index==FRAME_PERIOD || index==DELAY_AFTER_TRIGGER) { + // t=(int64_t)(val*1E+9); for precision of eg.0.0000325, following done + val*=1E9; + t = (int64_t)val; + if(fabs(val-t)) // to validate precision loss + t = t + val - t; //even t += vak-t loses precision + }else t=(int64_t)val; } @@ -4595,7 +4659,7 @@ string slsDetectorCommand::cmdAdvanced(int narg, char *args[], int action) { if (action==GET_ACTION) return string("cannot get"); #ifdef VERBOSE - std::cout<< " resetting fpga " << sval << std::endl; + std::cout<< " resetting fpga " << std::endl; #endif myDet->setOnline(ONLINE_FLAG); if(myDet->resetFPGA() == OK) @@ -4645,13 +4709,18 @@ string slsDetectorCommand::helpAdvanced(int narg, char *args[], int action) { os << "programfpga f \t programs the fpga with file f (with .pof extension)." << std::endl; os << "resetfpga f \t resets fpga, f can be any value" << std::endl; + os << "led s \t sets led status (0 off, 1 on)" << std::endl; + os << "powerchip i \t powers on or off the chip. i = 1 for on, i = 0 for off" << std::endl; } if (action==GET_ACTION || action==HELP_ACTION) { os << "extsig:i \t gets the mode of the external signal i. can be \n \t \t \t off, \n \t \t \t gate_in_active_high, \n \t \t \t gate_in_active_low, \n \t \t \t trigger_in_rising_edge, \n \t \t \t trigger_in_falling_edge, \n \t \t \t ro_trigger_in_rising_edge, \n \t \t \t ro_trigger_in_falling_edge, \n \t \t \t gate_out_active_high, \n \t \t \t gate_out_active_low, \n \t \t \t trigger_out_rising_edge, \n \t \t \t trigger_out_falling_edge, \n \t \t \t ro_trigger_out_rising_edge, \n \t \t \t ro_trigger_out_falling_edge" << std::endl; + os << "flags \t gets the readout flags. can be none, storeinram, tot, continous, parallel, nonparallel, safe, digital, analog_digital, unknown" << std::endl; os << "led \t returns led status (0 off, 1 on)" << std::endl; + os << "flags \t gets the readout flags. can be none, storeinram, tot, continous, parallel, nonparallel, safe, unknown" << std::endl; + os << "powerchip \t gets if the chip has been powered on or off" << std::endl; } return os.str(); @@ -4988,7 +5057,7 @@ string slsDetectorCommand::cmdPattern(int narg, char *args[], int action) { else return string("Could not scan address (hexadecimal fomat) ")+string(args[1]); - if (sscanf(args[2],"%llx",&word)) + if (sscanf(args[2],"%lx",&word)) ; else return string("Could not scan value (hexadecimal fomat) ")+string(args[2]); @@ -5004,7 +5073,7 @@ string slsDetectorCommand::cmdPattern(int narg, char *args[], int action) { if (action==PUT_ACTION) { - if (sscanf(args[1],"%llx",&word)) + if (sscanf(args[1],"%lx",&word)) ; else return string("Could not scan value (hexadecimal fomat) ")+string(args[1]); @@ -5021,7 +5090,7 @@ string slsDetectorCommand::cmdPattern(int narg, char *args[], int action) { if (action==PUT_ACTION) { - if (sscanf(args[1],"%llx",&word)) + if (sscanf(args[1],"%lx",&word)) ; else return string("Could not scan value (hexadecimal fomat) ")+string(args[1]); @@ -5292,7 +5361,7 @@ string slsDetectorCommand::cmdPattern(int narg, char *args[], int action) { if (action==PUT_ACTION) { - if (sscanf(args[1],"%lld",&t)) + if (sscanf(args[1],"%ld",&t)) ; else return string("Could not scan wait time")+string(args[1]); @@ -5315,7 +5384,7 @@ string slsDetectorCommand::cmdPattern(int narg, char *args[], int action) { if (action==PUT_ACTION) { - if (sscanf(args[1],"%lld",&t)) + if (sscanf(args[1],"%ld",&t)) ; else return string("Could not scan wait time ")+string(args[1]); @@ -5333,7 +5402,7 @@ string slsDetectorCommand::cmdPattern(int narg, char *args[], int action) { } else if (cmd=="patwaittime2") { if (action==PUT_ACTION) { - if (sscanf(args[1],"%lld",&t)) + if (sscanf(args[1],"%ld",&t)) ; else return string("Could not scan wait time ")+string(args[1]); @@ -5521,13 +5590,12 @@ string slsDetectorCommand::cmdPulse(int narg, char *args[], int action) { } - return string(""); -/* + if(retval == OK) return string(" successful"); else return string(" failed"); - */ + } diff --git a/slsDetectorSoftware/slsDetector/slsDetectorUsers.cpp b/slsDetectorSoftware/slsDetector/slsDetectorUsers.cpp index 4bf4e9c90..7da1668c6 100644 --- a/slsDetectorSoftware/slsDetector/slsDetectorUsers.cpp +++ b/slsDetectorSoftware/slsDetector/slsDetectorUsers.cpp @@ -147,14 +147,6 @@ int slsDetectorUsers::setThresholdEnergy(int e_eV){ return myDetector->setThresholdEnergy(e_eV); } -int slsDetectorUsers::getBeamEnergy(){ - return 2*myDetector->getThresholdEnergy(); -} - -int slsDetectorUsers::setBeamEnergy(int e_eV){ - return 2*myDetector->setThresholdEnergy(e_eV/2); -} - double slsDetectorUsers::setExposureTime(double t, bool inseconds){ int64_t tms = (int64_t)(t * (1E+9)); if (t < 0) tms = -1; diff --git a/slsDetectorSoftware/slsDetector/slsDetectorUsers.h b/slsDetectorSoftware/slsDetector/slsDetectorUsers.h index 214661384..7c7ed1a18 100644 --- a/slsDetectorSoftware/slsDetector/slsDetectorUsers.h +++ b/slsDetectorSoftware/slsDetector/slsDetectorUsers.h @@ -302,19 +302,6 @@ class slsDetectorUsers */ int setThresholdEnergy(int e_eV); - /** - @short get beam energy -- only for dectris! - \returns current beam energy - */ - int getBeamEnergy(); - - - /** - @short set beam energy -- only for dectris! - \param e_eV beam in eV - \returns current beam energyin ev (-1 failed) - */ - int setBeamEnergy(int e_eV); /** @short set/get exposure time value diff --git a/slsDetectorSoftware/slsDetector/slsDetectorUtils.cpp b/slsDetectorSoftware/slsDetector/slsDetectorUtils.cpp index b9fde9e1a..2da38b73d 100644 --- a/slsDetectorSoftware/slsDetector/slsDetectorUtils.cpp +++ b/slsDetectorSoftware/slsDetector/slsDetectorUtils.cpp @@ -226,9 +226,6 @@ int slsDetectorUtils::acquire(int delflag){ for (int ip=0; ip0) { @@ -298,20 +295,27 @@ int slsDetectorUtils::acquire(int delflag){ //start receiver if(startReceiver() == FAIL) { - cout << "Start receiver failed " << endl; + cout << "Start receiver failed " << endl; stopReceiver(); *stoppedFlag=1; pthread_mutex_unlock(&mg);//cout << "unlock"<< endl; break; } +#ifdef VERBOSE cout << "Receiver started " << endl; +#endif pthread_mutex_unlock(&mg);//cout << "unlock"<< endl; + + //let processing thread listen to these packets + sem_post(&sem_newRTAcquisition); } #ifdef VERBOSE cout << "Acquiring " << endl; #endif startAndReadAll(); +#ifdef VERBOSE cout << "detector finished " << endl; +#endif #ifdef VERBOSE cout << "returned! " << endl; #endif @@ -802,7 +806,6 @@ int slsDetectorUtils::dumpDetectorSetup(string const fname, int level){ slsDetectorCommand *cmd; string names[100]; int nvar=0; - int nvar1=0; names[nvar++]="fname"; names[nvar++]="index"; @@ -882,6 +885,9 @@ int slsDetectorUtils::dumpDetectorSetup(string const fname, int level){ names[nvar++]="patnloop2"; names[nvar++]="patwait2"; names[nvar++]="patwaittime2"; + break; + default: + break; } @@ -912,7 +918,8 @@ int slsDetectorUtils::dumpDetectorSetup(string const fname, int level){ names[nvar++]="flatfield"; names[nvar++]="badchannels"; break; - + default: + break; } switch (getDetectorsType()) { @@ -920,7 +927,8 @@ int slsDetectorUtils::dumpDetectorSetup(string const fname, int level){ case MYTHEN: names[nvar++]="trimbits"; break; - + default: + break; } // char ext[100]; diff --git a/slsDetectorSoftware/slsDetector/slsDetectorUtils.h b/slsDetectorSoftware/slsDetector/slsDetectorUtils.h index 70f2cebfb..1309df04e 100644 --- a/slsDetectorSoftware/slsDetector/slsDetectorUtils.h +++ b/slsDetectorSoftware/slsDetector/slsDetectorUtils.h @@ -642,6 +642,13 @@ class slsDetectorUtils : public slsDetectorActions, public postProcessing { */ virtual string setFileName(string s="")=0; + /** + Sets up the file format + @param f file format + \returns file format + */ + virtual fileFormat setFileFormat(fileFormat f=GET_FILE_FORMAT)=0; + /** \returns file dir */ @@ -652,6 +659,11 @@ class slsDetectorUtils : public slsDetectorActions, public postProcessing { */ virtual string getFileName()=0; + /** + \returns file name + */ + virtual fileFormat getFileFormat()=0; + /** \returns frames caught by receiver */ diff --git a/slsDetectorSoftware/slsDetectorAnalysis/angularConversionStatic.cpp b/slsDetectorSoftware/slsDetectorAnalysis/angularConversionStatic.cpp index 43e5a4436..2e380323c 100644 --- a/slsDetectorSoftware/slsDetectorAnalysis/angularConversionStatic.cpp +++ b/slsDetectorSoftware/slsDetectorAnalysis/angularConversionStatic.cpp @@ -255,8 +255,8 @@ int angularConversionStatic::readAngularConversion( ifstream& infile, int nmod, angOff[nm].etilt=epitch; } - // cout << angOff[nm].center << " " << \ - // angOff[nm].r_conversion << " " << \ + // cout << angOff[nm].center << " " << + // angOff[nm].r_conversion << " " << // angOff[nm].offset << endl; } else diff --git a/slsDetectorSoftware/slsDetectorAnalysis/energyConversion.cpp b/slsDetectorSoftware/slsDetectorAnalysis/energyConversion.cpp index aa54cb2ed..57eee451b 100644 --- a/slsDetectorSoftware/slsDetectorAnalysis/energyConversion.cpp +++ b/slsDetectorSoftware/slsDetectorAnalysis/energyConversion.cpp @@ -69,85 +69,58 @@ int energyConversion::writeCalibrationFile(string fname, double gain, double off }; -int energyConversion::readCalibrationFile(string fname, int *gain, int *offset, int64_t &tau, detectorType myDetectorType){ - - +int energyConversion::readCalibrationFile(string fname, int *gain, int *offset){ string str; ifstream infile; double o,g; int ig=0; - switch (myDetectorType) { - case EIGER: - - - #ifdef VERBOSE - std::cout<< "Opening file "<< fname << std::endl; + std::cout<< "Opening file "<< fname << std::endl; #endif - infile.open(fname.c_str(), ios_base::in); - if (infile.is_open()) { - //get gain and offset - for (ig=0; ig<4; ig++) { - //while ( (getline(infile,str)) > -1) { - getline(infile,str); + infile.open(fname.c_str(), ios_base::in); + if (infile.is_open()) { + //get gain and offset + for (ig=0; ig<4; ig++) { + //while ( (getline(infile,str)) > -1) { + getline(infile,str); #ifdef VERBOSE - std::cout<< str << std::endl; + std::cout<< str << std::endl; #endif - istringstream ssstr(str); - ssstr >> o >> g; - offset[ig]=(int)(o*1000); - gain[ig]=(int)(g*1000); - // ig++; - if (ig>=4) - break; - } - //get tau - if (myDetectorType == EIGER) { - if(getline(infile,str)){ - istringstream ssstr(str); - ssstr >> tau; -#ifdef VERBOSE - std::cout<< "tau:" << tau << std::endl; -#endif - } - } - infile.close(); - cout << "Calibration file loaded: " << fname << endl; - } else { - cout << "Could not open calibration file: "<< fname << std::endl; - gain[0]=0; - offset[0]=0; -#ifndef MYROOT - return FAIL; -#endif - return -1; + istringstream ssstr(str); + ssstr >> o >> g; + offset[ig]=(int)(o*1000); + gain[ig]=(int)(g*1000); + // ig++; + if (ig>=4) + break; } + infile.close(); + cout << "Calibration file loaded: " << fname << endl; + } else { + cout << "Could not open calibration file: "<< fname << std::endl; + gain[0]=0; + offset[0]=0; #ifndef MYROOT - return OK; -#endif - return 0; - break; - default: - std::cout<< "Writing Calibration Files for this detector not defined\n" << std::endl; return FAIL; +#endif + return -1; } +#ifndef MYROOT + return OK; +#endif + return 0; }; -int energyConversion::writeCalibrationFile(string fname, int *gain, int *offset, int64_t tau, detectorType myDetectorType){ +int energyConversion::writeCalibrationFile(string fname, int *gain, int *offset){ //std::cout<< "Function not yet implemented " << std::endl; ofstream outfile; - switch (myDetectorType) { - case EIGER: - outfile.open (fname.c_str()); - // >> i/o operations here << if (outfile.is_open()) { for (int ig=0; ig<4; ig++) outfile << ((double)offset[ig]/1000) << " " << ((double)gain[ig]/1000) << std::endl; - outfile << tau << std::endl; } else { std::cout<< "Could not open calibration file "<< fname << " for writing" << std::endl; #ifndef MYROOT @@ -161,21 +134,53 @@ int energyConversion::writeCalibrationFile(string fname, int *gain, int *offset, return OK; #endif return 0; - break; - default: - std::cout<< "Writing Calibration Files for this detector not defined\n" << std::endl; - return FAIL; - } - }; + +slsDetectorDefs::sls_detector_module* energyConversion::interpolateTrim(detectorType myDetectorType, sls_detector_module* a, sls_detector_module* b, const int energy, const int e1, const int e2){ + // only implemented for eiger currently (in terms of which dacs) + if(myDetectorType != EIGER) { + printf("Interpolation of Trim values not implemented for this detector!\n"); + return NULL; + } + + sls_detector_module* myMod = createModule(myDetectorType); + enum eiger_DacIndex{SVP,VTR,VRF,VRS,SVN,VTGSTV,VCMP_LL,VCMP_LR,CAL,VCMP_RL,RXB_RB,RXB_LB,VCMP_RR,VCP,VCN,VIS}; + + //Copy other dacs + int num_dacs_to_copy = 10; + int dacs_to_copy[] = {SVP,VTR,VRS,SVN,VTGSTV,CAL,RXB_RB,RXB_LB,VCN,VIS}; + for (int i = 0; i < num_dacs_to_copy; ++i) { + if(a->dacs[dacs_to_copy[i]] != b->dacs[dacs_to_copy[i]]) { + deleteModule(myMod); + return NULL; + } + myMod->dacs[dacs_to_copy[i]] = a->dacs[dacs_to_copy[i]]; + } + + //Interpolate vrf, vcmp, vcp + int num_dacs_to_interpolate = 6; + int dacs_to_interpolate[] = {VRF,VCMP_LL,VCMP_LR,VCMP_RL,VCMP_RR,VCP}; + for (int i = 0; i < num_dacs_to_interpolate; ++i) { + myMod->dacs[dacs_to_interpolate[i]] = linearInterpolation(energy, e1, e2, + a->dacs[dacs_to_interpolate[i]], b->dacs[dacs_to_interpolate[i]]); + } + + //Interpolate all trimbits + for (int i = 0; inchan; i++) + myMod->chanregs[i] = linearInterpolation(energy, e1, e2, a->chanregs[i], b->chanregs[i]); + return myMod; +} + + + #ifndef MYROOT /* I/O */ -slsDetectorDefs::sls_detector_module* energyConversion::readSettingsFile(string fname, detectorType myDetectorType, sls_detector_module *myMod, int* iodelay){ +slsDetectorDefs::sls_detector_module* energyConversion::readSettingsFile(string fname, detectorType myDetectorType, int& iodelay, int& tau, sls_detector_module* myMod){ @@ -353,7 +358,7 @@ slsDetectorDefs::sls_detector_module* energyConversion::readSettingsFile(string infile.close(); strcpy(settingsFile,fname.c_str()); - cout << "Settings file loaded: " << settingsFile << endl; + printf("Settings file loaded: %s\n",settingsFile); return myMod; } @@ -365,12 +370,14 @@ slsDetectorDefs::sls_detector_module* energyConversion::readSettingsFile(string infile.open(myfname.c_str(),ifstream::binary); if (infile.is_open()) { infile.read((char*) myMod->dacs,sizeof(dacs_t)*(myMod->ndac)); - infile.read((char*) iodelay,sizeof(*iodelay)); + infile.read((char*)&iodelay,sizeof(iodelay)); + infile.read((char*)&tau,sizeof(tau)); infile.read((char*) myMod->chanregs,sizeof(int)*(myMod->nchan)); #ifdef VERBOSE for(int i=0;indac;i++) std::cout << "dac " << i << ":" << myMod->dacs[i] << std::endl; - std::cout << "iodelay:" << *iodelay << std::endl; + std::cout << "iodelay:" << iodelay << std::endl; + std::cout << "tau:" << tau << std::endl; #endif if(infile.eof()){ cout<(&iodelay), sizeof(iodelay)); + outfile.write(reinterpret_cast(&tau), sizeof(tau)); outfile.write((char*)mod.chanregs, sizeof(int)*(mod.nchan)); outfile.close(); return slsDetectorDefs::OK; } - std::cout<< "could not open SETTINGS file " << fname << std::endl; + printf("Could not open Settings file %s\n", fname.c_str()); return slsDetectorDefs::FAIL; default: diff --git a/slsDetectorSoftware/slsDetectorAnalysis/energyConversion.h b/slsDetectorSoftware/slsDetectorAnalysis/energyConversion.h index 027a78677..8aec3cb47 100644 --- a/slsDetectorSoftware/slsDetectorAnalysis/energyConversion.h +++ b/slsDetectorSoftware/slsDetectorAnalysis/energyConversion.h @@ -10,7 +10,7 @@ //#include "sls_receiver_defs.h" #include "sls_detector_defs.h" //#endif - +#include #include using namespace std; @@ -35,7 +35,9 @@ class energyConversion reads a calibration file \param fname file to be read \param gain reference to the gain variable - \offset reference to the offset variable + \param offset reference to the offset variable + \returns OK if successful, else FAIL or -1 + */ static int readCalibrationFile(string fname, double &gain, double &offset); @@ -44,36 +46,51 @@ class energyConversion \param fname file to be written \param gain \param offset + \returns OK if successful, else FAIL or -1 */ static int writeCalibrationFile(string fname, double gain, double offset); - - - /** reads a calibration file \param fname file to be read \param gain reference to the gain variable - \offset reference to the offset variable - \tau tau - \tau tau + \param offset reference to the offset variable + \returns OK if successful, else FAIL or -1 */ - static int readCalibrationFile(string fname, int *gain, int *offset, int64_t &tau, detectorType myDetectorType); + static int readCalibrationFile(string fname, int *gain, int *offset); /** writes a calibration file \param fname file to be written - \param gain - \param offset - \param tau + \param gain reference to the gain variable + \param offset reference to the offset variable + \returns OK if successful, else FAIL or -1 */ - static int writeCalibrationFile(string fname, int *gain, int *offset, int64_t tau, detectorType myDetectorType); - + static int writeCalibrationFile(string fname, int *gain, int *offset); + //Template function to do linear interpolation between two points + template + V linearInterpolation(const E x, const E x1, const E x2, const V y1, const V y2){ + double k = static_cast(y2-y1)/(x2-x1); + double m = y1-k*x1; + int y = round( k*x+m ); + return static_cast(y); + } + /** + * interpolates dacs and trimbits between 2 trim files + \param myDetectorType detector type (needed for which dacs that neeeds to be interpolated & which kept same) + \param a first module structure + \param b second module structure + \param energy energy to trim at + \param e1 reference trim value + \param e2 reference trim value + \returns the pointer to the module structure with interpolated values or NULL if error + */ + sls_detector_module* interpolateTrim(detectorType myDetectorType, sls_detector_module* a, sls_detector_module* b, const int energy, const int e1, const int e2); @@ -83,12 +100,13 @@ class energyConversion reads a trim/settings file \param fname name of the file to be read \param myDetectorType detector type (needed for number of channels, chips, dacs etc.) - \param myMod pointer to the module structure which has to be set.
If it is NULL a new module structure will be created \param iodelay io delay (detector specific) + \param tau tau (detector specific) + \param myMod pointer to the module structure which has to be set.
If it is NULL a new module structure will be created \returns the pointer to myMod or NULL if reading the file failed */ - sls_detector_module* readSettingsFile(string fname, detectorType myDetectorType, sls_detector_module* myMod=NULL, int* iodelay=0); + sls_detector_module* readSettingsFile(string fname, detectorType myDetectorType, int& iodelay, int& tau, sls_detector_module* myMod=NULL); /** writes a trim/settings file @@ -96,11 +114,12 @@ class energyConversion \param myDetectorType detector type (needed for number of channels, chips, dacs etc.) \param mod module structure which has to be written to file \param iodelay io delay (detector specific) + \param tau tau (detector specific) \returns OK or FAIL if the file could not be written \sa ::sls_detector_module mythenDetector::writeSettingsFile(string, sls_detector_module) */ - int writeSettingsFile(string fname, detectorType myDetectorType, sls_detector_module mod, int* iodelay=0); + int writeSettingsFile(string fname, detectorType myDetectorType, sls_detector_module mod, int iodelay, int tau); /** allocates the momery for a detector module structure \param myDetectorType detector type (needed for number of channels, chips, dacs etc.) @@ -114,6 +133,7 @@ class energyConversion */ virtual void deleteModule(sls_detector_module *myMod)=0; + protected: /** pointer to settings file name */ char *settingsFile; diff --git a/slsDetectorSoftware/slsDetectorAnalysis/fileIO.h b/slsDetectorSoftware/slsDetectorAnalysis/fileIO.h index 7091eb388..fa486e7df 100644 --- a/slsDetectorSoftware/slsDetectorAnalysis/fileIO.h +++ b/slsDetectorSoftware/slsDetectorAnalysis/fileIO.h @@ -92,6 +92,15 @@ class fileIO : public fileIOStatic, public virtual slsDetectorBase { */ virtual int setDetectorIndex(int i) {detIndex=i;return detIndex;}; + /** + sets the default file format + \param i file format to be set + \returns actual file frame format + */ + virtual fileFormat setFileFormat(int i) {*fileFormatType=(fileFormat)i; return *fileFormatType;}; + + + /** \returns the output files path @@ -127,6 +136,11 @@ class fileIO : public fileIOStatic, public virtual slsDetectorBase { */ virtual int getFramesPerFile() {return *framesPerFile;}; + /** + \returns the max frames per file + */ + virtual fileFormat getFileFormat() {return *fileFormatType;}; + string createFileName(); @@ -306,8 +320,8 @@ yes */ int detIndex; /** frames per file */ int *framesPerFile; - - // int *fileFormat; + /** file format */ + fileFormat *fileFormatType; private: diff --git a/slsDetectorSoftware/slsDetectorAnalysis/fileIOStatic.h b/slsDetectorSoftware/slsDetectorAnalysis/fileIOStatic.h index 178f4b9b0..ae909b06b 100644 --- a/slsDetectorSoftware/slsDetectorAnalysis/fileIOStatic.h +++ b/slsDetectorSoftware/slsDetectorAnalysis/fileIOStatic.h @@ -534,9 +534,7 @@ class fileIOStatic { static int readDataFile(int nch, string fname, double *data, double *err=NULL, double *ang=NULL, char dataformat='f') { \ ifstream infile; \ int iline=0; \ - int maxchans; \ string str; \ - maxchans=nch; \ infile.open(fname.c_str(), ios_base::in); \ if (infile.is_open()) { \ iline=readDataFile(nch, infile, data, err, ang, dataformat, 0); \ diff --git a/slsDetectorSoftware/slsDetectorAnalysis/postProcessing.cpp b/slsDetectorSoftware/slsDetectorAnalysis/postProcessing.cpp index a3d8720e7..5eef5d150 100644 --- a/slsDetectorSoftware/slsDetectorAnalysis/postProcessing.cpp +++ b/slsDetectorSoftware/slsDetectorAnalysis/postProcessing.cpp @@ -38,7 +38,7 @@ int postProcessing::kbhit(){ } -postProcessing::postProcessing(): expTime(NULL), ang(NULL), val(NULL), err(NULL), numberOfChannels(0), badChannelMask(NULL){ +postProcessing::postProcessing(): expTime(NULL), badChannelMask(NULL), ang(NULL), val(NULL), err(NULL), numberOfChannels(0) { pthread_mutex_t mp1 = PTHREAD_MUTEX_INITIALIZER; mp=mp1; pthread_mutex_init(&mp, NULL); @@ -433,10 +433,9 @@ void* postProcessing::processData(int delflag) { int *myData; - char *p; int dum=1; - int nf=1, ii, nch; - int jctb=0; +// int nf=1, ii, nch; +// int jctb=0; // if (getDetectorsType()==JUNGFRAUCTB) { @@ -467,7 +466,7 @@ void* postProcessing::processData(int delflag) { // if (jctb) { -// p=(char*)myData; +// char* p=(char*)myData; // for (ii=0; ii -#define BUF_SIZE (16*1024*1024) //16mb +#define FILE_BUF_SIZE (16*1024*1024) //16mb #define HEADER_SIZE_NUM_FRAMES 2 #define HEADER_SIZE_NUM_PACKETS 1 @@ -206,7 +206,7 @@ int singlePhotonFilter::initTree(){ closeFile(); sprintf(savefilename, "%s/%s_f%012d_%d.raw", filePath,fileName,nTotalHits,fileIndex); myFile = fopen(savefilename, "w"); - setvbuf(myFile,NULL,_IOFBF,BUF_SIZE); + setvbuf(myFile,NULL,_IOFBF,FILE_BUF_SIZE); cout<<"File created: "< +#include //FILE @@ -18,33 +19,176 @@ Here are the definitions, but the actual implementation should be done for each ****************************************************/ - -void getModuleConfiguration(); -int initDetector(); -int initDetectorStop(); - -int setNMod(int nm, enum dimension dim); -int getNModBoard(enum dimension arg); - -int64_t getModuleId(enum idMode arg, int imod); -int64_t getDetectorId(enum idMode arg); -int getDetectorNumber(); -u_int64_t getDetectorMAC(); -int getDetectorIP(); - -int moduleTest( enum digitalTestMode arg, int imod); -int detectorTest( enum digitalTestMode arg); - - -void setDAC(enum detDacIndex ind, int val, int imod, int mV, int retval[]); -int getADC(enum detAdcIndex ind, int imod); - - -#if defined(EIGERD) || defined(GOTTHARD) -int setHighVoltage(int val, int imod); +// basic tests +void checkFirmwareCompatibility(); +#ifdef JUNGFRAUD +int checkType(); +u_int32_t testFpga(void); +int testBus(void); #endif +#if defined(MYTHEND) || defined(JUNGFRAUD) +int moduleTest( enum digitalTestMode arg, int imod); +int detectorTest( enum digitalTestMode arg); +#endif + +// Ids +int64_t getDetectorId(enum idMode arg); +u_int64_t getFirmwareVersion(); +#ifdef MYTHEND +int64_t getModuleId(enum idMode arg, int imod); +#elif JUNGFRAUD +u_int16_t getHardwareVersionNumber(); +u_int16_t getHardwareSerialNumber(); +#endif +u_int32_t getDetectorNumber(); +u_int64_t getDetectorMAC(); +u_int32_t getDetectorIP(); + + +// initialization +void initControlServer(); +void initStopServer(); #ifdef EIGERD +void getModuleConfiguration(); +#endif +#ifdef JUNGFRAUD +int mapCSP0(void); +void bus_w16(u_int32_t offset, u_int16_t data); +u_int16_t bus_r16(u_int32_t offset); +void bus_w(u_int32_t offset, u_int32_t data); +u_int32_t bus_r(u_int32_t offset); +int64_t set64BitReg(int64_t value, int aLSB, int aMSB); +int64_t get64BitReg(int aLSB, int aMSB); +void defineGPIOpins(); +void resetFPGA(); +void FPGAdontTouchFlash(); +void FPGATouchFlash(); +#endif + +// set up detector +void allocateDetectorStructureMemory(); +void setupDetector(); + + +// advanced read/write reg +#ifndef EIGERD +u_int32_t writeRegister(u_int32_t offset, u_int32_t data); +u_int32_t readRegister(u_int32_t offset); +#endif + + +// firmware functions (resets) +#ifdef JUNGFRAUD +int powerChip (int on); +void cleanFifos(); +void resetCore(); +void resetPeripheral(); +int adcPhase(int st); +int getPhase(); +#endif + +// parameters - nmod, dr, roi +int setNMod(int nm, enum dimension dim); // mythen specific, but for detector compatibility as a get +int getNModBoard(enum dimension arg); // mythen specific, but for detector compatibility as a get +int setDynamicRange(int dr); +#ifdef GOTTHARD +int setROI(int n, ROI arg[], int *retvalsize, int *ret); +#endif + +// parameters - readout +int setSpeed(enum speedVariable arg, int val); +#if defined(EIGERD) || defined(MYTHEND) +enum readOutFlags setReadOutFlags(enum readOutFlags val); +#endif +#ifdef MYTHEND +int executeTrimming(enum trimMode mode, int par1, int par2, int imod); +#endif + +// parameters - timer +int64_t setTimer(enum timerIndex ind, int64_t val); +#ifndef EIGERD +int64_t getTimeLeft(enum timerIndex ind); +#endif + + +// parameters - channel, chip, module, settings +#ifdef MYTHEND +int setChannel(sls_detector_channel myChan); +int getChannel(sls_detector_channel *myChan); +int setChip(sls_detector_chip myChip); +int getChip(sls_detector_chip *myChip); +#endif +#ifdef EIGERD +int setModule(sls_detector_module myMod, int delay); +#else +int setModule(sls_detector_module myMod); +#endif +int getModule(sls_detector_module *myMod); +enum detectorSettings setSettings(enum detectorSettings sett, int imod); +enum detectorSettings getSettings(); + + +// parameters - threshold +#if defined(MYTHEND) || defined(EIGERD) +int getThresholdEnergy(int imod); +int setThresholdEnergy(int ev, int imod); +#endif + +// parameters - dac, adc, hv +#ifdef JUNGFRAUD +void serializeToSPI(u_int32_t addr, u_int32_t val, u_int16_t csmask, int numbitstosend, u_int16_t clkmask, u_int16_t digoutmask, int digofset); +void initDac(int dacnum); +void prepareADC(); +void setAdc(int addr, int val); +int voltageToDac(int value); +int dacToVoltage(unsigned int digital); +#endif +void setDAC(enum DACINDEX ind, int val, int imod, int mV, int retval[]); +int getADC(enum ADCINDEX ind, int imod); +#ifndef MYTHEND +int setHighVoltage(int val); +#endif + + + +// parameters - timing, extsig +#ifdef MYTHEND +enum externalSignalFlag getExtSignal(int signalindex); +enum externalSignalFlag setExtSignal(int signalindex, enum externalSignalFlag flag); +#endif +enum externalCommunicationMode setTiming( enum externalCommunicationMode arg); + +// configure mac +#ifdef JUNGFRAUD +long int calcChecksum(int sourceip, int destip); +#endif +#ifndef MYTHEND +int configureMAC(uint32_t destip, uint64_t destmac, uint64_t sourcemac, uint32_t sourceip, uint32_t udpport, uint32_t udpport2, int ival); +#endif + + +// very detector specific + +// gotthard specific - image, pedestal +#ifdef GOTTHARDD +int loadImage(enum imageType index, char *imageVals); +int readCounterBlock(int startACQ, char *counterVals); +int resetCounterBlock(int startACQ); +int calibratePedestal(int frames); + +// jungfrau specific - pll, flashing firmware +#elif JUNGFRAUD +void resetPLL(); +u_int32_t setPllReconfigReg(u_int32_t reg, u_int32_t val); +void configurePll(); +void eraseFlash(); +int startWritingFPGAprogram(FILE** filefp); +int stopWritingFPGAprogram(FILE* filefp); +int writeFPGAProgram(char* fpgasrc, size_t fsize, FILE* filefp); + +// eiger specific - iodelay, 10g, pulse, rate, temp, activate, delay nw parameter +#elif EIGERD int setIODelay(int val, int imod); int enableTenGigabitEthernet(int val); int setCounterBit(int val); @@ -56,82 +200,39 @@ int getRateCorrectionEnable(); int getDefaultSettingsTau_in_nsec(); void setDefaultSettingsTau_in_nsec(int t); int64_t getCurrentTau(); -#endif - -#if defined(MYTHEND) || defined(GOTTHARDD) -u_int32_t writeRegister(u_int32_t offset, u_int32_t data); -u_int32_t readRegister(u_int32_t offset); -#endif - -#ifdef MYTHEND -int setChannel(sls_detector_channel myChan); -int getChannel(sls_detector_channel *myChan); -int setChip(sls_detector_chip myChip); -int getChip(sls_detector_chip *myChip); +void setExternalGating(int enable[]); +int setAllTrimbits(int val); +int getAllTrimbits(); +int getBebFPGATemp(); +int activate(int enable); +int setNetworkParameter(enum NETWORKINDEX mode, int value); #endif -#ifdef EIGERD -int setModule(sls_detector_module myMod, int* gain, int* offset,int* delay); -int getModule(sls_detector_module *myMod, int* gain, int* offset); -#else -int setModule(sls_detector_module myMod); -int getModule(sls_detector_module *myMod); + + +// aquisition +#if defined(EIGERD) || defined(GOTTHARD) +int prepareAcquisition(); #endif - - -enum detectorSettings setSettings(enum detectorSettings sett, int imod); -enum detectorSettings getSettings(); - -#if defined(MYTHEND) || defined(EIGERD) -int getThresholdEnergy(int imod); -int setThresholdEnergy(int ev, int imod); -#endif - int startStateMachine(); int stopStateMachine(); +#ifndef JUNGFRAUD int startReadOut(); +#endif enum runStatus getRunStatus(); void readFrame(int *ret, char *mess); - - -int64_t setTimer(enum timerIndex ind, int64_t val); -int64_t getTimeLeft(enum timerIndex ind); - - -int setDynamicRange(int dr); -int setROI(int n, ROI arg[], int *retvalsize, int *ret); - - -#if defined(EIGERD) || defined(MYTHEND) -enum readOutFlags setReadOutFlags(enum readOutFlags val); -int setSpeed(enum speedVariable arg, int val); -int executeTrimming(enum trimMode mode, int par1, int par2, int imod); +#ifdef JUNGFRAUD +u_int32_t runBusy(void); #endif -#ifndef MYTHEND -int configureMAC(int ipad, long long int macad, long long int detectormacadd, int detipad, int udpport, int udpport2, int ival); -#endif - -#ifdef GOTTHARDD -int loadImage(enum imageType index, char *imageVals); -int readCounterBlock(int startACQ, char *counterVals); -int resetCounterBlock(int startACQ); -int startReceiver(int d); -int calibratePedestal(int frames); -#endif - - - - +//common int copyModule(sls_detector_module *destMod, sls_detector_module *srcMod); - int calculateDataBytes(); int getTotalNumberOfChannels(); int getTotalNumberOfChips(); int getTotalNumberOfModules(); -int getNumberOfChannelsPerChip(); int getNumberOfChannelsPerModule(); int getNumberOfChipsPerModule(); int getNumberOfDACsPerModule(); @@ -140,26 +241,13 @@ int getNumberOfADCsPerModule(); int getNumberOfGainsPerModule(); int getNumberOfOffsetsPerModule(); #endif +int getNumberOfChannelsPerChip(); -enum externalSignalFlag getExtSignal(int signalindex); -enum externalSignalFlag setExtSignal(int signalindex, enum externalSignalFlag flag); -enum externalCommunicationMode setTiming( enum externalCommunicationMode arg); +// sync enum masterFlags setMaster(enum masterFlags arg); enum synchronizationMode setSynchronization(enum synchronizationMode arg); -#ifdef EIGERD -int startReceiver(int d); -void setExternalGating(int enable[]); -void setAllTrimbits(int val); -int getAllTrimbits(); -int getBebFPGATemp(); -int activate(int enable); -int setNetworkParameter(enum detNetworkParameter mode, int value); -#endif #endif - - - #endif diff --git a/slsDetectorSoftware/slsDetectorServer/slsDetectorServer.c b/slsDetectorSoftware/slsDetectorServer/slsDetectorServer.c index f3f9b2631..4a59e28c1 100755 --- a/slsDetectorSoftware/slsDetectorServer/slsDetectorServer.c +++ b/slsDetectorSoftware/slsDetectorServer/slsDetectorServer.c @@ -9,6 +9,7 @@ #include #include +#include extern int sockfd; @@ -23,38 +24,45 @@ int main(int argc, char *argv[]){ int retval=OK; int sd, fd; + // if socket crash, ignores SISPIPE, prevents global signal handler + // subsequent read/write to socket gives error - must handle locally + signal(SIGPIPE, SIG_IGN); + + #ifdef STOP_SERVER char cmd[100]; #endif if (argc==1) { - - checkFirmwareCompatibility(); -//#endif portno = DEFAULT_PORTNO; - printf("opening control server on port %d\n",portno ); + cprintf(BLUE, + "********************************************************\n" + "********* opening control server on port %d **********\n" + "********************************************************\n\n" + , portno); b=1; + basictests(); #ifdef STOP_SERVER sprintf(cmd,"%s %d &",argv[0],DEFAULT_PORTNO+1); system(cmd); #endif } else { portno = DEFAULT_PORTNO+1; - if ( sscanf(argv[1],"%d",&portno) ==0) { + if ( sscanf(argv[1],"%d",&portno) == 0) { printf("could not open stop server: unknown port\n"); return 1; } - printf("opening stop server on port %d\n",portno); + cprintf(BLUE, + "********************************************************\n" + "*********** opening stop server on port %d ***********\n" + "********************************************************\n\n" + , portno); b=0; } -//#endif - init_detector(b); //defined in slsDetectorServer_funcs sd=bindSocket(portno); //defined in communication_funcs - sockfd=sd; - if (getServerError(sd)) { //defined in communication_funcs printf("server error!\n"); return -1; diff --git a/slsDetectorSoftware/slsDetectorServer/slsDetectorServer_defs.h b/slsDetectorSoftware/slsDetectorServer/slsDetectorServer_defs.h index 488dc0a0f..02e45004a 100644 --- a/slsDetectorSoftware/slsDetectorServer/slsDetectorServer_defs.h +++ b/slsDetectorSoftware/slsDetectorServer/slsDetectorServer_defs.h @@ -11,27 +11,21 @@ #include "sls_detector_defs.h" #include -#define GOODBYE -200 - - -/* examples*/ -#ifdef JUNGFRAU_DHANYA -#define NCHAN (256*256) -#define NCHIP 8 -#define NADC 0 -#else -#define NCHAN 1 -#define NCHIP 1 -#define NDAC 1 -#define NADC 1 -#endif - -#define NMAXMODX 1 -#define NMAXMODY 1 -#define NMAXMOD NMAXMODX*NMAXMODY -#define NCHANS NCHAN*NCHIP*NMAXMOD -#define NDACS NDAC*NMAXMOD +/** This is only an example file!!! */ +/* +#define GOODBYE (-200) +enum DAC_INDEX {examplesdac} + Hardware Definitions +#define NMAXMOD (1) +#define NMOD (1) +#define NCHAN (256 * 256) +#define NCHIP (4) +#define NADC (0) +#define NDAC (16) +#define NGAIN (0) +#define NOFFSET (0) +*/ #endif /* SLSDETECTORSERVER_DEFS_H_ */ diff --git a/slsDetectorSoftware/slsDetectorServer/slsDetectorServer_funcs.c b/slsDetectorSoftware/slsDetectorServer/slsDetectorServer_funcs.c index b41c65a73..8fd8934b1 100755 --- a/slsDetectorSoftware/slsDetectorServer/slsDetectorServer_funcs.c +++ b/slsDetectorSoftware/slsDetectorServer/slsDetectorServer_funcs.c @@ -3,23 +3,21 @@ #include "slsDetectorServer_funcs.h" #include "slsDetectorFunctionList.h" #include "communication_funcs.h" - +#include "slsDetectorServer_defs.h" #include #include - #include -int sockfd; + + +// Global variables + extern int lockStatus; extern char lastClientIP[INET_ADDRSTRLEN]; extern char thisClientIP[INET_ADDRSTRLEN]; extern int differentClients; - - -// Global variables -int (*flist[256])(int); -//defined in the detector specific file +//defined in the detector specific Makefile #ifdef MYTHEND const enum detectorType myDetectorType=MYTHEN; #elif GOTTHARDD @@ -28,75 +26,47 @@ const enum detectorType myDetectorType=GOTTHARD; const enum detectorType myDetectorType=EIGER; #elif PICASSOD const enum detectorType myDetectorType=PICASSO; +#elif MOENCHD +const enum detectorType myDetectorType=MOENCH; +#elif JUNGFRAUD +const enum detectorType myDetectorType=JUNGFRAU; #else const enum detectorType myDetectorType=GENERIC; #endif -extern enum detectorSettings thisSettings; - -//global variables for optimized readout +int sockfd; // (updated in slsDetectorServer) as extern +int (*flist[NUM_DET_FUNCTIONS])(int); char mess[MAX_STR_LENGTH]; -int dataret; -//extern int dataBytes = 10; +/* initialization functions */ -void checkFirmwareCompatibility(){ - int64_t fwversion = getDetectorId(DETECTOR_FIRMWARE_VERSION); - int64_t swversion = getDetectorId(DETECTOR_SOFTWARE_VERSION); - int64_t sw_fw_apiversion = getDetectorId(SOFTWARE_FIRMWARE_API_VERSION); +int printSocketReadError() { + cprintf(BG_RED, "Error reading from socket. Possible socket crash\n"); + return FAIL; +} - cprintf(BLUE,"\n\n********************************************************\n" - "**********************EIGER Server**********************\n" - "********************************************************\n"); - cprintf(BLUE,"\n" - "Firmware Version:\t\t %lld\n" - "Software Version:\t\t %llx\n" - "F/w-S/w API Version:\t\t %lld\n" - "Required Firmware Version:\t %d\n" - "\n********************************************************\n", - fwversion,swversion,sw_fw_apiversion,REQUIRED_FIRMWARE_VERSION); - - //cant read versions - if(!fwversion || !sw_fw_apiversion){ - cprintf(RED,"FATAL ERROR: Cant read versions from FPGA. Please update firmware\n"); - cprintf(RED,"Exiting Server. Goodbye!\n\n"); - exit(-1); - } - - //check for API compatibility - old server - if(sw_fw_apiversion > REQUIRED_FIRMWARE_VERSION){ - cprintf(RED,"FATAL ERROR: This software version is incompatible.\n" - "Please update it to be compatible with this firmware\n\n"); - cprintf(RED,"Exiting Server. Goodbye!\n\n"); - exit(-1); - } - - //check for firmware compatibility - old firmware - if( REQUIRED_FIRMWARE_VERSION > fwversion){ - cprintf(RED,"FATAL ERROR: This firmware version is incompatible.\n" - "Please update it to v%d to be compatible with this server\n\n", REQUIRED_FIRMWARE_VERSION); - cprintf(RED,"Exiting Server. Goodbye!\n\n"); - exit(-1); - } +void basictests() { +#ifdef SLS_DETECTOR_FUNCTION_LIST + checkFirmwareCompatibility(); +#endif } -int init_detector(int b) { +void init_detector(int controlserver) { #ifdef VIRTUAL printf("This is a VIRTUAL detector\n"); #endif - #ifdef SLS_DETECTOR_FUNCTION_LIST - if(b) initDetector(); - else initDetectorStop(); + if (controlserver) + initControlServer(); + else initStopServer(); #endif strcpy(mess,"dummy message"); strcpy(lastClientIP,"none"); strcpy(thisClientIP,"none1"); lockStatus=0; - return OK; } @@ -104,12 +74,12 @@ int decode_function(int file_des) { int fnum,n; int ret=FAIL; #ifdef VERBOSE - printf( "receive data\n"); + printf( "\nreceive data\n"); #endif n = receiveData(file_des,&fnum,sizeof(fnum),INT32); if (n <= 0) { #ifdef VERBOSE - printf("ERROR reading from socket %d, %d %d\n", n, fnum, file_des); + printf("ERROR reading from socket %d, %d %d (%s)\n", n, fnum, file_des, getFunctionName((enum detFuncs)fnum)); #endif return FAIL; } @@ -119,1035 +89,840 @@ int decode_function(int file_des) { #endif #ifdef VERBOSE - printf( "calling function fnum = %d %x\n",fnum,(unsigned int)flist[fnum]); + printf(" calling function fnum=%d, (%s) located at 0x%x\n", fnum, getFunctionName((enum detFuncs)fnum), (unsigned int)flist[fnum]); #endif - if (fnum<0 || fnum>255) - fnum=255; - ret=(*flist[fnum])(file_des); - if (ret==FAIL) - cprintf( RED, "Error executing the function = %d \n",fnum); + if (fnum<0 || fnum>=NUM_DET_FUNCTIONS) { + cprintf(BG_RED,"Unknown function enum %d\n", fnum); + ret=(M_nofunc)(file_des); + }else + ret=(*flist[fnum])(file_des); + if (ret == FAIL) + cprintf(RED, "Error executing the function = %d (%s)\n", fnum, getFunctionName((enum detFuncs)fnum)); return ret; } -int function_table() { - int i; - for (i=0;i<256;i++){ - flist[i]=&M_nofunc; +const char* getFunctionName(enum detFuncs func) { + switch (func) { + case F_EXEC_COMMAND: return "F_EXEC_COMMAND"; + case F_GET_ERROR: return "F_GET_ERROR"; + case F_GET_DETECTOR_TYPE: return "F_GET_DETECTOR_TYPE"; + case F_SET_NUMBER_OF_MODULES: return "F_SET_NUMBER_OF_MODULES"; + case F_GET_MAX_NUMBER_OF_MODULES: return "F_GET_MAX_NUMBER_OF_MODULES"; + case F_SET_EXTERNAL_SIGNAL_FLAG: return "F_SET_EXTERNAL_SIGNAL_FLAG"; + case F_SET_EXTERNAL_COMMUNICATION_MODE: return "F_SET_EXTERNAL_COMMUNICATION_MODE"; + case F_GET_ID: return "F_GET_ID"; + case F_DIGITAL_TEST: return "F_DIGITAL_TEST"; + case F_ANALOG_TEST: return "F_ANALOG_TEST"; + case F_ENABLE_ANALOG_OUT: return "F_ENABLE_ANALOG_OUT"; + case F_CALIBRATION_PULSE: return "F_CALIBRATION_PULSE"; + case F_SET_DAC: return "F_SET_DAC"; + case F_GET_ADC: return "F_GET_ADC"; + case F_WRITE_REGISTER: return "F_WRITE_REGISTER"; + case F_READ_REGISTER: return "F_READ_REGISTER"; + case F_WRITE_MEMORY: return "F_WRITE_MEMORY"; + case F_READ_MEMORY: return "F_READ_MEMORY"; + case F_SET_CHANNEL: return "F_SET_CHANNEL"; + case F_GET_CHANNEL: return "F_GET_CHANNEL"; + case F_SET_ALL_CHANNELS: return "F_SET_ALL_CHANNELS"; + case F_SET_CHIP: return "F_SET_CHIP"; + case F_GET_CHIP: return "F_GET_CHIP"; + case F_SET_ALL_CHIPS: return "F_SET_ALL_CHIPS"; + case F_SET_MODULE: return "F_SET_MODULE"; + case F_GET_MODULE: return "F_GET_MODULE"; + case F_SET_ALL_MODULES: return "F_SET_ALL_MODULES"; + case F_SET_SETTINGS: return "F_SET_SETTINGS"; + case F_GET_THRESHOLD_ENERGY: return "F_GET_THRESHOLD_ENERGY"; + case F_SET_THRESHOLD_ENERGY: return "F_SET_THRESHOLD_ENERGY"; + case F_START_ACQUISITION: return "F_START_ACQUISITION"; + case F_STOP_ACQUISITION: return "F_STOP_ACQUISITION"; + case F_START_READOUT: return "F_START_READOUT"; + case F_GET_RUN_STATUS: return "F_GET_RUN_STATUS"; + case F_START_AND_READ_ALL: return "F_START_AND_READ_ALL"; + case F_READ_FRAME: return "F_READ_FRAME"; + case F_READ_ALL: return "F_READ_ALL"; + case F_SET_TIMER: return "F_SET_TIMER"; + case F_GET_TIME_LEFT: return "F_GET_TIME_LEFT"; + case F_SET_DYNAMIC_RANGE: return "F_SET_DYNAMIC_RANGE"; + case F_SET_READOUT_FLAGS: return "F_SET_READOUT_FLAGS"; + case F_SET_ROI: return "F_SET_ROI"; + case F_SET_SPEED: return "F_SET_SPEED"; + case F_EXECUTE_TRIMMING: return "F_EXECUTE_TRIMMING"; + case F_EXIT_SERVER: return "F_EXIT_SERVER"; + case F_LOCK_SERVER: return "F_LOCK_SERVER"; + case F_GET_LAST_CLIENT_IP: return "F_GET_LAST_CLIENT_IP"; + case F_SET_PORT: return "F_SET_PORT"; + case F_UPDATE_CLIENT: return "F_UPDATE_CLIENT"; + case F_CONFIGURE_MAC: return "F_CONFIGURE_MAC"; + case F_LOAD_IMAGE: return "F_LOAD_IMAGE"; + case F_SET_MASTER: return "F_SET_MASTER"; + case F_SET_SYNCHRONIZATION_MODE: return "F_SET_SYNCHRONIZATION_MODE"; + case F_READ_COUNTER_BLOCK: return "F_READ_COUNTER_BLOCK"; + case F_RESET_COUNTER_BLOCK: return "F_RESET_COUNTER_BLOCK"; + case F_CALIBRATE_PEDESTAL: return "F_CALIBRATE_PEDESTAL"; + case F_ENABLE_TEN_GIGA: return "F_ENABLE_TEN_GIGA"; + case F_SET_ALL_TRIMBITS: return "F_SET_ALL_TRIMBITS"; + case F_SET_CTB_PATTERN: return "F_SET_CTB_PATTERN"; + case F_WRITE_ADC_REG: return "F_WRITE_ADC_REG"; + case F_SET_COUNTER_BIT: return "F_SET_COUNTER_BIT"; + case F_PULSE_PIXEL: return "F_PULSE_PIXEL"; + case F_PULSE_PIXEL_AND_MOVE: return "F_PULSE_PIXEL_AND_MOVE"; + case F_PULSE_CHIP: return "F_PULSE_CHIP"; + case F_SET_RATE_CORRECT: return "F_SET_RATE_CORRECT"; + case F_GET_RATE_CORRECT: return "F_GET_RATE_CORRECT"; + case F_SET_NETWORK_PARAMETER: return "F_SET_NETWORK_PARAMETER"; + case F_PROGRAM_FPGA: return "F_PROGRAM_FPGA"; + case F_RESET_FPGA: return "F_RESET_FPGA"; + case F_POWER_CHIP: return "F_POWER_CHIP"; + case F_ACTIVATE: return "F_ACTIVATE"; + case F_PREPARE_ACQUISITION: return "F_PREPARE_ACQUISITION"; + case F_CLEANUP_ACQUISITION: return "F_CLEANUP_ACQUISITION"; + default: return "Unknown Function"; } - flist[F_EXIT_SERVER]=&exit_server; - flist[F_EXEC_COMMAND]=&exec_command; +} - flist[F_LOCK_SERVER]=&lock_server; - flist[F_GET_LAST_CLIENT_IP]=&get_last_client_ip; - flist[F_SET_PORT]=&set_port; - flist[F_UPDATE_CLIENT]=&update_client; - flist[F_SET_MASTER]=&set_master; - flist[F_SET_SYNCHRONIZATION_MODE]=&set_synchronization; +void function_table() { + flist[F_EXEC_COMMAND] = &exec_command; + flist[F_GET_ERROR] = &get_error; + flist[F_GET_DETECTOR_TYPE] = &get_detector_type; + flist[F_SET_NUMBER_OF_MODULES] = &set_number_of_modules; + flist[F_GET_MAX_NUMBER_OF_MODULES] = &get_max_number_of_modules; + flist[F_SET_EXTERNAL_SIGNAL_FLAG] = &set_external_signal_flag; + flist[F_SET_EXTERNAL_COMMUNICATION_MODE] = &set_external_communication_mode; + flist[F_GET_ID] = &get_id; + flist[F_DIGITAL_TEST] = &digital_test; + flist[F_ANALOG_TEST] = &analog_test; + flist[F_ENABLE_ANALOG_OUT] = &enable_analog_out; + flist[F_CALIBRATION_PULSE] = &calibration_pulse; + flist[F_SET_DAC] = &set_dac; + flist[F_GET_ADC] = &get_adc; + flist[F_WRITE_REGISTER] = &write_register; + flist[F_READ_REGISTER] = &read_register; + flist[F_WRITE_MEMORY] = &write_memory; + flist[F_READ_MEMORY] = &read_memory; + flist[F_SET_CHANNEL] = &set_channel; + flist[F_GET_CHANNEL] = &get_channel; + flist[F_SET_ALL_CHANNELS] = &set_all_channels; + flist[F_SET_CHIP] = &set_chip; + flist[F_GET_CHIP] = &get_chip; + flist[F_SET_ALL_CHIPS] = &set_all_chips; + flist[F_SET_MODULE] = &set_module; + flist[F_GET_MODULE] = &get_module; + flist[F_SET_ALL_MODULES] = &set_all_modules; + flist[F_SET_SETTINGS] = &set_settings; + flist[F_GET_THRESHOLD_ENERGY] = &get_threshold_energy; + flist[F_SET_THRESHOLD_ENERGY] = &set_threshold_energy; + flist[F_START_ACQUISITION] = &start_acquisition; + flist[F_STOP_ACQUISITION] = &stop_acquisition; + flist[F_START_READOUT] = &start_readout; + flist[F_GET_RUN_STATUS] = &get_run_status; + flist[F_START_AND_READ_ALL] = &start_and_read_all; + flist[F_READ_FRAME] = &read_frame; + flist[F_READ_ALL] = &read_all; + flist[F_SET_TIMER] = &set_timer; + flist[F_GET_TIME_LEFT] = &get_time_left; + flist[F_SET_DYNAMIC_RANGE] = &set_dynamic_range; + flist[F_SET_READOUT_FLAGS] = &set_readout_flags; + flist[F_SET_ROI] = &set_roi; + flist[F_SET_SPEED] = &set_speed; + flist[F_EXECUTE_TRIMMING] = &execute_trimming; + flist[F_EXIT_SERVER] = &exit_server; + flist[F_LOCK_SERVER] = &lock_server; + flist[F_GET_LAST_CLIENT_IP] = &get_last_client_ip; + flist[F_SET_PORT] = &set_port; + flist[F_UPDATE_CLIENT] = &update_client; + flist[F_CONFIGURE_MAC] = &configure_mac; + flist[F_LOAD_IMAGE] = &load_image; + flist[F_SET_MASTER] = &set_master; + flist[F_SET_SYNCHRONIZATION_MODE] = &set_synchronization; + flist[F_READ_COUNTER_BLOCK] = &read_counter_block; + flist[F_RESET_COUNTER_BLOCK] = &reset_counter_block; + flist[F_CALIBRATE_PEDESTAL] = &calibrate_pedestal; + flist[F_ENABLE_TEN_GIGA] = &enable_ten_giga; + flist[F_SET_ALL_TRIMBITS] = &set_all_trimbits; + flist[F_SET_CTB_PATTERN] = &set_ctb_pattern; + flist[F_WRITE_ADC_REG] = &write_adc_register; + flist[F_SET_COUNTER_BIT] = &set_counter_bit; + flist[F_PULSE_PIXEL] = &pulse_pixel; + flist[F_PULSE_PIXEL_AND_MOVE] = &pulse_pixel_and_move; + flist[F_PULSE_CHIP] = &pulse_chip; + flist[F_SET_RATE_CORRECT] = &set_rate_correct; + flist[F_GET_RATE_CORRECT] = &get_rate_correct; + flist[F_SET_NETWORK_PARAMETER] = &set_network_parameter; + flist[F_PROGRAM_FPGA] = &program_fpga; + flist[F_RESET_FPGA] = &reset_fpga; + flist[F_POWER_CHIP] = &power_chip; + flist[F_ACTIVATE] = &set_activate; + flist[F_PREPARE_ACQUISITION] = &prepare_acquisition; + flist[F_CLEANUP_ACQUISITION] = &cleanup_acquisition; - //F_GET_ERROR - flist[F_GET_DETECTOR_TYPE]=&get_detector_type; - flist[F_SET_NUMBER_OF_MODULES]=&set_number_of_modules; - flist[F_GET_MAX_NUMBER_OF_MODULES]=&get_max_number_of_modules; - flist[F_SET_EXTERNAL_SIGNAL_FLAG]=&set_external_signal_flag; - flist[F_SET_EXTERNAL_COMMUNICATION_MODE]=&set_external_communication_mode; - flist[F_GET_ID]=&get_id; - flist[F_DIGITAL_TEST]=&digital_test; - //F_ANALOG_TEST - //F_ENABLE_ANALOG_OUT - //F_CALIBRATION_PULSE - flist[F_SET_DAC]=&set_dac; - flist[F_GET_ADC]=&get_adc; - flist[F_WRITE_REGISTER]=&write_register; - flist[F_READ_REGISTER]=&read_register; - //F_WRITE_MEMORY - //F_READ_MEMORY - flist[F_SET_CHANNEL]=&set_channel; - flist[F_GET_CHANNEL]=&get_channel; - //F_SET_ALL_CHANNELS - flist[F_SET_CHIP]=&set_chip; - flist[F_GET_CHIP]=&get_chip; - //F_SET_ALL_CHIPS - flist[F_SET_MODULE]=&set_module; - flist[F_GET_MODULE]=&get_module; - //F_SET_ALL_MODULES - flist[F_SET_SETTINGS]=&set_settings; - flist[F_GET_THRESHOLD_ENERGY]=&get_threshold_energy; - flist[F_SET_THRESHOLD_ENERGY]=&set_threshold_energy; - flist[F_START_ACQUISITION]=&start_acquisition; - flist[F_STOP_ACQUISITION]=&stop_acquisition; - flist[F_START_READOUT]=&start_readout; - flist[F_GET_RUN_STATUS]=&get_run_status; - flist[F_START_AND_READ_ALL]=&start_and_read_all; - flist[F_READ_FRAME]=&read_frame; - flist[F_READ_ALL]=&read_all; - flist[F_SET_TIMER]=&set_timer; - flist[F_GET_TIME_LEFT]=&get_time_left; - flist[F_SET_DYNAMIC_RANGE]=&set_dynamic_range; - flist[F_SET_READOUT_FLAGS]=&set_readout_flags; - flist[F_SET_ROI]=&set_roi; - flist[F_SET_SPEED]=&set_speed; - flist[F_EXECUTE_TRIMMING]=&execute_trimming; - flist[F_CONFIGURE_MAC]=&configure_mac; - flist[F_LOAD_IMAGE]=&load_image; - flist[F_READ_COUNTER_BLOCK]=&read_counter_block; - flist[F_RESET_COUNTER_BLOCK]=&reset_counter_block; - flist[F_START_RECEIVER]=&start_receiver; - flist[F_STOP_RECEIVER]=&stop_receiver; - flist[F_CALIBRATE_PEDESTAL]=&calibrate_pedestal; - flist[F_ENABLE_TEN_GIGA]=&enable_ten_giga; - flist[F_SET_ALL_TRIMBITS]=&set_all_trimbits; - flist[F_SET_COUNTER_BIT]=&set_counter_bit; - flist[F_PULSE_PIXEL]=&pulse_pixel; - flist[F_PULSE_PIXEL_AND_MOVE]=&pulse_pixel_and_move; - flist[F_PULSE_CHIP]=&pulse_chip; - flist[F_SET_RATE_CORRECT]=&set_rate_correct; - flist[F_GET_RATE_CORRECT]=&get_rate_correct; - flist[F_ACTIVATE]=&set_activate; - flist[F_SET_NETWORK_PARAMETER]=&set_network_parameter; + // check + if (NUM_DET_FUNCTIONS >= TOO_MANY_FUNCTIONS_DEFINED) { + cprintf(BG_RED,"The last detector function enum has reached its limit\nGoodbye!\n"); + exit(EXIT_FAILURE); + } - -#ifdef VERBOSE - /* for (i=0;i<256;i++){ - printf("function %d located at %x\n",i,flist[i]); - }*/ +#ifdef VERYVERBOSE + { + int i=0; + for (i = 0; i < NUM_DET_FUNCTIONS ; i++) { + printf("function fnum=%d, (%s) located at 0x%x\n", i, getFunctionName((enum detFuncs)i), (unsigned int)flist[i]); + } + } #endif - return OK; } int M_nofunc(int file_des){ - - int ret=FAIL; - sprintf(mess,"Unrecognized Function\n"); - printf(mess); - sendData(file_des,&ret,sizeof(ret),INT32); - sendData(file_des,mess,sizeof(mess),OTHER); - return GOODBYE; -} - - -int exit_server(int file_des) { - int ret=FAIL; - sendData(file_des,&ret,sizeof(ret),INT32); - printf("closing server."); - sprintf(mess,"closing server"); - sendData(file_des,mess,sizeof(mess),OTHER); - return GOODBYE; -} - -int exec_command(int file_des) { - char cmd[MAX_STR_LENGTH]; - char answer[MAX_STR_LENGTH]; - int ret=OK,ret1=OK; - int sysret=0; + int ret=FAIL,ret1=FAIL; int n=0; - /* receive arguments */ + //to receive any arguments + while (n > 0) + n = receiveData(file_des,mess,MAX_STR_LENGTH,OTHER); + + sprintf(mess,"Unrecognized Function. Please do not proceed.\n"); + cprintf(BG_RED,"Error: %s",mess); + n = sendData(file_des,&ret1,sizeof(ret1),INT32); + n = sendData(file_des,mess,sizeof(mess),OTHER); + + // return ok / fail + return ret; +} + + + + + + +/* functions called by client */ + + + +int exec_command(int file_des) { + int ret=OK,ret1=OK; + int n=0; + char cmd[MAX_STR_LENGTH]=""; + int sysret=0; + + // receive arguments n = receiveData(file_des,cmd,MAX_STR_LENGTH,OTHER); - if (n < 0) { - sprintf(mess,"Error reading from socket\n"); - ret=FAIL; - } + if (n < 0) return printSocketReadError(); - /* execute action if the arguments correctly arrived*/ - if (ret==OK) { + // execute action if the arguments correctly arrived #ifdef VERBOSE - printf("executing command %s\n", cmd); + printf("executing command %s\n", cmd); #endif - if (lockStatus==0 || differentClients==0) - sysret=system(cmd); - + if (differentClients && lockStatus) { + ret = FAIL; + sprintf(mess,"Detector locked by %s\n",lastClientIP); + cprintf(RED, "Warning: %s", mess); + } else { + sysret=system(cmd); //should be replaced by popen if (sysret==0) { - sprintf(answer,"Succeeded\n"); - if (lockStatus==1 && differentClients==1) - sprintf(answer,"Detector locked by %s\n", lastClientIP); + sprintf(mess,"Succeeded\n"); } else { - sprintf(answer,"Failed\n"); - ret=FAIL; - } - } else { - sprintf(answer,"Could not receive the command\n"); - } - - /* send answer */ - //ret could be swapped during sendData - ret1 = ret; - n = sendData(file_des,&ret1,sizeof(ret),INT32); - n = sendData(file_des,answer,MAX_STR_LENGTH,OTHER); - if (n < 0) { - sprintf(mess,"Error writing to socket"); - ret=FAIL; - } - - - /*return ok/fail*/ - return ret; - -} - - - - - -int lock_server(int file_des) { - - - int n; - int ret=OK,ret1=OK; - - - int lock; - n = receiveData(file_des,&lock,sizeof(lock),INT32); - if (n < 0) { - sprintf(mess,"Error reading from socket\n"); - printf("Error reading from socket (lock)\n"); - ret=FAIL; - } - if (lock>=0) { - if (lockStatus==0 || strcmp(lastClientIP,thisClientIP)==0 || strcmp(lastClientIP,"none")==0) { - lockStatus=lock; - strcpy(lastClientIP,thisClientIP); - } else { - ret=FAIL; - sprintf(mess,"Server already locked by %s\n", lastClientIP); + ret = FAIL; + sprintf(mess,"Executing Command failed\n"); + cprintf(RED, "Warning: %s", mess); } } - if (differentClients && ret==OK) - ret=FORCE_UPDATE; - //ret could be swapped during sendData - ret1 = ret; + ret1=ret; n = sendData(file_des,&ret1,sizeof(ret),INT32); - if (ret==FAIL) { - n = sendData(file_des,mess,sizeof(mess),OTHER); - } else - n = sendData(file_des,&lockStatus,sizeof(lockStatus),INT32); + n = sendData(file_des,mess,MAX_STR_LENGTH,OTHER); - return ret; - -} - - - - -int get_last_client_ip(int file_des) { - int ret=OK,ret1=OK; - if (differentClients ) - ret=FORCE_UPDATE; - sendData(file_des,&ret1,sizeof(ret),INT32); - sendData(file_des,lastClientIP,sizeof(lastClientIP),OTHER); + // return ok / fail return ret; } +int get_error(int file_des) { + int ret=FAIL,ret1=FAIL; + int n=0; + sprintf(mess,"Function (Get Error) is not implemented for this detector\n"); + cprintf(RED, "Error: %s", mess); -int set_port(int file_des) { - int n; - int ret=OK,ret1=OK; - int sd=-1; + //to receive any arguments + while (n > 0) + n = receiveData(file_des,mess,MAX_STR_LENGTH,OTHER); - enum portType p_type; /** data? control? stop? Unused! */ - int p_number; /** new port number */ - - n = receiveData(file_des,&p_type,sizeof(p_type),INT32); - if (n < 0) { - sprintf(mess,"Error reading from socket\n"); - printf("Error reading from socket (ptype)\n"); - ret=FAIL; - } - - n = receiveData(file_des,&p_number,sizeof(p_number),INT32); - if (n < 0) { - sprintf(mess,"Error reading from socket\n"); - printf("Error reading from socket (pnum)\n"); - ret=FAIL; - } - if (differentClients==1 && lockStatus==1 ) { - ret=FAIL; - sprintf(mess,"Detector locked by %s\n",lastClientIP); - } else { - if (p_number<1024) { - sprintf(mess,"Too low port number %d\n", p_number); - printf("\n"); - ret=FAIL; - } - - printf("set port %d to %d\n",p_type, p_number); - - sd=bindSocket(p_number); - } - if (sd>=0) { - ret=OK; - if (differentClients ) - ret=FORCE_UPDATE; - } else { - ret=FAIL; - sprintf(mess,"Could not bind port %d\n", p_number); - printf("Could not bind port %d\n", p_number); - if (sd==-10) { - sprintf(mess,"Port %d already set\n", p_number); - printf("Port %d already set\n", p_number); - - } - } - //ret could be swapped during sendData - ret1 = ret; n = sendData(file_des,&ret1,sizeof(ret),INT32); - if (ret==FAIL) { - n = sendData(file_des,mess,sizeof(mess),OTHER); - } else { - n = sendData(file_des,&p_number,sizeof(p_number),INT32); - closeConnection(file_des); - exitServer(sockfd); - sockfd=sd; + n = sendData(file_des,mess,MAX_STR_LENGTH,OTHER); - } - - return ret; - -} - - - -int send_update(int file_des) { - - enum detectorSettings t; - int n = 0, nm = 0; - int64_t retval = 0; - - n += sendData(file_des,lastClientIP,sizeof(lastClientIP),OTHER); -#ifdef SLS_DETECTOR_FUNCTION_LIST - nm=setNMod(GET_FLAG,X); -#endif - n += sendData(file_des,&nm,sizeof(nm),INT32); -#ifdef SLS_DETECTOR_FUNCTION_LIST - nm=setNMod(GET_FLAG,Y); -#endif - n += sendData(file_des,&nm,sizeof(nm),INT32); -#ifdef SLS_DETECTOR_FUNCTION_LIST - nm=setDynamicRange(GET_FLAG); -#endif - n += sendData(file_des,&nm,sizeof(nm),INT32); - nm = dataBytes; - n += sendData(file_des,&nm,sizeof(nm),INT32); -#ifdef SLS_DETECTOR_FUNCTION_LIST - t=setSettings(GET_SETTINGS, GET_FLAG); -#endif - n += sendData(file_des,&t,sizeof(t),INT32); -#ifdef SLS_DETECTOR_FUNCTION_LIST - nm=getThresholdEnergy(GET_FLAG); -#endif - n += sendData(file_des,&nm,sizeof(nm),INT32); -#ifdef SLS_DETECTOR_FUNCTION_LIST - retval=setTimer(FRAME_NUMBER,GET_FLAG); -#endif - n += sendData(file_des,&retval,sizeof(int64_t),INT64); -#ifdef SLS_DETECTOR_FUNCTION_LIST - retval=setTimer(ACQUISITION_TIME,GET_FLAG); -#endif - n += sendData(file_des,&retval,sizeof(int64_t),INT64); -#ifdef SLS_DETECTOR_FUNCTION_LIST - retval=setTimer(SUBFRAME_ACQUISITION_TIME,GET_FLAG); -#endif - n += sendData(file_des,&retval,sizeof(int64_t),INT64); -#ifdef SLS_DETECTOR_FUNCTION_LIST - retval=setTimer(FRAME_PERIOD,GET_FLAG); -#endif - n += sendData(file_des,&retval,sizeof(int64_t),INT64); -#ifdef SLS_DETECTOR_FUNCTION_LIST - retval=setTimer(DELAY_AFTER_TRIGGER,GET_FLAG); -#endif - n += sendData(file_des,&retval,sizeof(int64_t),INT64); -#ifdef SLS_DETECTOR_FUNCTION_LIST - retval=setTimer(GATES_NUMBER,GET_FLAG); -#endif - n += sendData(file_des,&retval,sizeof(int64_t),INT64); -/* retval=setTimer(PROBES_NUMBER,GET_FLAG); - n += sendData(file_des,&retval,sizeof(int64_t),INT64);*/ -#ifdef SLS_DETECTOR_FUNCTION_LIST - retval=setTimer(CYCLES_NUMBER,GET_FLAG); -#endif - n += sendData(file_des,&retval,sizeof(int64_t),INT64); - - if (lockStatus==0) { - strcpy(lastClientIP,thisClientIP); - } - - return OK; - -} - - -int update_client(int file_des) { - - int ret=OK; - sendData(file_des,&ret,sizeof(ret),INT32); - return send_update(file_des); - -} - - - - -int set_master(int file_des) { - - enum masterFlags retval=GET_MASTER; - enum masterFlags arg; - int n; - int ret=OK,ret1=OK; - // int regret=OK; - - - sprintf(mess,"can't set master flags\n"); - - - n = receiveData(file_des,&arg,sizeof(arg),INT32); - if (n < 0) { - sprintf(mess,"Error reading from socket\n"); - ret=FAIL; - } - - -#ifdef VERBOSE - printf("setting master flags to %d\n",arg); -#endif - -#ifdef SLS_DETECTOR_FUNCTION_LIST - if (differentClients==1 && lockStatus==1 && ((int)arg!=(int)GET_READOUT_FLAGS)) { - ret=FAIL; - sprintf(mess,"Detector locked by %s\n",lastClientIP); - } else { - retval=setMaster(arg); - - } -#endif - if (retval==GET_MASTER) { - ret=FAIL; - } - - //ret could be swapped during sendData - ret1 = ret; - n = sendData(file_des,&ret1,sizeof(ret),INT32); - if (ret==FAIL) { - n = sendData(file_des,mess,sizeof(mess),OTHER); - } else { - n = sendData(file_des,&retval,sizeof(retval),INT32); - } + // return ok / fail return ret; } - - - -int set_synchronization(int file_des) { - - enum synchronizationMode retval=GET_SYNCHRONIZATION_MODE; - enum synchronizationMode arg; - int n; - int ret=OK,ret1=OK; - //int regret=OK; - - - sprintf(mess,"can't set synchronization mode\n"); - - - n = receiveData(file_des,&arg,sizeof(arg),INT32); - if (n < 0) { - sprintf(mess,"Error reading from socket\n"); - ret=FAIL; - } -#ifdef VERBOSE - printf("setting master flags to %d\n",arg); -#endif - -#ifdef SLS_DETECTOR_FUNCTION_LIST - if (differentClients==1 && lockStatus==1 && ((int)arg!=(int)GET_READOUT_FLAGS)) { - ret=FAIL; - sprintf(mess,"Detector locked by %s\n",lastClientIP); - } else { - retval=setSynchronization(arg); - } -#endif - - if (retval==GET_SYNCHRONIZATION_MODE) { - ret=FAIL; - } - - //ret could be swapped during sendData - ret1 = ret; - n = sendData(file_des,&ret1,sizeof(ret),INT32); - if (ret==FAIL) { - n = sendData(file_des,mess,sizeof(mess),OTHER); - } else { - n = sendData(file_des,&retval,sizeof(retval),INT32); - } - return ret; -} - - - - - - - int get_detector_type(int file_des) { - int n=0; - enum detectorType retval; int ret=OK,ret1=OK; + int n=0; + enum detectorType retval=-1; - sprintf(mess,"Can't return detector type\n"); - - - /* receive arguments */ - /* execute action */ + // execute action retval=myDetectorType; - #ifdef VERBOSE printf("Returning detector type %d\n",retval); #endif - /* send answer */ - /* send OK/failed */ - if (differentClients==1) + if (differentClients) ret=FORCE_UPDATE; - //ret could be swapped during sendData - ret1 = ret; + // send ok / fail n += sendData(file_des,&ret1,sizeof(ret),INT32); - if (ret!=FAIL) { - /* send return argument */ - n += sendData(file_des,&retval,sizeof(retval),INT32); - } else { - n += sendData(file_des,mess,sizeof(mess),OTHER); - } - /*return ok/fail*/ + // send return argument + n += sendData(file_des,&retval,sizeof(retval),INT32); + + // return ok / fail return ret; } + + int set_number_of_modules(int file_des) { - int n; - int arg[2], retval=0; int ret=OK,ret1=OK; - int nm; -#ifdef SLS_DETECTOR_FUNCTION_LIST - enum dimension dim; -#endif - sprintf(mess,"Can't set number of modules\n"); + int n=0; + int retval=0; + int arg[2]={-1,-1}; + sprintf(mess,"set number of modules failed\n"); - /* receive arguments */ + // receive arguments n = receiveData(file_des,&arg,sizeof(arg),INT32); - if (n < 0) { - sprintf(mess,"Error reading from socket %d", n); - ret=GOODBYE; + if (n < 0) return printSocketReadError(); + enum dimension dim=arg[0]; + int nm=arg[1]; + + // execute action +#ifdef VERBOSE + printf("Setting the number of modules in dimension %d to %d\n",dim,nm ); +#endif + if (lockStatus && differentClients && nm!=GET_FLAG) { + ret = FAIL; + sprintf(mess,"Detector locked by %s\n",lastClientIP); + cprintf(RED, "Warning: %s", mess); } #ifdef SLS_DETECTOR_FUNCTION_LIST - if (ret==OK) { - dim=arg[0]; - nm=arg[1]; - - /* execute action */ -#ifdef VERBOSE - printf("Setting the number of modules in dimension %d to %d\n",dim,nm ); -#endif - if (lockStatus==1 && differentClients==1 && nm!=GET_FLAG) { - sprintf(mess,"Detector locked by %s\n", lastClientIP); - ret=FAIL; - } else - retval=setNMod(nm, dim); + else { + retval=setNMod(nm, dim); + dataBytes=calculateDataBytes(); } - dataBytes=calculateDataBytes(); #endif if (retval==nm || nm==GET_FLAG) { ret=OK; - if (differentClients==1) + if (differentClients) ret=FORCE_UPDATE; } else ret=FAIL; - /* send answer */ - /* send OK/failed */ - //ret could be swapped during sendData + // ret could be swapped during sendData ret1 = ret; + // send ok / fail n = sendData(file_des,&ret1,sizeof(ret),INT32); + // send return argument if (ret!=FAIL) { - /* send return argument */ n += sendData(file_des,&retval,sizeof(retval),INT32); } else { n += sendData(file_des,mess,sizeof(mess),OTHER); } - /*return ok/fail*/ + // return ok / fail return ret; } -int get_max_number_of_modules(int file_des) { - int n; - int retval; - int ret=OK,ret1=OK; - enum dimension arg; - sprintf(mess,"Can't get max number of modules\n"); - /* receive arguments */ + +int get_max_number_of_modules(int file_des) { + int ret=OK,ret1=OK; + int n=0; + int retval=-1; + enum dimension arg=0; + sprintf(mess,"get max number of modules failed\n"); + + // receive arguments n = receiveData(file_des,&arg,sizeof(arg),INT32); - if (n < 0) { - sprintf(mess,"Error reading from socket\n"); - ret=FAIL; - } - /* execute action */ + if (n < 0) return printSocketReadError(); + + // execute action #ifdef VERBOSE printf("Getting the max number of modules in dimension %d \n",arg); #endif - #ifdef SLS_DETECTOR_FUNCTION_LIST - retval=getNModBoard(arg); #endif #ifdef VERBOSE printf("Max number of module in dimension %d is %d\n",arg,retval ); -#endif - - if (differentClients==1 && ret==OK) { +#endif + if (differentClients && ret==OK) { ret=FORCE_UPDATE; } - /* send answer */ - /* send OK/failed */ - //ret could be swapped during sendData + // ret could be swapped during sendData ret1 = ret; + // send ok / fail n = sendData(file_des,&ret1,sizeof(ret),INT32); + // send return argument if (ret!=FAIL) { - /* send return argument */ n += sendData(file_des,&retval,sizeof(retval),INT32); } else { n += sendData(file_des,mess,sizeof(mess),OTHER); } - /*return ok/fail*/ + // return ok / fail return ret; } -//index 0 is in gate -//index 1 is in trigger -//index 2 is out gate -//index 3 is out trigger + int set_external_signal_flag(int file_des) { - int n; - int arg[2]; int ret=OK,ret1=OK; - enum externalSignalFlag retval=SIGNAL_OFF; -#ifdef SLS_DETECTOR_FUNCTION_LIST - int signalindex; - enum externalSignalFlag flag; -#endif + int n=0; + enum externalSignalFlag retval=GET_EXTERNAL_SIGNAL_FLAG; + sprintf(mess,"set external signal flag failed\n"); - sprintf(mess,"Can't set external signal flag\n"); +#ifndef MYTHEND + //to receive any arguments + while (n > 0) + n = receiveData(file_des,mess,MAX_STR_LENGTH,OTHER); + ret = FAIL; + sprintf(mess,"Function (Set External Signal Flag) is not implemented for this detector\n"); + cprintf(RED, "%s", mess); +#else - /* receive arguments */ + // receive arguments + int arg[2]={-1,-1}; n = receiveData(file_des,&arg,sizeof(arg),INT32); - if (n < 0) { - sprintf(mess,"Error reading from socket\n"); - ret=FAIL; + if (n < 0) return printSocketReadError(); + + int signalindex=arg[0]; + enum externalSignalFlag flag=arg[1]; + + // execute action + if (lockStatus && differentClients && flag!=GET_EXTERNAL_SIGNAL_FLAG) { + ret = FAIL; + sprintf(mess,"Detector locked by %s\n",lastClientIP); + cprintf(RED, "Warning: %s", mess); } + #ifdef SLS_DETECTOR_FUNCTION_LIST - if (ret==OK) { - signalindex=arg[0]; - flag=arg[1]; - /* execute action */ + else{ +#ifdef VERBOSE + printf("Setting external signal %d to flag %d\n",signalindex,flag); +#endif switch (flag) { case GET_EXTERNAL_SIGNAL_FLAG: retval=getExtSignal(signalindex); break; default: - if (differentClients==0 || lockStatus==0) { - retval=setExtSignal(signalindex,flag); - if (retval!=flag) { - ret=FAIL; - sprintf(mess,"External signal %d flag should be 0x%04x but is 0x%04x\n", signalindex, flag, retval); - } - - } else if (lockStatus!=0) { - ret=FAIL; - sprintf(mess,"Detector locked by %s\n", lastClientIP); + retval=setExtSignal(signalindex,flag); + if (retval!=flag) { + ret=FAIL; + sprintf(mess,"External signal %d flag should be 0x%04x but is 0x%04x\n", signalindex, flag, retval); + cprintf(RED, "%s", mess); } break; } #ifdef VERBOSE - printf("Setting external signal %d to flag %d\n",signalindex,flag ); printf("Set to flag %d\n",retval); #endif - } else { - ret=FAIL; } #endif - - if (ret==OK && differentClients!=0) + if (ret==OK && differentClients) ret=FORCE_UPDATE; +#endif - - /* send answer */ - /* send OK/failed */ - //ret could be swapped during sendData + // ret could be swapped during sendData ret1 = ret; + // send ok / fail n = sendData(file_des,&ret1,sizeof(ret),INT32); + // send return argument if (ret!=FAIL) { - /* send return argument */ n += sendData(file_des,&retval,sizeof(retval),INT32); } else { n += sendData(file_des,mess,sizeof(mess),OTHER); } - - /*return ok/fail*/ + // return ok / fail return ret; } int set_external_communication_mode(int file_des) { - int n; - enum externalCommunicationMode arg, retval=GET_EXTERNAL_COMMUNICATION_MODE; int ret=OK,ret1=OK; + int n=0; + enum externalCommunicationMode arg=GET_EXTERNAL_COMMUNICATION_MODE; + enum externalCommunicationMode retval=GET_EXTERNAL_COMMUNICATION_MODE; + sprintf(mess,"set external communication mode failed\n"); - sprintf(mess,"Can't set external communication mode\n"); - - - /* receive arguments */ + // receive arguments n = receiveData(file_des,&arg,sizeof(arg),INT32); - if (n < 0) { - sprintf(mess,"Error reading from socket\n"); - ret=FAIL; - } - /* -enum externalCommunicationMode{ - GET_EXTERNAL_COMMUNICATION_MODE, - AUTO, - TRIGGER_EXPOSURE_SERIES, - TRIGGER_EXPOSURE_BURST, - TRIGGER_READOUT, - TRIGGER_COINCIDENCE_WITH_INTERNAL_ENABLE, - GATE_FIX_NUMBER, - GATE_FIX_DURATION, - GATE_WITH_START_TRIGGER, - // GATE_COINCIDENCE_WITH_INTERNAL_ENABLE, - BURST_TRIGGER -}; - */ -#ifdef SLS_DETECTOR_FUNCTION_LIST - if (ret==OK) { - /* execute action */ - switch(arg){ -#ifdef EIGERD - case GET_EXTERNAL_COMMUNICATION_MODE: - case AUTO_TIMING: - case TRIGGER_EXPOSURE: - case BURST_TRIGGER: - case GATE_FIX_NUMBER: - break; -#endif - default: - ret = FAIL; - sprintf(mess,"This timing mode %d not implemented in this detector\n",(int)arg); - break; - } - } - if (ret==OK) { + if (n < 0) return printSocketReadError(); + + // execute action #ifdef VERBOSE - printf("Setting external communication mode to %d\n", arg); + printf("Setting external communication mode to %d\n", arg); +#endif +#ifdef SLS_DETECTOR_FUNCTION_LIST + switch(arg){ +#ifdef EIGERD + case GET_EXTERNAL_COMMUNICATION_MODE: + case AUTO_TIMING: + case TRIGGER_EXPOSURE: + case GATE_FIX_NUMBER: + case BURST_TRIGGER: +#elif JUNGFRAUD + case GET_EXTERNAL_COMMUNICATION_MODE: + case AUTO_TIMING: + case TRIGGER_EXPOSURE: #endif retval=setTiming(arg); - - if (differentClients==1) - ret=FORCE_UPDATE; + break; + default: + ret = FAIL; + sprintf(mess,"Timing mode (%d) is not implemented for this detector\n",(int)arg); + cprintf(RED, "Warning: %s", mess); + break; } +#ifdef VERBOSE + if(ret==OK) + printf("retval:%d\n",retval); +#endif + if (ret==OK && differentClients==1) + ret=FORCE_UPDATE; + #endif - - /* send answer */ - /* send OK/failed */ - //ret could be swapped during sendData + // ret could be swapped during sendData ret1 = ret; + // send ok / fail n = sendData(file_des,&ret1,sizeof(ret),INT32); + // send return argument if (ret!=FAIL) { - /* send return argument */ n += sendData(file_des,&retval,sizeof(retval),INT32); } else { n += sendData(file_des,mess,sizeof(mess),OTHER); } - /*return ok/fail*/ + // return ok / fail return ret; - - } + int get_id(int file_des) { - // sends back 64 bits! - int64_t retval; int ret=OK,ret1=OK; -#ifndef EIGERD - int imod=-1; -#endif int n=0; - enum idMode arg; + enum idMode arg=0; + int imod=-1; + int64_t retval=-1; + sprintf(mess,"get id failed\n"); - sprintf(mess,"Can't return id\n"); - - /* receive arguments */ + // receive arguments n = receiveData(file_des,&arg,sizeof(arg),INT32); - if (n < 0) { - sprintf(mess,"Error reading from socket\n"); - ret=FAIL; + if (n < 0) return printSocketReadError(); + + if (arg == MODULE_FIRMWARE_VERSION) { + n = receiveData(file_des,&imod,sizeof(imod),INT32); + if (n < 0) return printSocketReadError(); } + // execute action #ifdef VERBOSE printf("Getting id %d\n", arg); #endif - switch (arg) { -#ifndef EIGERD - case MODULE_SERIAL_NUMBER: - case MODULE_FIRMWARE_VERSION: - n = receiveData(file_des,&imod,sizeof(imod),INT32); - if (n < 0) { - sprintf(mess,"Error reading from socket\n"); - ret=FAIL; - } #ifdef SLS_DETECTOR_FUNCTION_LIST - if (ret==OK) { + switch (arg) { +#ifdef MYTHEND + case MODULE_SERIAL_NUMBER: + case MODULE_FIRMWARE_VERSION: #ifdef VERBOSE - printf("of module %d\n", imod); + printf("of module %d\n", imod); #endif - if (imod>=0 && imod=0 && imod 0) + n = receiveData(file_des,mess,MAX_STR_LENGTH,OTHER); + ret = FAIL; + sprintf(mess,"Function (Digital Test) is not implemented for this detector\n"); + cprintf(RED, "%s", mess); +#else + enum digitalTestMode arg=0; + int imod=-1; + int ival=-1; + + // receive arguments n = receiveData(file_des,&arg,sizeof(arg),INT32); - if (n < 0) { - sprintf(mess,"Error reading from socket\n"); - ret=FAIL; + if (n < 0) return printSocketReadError(); + + if (arg == CHIP_TEST) { + n = receiveData(file_des,&imod,sizeof(imod),INT32); + if (n < 0) return printSocketReadError(); } -#ifdef VERBOSE - printf("Digital test mode %d\n",arg ); -#endif + if (arg == DIGITAL_BIT_TEST) { + n = receiveData(file_des,&ival,sizeof(ival),INT32); + if (n < 0) return printSocketReadError(); + } - if (differentClients==1 && lockStatus==1) { - ret=FAIL; + // execute action + if (differentClients && lockStatus) { + ret = FAIL; sprintf(mess,"Detector locked by %s\n",lastClientIP); + cprintf(RED, "Warning: %s", mess); } else { +#ifdef VERBOSE + printf("Digital test mode %d\n",arg ); +#endif +#ifdef SLS_DETECTOR_FUNCTION_LIST switch (arg) { + +#ifdef GOTTHARD + case DIGITAL_BIT_TEST: + retval=0; + break; + +#elif MYTHEND case CHIP_TEST: - n = receiveData(file_des,&imod,sizeof(imod),INT32); - if (n < 0) { - sprintf(mess,"Error reading from socket\n"); - retval=FAIL; - } #ifdef VERBOSE printf("of module %d\n", imod); -#endif -#ifndef MYTHEND - ret = FAIL; - strcpy(mess,"Not applicable/implemented for this detector\n"); -#else -#ifdef SLS_DETECTOR_FUNCTION_LIST +#endif if (imod>=0 && imod 0) + n = receiveData(file_des,mess,MAX_STR_LENGTH,OTHER); + + n = sendData(file_des,&ret1,sizeof(ret),INT32); + n = sendData(file_des,mess,MAX_STR_LENGTH,OTHER); + + // return ok / fail + return ret; +} + + + +int enable_analog_out(int file_des) { + int ret=FAIL,ret1=FAIL; + int n=0; + sprintf(mess,"Function (Enable Analog Out) is not implemented for this detector\n"); + cprintf(RED, "Error: %s", mess); + + //to receive any arguments + while (n > 0) + n = receiveData(file_des,mess,MAX_STR_LENGTH,OTHER); + + n = sendData(file_des,&ret1,sizeof(ret),INT32); + n = sendData(file_des,mess,MAX_STR_LENGTH,OTHER); + + // return ok / fail + return ret; +} + + + +int calibration_pulse(int file_des) { + int ret=FAIL,ret1=FAIL; + int n=0; + sprintf(mess,"Function (Calibration Pulse) is not implemented for this detector\n"); + cprintf(RED, "Error: %s", mess); + + //to receive any arguments + while (n > 0) + n = receiveData(file_des,mess,MAX_STR_LENGTH,OTHER); + + n = sendData(file_des,&ret1,sizeof(ret),INT32); + n = sendData(file_des,mess,MAX_STR_LENGTH,OTHER); + + // return ok / fail + return ret; +} + int set_dac(int file_des) { - - int retval[2];retval[1]=-1; - int temp; int ret=OK,ret1=OK; - int arg[3]; - enum dacIndex ind; - int imod; - int n; - int val; - int mV; - enum detDacIndex idac=0; - - sprintf(mess,"Can't set DAC\n"); - + int n=0; + int arg[3]={-1,-1,-1}; + int val=-1; + enum dacIndex ind=0; + int imod=-1; + int retval[2]={-1,-1}; + int mV=0; + sprintf(mess,"set DAC failed\n"); + // receive arguments n = receiveData(file_des,arg,sizeof(arg),INT32); - if (n < 0) { - sprintf(mess,"Error reading from socket\n"); - ret=FAIL; - } + if (n < 0) return printSocketReadError(); ind=arg[0]; imod=arg[1]; mV=arg[2]; n = receiveData(file_des,&val,sizeof(val),INT32); - if (n < 0) { - sprintf(mess,"Error reading from socket\n"); - ret=FAIL; - } + if (n < 0) return printSocketReadError(); + // checks +#ifdef MYTHEND #ifdef SLS_DETECTOR_FUNCTION_LIST if (imod>=getTotalNumberOfModules()) { - ret=FAIL; + ret = FAIL; sprintf(mess,"Module number %d out of range\n",imod); + cprintf(RED, "Warning: %s", mess); } #endif - +#endif // check if dac exists for this detector + enum DACINDEX idac=0; +#ifdef JUNGFRAUD + if ((ind != HV_NEW) && (ind >= NDAC_OLDBOARD)) { //for compatibility with old board + ret = FAIL; + sprintf(mess,"Dac Index (%d) is not implemented for this detector\n",(int)ind); + cprintf(RED, "Warning: %s", mess); + }else + idac = ind; +#else switch (ind) { #ifdef MYTHEND case TRIMBIT_SIZE: //ind = VTRIM; - break; case THRESHOLD: - break; case SHAPER1: - break; case SHAPER2: - break; case CALIBRATION_PULSE: - break; case PREAMP: - break; -#endif -#ifdef GOTTHARDD + break; +#elif GOTTHARDD case G_VREF_DS : break; case G_VCASCN_PB: @@ -1166,8 +941,7 @@ int set_dac(int file_des) { break; case HV_POT: break; -#endif -#ifdef EIGERD +#elif EIGERD case TRIMBIT_SIZE: idac = VTR; break; @@ -1226,118 +1000,168 @@ int set_dac(int file_des) { break; case IO_DELAY: break; + /* +#elif JUNGFRAUD + case V_DAC0: + idac = VB_COMP; + break; + case V_DAC1: + idac = VDD_PROT; + break; + case V_DAC2: + idac = VIN_COM; + break; + case V_DAC3: + idac = VREF_PRECH; + break; + case V_DAC4: + idac = VB_PIXBUF; + break; + case V_DAC5: + idac = VB_DS; + break; + case V_DAC6: + idac = VREF_DS; + break; + case V_DAC7: + idac = VREF_COMP; + break; + case HV_POT: + break; + */ #endif default: - printf("Unknown DAC index %d\n",(int)ind); - sprintf(mess,"Unknown DAC index %d for this detector\n",ind); - ret=FAIL; + ret = FAIL; + sprintf(mess,"Dac Index (%d) is not implemented for this detector\n",(int)ind); + cprintf(RED, "Warning: %s", mess); break; } +#endif + + // execute action #ifdef VERBOSE - printf("Setting DAC %d of module %d to %d \n", idac, imod, val); + printf("Setting DAC %d of module %d to %d \n", idac, imod, val); #endif #ifdef SLS_DETECTOR_FUNCTION_LIST + int temp; if (ret==OK) { - if (differentClients==1 && lockStatus==1 && val!=-1) { - ret=FAIL; + if (differentClients && lockStatus && val!=-1) { + ret = FAIL; sprintf(mess,"Detector locked by %s\n",lastClientIP); - } else{ - if((ind == HV_POT) ||(ind == HV_NEW)) - retval[0] = setHighVoltage(val,imod); - else if(ind == IO_DELAY) + cprintf(RED, "Warning: %s", mess); + } else { +#ifdef EIGERD + //iodelay + if(ind == IO_DELAY) retval[0] = setIODelay(val,imod); + //high voltage else +#endif + if((ind == HV_POT) || (ind == HV_NEW)) { + retval[0] = setHighVoltage(val); +#ifdef EIGERD + if(retval[0] < 0){ + ret = FAIL; + if(retval[0] == -1) + sprintf(mess, "Setting high voltage failed.Bad value %d. The range is from 0 to 200 V.\n",val); + else if(retval[0] == -2) + strcpy(mess, "Setting high voltage failed. Serial/i2c communication failed.\n"); + else if(retval[0] == -3) + strcpy(mess, "Getting high voltage failed. Serial/i2c communication failed.\n"); + cprintf(RED, "Warning: %s", mess); + } +#endif + } + //dac + else{ setDAC(idac,val,imod,mV,retval); +#ifdef EIGERD + if(val != -1) { + //changing dac changes settings to undefined + switch(idac){ + case VCMP_LL: + case VCMP_LR: + case VCMP_RL: + case VCMP_RR: + case VRF: + case VCP: + setSettings(UNDEFINED,-1); + cprintf(RED,"Settings has been changed to undefined (changed specific dacs)\n"); + break; + default: + break; + } + } +#endif + //check + if(mV) + temp = retval[1]; + else + temp = retval[0]; + if ((abs(temp-val)<=5) || val==-1) { + ret=OK; + } else { + ret = FAIL; + sprintf(mess,"Setting dac %d of module %d: wrote %d but read %d\n", idac, imod, val, temp); + cprintf(RED, "Warning: %s", mess); + } + } } - - - } #endif #ifdef VERBOSE printf("DAC set to %d in dac units and %d mV\n", retval[0],retval[1]); #endif - //takes time to set high voltage, so no check for it - if(ret == OK){ - if(ind != HV_POT && ind != HV_NEW){ - - if(mV) - temp = retval[1]; - else - temp = retval[0]; - if ((abs(temp-val)<=5) || val==-1) { - ret=OK; - } else { - ret=FAIL; - printf("Setting dac %d of module %d: wrote %d but read %d\n", idac, imod, val, temp); - } - }else { - if(retval[0] < 0){ - if(retval[0] == -1) - sprintf(mess, "Setting high voltage failed.Bad value %d. The range is from 0 to 200 V.\n",val); - else if(retval[0] == -2) - strcpy(mess, "Setting high voltage failed. Serial/i2c communication failed.\n"); - else if(retval[0] == -3) - strcpy(mess, "Getting high voltage failed. Serial/i2c communication failed.\n"); - ret = FAIL; - } - - } - } - if(ret == OK && differentClients) ret=FORCE_UPDATE; - - /* send answer */ - /* send OK/failed */ - //ret could be swapped during sendData + // ret could be swapped during sendData ret1 = ret; + // send ok / fail n = sendData(file_des,&ret1,sizeof(ret),INT32); + // send return argument if (ret!=FAIL) { - /* send return argument */ n += sendData(file_des,&retval,sizeof(retval),INT32); } else { n += sendData(file_des,mess,sizeof(mess),OTHER); } - /* Maybe this is done inside the initialization funcs */ - //detectorDacs[imod][ind]=val; - /*return ok/fail*/ + // return ok / fail return ret; - } + + + int get_adc(int file_des) { - - int retval=-1; int ret=OK,ret1=OK; - int arg[2]; - enum dacIndex ind; - int imod; - int n; - enum detAdcIndex iadc=0; - - sprintf(mess,"Can't read ADC\n"); - + int n=0; + int arg[2]={-1,-1}; + int retval=-1; + enum dacIndex ind=0; + int imod=-1; + sprintf(mess,"get ADC failed\n"); + // receive arguments n = receiveData(file_des,arg,sizeof(arg),INT32); - if (n < 0) { - sprintf(mess,"Error reading from socket\n"); - ret=FAIL; - } + if (n < 0) return printSocketReadError(); ind=arg[0]; imod=arg[1]; +#ifdef MYTHEND #ifdef SLS_DETECTOR_FUNCTION_LIST if (imod>=getTotalNumberOfModules() || imod<0) { - ret=FAIL; + ret = FAIL; sprintf(mess,"Module number %d out of range\n",imod); + cprintf(RED, "Warning: %s", mess); } #endif +#endif + + enum ADCINDEX iadc=0; switch (ind) { #ifdef EIGERD case TEMPERATURE_FPGAEXT: @@ -1365,142 +1189,144 @@ int get_adc(int file_des) { iadc = TEMP_FPGAFEBR; break; #endif -#ifdef GOTTHARDD +#if defined(GOTTHARD) || defined(JUNGFRAUD) case TEMPERATURE_FPGA: + iadc = TEMP_FPGA; break; case TEMPERATURE_ADC: + iadc = TEMP_ADC; break; #endif default: - printf("Unknown DAC index %d\n",ind); - ret=FAIL; - sprintf(mess,"Unknown ADC index %d. Not implemented for this detector\n",ind); + ret = FAIL; + sprintf(mess,"Dac Index (%d) is not implemented for this detector\n",(int)ind); + cprintf(RED, "Warning: %s", mess); break; } -#ifdef SLS_DETECTOR_FUNCTION_LIST - if (ret==OK) { - retval=getADC(iadc,imod); - } -#endif + #ifdef VERBOSE printf("Getting ADC %d of module %d\n", iadc, imod); -#endif - +#endif +#ifdef SLS_DETECTOR_FUNCTION_LIST + if (ret==OK) + retval=getADC(iadc,imod); +#endif #ifdef VERBOSE - printf("ADC is %f V\n", retval); -#endif - if (ret==FAIL) { - printf("Getting adc %d of module %d failed\n", iadc, imod); - } + printf("ADC is %f\n", retval); +#endif - - if (differentClients) + if (ret==OK && differentClients) ret=FORCE_UPDATE; - /* send answer */ - /* send OK/failed */ - //ret could be swapped during sendData + // ret could be swapped during sendData ret1 = ret; + // send ok / fail n = sendData(file_des,&ret1,sizeof(ret),INT32); + // send return argument if (ret!=FAIL) { - /* send return argument */ n += sendData(file_des,&retval,sizeof(retval),INT32); } else { n += sendData(file_des,mess,sizeof(mess),OTHER); } - /*return ok/fail*/ + // return ok / fail return ret; - } - int write_register(int file_des) { - - int retval; int ret=OK,ret1=OK; - int arg[2]; - int addr, val; - int n; + int n=0; + int retval=-1; + sprintf(mess,"write to register failed\n"); +#ifdef EIGERD + //to receive any arguments + while (n > 0) + n = receiveData(file_des,mess,MAX_STR_LENGTH,OTHER); + ret = FAIL; + sprintf(mess,"Function (Write Register) is not implemented for this detector\n"); + cprintf(RED, "Warning: %s", mess); +#else - sprintf(mess,"Can't write to register\n"); - + // receive arguments + int arg[2]={-1,-1}; n = receiveData(file_des,arg,sizeof(arg),INT32); - if (n < 0) { - sprintf(mess,"Error reading from socket\n"); - ret=FAIL; - } - addr=arg[0]; - val=arg[1]; + if (n < 0) return printSocketReadError(); + int addr=arg[0]; + int val=arg[1]; -#if defined(MYTHEND) || defined(GOTTHARDD) -#ifdef VERBOSE - printf("writing to register 0x%x data 0x%x\n", addr, val); -#endif -#ifdef SLS_DETECTOR_FUNCTION_LIST - if (differentClients==1 && lockStatus==1) { - ret=FAIL; + // execute action + if (differentClients && lockStatus) { + ret = FAIL; sprintf(mess,"Detector locked by %s\n",lastClientIP); - } else + cprintf(RED, "Warning: %s", mess); + } +#ifdef SLS_DETECTOR_FUNCTION_LIST + else { +#ifdef VERBOSE + printf("writing to register 0x%x data 0x%x\n", addr, val); +#endif retval=writeRegister(addr,val); + if (retval!=val) { + ret = FAIL; + sprintf(mess,"Writing to register 0x%x failed: wrote 0x%x but read 0x%x\n", addr, val, retval); + cprintf(RED, "Warning: %s", mess); + } + } #endif #ifdef VERBOSE printf("Data set to 0x%x\n", retval); #endif -#else - ret = FAIL; - strcpy(mess,"Not applicable/implemented for this detector\n"); + if (ret==OK && differentClients) + ret=FORCE_UPDATE; #endif - if (retval==val) { - ret=OK; - if (differentClients) - ret=FORCE_UPDATE; - } else { - ret=FAIL; - sprintf(mess,"Writing to register 0x%x failed: wrote 0x%x but read 0x%x\n", addr, val, retval); - } - /* send answer */ - /* send OK/failed */ - //ret could be swapped during sendData + // ret could be swapped during sendData ret1 = ret; + // send ok / fail n = sendData(file_des,&ret1,sizeof(ret),INT32); + // send return argument if (ret!=FAIL) { - /* send return argument */ n += sendData(file_des,&retval,sizeof(retval),INT32); } else { n += sendData(file_des,mess,sizeof(mess),OTHER); } - /*return ok/fail*/ + // return ok / fail return ret; } + + + + int read_register(int file_des) { - - int retval; int ret=OK,ret1=OK; - int arg; - int addr; - int n; + int n=0; + int retval=-1; + sprintf(mess,"read register failed\n"); +#ifdef EIGERD + //to receive any arguments + while (n > 0) + n = receiveData(file_des,mess,MAX_STR_LENGTH,OTHER); + ret = FAIL; + sprintf(mess,"Function (Read Register) is not implemented for this detector\n"); + cprintf(RED, "Warning: %s", mess); +#else - sprintf(mess,"Can't read register\n"); - + // receive arguments + int arg=0; n = receiveData(file_des,&arg,sizeof(arg),INT32); - if (n < 0) { - sprintf(mess,"Error reading from socket\n"); - ret=FAIL; - } - addr=arg; + if (n < 0) return printSocketReadError(); + int addr=arg; -#if defined(MYTHEND) || defined(GOTTHARDD) + // execute action #ifdef VERBOSE printf("reading register 0x%x\n", addr); #endif @@ -1510,268 +1336,298 @@ int read_register(int file_des) { #ifdef VERBOSE printf("Returned value 0x%x\n", retval); #endif -#else - ret = FAIL; - strcpy(mess,"Not applicable/implemented for this detector\n"); + if (ret==OK && differentClients) + ret=FORCE_UPDATE; #endif - if (ret==FAIL) { - printf("Reading register 0x%x failed\n", addr); - } else if (differentClients) - ret=FORCE_UPDATE; - - - /* send answer */ - /* send OK/failed */ - //ret could be swapped during sendData + // ret could be swapped during sendData ret1 = ret; + // send ok / fail n = sendData(file_des,&ret1,sizeof(ret),INT32); + // send return argument if (ret!=FAIL) { - /* send return argument */ n += sendData(file_des,&retval,sizeof(retval),INT32); } else { n += sendData(file_des,mess,sizeof(mess),OTHER); } - /*return ok/fail*/ + // return ok / fail return ret; - } +int write_memory(int file_des) { + int ret=FAIL,ret1=FAIL; + int n=0; + sprintf(mess,"Function (Write Memory) is not implemented for this detector\n"); + cprintf(RED, "Error: %s", mess); + + //to receive any arguments + while (n > 0) + n = receiveData(file_des,mess,MAX_STR_LENGTH,OTHER); + + n = sendData(file_des,&ret1,sizeof(ret),INT32); + n = sendData(file_des,mess,MAX_STR_LENGTH,OTHER); + + // return ok / fail + return ret; +} + + +int read_memory(int file_des) { + int ret=FAIL,ret1=FAIL; + int n=0; + sprintf(mess,"Function (Read Memory) is not implemented for this detector\n"); + cprintf(RED, "Error: %s", mess); + + //to receive any arguments + while (n > 0) + n = receiveData(file_des,mess,MAX_STR_LENGTH,OTHER); + + n = sendData(file_des,&ret1,sizeof(ret),INT32); + n = sendData(file_des,mess,MAX_STR_LENGTH,OTHER); + + // return ok / fail + return ret; +} + int set_channel(int file_des) { int ret=OK,ret1=OK; + int n=0; + int retval=-1; + sprintf(mess,"set channel failed\n"); + +#ifndef MYTHEND + //to receive any arguments + while (n > 0) + n = receiveData(file_des,mess,MAX_STR_LENGTH,OTHER); + ret = FAIL; + sprintf(mess,"Function (Set Channel) is not implemented for this detector\n"); + cprintf(RED, "Warning: %s", mess); +#else + + // receive arguments sls_detector_channel myChan; - int retval; - int n; - - - sprintf(mess,"Can't set channel\n"); + n=receiveChannel(file_des, &myChan); + if (n < 0) return printSocketReadError(); + // execute action #ifdef VERBOSE printf("Setting channel\n"); -#endif - ret=receiveChannel(file_des, &myChan); - if (ret>=0) - ret=OK; - else - ret=FAIL; -#ifndef MYTHEND - ret = FAIL; - strcpy(mess,"Not applicable/implemented for this detector\n"); -#else -#ifdef VERBOSE printf("channel number is %d, chip number is %d, module number is %d, register is %lld\n", myChan.chan,myChan.chip, myChan.module, myChan.reg); #endif + if (differentClients && lockStatus) { + ret = FAIL; + sprintf(mess,"Detector locked by %s\n",lastClientIP); + cprintf(RED, "Warning: %s", mess); + } #ifdef SLS_DETECTOR_FUNCTION_LIST - if (myChan.chan>=getNumberOfChannelsPerChip()) { - ret=FAIL; - sprintf(mess, "channel number %d too large!\n",myChan.chan); + else if (myChan.chan>=getNumberOfChannelsPerChip()) { + ret = FAIL; + sprintf(mess,"channel number %d too large!\n",myChan.chan); + cprintf(RED, "Warning: %s", mess); } - if (myChan.chip>=getNumberOfChipsPerModule()) { - ret=FAIL; - sprintf(mess, "chip number %d too large!\n",myChan.chip); + else if (myChan.chip>=getNumberOfChipsPerModule()) { + ret = FAIL; + sprintf(mess,"chip number %d too large!\n",myChan.chip); + cprintf(RED, "Warning: %s", mess); } - - if (myChan.module>=getTotalNumberOfModules()) { - ret=FAIL; - sprintf(mess, "chip number %d too large!\n",myChan.module); - } - - - if (ret==OK) { - if (differentClients==1 && lockStatus==1) { - ret=FAIL; - sprintf(mess,"Detector locked by %s\n",lastClientIP); - } else { - retval=setChannel(myChan); - } + else if (myChan.module>=getTotalNumberOfModules()) { + ret = FAIL; + sprintf(mess,"module number %d too large!\n",myChan.module); + cprintf(RED, "Warning: %s", mess); } + else + retval=setChannel(myChan); #endif -#endif - /* Maybe this is done inside the initialization funcs */ - //copyChannel(detectorChans[myChan.module][myChan.chip]+(myChan.chan), &myChan); - - if (differentClients==1 && ret==OK) + if (ret==OK && differentClients) ret=FORCE_UPDATE; +#endif - /* send answer */ - /* send OK/failed */ - //ret could be swapped during sendData + // ret could be swapped during sendData ret1 = ret; + // send ok / fail n = sendData(file_des,&ret1,sizeof(ret),INT32); + // send return argument if (ret!=FAIL) { - /* send return argument */ n += sendData(file_des,&retval,sizeof(retval),INT32); } else { n += sendData(file_des,mess,sizeof(mess),OTHER); } - - /*return ok/fail*/ + // return ok / fail return ret; - } int get_channel(int file_des) { - int ret=OK,ret1=OK; + int n=0; sls_detector_channel retval; - - int arg[3]; -#ifdef MYTHEND - int ichan, ichip, imod; -#endif - int n; - - sprintf(mess,"Can't get channel\n"); - - - - n = receiveData(file_des,arg,sizeof(arg),INT32); - if (n < 0) { - sprintf(mess,"Error reading from socket\n"); - ret=FAIL; - } + sprintf(mess,"get channel failed\n"); #ifndef MYTHEND + //to receive any arguments + while (n > 0) + n = receiveData(file_des,mess,MAX_STR_LENGTH,OTHER); ret = FAIL; - strcpy(mess,"Not applicable/implemented for this detector\n"); + sprintf(mess,"Function (Get Channel) is not implemented for this detector\n"); + cprintf(RED, "Warning: %s", mess); #else - ichan=arg[0]; - ichip=arg[1]; - imod=arg[2]; + + // receive arguments + int arg[3]={-1,-1,-1}; + n = receiveData(file_des,arg,sizeof(arg),INT32); + if (n < 0) return printSocketReadError(); + + // execute action + int ichan=arg[0]; + int ichip=arg[1]; + int imod=arg[2]; #ifdef SLS_DETECTOR_FUNCTION_LIST if (ichan>=getNumberOfChannelsPerChip()) { ret=FAIL; - sprintf(mess, "channel number %d too large!\n",ichan); + sprintf(mess, "channel number %d too large!\n",myChan.chan); + cprintf(RED, "Warning: %s", mess); } else retval.chan=ichan; if (ichip>=getNumberOfChipsPerModule()) { ret=FAIL; - sprintf(mess, "chip number %d too large!\n",ichip); + sprintf(mess, "chip number %d too large!\n",myChan.chip); + cprintf(RED, "Warning: %s", mess); } else retval.chip=ichip; if (imod>=getTotalNumberOfModules()) { ret=FAIL; - sprintf(mess, "chip number %d too large!\n",imod); - } else + sprintf(mess, "module number %d too large!\n",myChan.module); + cprintf(RED, "Warning: %s", mess); + } else { retval.module=imod; - - - if (ret==OK) ret=getChannel(&retval); -#endif -#endif - if (differentClients && ret==OK) - ret=FORCE_UPDATE; - -#ifdef MYTHEND #ifdef VERBOSE printf("Returning channel %d %d %d, 0x%llx\n", retval.chan, retval.chip, retval.mod, (retval.reg)); -#endif +#endif + } +#endif + if (ret==OK && differentClients) + ret=FORCE_UPDATE; #endif - /* send answer */ - /* send OK/failed */ - //ret could be swapped during sendData + // ret could be swapped during sendData ret1 = ret; + // send ok / fail n = sendData(file_des,&ret1,sizeof(ret),INT32); + // send return argument if (ret!=FAIL) { - /* send return argument */ ret=sendChannel(file_des, &retval); } else { n += sendData(file_des,mess,sizeof(mess),OTHER); } - - - /*return ok/fail*/ + // return ok / fail return ret; - - } + +int set_all_channels(int file_des) { + int ret=FAIL,ret1=FAIL; + int n=0; + sprintf(mess,"Function (Set All Channels) is not implemented for this detector\n"); + cprintf(RED, "Error: %s", mess); + + //to receive any arguments + while (n > 0) + n = receiveData(file_des,mess,MAX_STR_LENGTH,OTHER); + + n = sendData(file_des,&ret1,sizeof(ret),INT32); + n = sendData(file_des,mess,MAX_STR_LENGTH,OTHER); + + // return ok / fail + return ret; +} + + + + + int set_chip(int file_des) { - - int *ch; - int n, retval; int ret=OK,ret1=OK; -#ifdef SLS_DETECTOR_FUNCTION_LIST - sls_detector_chip myChip; - - myChip.nchan=getNumberOfChannelsPerChip(); - ch=(int*)malloc((myChip.nchan)*sizeof(int)); - myChip.chanregs=ch; - - - -#ifdef VERBOSE - printf("Setting chip\n"); -#endif - ret=receiveChip(file_des, &myChip); + int n=0; + int retval=-1; + sprintf(mess,"set chip failed\n"); #ifndef MYTHEND + //to receive any arguments + while (n > 0) + n = receiveData(file_des,mess,MAX_STR_LENGTH,OTHER); ret = FAIL; - strcpy(mess,"Not applicable/implemented for this detector\n"); + sprintf(mess,"Function (Set Channel) is not implemented for this detector\n"); + cprintf(RED, "Warning: %s", mess); #else + sls_detector_chip myChip; + +#ifdef SLS_DETECTOR_FUNCTION_LIST + myChip.nchan=getNumberOfChannelsPerChip(); + int *ch(int*)malloc((myChip.nchan)*sizeof(int)); + myChip.chanregs=ch; + + // receive arguments + n=receiveChip(file_des, &myChip); #ifdef VERBOSE printf("Chip received\n"); #endif - if (ret>=0) - ret=OK; - else - ret=FAIL; -#ifdef VERBOSE - printf("chip number is %d, module number is %d, register is %d, nchan %d\n",myChip.chip, myChip.module, myChip.reg, myChip.nchan); -#endif - - if (myChip.chip>=getNumberOfChipsPerModule()) { - ret=FAIL; - sprintf(mess, "chip number %d too large!\n",myChip.chip); - } - - if (myChip.module>=getTotalNumberOfModules()) { - ret=FAIL; - sprintf(mess, "chip number %d too large!\n",myChip.module); - } - + if(n < 0) return FAIL; + // execute action if (differentClients==1 && lockStatus==1) { - ret=FAIL; + ret = FAIL; sprintf(mess,"Detector locked by %s\n",lastClientIP); - } else { - retval=setChip(myChip); + cprintf(RED, "Warning: %s", mess); } + else{ +#ifdef VERBOSE + printf("Setting chip\n"); + printf("chip number is %d, module number is %d, register is %d, nchan %d\n",myChip.chip, myChip.module, myChip.reg, myChip.nchan); #endif + if (myChip.chip>=getNumberOfChipsPerModule()) { + ret = FAIL; + sprintf(mess,"chip number %d too large!\n",myChan.chip); + cprintf(RED, "Warning: %s", mess); + } + else if (myChip.module>=getTotalNumberOfModules()) { + ret = FAIL; + sprintf(mess,"module number %d too large!\n",myChan.module); + cprintf(RED, "Warning: %s", mess); + } + else + retval=setChip(myChip); + } + free(ch); #endif - /* Maybe this is done inside the initialization funcs */ - //copyChip(detectorChips[myChip.module]+(myChip.chip), &myChip); - - if (differentClients && ret==OK) + if (ret==OK && differentClients) ret=FORCE_UPDATE; - /* send answer */ - /* send OK/failed */ - //ret could be swapped during sendData +#endif + + // ret could be swapped during sendData ret1 = ret; + // send ok / fail n = sendData(file_des,&ret1,sizeof(ret),INT32); + // send return argument if (ret!=FAIL) { - /* send return argument */ n += sendData(file_des,&retval,sizeof(retval),INT32); } else { n += sendData(file_des,mess,sizeof(mess),OTHER); } - free(ch); + // return ok / fail return ret; } @@ -1779,79 +1635,87 @@ int set_chip(int file_des) { int get_chip(int file_des) { - - int ret=OK,ret1=OK; + int n=0; sls_detector_chip retval; - int arg[2]; - int n, *ch; -#ifdef MYTHEND - int ichip, imod; -#endif - - -#ifdef SLS_DETECTOR_FUNCTION_LIST - retval.nchan=getNumberOfChannelsPerChip(); - ch=(int*)malloc((retval.nchan)*sizeof(int)); - retval.chanregs=ch; -#endif - - n = receiveData(file_des,arg,sizeof(arg),INT32); - if (n < 0) { - sprintf(mess,"Error reading from socket\n"); - ret=FAIL; - } + sprintf(mess,"get chip failed\n"); #ifndef MYTHEND + //to receive any arguments + while (n > 0) + n = receiveData(file_des,mess,MAX_STR_LENGTH,OTHER); ret = FAIL; - strcpy(mess,"Not applicable/implemented for this detector\n"); + sprintf(mess,"Function (Set Channel) is not implemented for this detector\n"); + cprintf(RED, "Warning: %s", mess); #else - ichip=arg[0]; - imod=arg[1]; + + // receive arguments + int arg[2]={-1,-1}; + n = receiveData(file_des,arg,sizeof(arg),INT32); + if (n < 0) return printSocketReadError(); + #ifdef SLS_DETECTOR_FUNCTION_LIST + int ichip=arg[0]; + int imod=arg[1]; + + // execute action if (ichip>=getNumberOfChipsPerModule()) { - ret=FAIL; - sprintf(mess, "chip number %d too large!\n",ichip); + ret = FAIL; + sprintf(mess,"channel number %d too large!\n",myChan.chan); + cprintf(RED, "Warning: %s", mess); } else retval.chip=ichip; if (imod>=getTotalNumberOfModules()) { - ret=FAIL; - sprintf(mess, "chip number %d too large!\n",imod); + ret = FAIL; + sprintf(mess,"module number %d too large!\n",imod); + cprintf(RED, "Warning: %s", mess); } else retval.module=imod; if (ret==OK) ret=getChip(&retval); #endif - -#endif - if (differentClients && ret==OK) - ret=FORCE_UPDATE; -#ifdef MYTHEND #ifdef VERBOSE printf("Returning chip %d %d\n", ichip, imod); -#endif +#endif + if (ret==OK && differentClients) + ret=FORCE_UPDATE; #endif - /* send answer */ - /* send OK/failed */ - //ret could be swapped during sendData + // ret could be swapped during sendData ret1 = ret; + // send ok / fail n = sendData(file_des,&ret1,sizeof(ret),INT32); + // send return argument if (ret!=FAIL) { - /* send return argument */ ret=sendChip(file_des, &retval); } else { n += sendData(file_des,mess,sizeof(mess),OTHER); } - free(ch); - - /*return ok/fail*/ + // return ok / fail return ret; +} + + +int set_all_chips(int file_des) { + int ret=FAIL,ret1=FAIL; + int n=0; + sprintf(mess,"Function (Set All Chips) is not implemented for this detector\n"); + cprintf(RED, "Error: %s", mess); + + //to receive any arguments + while (n > 0) + n = receiveData(file_des,mess,MAX_STR_LENGTH,OTHER); + + n = sendData(file_des,&ret1,sizeof(ret),INT32); + n = sendData(file_des,mess,MAX_STR_LENGTH,OTHER); + + // return ok / fail + return ret; } @@ -1859,137 +1723,176 @@ int get_chip(int file_des) { int set_module(int file_des) { - int retval, n; int ret=OK,ret1=OK; - - strcpy(mess,"could not set module."); + int n=0; + sls_detector_module myModule; + int retval=-1; +#ifdef EIGERD + int myIODelay=-1; + int myTau=-1; + int myEV=-1; +#endif + sprintf(mess,"set module failed\n"); #ifdef SLS_DETECTOR_FUNCTION_LIST - sls_detector_module myModule; -#ifdef EIGERD - int *myGain = (int*)malloc(getNumberOfGainsPerModule()*sizeof(int)); - int *myOffset = (int*)malloc(getNumberOfOffsetsPerModule()*sizeof(int)); - int *myIODelay = (int*)malloc(sizeof(int)); - int64_t myTau=-1; -#endif - int *myChip=(int*)malloc(getNumberOfChipsPerModule()*sizeof(int)); - int *myChan=(int*)malloc(getNumberOfChannelsPerModule()*sizeof(int)); - int *myDac=(int*)malloc(getNumberOfDACsPerModule()*sizeof(int)); - int *myAdc=(int*)malloc(getNumberOfADCsPerModule()*sizeof(int)); + int *myDac=NULL; + int *myAdc=NULL; + int *myChip = NULL; + int *myChan = NULL; - - if (myDac) - myModule.dacs=myDac; - else { - sprintf(mess,"could not allocate dacs\n"); - ret=FAIL; - } - if (myAdc) - myModule.adcs=myAdc; - else { - sprintf(mess,"could not allocate adcs\n"); - ret=FAIL; - } - if (myChip) - myModule.chipregs=myChip; - else { - sprintf(mess,"could not allocate chips\n"); - ret=FAIL; - } - if (myChan) - myModule.chanregs=myChan; - else { - sprintf(mess,"could not allocate chans\n"); - ret=FAIL; - } -#ifdef EIGERD - if (!myGain){ - sprintf(mess,"could not allocate gains\n"); - ret=FAIL; - } - if (!myOffset){ - sprintf(mess,"could not allocate offsets\n"); - ret=FAIL; - } -#endif - myModule.nchip=getNumberOfChipsPerModule(); - myModule.nchan=getNumberOfChannelsPerModule(); - myModule.ndac=getNumberOfDACsPerModule(); - myModule.nadc=getNumberOfADCsPerModule(); - - -#ifdef VERBOSE - printf("Setting module\n"); -#endif - ret=receiveModule(file_des, &myModule); -#ifdef EIGERD - n = receiveData(file_des,myGain,sizeof(int)*getNumberOfGainsPerModule(),INT32); - n = receiveData(file_des,myOffset,sizeof(int)*getNumberOfOffsetsPerModule(),INT32); - n = receiveData(file_des,myIODelay,sizeof(int),INT32); - n = receiveData(file_des,&myTau,sizeof(myTau),INT64); -#endif - if (ret>=0) - ret=OK; - else - ret=FAIL; - - -#ifdef VERBOSE - printf("module number is %d,register is %d, nchan %d, nchip %d, ndac %d, nadc %d, gain %f, offset %f\n",myModule.module, myModule.reg, myModule.nchan, myModule.nchip, myModule.ndac, myModule.nadc, myModule.gain,myModule.offset); -#ifdef EIGERD - int i; - for(i=0;i=getNModBoard()) { + ret = FAIL; + sprintf(mess,"Module Number to Set Module (%d) is too large\n", myModule.module); + cprintf(RED, "Warning: %s", mess); + } + if (myModule.module<0) + myModule.module=ALLMOD; +#endif +#if defined(JUNGFRAUD) || defined(EIGERD) + switch(myModule.reg){ + case GET_SETTINGS: + case UNINITIALIZED: #ifdef EIGERD - ret=setModule(myModule, myGain, myOffset,myIODelay); + case STANDARD: + case HIGHGAIN: + case LOWGAIN: + case VERYHIGHGAIN: + case VERYLOWGAIN: +#elif JUNGFRAUD + case DYNAMICGAIN: + case DYNAMICHG0: + case FIXGAIN1: + case FIXGAIN2: + case FORCESWITCHG1: + case FORCESWITCHG2: +#endif + break; + default: + ret = FAIL; + sprintf(mess,"Setting (%d) is not implemented for this detector\n", myModule.reg); + cprintf(RED, "Warning: %s", mess); + break; + } + } +#endif + + + // execute action + if (ret==OK) { + if (differentClients && lockStatus) { + ret = FAIL; + sprintf(mess,"Detector locked by %s\n",lastClientIP); + cprintf(RED, "Warning: %s", mess); + } +#ifdef EIGERD + //set dacs, trimbits and iodelay + ret=setModule(myModule, myIODelay); + //set threshhold + if (myEV >= 0) + setThresholdEnergy(myEV,-1); + else { + //changes settings to undefined (loading a random trim file) + setSettings(UNDEFINED,-1); + cprintf(RED,"Settings has been changed to undefined (random trim file)\n"); + } //rate correction - if(myTau > -2){ //ignore -2: from load settings) - - //set default tau value (-1 or a normal value) - setDefaultSettingsTau_in_nsec(myTau); - - //switch off rate correction: no value read from load calib/load settings) - if(myTau == -1){ - if(getRateCorrectionEnable()){ - ret = FAIL; - setRateCorrection(0); - strcat(mess,"Cannot set Rate correction. No default tau provided. Deactivating Rate Correction\n"); - cprintf(RED,"%s",mess); - } + //switch off rate correction: no value read from load calib/load settings) + if(myTau == -1){ + if(getRateCorrectionEnable()){ + setRateCorrection(0); + ret = FAIL; + strcat(mess,"Cannot set Rate correction. No default tau provided. Deactivating Rate Correction\n"); + cprintf(RED, "Warning: %s", mess); } - - - //normal tau value (only if enabled) - else if (getRateCorrectionEnable()){ - int64_t retvalTau = setRateCorrection(myTau); //myTau will not be -1 here + } + //normal tau value (only if enabled) + else{ + setDefaultSettingsTau_in_nsec(myTau); + if (getRateCorrectionEnable()){ + int64_t retvalTau = setRateCorrection(myTau); if(myTau != retvalTau){ cprintf(RED,"%s",mess); ret=FAIL; @@ -1997,510 +1900,517 @@ int set_module(int file_des) { } } retval = getSettings(); - #else - ret=setModule(myModule); - retval = ret; + retval=setModule(myModule); + if (retval != myModule.reg) + ret = FAIL; #endif - } + if(myChip != NULL) free(myChip); + if(myChan != NULL) free(myChan); + if(myDac != NULL) free(myDac); + if(myAdc != NULL) free(myAdc); } -#endif - if (differentClients==1 && ret==OK) + if (ret==OK && differentClients) ret=FORCE_UPDATE; +#endif - /* Maybe this is done inside the initialization funcs */ - //copyChip(detectorChips[myChip.module]+(myChip.chip), &myChip); - - /* send answer */ - /* send OK/failed */ - //ret could be swapped during sendData + // ret could be swapped during sendData ret1 = ret; + // send ok / fail n = sendData(file_des,&ret1,sizeof(ret),INT32); + // send return argument if (ret!=FAIL) { - /* send return argument */ n += sendData(file_des,&retval,sizeof(retval),INT32); } else { n += sendData(file_des,mess,sizeof(mess),OTHER); } -#ifdef SLS_DETECTOR_FUNCTION_LIST - free(myChip); - free(myChan); - free(myDac); - free(myAdc); -#ifdef EIGERD - free(myGain); - free(myOffset); -#endif -#endif + + // return ok / fail return ret; } + + + + int get_module(int file_des) { - - int ret=OK,ret1=OK; - int arg; - int imod; - int n; + int n=0; + int arg=-1; + int imod=-1; sls_detector_module myModule; + sprintf(mess,"get module failed\n"); -#ifdef SLS_DETECTOR_FUNCTION_LIST -#ifdef EIGERD - int *myGain = (int*)malloc(getNumberOfGainsPerModule()*sizeof(int)); - int *myOffset = (int*)malloc(getNumberOfOffsetsPerModule()*sizeof(int)); -#endif - int *myChip=(int*)malloc(getNumberOfChipsPerModule()*sizeof(int)); - int *myChan=(int*)malloc(getNumberOfChannelsPerModule()*sizeof(int)); - int *myDac=(int*)malloc(getNumberOfDACsPerModule()*sizeof(int)); - int *myAdc=(int*)malloc(getNumberOfADCsPerModule()*sizeof(int)); - - - if (myDac) - myModule.dacs=myDac; - else { - sprintf(mess,"could not allocate dacs\n"); - ret=FAIL; - } - if (myAdc) - myModule.adcs=myAdc; - else { - sprintf(mess,"could not allocate adcs\n"); - ret=FAIL; - } - if (myChip) - myModule.chipregs=myChip; - else { - sprintf(mess,"could not allocate chips\n"); - ret=FAIL; - } - if (myChan) - myModule.chanregs=myChan; - else { - sprintf(mess,"could not allocate chans\n"); - ret=FAIL; - } -#ifdef EIGERD - if (!myGain){ - sprintf(mess,"could not allocate gains\n"); - ret=FAIL; - } - if (!myOffset){ - sprintf(mess,"could not allocate offsets\n"); - ret=FAIL; - } -#endif - myModule.ndac=getNumberOfDACsPerModule(); - myModule.nchip=getNumberOfChipsPerModule(); - myModule.nchan=getNumberOfChannelsPerModule(); - myModule.nadc=getNumberOfADCsPerModule(); - -#endif - - - + // receive arguments n = receiveData(file_des,&arg,sizeof(arg),INT32); - if (n < 0) { - sprintf(mess,"Error reading from socket\n"); - ret=FAIL; - } + if (n < 0) return printSocketReadError(); imod=arg; + // execute action #ifdef SLS_DETECTOR_FUNCTION_LIST - if (ret==OK) { - ret=FAIL; - if (imod>=0) { - ret=OK; - myModule.module=imod; -#ifdef EIGERD - getModule(&myModule, myGain, myOffset); -#ifdef VERBOSE - for(i=0;igetTotalNumberOfModules()) { + ret = FAIL; + sprintf(mess,"Module Index (%d) is out of range\n", imod); + cprintf(RED, "Warning: %s", mess); + } + else { + myDac=(int*)malloc(getNumberOfDACsPerModule()*sizeof(int)); + if (myDac == NULL) { + ret = FAIL; + sprintf(mess,"could not allocate dacs\n"); + cprintf(RED, "Warning: %s", mess); + } + else { + myModule.dacs=myDac; + myAdc=(int*)malloc(getNumberOfADCsPerModule()*sizeof(int)); + if (myAdc == NULL) { + ret = FAIL; + sprintf(mess,"could not allocate adcs\n"); + cprintf(RED, "Warning: %s", mess); + } + else { + myModule.adcs=myAdc; + //no chips and chans allocated for jungfrau, too much memory +#ifdef JUNGFRAUD + myModule.chipregs=NULL; + myModule.chanregs=NULL; #else - getModule(&myModule); + myChip=(int*)malloc(getNumberOfChipsPerModule()*sizeof(int)); + if (myChip == NULL) { + ret = FAIL; + sprintf(mess,"could not allocate chips\n"); + cprintf(RED, "Warning: %s", mess); + } + else { + myModule.chipregs=myChip; + myChan=(int*)malloc(getNumberOfChannelsPerModule()*sizeof(int)); + if (myChan == NULL) { + ret = FAIL; + sprintf(mess,"could not allocate chans\n"); + cprintf(RED, "Warning: %s", mess); + } + else { + myModule.chanregs=myChan; #endif - - + myModule.nchip=getNumberOfChipsPerModule(); + myModule.nchan=getNumberOfChannelsPerModule(); + myModule.ndac=getNumberOfDACsPerModule(); + myModule.nadc=getNumberOfADCsPerModule(); + myModule.module=imod; + getModule(&myModule); #ifdef VERBOSE - printf("Returning module %d of register %x\n", imod, myModule.reg); -#endif + printf("Returning module %d of register %x\n", imod, myModule.reg); +#endif +#ifndef JUNGFRAUD + } + } +#endif + } } } #endif - if (differentClients==1 && ret==OK) + if (ret==OK && differentClients) ret=FORCE_UPDATE; - /* send answer */ - /* send OK/failed */ - //ret could be swapped during sendData + // ret could be swapped during sendData ret1 = ret; + // send ok / fail n = sendData(file_des,&ret1,sizeof(ret),INT32); + // send return argument if (ret!=FAIL) { - /* send return argument */ - ret=sendModule(file_des, &myModule); -#ifdef EIGERD - n = sendData(file_des,myGain,sizeof(int)*getNumberOfGainsPerModule(),INT32); - n = sendData(file_des,myOffset,sizeof(int)*getNumberOfOffsetsPerModule(),INT32); + ret=sendModuleGeneral(file_des, &myModule, +#ifdef JUNGFRAUD + 0 //0 is to receive partially (without trimbits etc.) +#else + 1 #endif + ); } else { n += sendData(file_des,mess,sizeof(mess),OTHER); } #ifdef SLS_DETECTOR_FUNCTION_LIST - free(myChip); - free(myChan); - free(myDac); - free(myAdc); -#ifdef EIGERD - free(myGain); - free(myOffset); + if(myChip != NULL) free(myChip); + if(myChan != NULL) free(myChan); + if(myDac != NULL) free(myDac); + if(myAdc != NULL) free(myAdc); #endif -#endif - /*return ok/fail*/ + + // return ok / fail return ret; } +int set_all_modules(int file_des) { + int ret=FAIL,ret1=FAIL; + int n=0; + sprintf(mess,"Function (Set All Modules) is not implemented for this detector\n"); + cprintf(RED, "Error: %s", mess); + + //to receive any arguments + while (n > 0) + n = receiveData(file_des,mess,MAX_STR_LENGTH,OTHER); + + n = sendData(file_des,&ret1,sizeof(ret),INT32); + n = sendData(file_des,mess,MAX_STR_LENGTH,OTHER); + + // return ok / fail + return ret; +} + + int set_settings(int file_des) { - - int retval; int ret=OK,ret1=OK; - int arg[2]; - int n; - int imod; - enum detectorSettings isett; - + int n=0; + int arg[2]={-1,-1}; + int retval=-1; + int imod=-1; + enum detectorSettings isett=-1; + sprintf(mess,"set settings failed\n"); + // receive arguments n = receiveData(file_des,&arg,sizeof(arg),INT32); - if (n < 0) { - sprintf(mess,"Error reading from socket\n"); - ret=FAIL; - } + if (n < 0) return printSocketReadError(); imod=arg[1]; isett=arg[0]; -#ifdef VERBOSE - printf("In set_settings, isett:%d, imod =%d\n",isett,imod); -#endif -#ifdef SLS_DETECTOR_FUNCTION_LIST - if (imod>=getTotalNumberOfModules()) { - ret=FAIL; - sprintf(mess,"Module number %d out of range\n",imod); - } + // execute action + if (differentClients && lockStatus && isett!=GET_SETTINGS) { + ret = FAIL; + sprintf(mess,"Detector locked by %s\n",lastClientIP); + cprintf(RED, "Warning: %s", mess); + } +#ifdef SLS_DETECTOR_FUNCTION_LIST + else if (imod>=getTotalNumberOfModules()) { + ret = FAIL; + sprintf(mess,"Module number %d out of range\n",imod); + cprintf(RED, "Warning: %s", mess); + } + else { #ifdef VERBOSE printf("Changing settings of module %d to %d\n", imod, isett); #endif - - if (differentClients==1 && lockStatus==1 && isett!=GET_SETTINGS) { - ret=FAIL; - sprintf(mess,"Detector locked by %s\n",lastClientIP); - } else { retval=setSettings(isett, imod); #ifdef VERBOSE printf("Settings changed to %d\n", isett); #endif - if (retval==isett || isett<0) { ret=OK; } else { - ret=FAIL; - printf("Changing settings of module %d: wrote %d but read %d\n", imod, isett, retval); + ret = FAIL; + sprintf(mess,"Changing settings of module %d: wrote %d but read %d\n", imod, isett, retval); + cprintf(RED, "Warning: %s", mess); } - } #endif - if (ret==OK && differentClients==1) + if (ret==OK && differentClients) ret=FORCE_UPDATE; - /* send answer */ - //ret could be swapped during sendData + // ret could be swapped during sendData ret1 = ret; + // send ok / fail n = sendData(file_des,&ret1,sizeof(ret),INT32); + // send return argument if (ret==FAIL) { n += sendData(file_des,mess,sizeof(mess),OTHER); } else n += sendData(file_des,&retval,sizeof(retval),INT32); + // return ok / fail return ret; - - } - -int get_threshold_energy(int file_des) { - int retval; +int get_threshold_energy(int file_des) { int ret=OK,ret1=OK; - int n; - int imod; + int n=0; + int retval=-1; + sprintf(mess,"get threshold energy failed\n"); +#if !defined(MYTHEND) && !defined(EIGERD) + //to receive any arguments + while (n > 0) + n = receiveData(file_des,mess,MAX_STR_LENGTH,OTHER); + ret = FAIL; + sprintf(mess,"Function (Get Threshold Energy) is not implemented for this detector\n"); + cprintf(RED, "Warning: %s", mess); +#else + // receive arguments + int imod=-1; n = receiveData(file_des,&imod,sizeof(imod),INT32); - if (n < 0) { - sprintf(mess,"Error reading from socket\n"); - ret=FAIL; - } + if (n < 0) return printSocketReadError(); -#if defined(MYTHEND) || defined(EIGERD) + // execute action #ifdef VERBOSE printf("Getting threshold energy of module %d\n", imod); -#endif +#endif #ifdef SLS_DETECTOR_FUNCTION_LIST if (imod>=getTotalNumberOfModules()) { ret=FAIL; sprintf(mess,"Module number %d out of range\n",imod); } - - retval=getThresholdEnergy(imod); -#endif + else { + retval=getThresholdEnergy(imod); #ifdef VERBOSE printf("Threshold is %d eV\n", retval); -#endif +#endif + } +#endif + if (ret==OK && differentClients) + ret=FORCE_UPDATE; #endif - if (differentClients==1 && ret==OK) - ret=FORCE_UPDATE; - - /* send answer */ - //ret could be swapped during sendData + // ret could be swapped during sendData ret1 = ret; + // send ok / fail n = sendData(file_des,&ret1,sizeof(ret),INT32); + // send return argument if (ret==FAIL) { n += sendData(file_des,mess,sizeof(mess),OTHER); } else n += sendData(file_des,&retval,sizeof(retval),INT32); - - /* Maybe this is done inside the initialization funcs */ - //detectorDacs[imod][ind]=val; - /*return ok/fail*/ + // return ok / fail return ret; - } -int set_threshold_energy(int file_des) { - int retval; +int set_threshold_energy(int file_des) { int ret=OK,ret1=OK; - int arg[3]; - int n; -#if defined(MYTHEND) || defined(EIGERD) - int ethr, imod; - enum detectorSettings isett; + int n=0; + int retval=-1; + sprintf(mess,"set thhreshold energy failed\n"); + +#ifndef MYTHEND + //to receive any arguments + while (n > 0) + n = receiveData(file_des,mess,MAX_STR_LENGTH,OTHER); + ret = FAIL; +#ifdef EIGERD + sprintf(mess,"Function (Set Threshold Energy) is only implemented via Set Settings for this detector\n"); +#else + sprintf(mess,"Function (Set Threshold Energy) is not implemented for this detector\n"); #endif + cprintf(RED, "Warning: %s", mess); +#else + // receive arguments + int arg[3]={-1,-1,-1}; n = receiveData(file_des,&arg,sizeof(arg),INT32); - if (n < 0) { - sprintf(mess,"Error reading from socket\n"); - ret=FAIL; - } + if (n < 0) return printSocketReadError(); -#if defined(MYTHEND) || defined(EIGERD) - ethr=arg[0]; - imod=arg[1]; - isett=arg[2]; + // execute action + int ethr=arg[0]; + int imod=arg[1]; + enum detectorSettings isett=arg[2]; + if (differentClients && lockStatus) { + ret=FAIL; + sprintf(mess,"Detector locked by %s\n",lastClientIP); + } #ifdef SLS_DETECTOR_FUNCTION_LIST - if (imod>=getTotalNumberOfModules()) { + else if (imod>=getTotalNumberOfModules()) { ret=FAIL; sprintf(mess,"Module number %d out of range\n",imod); } - printf("Setting threshold energy of module %d to %d eV with settings %d\n", imod, ethr, isett); - if (differentClients==1 && lockStatus==1) { - ret=FAIL; - sprintf(mess,"Detector locked by %s\n",lastClientIP); - } else { + else { + printf("Setting threshold energy of module %d to %d eV with settings %d\n", imod, ethr, isett); retval=setThresholdEnergy(ethr, imod); - } #ifdef VERBOSE printf("Threshold set to %d eV\n", retval); -#endif - if (retval==ethr) - ret=OK; - else { +#endif + if (retval!=ethr) { ret=FAIL; - printf("Setting threshold of module %d: wrote %d but read %d\n", imod, ethr, retval); sprintf(mess,"Setting threshold of module %d: wrote %d but read %d\n", imod, ethr, retval); + cprintf(RED, "Warning: %s", mess); } #endif -#endif - if (ret==OK && differentClients==1) + if (ret==OK && differentClients) ret=FORCE_UPDATE; +#endif - /* send answer */ - //ret could be swapped during sendData + // ret could be swapped during sendData ret1 = ret; + // send ok / fail n = sendData(file_des,&ret1,sizeof(ret),INT32); + // send return argument if (ret==FAIL) { n += sendData(file_des,mess,sizeof(mess),OTHER); } else n += sendData(file_des,&retval,sizeof(retval),INT32); - - /* Maybe this is done inside the initialization funcs */ - //detectorDacs[imod][ind]=val; - /*return ok/fail*/ + // return ok / fail return ret; - } + int start_acquisition(int file_des) { - int ret=OK,ret1=OK; - int n; + int n=0; + sprintf(mess,"start acquisition failed\n"); - - sprintf(mess,"can't start acquisition\n"); - -#ifdef VERBOSE - printf("Starting acquisition\n"); -#endif -#ifdef SLS_DETECTOR_FUNCTION_LIST - if (differentClients==1 && lockStatus==1) { - ret=FAIL; + // execute action + if (differentClients && lockStatus) { + ret = FAIL; sprintf(mess,"Detector locked by %s\n",lastClientIP); - } else { + cprintf(RED, "Warning: %s", mess); + } +#ifdef SLS_DETECTOR_FUNCTION_LIST + else { + printf("Starting acquisition\n"); ret=startStateMachine(); + if (ret==FAIL) + cprintf(RED, "Warning: %s", mess); } #endif - if (ret==FAIL) - sprintf(mess,"Start acquisition failed\n"); - else if (differentClients) + if (ret==OK && differentClients) ret=FORCE_UPDATE; - //ret could be swapped during sendData + // ret could be swapped during sendData ret1 = ret; + // send ok / fail n = sendData(file_des,&ret1,sizeof(ret),INT32); + // send return argument if (ret==FAIL) { n += sendData(file_des,mess,sizeof(mess),OTHER); } - return ret; + // return ok / fail + return ret; } + + int stop_acquisition(int file_des) { - int ret=OK,ret1=OK; - int n; + int n=0; + sprintf(mess,"stop acquisition failed\n"); - - sprintf(mess,"can't stop acquisition\n"); - -//#ifdef VERBOSE - printf("Stopping acquisition\n"); -//#endif -#ifdef SLS_DETECTOR_FUNCTION_LIST - if (differentClients==1 && lockStatus==1) { - ret=FAIL; + // execute action + if (differentClients && lockStatus) { + ret = FAIL; sprintf(mess,"Detector locked by %s\n",lastClientIP); - } else { + cprintf(RED, "Warning: %s", mess); + } +#ifdef SLS_DETECTOR_FUNCTION_LIST + else { + printf("Stopping acquisition\n"); ret=stopStateMachine(); + if (ret==FAIL) + cprintf(RED, "Warning: %s", mess); } #endif - if (ret==FAIL) - sprintf(mess,"Stop acquisition failed\n"); - else if (differentClients) + if (ret==OK && differentClients) ret=FORCE_UPDATE; - //ret could be swapped during sendData + // ret could be swapped during sendData ret1 = ret; + // send ok / fail n = sendData(file_des,&ret1,sizeof(ret),INT32); + // send return argument if (ret==FAIL) { n += sendData(file_des,mess,sizeof(mess),OTHER); } + + // return ok / fail return ret; - - } + int start_readout(int file_des) { - - int ret=OK,ret1=OK; - int n; + int n=0; + sprintf(mess,"start readout failed\n"); +#ifdef JUNGFRAUD + //to receive any arguments + while (n > 0) + n = receiveData(file_des,mess,MAX_STR_LENGTH,OTHER); + ret = FAIL; + sprintf(mess,"Function (Start Readout) is not implemented for this detector\n"); + cprintf(RED, "%s", mess); +#else - sprintf(mess,"can't start readout\n"); - -#ifdef VERBOSE - printf("Starting readout\n"); -#endif -#ifdef SLS_DETECTOR_FUNCTION_LIST - if (differentClients==1 && lockStatus==1) { - ret=FAIL; + // execute action + if (differentClients && lockStatus) { + ret = FAIL; sprintf(mess,"Detector locked by %s\n",lastClientIP); - } else { + cprintf(RED, "Warning: %s", mess); + } +#ifdef SLS_DETECTOR_FUNCTION_LIST + else { + printf("Starting readout\n"); ret=startReadOut(); + if (ret==FAIL) + cprintf(RED, "Warning: %s", mess); } #endif - if (ret==FAIL) - sprintf(mess,"Start readout failed\n"); - else if (differentClients) + if (ret==OK && differentClients) ret=FORCE_UPDATE; +#endif - //ret could be swapped during sendData + // ret could be swapped during sendData ret1 = ret; + // send ok / fail n = sendData(file_des,&ret1,sizeof(ret),INT32); + // send return argument if (ret==FAIL) { n += sendData(file_des,mess,sizeof(mess),OTHER); } + + // return ok / fail return ret; - - - } -int get_run_status(int file_des) { + +int get_run_status(int file_des) { int ret=OK,ret1=OK; - int n; - enum runStatus s; - sprintf(mess,"getting run status\n"); + enum runStatus s=ERROR; + // execute action #ifdef VERBOSE printf("Getting status\n"); #endif -//#ifdef SLS_DETECTOR_FUNCTION_LIST - s= getRunStatus();printf("status:%x\n",s); -//#endif - - if (ret!=OK) { - printf("get status failed\n"); - } else if (differentClients) +#ifdef SLS_DETECTOR_FUNCTION_LIST + s= getRunStatus(); +#endif + if (differentClients) ret=FORCE_UPDATE; - //ret could be swapped during sendData - ret1 = ret; - n = sendData(file_des,&ret1,sizeof(ret),INT32); - if (ret==FAIL) { - n += sendData(file_des,mess,sizeof(mess),OTHER); - } else { - n += sendData(file_des,&s,sizeof(s),INT32); - } + // send ok / fail + sendData(file_des,&ret1,sizeof(ret),INT32); + // send return argument + sendData(file_des,&s,sizeof(s),INT32); + + // return ok / fail return ret; } @@ -2509,197 +2419,179 @@ int get_run_status(int file_des) { int start_and_read_all(int file_des) { - int dataret1; + int dataret1=FAIL, dataret=FAIL; #ifdef VERBOSE printf("Starting and reading all frames\n"); #endif - if (differentClients==1 && lockStatus==1) { - dataret=FAIL; + // execute action + if (differentClients && lockStatus) { + dataret = FAIL; sprintf(mess,"Detector locked by %s\n",lastClientIP); - //ret could be swapped during sendData + cprintf(RED, "Warning: %s", mess); + // ret could be swapped during sendData dataret1 = dataret; + // send fail sendData(file_des,&dataret1,sizeof(dataret),INT32); + // send return argument sendData(file_des,mess,sizeof(mess),OTHER); + // return fail return dataret; - } #ifdef SLS_DETECTOR_FUNCTION_LIST startStateMachine(); read_all(file_des); #endif -#ifdef VERBOSE - printf("Frames finished\n"); -#endif - - return OK; - - } int read_frame(int file_des) { - int dataret1; + int dataret1=FAIL, dataret=FAIL; + int n=0; + sprintf(mess, "read frame failed\n"); - if (differentClients==1 && lockStatus==1) { - dataret=FAIL; + // execute action + if (differentClients && lockStatus) { + dataret = FAIL; sprintf(mess,"Detector locked by %s\n",lastClientIP); - cprintf(RED,"%s",mess); - //dataret could be swapped during sendData + cprintf(RED, "Warning: %s", mess); + // ret could be swapped during sendData dataret1 = dataret; - sendData(file_des,&dataret1,sizeof(dataret1),INT32); + // send fail + sendData(file_des,&dataret1,sizeof(dataret),INT32); + // send return argument sendData(file_des,mess,sizeof(mess),OTHER); -#ifdef VERBOSE - printf("dataret %d\n",dataret); -#endif + // return fail return dataret; } - #ifdef SLS_DETECTOR_FUNCTION_LIST - readFrame(&dataret, mess); + readFrame(&dataret, mess); #endif + if(dataret == FAIL) + cprintf(RED,"%s\n",mess); + else + cprintf(GREEN,"%s",mess); - if (differentClients) - dataret=FORCE_UPDATE; - //dataret could be swapped during sendData - dataret1 = dataret; - sendData(file_des,&dataret1,sizeof(dataret1),INT32); - //always fail or finished - sendData(file_des,mess,sizeof(mess),OTHER); - if(dataret == FAIL) - cprintf(RED,"%s\n",mess); - else - cprintf(GREEN,"%s",mess); - return dataret; + if (differentClients) + dataret=FORCE_UPDATE; + + //dataret could be swapped during sendData + dataret1 = dataret; + // send finished / fail + n=sendData(file_des,&dataret1,sizeof(dataret1),INT32); + if (n<0) return FAIL; // if called from read_all, should fail to stop talking to a closed client socket + // send return argument + n=sendData(file_des,mess,sizeof(mess),OTHER); + if (n<0) return FAIL; // if called from read_all, should fail to stop talking to a closed client socket + // return finished / fail + return dataret; } - - - int read_all(int file_des) { #ifdef SLS_DETECTOR_FUNCTION_LIST while(read_frame(file_des)==OK) { #ifdef VERBOSE printf("frame read\n"); -#endif +#endif ; } #endif #ifdef VERBOSE - printf("Frames finished\n"); -#endif + printf("Frames finished or failed\n"); +#endif return OK; } - - int set_timer(int file_des) { - enum timerIndex ind; - int64_t tns; - int n; - int64_t retval; int ret=OK,ret1=OK; + int n=0; + enum timerIndex ind=0; + int64_t tns=-1; + int64_t retval=-1; + sprintf(mess,"set timer failed\n"); - - sprintf(mess,"can't set timer\n"); - + // receive arguments n = receiveData(file_des,&ind,sizeof(ind),INT32); - if (n < 0) { - sprintf(mess,"Error reading from socket\n"); - ret=FAIL; - } + if (n < 0) return printSocketReadError(); n = receiveData(file_des,&tns,sizeof(tns),INT64); - if (n < 0) { - sprintf(mess,"Error reading from socket\n"); - ret=FAIL; - } + if (n < 0) return printSocketReadError(); - if (ret!=OK) { - printf(mess); + // execute action + if (differentClients && lockStatus && tns!=-1) { + ret = FAIL; + sprintf(mess,"Detector locked by %s\n",lastClientIP); + cprintf(RED, "Warning: %s", mess); } - -#ifdef VERBOSE - printf("setting timer %d to %lld ns\n",ind,tns); -#endif #ifdef SLS_DETECTOR_FUNCTION_LIST - if (ret==OK) { - if (differentClients==1 && lockStatus==1 && tns!=-1) { - ret=FAIL; - sprintf(mess,"Detector locked by %s\n",lastClientIP); - } else { - switch(ind) { + else { +#ifdef VERBOSE + printf("setting timer %d to %lld ns\n",ind,tns); +#endif + switch(ind) { #ifdef EIGERD - case SUBFRAME_ACQUISITION_TIME: - if (tns > ((int64_t)MAX_SUBFRAME_EXPOSURE_VAL_IN_10NS*10) ){ - ret=FAIL; - strcpy(mess,"Sub Frame exposure time should not exceed 5.368 seconds\n"); - break; - } - retval = setTimer(ind,tns); - break; -#endif -#ifdef MYTHEN - case PROBES_NUMBER: -#endif - case FRAME_NUMBER: - case ACQUISITION_TIME: - case FRAME_PERIOD: - case DELAY_AFTER_TRIGGER: - case GATES_NUMBER: - case CYCLES_NUMBER: - retval = setTimer(ind,tns); - break; - default: + case SUBFRAME_ACQUISITION_TIME: + if (tns > ((int64_t)MAX_SUBFRAME_EXPOSURE_VAL_IN_10NS*10) ){ ret=FAIL; - sprintf(mess,"timer index unknown for this detector %d\n",ind); + strcpy(mess,"Sub Frame exposure time should not exceed 5.368 seconds\n"); break; } - +#endif +#ifdef MYTHEN + case PROBES_NUMBER: + case GATES_NUMBER: + case DELAY_AFTER_TRIGGER: +#elif JUNGFRAUD + case DELAY_AFTER_TRIGGER: +#endif + case FRAME_NUMBER: + case ACQUISITION_TIME: + case FRAME_PERIOD: + case CYCLES_NUMBER: + retval = setTimer(ind,tns); + break; + default: + ret = FAIL; + sprintf(mess,"Timer Index (%d) is not implemented for this detector\n", (int) ind); + cprintf(RED, "%s", mess); + break; } - } -#endif - if (ret!=OK) { - printf(mess); - printf("set timer failed\n"); - sprintf(mess, "set timer %d failed\n", ind); - } - else{ #if defined(MYTHEND) || defined(GOTTHARD) - if (ind==FRAME_NUMBER) { - ret=allocateRAM(); - if (ret!=OK) - sprintf(mess, "could not allocate RAM for %lld frames\n", tns); + if (ret == OK && ind==FRAME_NUMBER) { + ret=allocateRAM(); + if (ret!=OK) { + ret = FAIL; + sprintf(mess,"Could not allocate RAM for %lld frames\n", tns); + cprintf(RED, "%s", mess); + } + } +#endif } #endif - - if (differentClients) + if (ret==OK && differentClients) ret=FORCE_UPDATE; -} - //ret could be swapped during sendData + + // ret could be swapped during sendData ret1 = ret; + // send ok / fail n = sendData(file_des,&ret1,sizeof(ret),INT32); + // send return argument if (ret==FAIL) { - n = sendData(file_des,mess,sizeof(mess),OTHER); - } else { -#ifdef VERBOSE - printf("returning ok %d\n",sizeof(retval)); -#endif - - n = sendData(file_des,&retval,sizeof(retval),INT64); - } + n += sendData(file_des,mess,sizeof(mess),OTHER); + } else + n += sendData(file_des,&retval,sizeof(retval),INT64); + // return ok / fail return ret; - } @@ -2709,71 +2601,79 @@ int set_timer(int file_des) { + int get_time_left(int file_des) { - - enum timerIndex ind; - int n; - int64_t retval; int ret=OK,ret1=OK; + int n=0; + int64_t retval=-1; + sprintf(mess,"get timer left failed\n"); - sprintf(mess,"can't get timer\n"); + + +#ifdef EIGERD + //to receive any arguments + while (n > 0) + n = receiveData(file_des,mess,MAX_STR_LENGTH,OTHER); + ret = FAIL; + sprintf(mess,"Function (Get Timer Left) is not implemented for this detector\n"); + cprintf(RED, "%s", mess); +#else + + // receive arguments + enum timerIndex ind=0; n = receiveData(file_des,&ind,sizeof(ind),INT32); - if (n < 0) { - sprintf(mess,"Error reading from socket\n"); - ret=FAIL; - } + if (n < 0) return printSocketReadError(); #ifdef VERBOSE printf("getting time left on timer %d \n",ind); -#endif +#endif #ifdef SLS_DETECTOR_FUNCTION_LIST - if (ret==OK) { - switch(ind) { - case PROBES_NUMBER: -#ifndef MYTHEND - ret=FAIL; - strcpy(mess,"Not applicable/implemented for this detector\n"); - break; + switch(ind) { +#ifdef MYTHEND + case PROBES_NUMBER: #endif - case FRAME_NUMBER: - case ACQUISITION_TIME: - case FRAME_PERIOD: - case DELAY_AFTER_TRIGGER: - case GATES_NUMBER: - case CYCLES_NUMBER: - case PROGRESS: - case ACTUAL_TIME: - case MEASUREMENT_TIME: - getTimeLeft(ind); - break; - default: - ret=FAIL; - sprintf(mess,"timer index unknown %d\n",ind); - break; - } + case FRAME_NUMBER: + case ACQUISITION_TIME: + case FRAME_PERIOD: + case DELAY_AFTER_TRIGGER: +#ifndef JUNGFRAUD + case GATES_NUMBER: +#endif + case CYCLES_NUMBER: + case PROGRESS: + case ACTUAL_TIME: + case MEASUREMENT_TIME: +#ifdef JUNGFRAUD + case FRAMES_FROM_START: + case FRAMES_FROM_START_PG: +#endif + getTimeLeft(ind); + break; + default: + ret = FAIL; + sprintf(mess,"Timer Left Index (%d) is not implemented for this detector\n", (int)ind); + cprintf(RED, "%s", mess); + break; } +#ifdef VERBOSE + printf("Time left on timer %d is %lld\n",ind, retval); +#endif +#endif + if (ret==OK && differentClients) + ret=FORCE_UPDATE; #endif - if (ret!=OK) { - printf("get time left failed\n"); - } else if (differentClients) - ret=FORCE_UPDATE; - -#ifdef VERBOSE - printf("time left on timer %d is %lld\n",ind, retval); -#endif - - //ret could be swapped during sendData + // ret could be swapped during sendData ret1 = ret; + // send ok / fail n = sendData(file_des,&ret1,sizeof(ret),INT32); + // send return argument if (ret==FAIL) { n += sendData(file_des,mess,sizeof(mess),OTHER); - } else { - n = sendData(file_des,&retval,sizeof(retval),INT64); - } -#ifdef VERBOSE - printf("data sent\n"); -#endif + } else + n += sendData(file_des,&retval,sizeof(retval),INT64); + + // return ok / fail return ret; } @@ -2781,36 +2681,42 @@ int get_time_left(int file_des) { -int set_dynamic_range(int file_des) { - int dr; - int n; - int retval; +int set_dynamic_range(int file_des) { int ret=OK,ret1=OK; int rateret=OK,rateret1=OK; + int n=0; + int dr=-1; + int retval=-1; + sprintf(mess,"set dynamic range failed\n"); - sprintf(mess,"can't set dynamic range\n"); - + // receive arguments n = receiveData(file_des,&dr,sizeof(dr),INT32); - if (n < 0) { - sprintf(mess,"Error reading from socket\n"); - ret=FAIL; + if (n < 0) return printSocketReadError(); + + // execute action + if (differentClients && lockStatus && dr>=0) { + ret = FAIL; + sprintf(mess,"Detector locked by %s\n",lastClientIP); + cprintf(RED, "Warning: %s", mess); } #ifdef SLS_DETECTOR_FUNCTION_LIST - if (differentClients==1 && lockStatus==1 && dr>=0) { - ret=FAIL; - sprintf(mess,"Detector locked by %s\n",lastClientIP); - } else { -#ifdef EIGERD + else { switch(dr){ - case -1:case 4: case 8: case 16:case 32:break; - default: - strcpy(mess,"could not set dynamic range. Must be 4,8,16 or 32.\n"); - ret = FAIL; - } + case -1: + case 16: +#ifdef EIGERD + case 4: case 8: case 32: #endif + break; + default: + ret = FAIL; + sprintf(mess,"Dynamic Range (%d) is not implemented for this detector\n", dr); + cprintf(RED, "Warning: %s", mess); + } } if(ret == OK){ +#ifdef EIGERD int old_dr = setDynamicRange(-1); retval=setDynamicRange(dr); if (dr>=0 && retval!=dr) @@ -2818,46 +2724,55 @@ int set_dynamic_range(int file_des) { //look at rate correction only if dr change worked if((ret==OK) && (dr!=32) && (dr!=16) && (dr!=-1) && (getRateCorrectionEnable())){ setRateCorrection(0); + rateret = FAIL; strcpy(mess,"Switching off Rate Correction. Must be in 32 or 16 bit mode\n"); cprintf(RED,"%s",mess); - rateret = FAIL; }else{ //setting it if dr changed from 16 to 32 or vice versa with tau value as in rate table if((dr!=-1) && (old_dr != dr) && getRateCorrectionEnable() && (dr == 16 || dr == 32)){ setRateCorrection(-1); //tau_ns will not be -1 here if(!getRateCorrectionEnable()){ + ret = FAIL; strcpy(mess,"Deactivating Rate Correction. Could not set it.\n"); cprintf(RED,"%s",mess); - ret=FAIL; } } } + +#else + retval = setDynamicRange(dr); +#endif + if (dr>=0) dataBytes=calculateDataBytes(); } #endif - if (dr>=0 && retval!=dr) - ret=FAIL; - if ((ret==OK) && (differentClients)) + if ((ret == OK) && dr>=0 && retval!=dr) { + ret = FAIL; + cprintf(RED,"%s",mess); + } + if (ret==OK && differentClients) ret=FORCE_UPDATE; -#ifdef SLS_DETECTOR_FUNCTION_LIST - if (dr>=0) dataBytes=calculateDataBytes(); -#endif - //rate correction ret - //ret could be swapped during sendData + // ret could be swapped during sendData rateret1 = rateret; - n = sendData(file_des,&rateret1,sizeof(rateret),INT32); - if (rateret==FAIL) - n = sendData(file_des,mess,sizeof(mess),OTHER); + // send ok / fail + n = sendData(file_des,&rateret1,sizeof(rateret1),INT32); + // send return argument + if (ret==FAIL) { + n += sendData(file_des,mess,sizeof(mess),OTHER); + } - //dynamic range ret - //ret could be swapped during sendData + // ret could be swapped during sendData ret1 = ret; + // send ok / fail n = sendData(file_des,&ret1,sizeof(ret),INT32); - if (ret==FAIL) - n = sendData(file_des,mess,sizeof(mess),OTHER); - else - n = sendData(file_des,&retval,sizeof(retval),INT32); + // send return argument + if (ret==FAIL) { + n += sendData(file_des,mess,sizeof(mess),OTHER); + } else + n += sendData(file_des,&retval,sizeof(retval),INT32); + + // return ok / fail return ret; } @@ -2867,86 +2782,81 @@ int set_dynamic_range(int file_des) { int set_readout_flags(int file_des) { - - enum readOutFlags retval; - enum readOutFlags arg; - int n; int ret=OK,ret1=OK; - - sprintf(mess,"can't set readout flags\n"); - - n = receiveData(file_des,&arg,sizeof(arg),INT32); - if (n < 0) { - sprintf(mess,"Error reading from socket\n"); - ret=FAIL; - } - - + int n=0; + enum readOutFlags retval=-1; + sprintf(mess,"set readout flags failed\n"); #if !defined(MYTHEND) && !defined(EIGERD) - sprintf(mess,"Read out flags not implemented for this detector\n"); - cprintf(RED, "%s",mess); + //to receive any arguments + while (n > 0) + n = receiveData(file_des,mess,MAX_STR_LENGTH,OTHER); ret=FAIL; + sprintf(mess,"Function (Set Read Out Flags) is not implemented for this detector\n"); + cprintf(RED, "%s",mess); #else + // receive arguments + enum readOutFlags arg=-1; + n = receiveData(file_des,&arg,sizeof(arg),INT32); + if (n < 0) return printSocketReadError(); -#ifdef VERBOSE - printf("setting readout flags to %d\n",arg); -#endif - -#ifdef SLS_DETECTOR_FUNCTION_LIST - if (differentClients==1 && lockStatus==1 && arg!=GET_READOUT_FLAGS) { - ret=FAIL; + // execute action + if (differentClients && lockStatus && arg!=GET_READOUT_FLAGS) { + ret = FAIL; sprintf(mess,"Detector locked by %s\n",lastClientIP); - } else { + cprintf(RED, "Warning: %s", mess); + } +#ifdef SLS_DETECTOR_FUNCTION_LIST + else { +#ifdef VERBOSE + printf("setting readout flags to %d\n",arg); +#endif switch(arg) { case GET_READOUT_FLAGS: #ifdef MYTHEND case TOT_MODE: case NORMAL_READOUT: -#endif -#if defined(MYTHEND) || defined(EIGERD) case STORE_IN_RAM: case CONTINOUS_RO: -#endif -#ifdef EIGERD +#elif EIGERD + case STORE_IN_RAM: + case CONTINOUS_RO: case PARALLEL: case NONPARALLEL: case SAFE: #endif retval=setReadOutFlags(arg); break; - default: - sprintf(mess,"Unknown readout flag %d for this detector\n", arg); - cprintf(RED, "%s",mess); - ret=FAIL; + ret = FAIL; + sprintf(mess,"Readout Flag Index (%d) is not implemented for this detector\n", (int)arg); + cprintf(RED, "Warning: %s", mess); break; } - } #endif - -#endif - - if (ret==OK) { - if ((retval == -1) || ((arg!=-1)&&((retval&arg)!=arg))){ - cprintf(RED,"arg:0x%x, retval:0x%x retval&arg:0x%x\n",(int)arg,(int)retval,retval&arg); - ret=FAIL; + if (ret==OK && ((retval == -1) || ((arg!=-1) && ((retval&arg)!=arg)))){ + ret = FAIL; sprintf(mess,"Could not change readout flag: should be 0x%x but is 0x%x\n", arg, retval); - cprintf(RED, "%s",mess); - }else if (differentClients) + cprintf(RED, "Warning: %s", mess); + } + + if (ret==OK && differentClients) ret=FORCE_UPDATE; } +#endif - - //ret could be swapped during sendData + // ret could be swapped during sendData ret1 = ret; + // send ok / fail n = sendData(file_des,&ret1,sizeof(ret),INT32); + // send return argument if (ret==FAIL) { - n = sendData(file_des,mess,sizeof(mess),OTHER); - } else { - n = sendData(file_des,&retval,sizeof(retval),INT32); - } + n += sendData(file_des,mess,sizeof(mess),OTHER); + } else + n += sendData(file_des,&retval,sizeof(retval),INT32); + + // return ok / fail return ret; } @@ -2954,76 +2864,90 @@ int set_readout_flags(int file_des) { + int set_roi(int file_des) { - int ret=OK,ret1=OK; - ROI arg[MAX_ROIS]; - ROI* retval=0; - int nroi=-1, n=0, retvalsize=0,retvalsize1,i; - strcpy(mess,"Could not set/get roi\n"); + int n=0; + strcpy(mess,"set nroi failed\n"); - n = receiveData(file_des,&nroi,sizeof(nroi),INT32); - if (n < 0) { - sprintf(mess,"Error reading from socket\n"); - ret=FAIL; - } - - if(nroi!=-1){ - for(i=0;i 0) + n = receiveData(file_des,mess,MAX_STR_LENGTH,OTHER); + ret=FAIL; + sprintf(mess,"Function (Set ROI) is not implemented for this detector\n"); + cprintf(RED, "%s",mess); #else -#ifdef VERBOSE - printf("Setting ROI to:"); - for( i=0;i=0) { + ret = FAIL; + sprintf(mess,"Detector locked by %s\n",lastClientIP); + cprintf(RED, "Warning: %s", mess); } - -#ifdef VERBOSE - printf("setting speed variable %d to %d\n",arg,val); -#endif - if (ret==OK) { - - if (differentClients==1 && lockStatus==1 && val>=0) { - ret=FAIL; - sprintf(mess,"Detector locked by %s\n",lastClientIP); - } else { #ifdef SLS_DETECTOR_FUNCTION_LIST - switch (arg) { + else { +#ifdef VERBOSE + printf("setting speed variable %d to %d\n",arg,val); +#endif + switch (arg) { +#ifdef JUNGFRAUD + case ADC_PHASE: + adcPhase(val); + break; +#endif #ifdef MYTHEND - case CLOCK_DIVIDER: - case WAIT_STATES: - case SET_SIGNAL_LENGTH: - case TOT_CLOCK_DIVIDER: - case TOT_DUTY_CYCLE: - retval=setSpeed(arg, val); - break; + case CLOCK_DIVIDER: + case WAIT_STATES: + case SET_SIGNAL_LENGTH: + case TOT_CLOCK_DIVIDER: + case TOT_DUTY_CYCLE: #elif EIGERD - case CLOCK_DIVIDER: - retval=setSpeed(arg, val); - break; + case CLOCK_DIVIDER: +#elif JUNGFRAUD + case CLOCK_DIVIDER: #endif - default: - sprintf(mess,"unknown speed variable %d for this detector\n",arg); - ret=FAIL; - break; - } -#endif - } - if (ret==OK){ + retval=setSpeed(arg, val); if ((retval!=val) && (val>=0)) { ret=FAIL; sprintf(mess,"could not change speed variable %d: should be %d but is %d \n",arg, val, retval); - }else if (differentClients) - ret=FORCE_UPDATE; - + cprintf(RED, "Warning: %s", mess); + } + break; + default: + ret = FAIL; + sprintf(mess,"Speed Index (%d) is not implemented for this detector\n",(int) arg); + cprintf(RED, "Warning: %s", mess); + break; } } +#endif + if (ret==OK && differentClients) + ret=FORCE_UPDATE; - - //ret could be swapped during sendData + // ret could be swapped during sendData ret1 = ret; + // send ok / fail n = sendData(file_des,&ret1,sizeof(ret),INT32); + // send return argument if (ret==FAIL) { - n = sendData(file_des,mess,sizeof(mess),OTHER); - } else { - n = sendData(file_des,&retval,sizeof(retval),INT32); - } + n += sendData(file_des,mess,sizeof(mess),OTHER); + } else + n += sendData(file_des,&retval,sizeof(retval),INT32); + + // return ok / fail return ret; } + int execute_trimming(int file_des) { + int ret=OK,ret1=OK; + int n=0; + sprintf(mess,"execute trimming failed\n"); - int arg[3]; - int n; - int ret=OK, ret1=OK, retval=0; -#if defined(MYTHEND) || defined(EIGERD) - int imod, par1,par2; -#endif - enum trimMode mode; - - printf("called function execute trimming\n"); - - sprintf(mess,"can't set execute trimming\n"); - - n = receiveData(file_des,&mode,sizeof(mode),INT32); - printf("mode received\n"); - if (n < 0) { - sprintf(mess,"Error reading from socket\n"); - printf("Error reading from socket (mode)\n"); - ret=FAIL; - } - - n = receiveData(file_des,arg,sizeof(arg),INT32); - printf("arg received\n"); - if (n < 0) { - sprintf(mess,"Error reading from socket\n"); - printf("Error reading from socket (args)\n"); - ret=FAIL; - } - -#if !defined(MYTHEND) && !defined(EIGERD) +#ifndef MYTHEND + //to receive any arguments + while (n > 0) + n = receiveData(file_des,mess,MAX_STR_LENGTH,OTHER); ret = FAIL; - strcpy(mess,"Not applicable/implemented for this detector\n"); + sprintf(mess,"Function (Execute Trimming) is not implemented for this detector\n"); + cprintf(RED, "Warning: %s", mess); #else + int retval=-1; + + // receive arguments + enum trimMode mode=0; + int arg[3]={-1,-1,-1}; + n = receiveData(file_des,&mode,sizeof(mode),INT32); + if (n < 0) return printSocketReadError(); + + n = receiveData(file_des,arg,sizeof(arg),INT32); + if (n < 0) return printSocketReadError(); + + // execute action + int imod, par1,par2; imod=arg[0]; par1=arg[1]; par2=arg[2]; -#ifdef SLS_DETECTOR_FUNCTION_LIST - if (imod>=getTotalNumberOfModules()) { - ret=FAIL; - sprintf(mess,"Module number out of range %d\n",imod); + if (differentClients && lockStatus) { + ret = FAIL; + sprintf(mess,"Detector locked by %s\n",lastClientIP); + cprintf(RED, "Warning: %s", mess); } -#endif - if (ret==OK) { - +#ifdef SLS_DETECTOR_FUNCTION_LIST + else if (imod>=getTotalNumberOfModules()) { + ret = FAIL; + sprintf(mess,"Module Number (%d) is out of range\n"); + cprintf(RED, "Warning: %s", mess); + } + else { #ifdef VERBOSE printf("trimming module %d mode %d, parameters %d %d \n",imod,mode, par1, par2); #endif - - if (differentClients==1 && lockStatus==1 ) { - ret=FAIL; - sprintf(mess,"Detector locked by %s\n",lastClientIP); - } else { -#ifdef SLS_DETECTOR_FUNCTION_LIST - if (ret==OK) { - switch(mode) { - case NOISE_TRIMMING: - case BEAM_TRIMMING: - case IMPROVE_TRIMMING: - case FIXEDSETTINGS_TRIMMING: - if (myDetectorType==MYTHEN) { - retval=executeTrimming(mode, par1, par2, imod); - break; - } - break; - default: - printf("Unknown trimming mode %d\n",mode); - sprintf(mess,"Unknown trimming mode %d\n",mode); - ret=FAIL; - break; - } + switch(mode) { + case NOISE_TRIMMING: + case BEAM_TRIMMING: + case IMPROVE_TRIMMING: + case FIXEDSETTINGS_TRIMMING: + retval=executeTrimming(mode, par1, par2, imod); + if ((ret!=OK) && (retval>0)) { + ret=FAIL; + sprintf(mess,"Could not trim %d channels\n", retval); + cprintf(RED, "Warning: %s", mess); } -#endif + break; + default: + ret = FAIL; + sprintf(mess,"Trimming Mode (%d) is not implemented for this detector\n", (int) mode); + cprintf(RED, "Warning: %s", mess); + break; } + } #endif - - if (ret!=OK) { - sprintf(mess,"can't set execute trimming\n"); - ret=FAIL; - } else if (retval>0) { - sprintf(mess,"Could not trim %d channels\n", retval); - ret=FAIL; - } else if (differentClients) + if (ret==OK && differentClients) ret=FORCE_UPDATE; +#endif - //ret could be swapped during sendData + // ret could be swapped during sendData ret1 = ret; + // send ok / fail n = sendData(file_des,&ret1,sizeof(ret),INT32); + // send return argument if (ret==FAIL) { - n = sendData(file_des,mess,sizeof(mess),OTHER); + n += sendData(file_des,mess,sizeof(mess),OTHER); } + // return ok / fail return ret; } @@ -3220,39 +3131,307 @@ int execute_trimming(int file_des) { +int exit_server(int file_des) { + int ret=FAIL; + sprintf(mess,"Closing Server\n"); + cprintf(BG_RED,"Error: %s",mess); + // send ok / fail + sendData(file_des,&ret,sizeof(ret),INT32); + // send return argument + sendData(file_des,mess,sizeof(mess),OTHER); + return GOODBYE; +} + + + + +int lock_server(int file_des) { + int ret=OK,ret1=OK; + int n=0; + int lock=0; + sprintf(mess,"lock server failed\n"); + + // receive arguments + n = receiveData(file_des,&lock,sizeof(lock),INT32); + if (n < 0) return printSocketReadError(); + + // execute action + if (lock>=0) { + if (lockStatus==0 || strcmp(lastClientIP,thisClientIP)==0 || strcmp(lastClientIP,"none")==0) { + lockStatus=lock; + strcpy(lastClientIP,thisClientIP); + } else { + ret = FAIL; + sprintf(mess,"Server already locked by %s\n", lastClientIP); + cprintf(RED, "Warning: %s", mess); + } + } + if (ret==OK && differentClients) + ret=FORCE_UPDATE; + + // ret could be swapped during sendData + ret1 = ret; + // send ok / fail + n = sendData(file_des,&ret1,sizeof(ret),INT32); + // send return argument + if (ret==FAIL) { + n += sendData(file_des,mess,sizeof(mess),OTHER); + } else + n += sendData(file_des,&lockStatus,sizeof(lockStatus),INT32); + + // return ok / fail + return ret; +} + + + + + +int get_last_client_ip(int file_des) { + int ret=OK,ret1=OK; + if (differentClients) + ret=FORCE_UPDATE; + // send ok / fail + sendData(file_des,&ret1,sizeof(ret),INT32); + // send return argument + sendData(file_des,lastClientIP,sizeof(lastClientIP),OTHER); + // return ok / fail + return ret; +} + + + + +int set_port(int file_des) { + int ret=OK,ret1=OK; + int n=0; + enum portType p_type=0; + int p_number=-1; + sprintf(mess,"set port failed\n"); + + // receive arguments + n = receiveData(file_des,&p_type,sizeof(p_type),INT32); + if (n < 0) return printSocketReadError(); + + n = receiveData(file_des,&p_number,sizeof(p_number),INT32); + if (n < 0) return printSocketReadError(); + + // execute action + int sd=-1; + if (differentClients && lockStatus) { + ret = FAIL; + sprintf(mess,"Detector locked by %s\n",lastClientIP); + cprintf(RED, "Warning: %s", mess); + } + else { + if (p_number<1024) { + ret = FAIL; + sprintf(mess,"Port Number (%d) too low\n", p_number); + cprintf(RED, "Warning: %s", mess); + } + printf("set port %d to %d\n",p_type, p_number); + sd=bindSocket(p_number); + if (sd<0) { + ret = FAIL; + sprintf(mess,"Could not bind port %d\n", p_number); + cprintf(RED, "Warning: %s", mess); + if (sd==-10) { + ret = FAIL; + sprintf(mess,"Port %d already set\n", p_number); + cprintf(RED, "Warning: %s", mess); + } + } + if (ret==OK && differentClients) + ret=FORCE_UPDATE; + } + + // ret could be swapped during sendData + ret1 = ret; + // send ok / fail + n = sendData(file_des,&ret1,sizeof(ret),INT32); + // send return argument + if (ret==FAIL) { + n = sendData(file_des,mess,sizeof(mess),OTHER); + } else { + n = sendData(file_des,&p_number,sizeof(p_number),INT32); + closeConnection(file_des); + exitServer(sockfd); + sockfd=sd; + } + + // return ok / fail + return ret; +} + + + + +int update_client(int file_des) { + int ret=OK; + sendData(file_des,&ret,sizeof(ret),INT32); + return send_update(file_des); +} + + + + +int send_update(int file_des) { + int n=0; // if (n<0) should fail to stop talking to a closed client socket + int nm=0; + int64_t retval = 0; + enum detectorSettings t; + + n = sendData(file_des,lastClientIP,sizeof(lastClientIP),OTHER); + if (n < 0) return printSocketReadError(); + + +#ifdef SLS_DETECTOR_FUNCTION_LIST + nm=setNMod(GET_FLAG,X); +#endif + n = sendData(file_des,&nm,sizeof(nm),INT32); + if (n < 0) return printSocketReadError(); + + +#ifdef SLS_DETECTOR_FUNCTION_LIST + nm=setNMod(GET_FLAG,Y); +#endif + n = sendData(file_des,&nm,sizeof(nm),INT32); + if (n < 0) return printSocketReadError(); + + +#ifdef SLS_DETECTOR_FUNCTION_LIST + nm=setDynamicRange(GET_FLAG); +#endif + n = sendData(file_des,&nm,sizeof(nm),INT32); + if (n < 0) return printSocketReadError(); + + +#ifdef SLS_DETECTOR_FUNCTION_LIST + dataBytes=calculateDataBytes(); +#endif + n = sendData(file_des,&dataBytes,sizeof(dataBytes),INT32); + if (n < 0) return printSocketReadError(); + + +#ifdef SLS_DETECTOR_FUNCTION_LIST + t=setSettings(GET_SETTINGS, GET_FLAG); +#endif + n = sendData(file_des,&t,sizeof(t),INT32); + if (n < 0) return printSocketReadError(); + + +#if defined(MYTHEND) || defined(EIGERD) +#ifdef SLS_DETECTOR_FUNCTION_LIST + nm=getThresholdEnergy(GET_FLAG); +#endif + n = sendData(file_des,&nm,sizeof(nm),INT32); + if (n < 0) return printSocketReadError(); +#endif + + +#ifdef SLS_DETECTOR_FUNCTION_LIST + retval=setTimer(FRAME_NUMBER,GET_FLAG); +#endif + n = sendData(file_des,&retval,sizeof(int64_t),INT64); + if (n < 0) return printSocketReadError(); + + +#ifdef SLS_DETECTOR_FUNCTION_LIST + retval=setTimer(ACQUISITION_TIME,GET_FLAG); +#endif + n = sendData(file_des,&retval,sizeof(int64_t),INT64); + if (n < 0) return printSocketReadError(); + + +#ifdef EIGERD +#ifdef SLS_DETECTOR_FUNCTION_LIST + retval=setTimer(SUBFRAME_ACQUISITION_TIME,GET_FLAG); +#endif + n = sendData(file_des,&retval,sizeof(int64_t),INT64); + if (n < 0) return printSocketReadError(); +#endif + + +#ifdef SLS_DETECTOR_FUNCTION_LIST + retval=setTimer(FRAME_PERIOD,GET_FLAG); +#endif + n = sendData(file_des,&retval,sizeof(int64_t),INT64); + if (n < 0) return printSocketReadError(); + + +#ifndef EIGERD +#ifdef SLS_DETECTOR_FUNCTION_LIST + retval=setTimer(DELAY_AFTER_TRIGGER,GET_FLAG); +#endif + n = sendData(file_des,&retval,sizeof(int64_t),INT64); + if (n < 0) return printSocketReadError(); +#endif + + +#if !defined(EIGERD) && !defined(JUNGFRAUD) +#ifdef SLS_DETECTOR_FUNCTION_LIST + retval=setTimer(GATES_NUMBER,GET_FLAG); +#endif + n = sendData(file_des,&retval,sizeof(int64_t),INT64); + if (n < 0) return printSocketReadError(); +#endif + + +#ifdef MYTHEND +#ifdef SLS_DETECTOR_FUNCTION_LIST + retval=setTimer(PROBES_NUMBER,GET_FLAG); +#endif + n = sendData(file_des,&retval,sizeof(int64_t),INT64); + if (n < 0) return printSocketReadError(); +#endif + + +#ifdef SLS_DETECTOR_FUNCTION_LIST + retval=setTimer(CYCLES_NUMBER,GET_FLAG); +#endif + n = sendData(file_des,&retval,sizeof(int64_t),INT64); + if (n < 0) return printSocketReadError(); + + + if (lockStatus==0) { + strcpy(lastClientIP,thisClientIP); + } + + return OK; +} + + int configure_mac(int file_des) { - - int retval=-100; int ret=OK,ret1=OK; - char arg[6][50]; - int n; - -#ifndef MYTHEND - int imod=0;//should be in future sent from client as -1, arg[2] - int ipad; - long long int imacadd; - long long int idetectormacadd; - int udpport; - int udpport2; - int detipad; -#endif - - sprintf(mess,"Can't configure MAC\n"); - - n = receiveData(file_des,arg,sizeof(arg),OTHER); - if (n < 0) { - sprintf(mess,"Error reading from socket\n"); - ret=FAIL; - } + int n=0; + int retval=-100; + sprintf(mess,"configure mac failed\n"); #ifdef MYTHEND + //to receive any arguments + while (n > 0) + n = receiveData(file_des,mess,MAX_STR_LENGTH,OTHER); ret = FAIL; - strcpy(mess,"Not applicable/implemented for this detector\n"); + strcpy(mess,"Function (Configure MAC) is not implemented for this detector\n"); + cprintf(RED, "Warning: %s", mess); #else + + // receive arguments + char arg[6][50]; + memset(arg,0,sizeof(arg)); + n = receiveData(file_des,arg,sizeof(arg),OTHER); + if (n < 0) return printSocketReadError(); + + uint32_t ipad; + uint64_t imacadd; + uint64_t idetectormacadd; + uint32_t udpport; + uint32_t udpport2; + uint32_t detipad; sscanf(arg[0], "%x", &ipad); sscanf(arg[1], "%llx", &imacadd); sscanf(arg[2], "%x", &udpport); @@ -3260,103 +3439,110 @@ int configure_mac(int file_des) { sscanf(arg[4], "%x", &detipad); sscanf(arg[5], "%x", &udpport2); - -#ifdef SLS_DETECTOR_FUNCTION_LIST - if (imod>=getTotalNumberOfModules()) { - ret=FAIL; - sprintf(mess,"Module number out of range %d\n",imod); - printf("mess:%s\n",mess); + if (differentClients && lockStatus) { + ret = FAIL; + sprintf(mess,"Detector locked by %s\n",lastClientIP); + cprintf(RED, "Warning: %s", mess); } -#endif -#ifdef VERBOSE - int i; - /*printf("\ndigital_test_bit in server %d\t",digitalTestBit);for gotthard*/ - printf("\nipadd %x\t",ipad); - printf("destination ip is %d.%d.%d.%d = 0x%x \n",(ipad>>24)&0xff,(ipad>>16)&0xff,(ipad>>8)&0xff,(ipad)&0xff,ipad); - printf("macad:%llx\n",imacadd); - for (i=0;i<6;i++) - printf("mac adress %d is 0x%x \n",6-i,(unsigned int)(((imacadd>>(8*i))&0xFF))); - printf("udp port:0x%x\n",udpport); - printf("detector macad:%llx\n",idetectormacadd); - for (i=0;i<6;i++) - printf("detector mac adress %d is 0x%x \n",6-i,(unsigned int)(((idetectormacadd>>(8*i))&0xFF))); - printf("detipad %x\n",detipad); - printf("udp port2:0x%x\n",udpport2); - printf("\n"); - printf("Configuring MAC of module %d at port %x\n", imod, udpport); -#endif - #ifdef SLS_DETECTOR_FUNCTION_LIST - if (ret==OK) { + else { +#ifdef VERBOSE + int i; + //#ifdef GOTTHARD + //printf("\ndigital_test_bit in server %d\t",digitalTestBit); + //#endif + printf("\nipadd %x\t",ipad); + printf("destination ip is %d.%d.%d.%d = 0x%x \n",(ipad>>24)&0xff,(ipad>>16)&0xff,(ipad>>8)&0xff,(ipad)&0xff,ipad); + printf("macad:%llx\n",imacadd); + for (i=0;i<6;i++) + printf("mac adress %d is 0x%x \n",6-i,(unsigned int)(((imacadd>>(8*i))&0xFF))); + printf("udp port:0x%x\n",udpport); + printf("detector macad:%llx\n",idetectormacadd); + for (i=0;i<6;i++) + printf("detector mac adress %d is 0x%x \n",6-i,(unsigned int)(((idetectormacadd>>(8*i))&0xFF))); + printf("detipad %x\n",detipad); + printf("udp port2:0x%x\n",udpport2); + printf("\n"); + printf("Configuring MAC of module %d at port %x\n", imod, udpport); +#endif if(getRunStatus() == RUNNING){ - stopStateMachine(); + ret = stopStateMachine(); } - - retval=configureMAC(ipad,imacadd,idetectormacadd,detipad,udpport,udpport2,0); /*digitalTestBit);*/ - if(retval==-1) ret=FAIL; - } -#endif + if(ret==FAIL) { + sprintf(mess,"Could not stop detector acquisition to configure mac\n"); + cprintf(RED, "Warning: %s", mess); + } + else { + retval=configureMAC(ipad,imacadd,idetectormacadd,detipad,udpport,udpport2,0); //digitalTestBit); + if(retval==-1) { + ret = FAIL; + sprintf(mess,"Configure Mac failed\n"); + cprintf(RED, "Warning: %s", mess); + } + else + printf("Configure MAC successful\n"); #ifdef VERBOSE - printf("Configured MAC with retval %d\n", retval); + printf("Configured MAC with retval %d\n", retval); #endif - if (ret==FAIL) { - printf("configuring MAC of mod %d failed\n", imod); - } + } + } +#endif if (differentClients) ret=FORCE_UPDATE; #endif - /* send answer */ - /* send OK/failed */ - //ret could be swapped during sendData + + // ret could be swapped during sendData ret1 = ret; + // send ok / fail n = sendData(file_des,&ret1,sizeof(ret),INT32); - if (ret!=FAIL) { - /* send return argument */ - n += sendData(file_des,&retval,sizeof(retval),INT32); - } else { + // send return argument + if (ret==FAIL) { n += sendData(file_des,mess,sizeof(mess),OTHER); - } + } else + n += sendData(file_des,&retval,sizeof(retval),INT32); - /*return ok/fail*/ + // return ok / fail return ret; - } -int load_image(int file_des) { - int retval; - int ret=OK,ret1=OK; - int n; - enum imageType index; - char ImageVals[dataBytes]; + +int load_image(int file_des) { + int ret=OK,ret1=OK; + int n=0; + int retval=-1; sprintf(mess,"Loading image failed\n"); +#ifndef GOTTHARDD + //to receive any arguments + while (n > 0) + n = receiveData(file_des,mess,MAX_STR_LENGTH,OTHER); + ret = FAIL; + sprintf(mess,"Function (Load Image) is not implemented for this detector\n"); + cprintf(RED, "Warning: %s", mess); +#else + + // receive arguments + enum imageType index=0; + char ImageVals[dataBytes]; + memset(ImageVals,0,dataBytes); n = receiveData(file_des,&index,sizeof(index),INT32); - if (n < 0) { - sprintf(mess,"Error reading from socket\n"); - ret=FAIL; - } + if (n < 0) return printSocketReadError(); n = receiveData(file_des,ImageVals,dataBytes,OTHER); - if (n < 0) { - sprintf(mess,"Error reading from socket\n"); - ret=FAIL; + if (n < 0) return printSocketReadError(); + + // execute action + if (differentClients && lockStatus) { + ret = FAIL; + sprintf(mess,"Detector locked by %s\n",lastClientIP); + cprintf(RED, "Warning: %s", mess); } - -#ifndef GOTTHARDD - ret = FAIL; - strcpy(mess,"Not applicable/implemented for this detector\n"); -#else - if (ret==OK) { - if (differentClients==1 && lockStatus==1) { - ret=FAIL; - sprintf(mess,"Detector locked by %s\n",lastClientIP); - } - #ifdef SLS_DETECTOR_FUNCTION_LIST + else { switch (index) { case DARK_IMAGE : #ifdef VERBOSE @@ -3366,41 +3552,135 @@ int load_image(int file_des) { #ifdef VERBOSE printf("Loading Gain image\n"); #endif - if (myDetectorType==GOTTHARD) { - retval=loadImage(index,ImageVals); - if (retval==-1) - ret = FAIL; + retval=loadImage(index,ImageVals); + if (retval==-1) { + ret = FAIL; + cprintf(RED, "Warning: %s", mess); } break; default: - printf("Unknown index %d\n",index); - sprintf(mess,"Unknown index %d\n",index); - ret=FAIL; + ret = FAIL; + sprintf(mess,"Load Image Index (%d) is not implemented for this detector\n", (int)index); + cprintf(RED, "Warning: %s", mess); break; } -#endif } #endif + if (ret==OK && differentClients) + ret=FORCE_UPDATE; +#endif + + // ret could be swapped during sendData + ret1 = ret; + // send ok / fail + n = sendData(file_des,&ret1,sizeof(ret),INT32); + // send return argument + if (ret==FAIL) { + n += sendData(file_des,mess,sizeof(mess),OTHER); + } else + n += sendData(file_des,&retval,sizeof(retval),INT32); + + // return ok / fail + return ret; +} - if(ret==OK){ - if (differentClients) + + + +int set_master(int file_des) { + int ret=OK,ret1=OK; + int n=0; + enum masterFlags arg=GET_MASTER; + enum masterFlags retval=GET_MASTER; + sprintf(mess,"set master failed\n"); + + // receive arguments + n = receiveData(file_des,&arg,sizeof(arg),INT32); + if (n < 0) return printSocketReadError(); + + // execute action + if (differentClients && lockStatus && ((int)arg!=(int)GET_MASTER)) { + ret = FAIL; + sprintf(mess,"Detector locked by %s\n",lastClientIP); + cprintf(RED, "Warning: %s", mess); + } +#ifdef SLS_DETECTOR_FUNCTION_LIST + else { +#ifdef VERBOSE + printf("setting master flags to %d\n",arg); +#endif + retval=setMaster(arg); + if (retval==GET_MASTER) + ret=FAIL; + + if (ret==OK && differentClients) ret=FORCE_UPDATE; } +#endif - /* send answer */ - /* send OK/failed */ - //ret could be swapped during sendData + // ret could be swapped during sendData ret1 = ret; + // send ok / fail n = sendData(file_des,&ret1,sizeof(ret),INT32); - if (ret!=FAIL) { - /* send return argument */ - n += sendData(file_des,&retval,sizeof(retval),INT32); - } else { + // send return argument + if (ret==FAIL) { n += sendData(file_des,mess,sizeof(mess),OTHER); - } + } else + n += sendData(file_des,&retval,sizeof(retval),INT32); - /*return ok/fail*/ + // return ok / fail + return ret; +} + + + + + + + +int set_synchronization(int file_des) { + int ret=OK,ret1=OK; + int n=0; + enum synchronizationMode arg=GET_SYNCHRONIZATION_MODE; + enum synchronizationMode retval=GET_SYNCHRONIZATION_MODE; + sprintf(mess,"synchronization mode failed\n"); + + // receive arguments + n = receiveData(file_des,&arg,sizeof(arg),INT32); + if (n < 0) return printSocketReadError(); + + // execute action + if (differentClients && lockStatus && ((int)arg!=(int)GET_SYNCHRONIZATION_MODE)) { + ret = FAIL; + sprintf(mess,"Detector locked by %s\n",lastClientIP); + cprintf(RED, "Warning: %s", mess); + } +#ifdef SLS_DETECTOR_FUNCTION_LIST + else { +#ifdef VERBOSE + printf("setting master flags to %d\n",arg); +#endif + retval=setSynchronization(arg); + if (retval==GET_SYNCHRONIZATION_MODE) + ret=FAIL; + + if (ret==OK && differentClients) + ret=FORCE_UPDATE; + } +#endif + + // ret could be swapped during sendData + ret1 = ret; + // send ok / fail + n = sendData(file_des,&ret1,sizeof(ret),INT32); + // send return argument + if (ret==FAIL) { + n += sendData(file_des,mess,sizeof(mess),OTHER); + } else + n += sendData(file_des,&retval,sizeof(retval),INT32); + + // return ok / fail return ret; } @@ -3409,63 +3689,59 @@ int load_image(int file_des) { int read_counter_block(int file_des) { - int ret=OK,ret1=OK; - int n; - int startACQ; - //char *retval=NULL; -#ifdef GOTTHARDD - char CounterVals[NCHAN*NCHIP]; -#else + int n=0; char CounterVals[dataBytes]; -#endif - + memset(CounterVals,0,dataBytes); sprintf(mess,"Read counter block failed\n"); - n = receiveData(file_des,&startACQ,sizeof(startACQ),INT32); - if (n < 0) { - sprintf(mess,"Error reading from socket\n"); - ret=FAIL; - } #ifndef GOTTHARDD + //to receive any arguments + while (n > 0) + n = receiveData(file_des,mess,MAX_STR_LENGTH,OTHER); ret = FAIL; - strcpy(mess,"Not applicable/implemented for this detector\n"); + sprintf(mess,"Function (Read Counter Block) is not implemented for this detector\n"); + cprintf(RED, "Warning: %s", mess); #else + + // receive arguments + int startACQ=-1; + n = receiveData(file_des,&startACQ,sizeof(startACQ),INT32); + if (n < 0) return printSocketReadError(); + + // execute action + if (differentClients && lockStatus) { + ret = FAIL; + sprintf(mess,"Detector locked by %s\n",lastClientIP); + cprintf(RED, "Warning: %s", mess); + } #ifdef SLS_DETECTOR_FUNCTION_LIST - if (ret==OK) { - if (differentClients==1 && lockStatus==1) { - ret=FAIL; - sprintf(mess,"Detector locked by %s\n",lastClientIP); - } else{ - ret=readCounterBlock(startACQ,CounterVals); + else { + ret=readCounterBlock(startACQ,CounterVals); + if (ret == FAIL) + cprintf(RED, "Warning: %s", mess); #ifdef VERBOSE - int i; - for(i=0;i<6;i++) - printf("%d:%d\t",i,CounterVals[i]); + int i; + for(i=0;i<6;i++) + printf("%d:%d\t",i,CounterVals[i]); #endif - } } #endif + if (ret==OK && differentClients) + ret=FORCE_UPDATE; #endif - if(ret!=FAIL){ - if (differentClients) - ret=FORCE_UPDATE; - } - - /* send answer */ - /* send OK/failed */ - //ret could be swapped during sendData + // ret could be swapped during sendData ret1 = ret; + // send ok / fail n = sendData(file_des,&ret1,sizeof(ret),INT32); - if (ret!=FAIL) { - /* send return argument */ - n += sendData(file_des,CounterVals,dataBytes,OTHER);//1280*2 - } else { + // send return argument + if (ret==FAIL) { n += sendData(file_des,mess,sizeof(mess),OTHER); - } + } else + n += sendData(file_des,CounterVals,dataBytes,OTHER); - /*return ok/fail*/ + // return ok / fail return ret; } @@ -3474,131 +3750,52 @@ int read_counter_block(int file_des) { int reset_counter_block(int file_des) { - int ret=OK,ret1=OK; - int n; - int startACQ; - + int n=0; sprintf(mess,"Reset counter block failed\n"); +#ifndef GOTTHARDD + //to receive any arguments + while (n > 0) + n = receiveData(file_des,mess,MAX_STR_LENGTH,OTHER); + ret = FAIL; + sprintf(mess,"Function (Reset Counter Block) is not implemented for this detector\n"); + cprintf(RED, "Warning: %s", mess); +#else + + // receive arguments + int startACQ=-1; n = receiveData(file_des,&startACQ,sizeof(startACQ),INT32); - if (n < 0) { - sprintf(mess,"Error reading from socket\n"); - ret=FAIL; + if (n < 0) return printSocketReadError(); + + // execute action + if (differentClients && lockStatus) { + ret = FAIL; + sprintf(mess,"Detector locked by %s\n",lastClientIP); + cprintf(RED, "Warning: %s", mess); } -#ifndef GOTTHARDD - ret = FAIL; - strcpy(mess,"Not applicable/implemented for this detector\n"); -#else #ifdef SLS_DETECTOR_FUNCTION_LIST - if (ret==OK) { - if (differentClients==1 && lockStatus==1) { - ret=FAIL; - sprintf(mess,"Detector locked by %s\n",lastClientIP); - } else - ret=resetCounterBlock(startACQ); + else { + ret=resetCounterBlock(startACQ); + if (ret == FAIL) + cprintf(RED, "Warning: %s", mess); } #endif -#endif - if(ret==OK){ - if (differentClients) - ret=FORCE_UPDATE; - } - - /* send answer */ - /* send OK/failed */ - //ret could be swapped during sendData - ret1 = ret; - n = sendData(file_des,&ret1,sizeof(ret),INT32); - if (ret==FAIL) - n += sendData(file_des,mess,sizeof(mess),OTHER); - - /*return ok/fail*/ - return ret; -} - - - - - - - - -int start_receiver(int file_des) { - int ret=OK,ret1=OK; - int n=0; - strcpy(mess,"Could not start receiver\n"); - - /* execute action if the arguments correctly arri ved*/ -#if defined(GOTTHARDD) || defined(EIGERD) -#ifdef SLS_DETECTOR_FUNCTION_LIST - if (lockStatus==1 && differentClients==1){//necessary??? - sprintf(mess,"Detector locked by %s\n", lastClientIP); - ret=FAIL; - } - else - ret = startReceiver(1); - -#endif -#else - ret = FAIL; - strcpy(mess,"Not applicable/implemented for this detector\n"); -#endif - - if(ret==OK && differentClients){ - printf("Force update\n"); + if (ret==OK && differentClients) ret=FORCE_UPDATE; - } - - /* send answer */ - //ret could be swapped during sendData - ret1 = ret; - n = sendData(file_des,&ret1,sizeof(ret),INT32); - if(ret==FAIL) - n += sendData(file_des,mess,sizeof(mess),OTHER); - /*return ok/fail*/ - return ret; -} - - - - - - -int stop_receiver(int file_des) { - int ret=OK,ret1=OK; - int n=0; - - strcpy(mess,"Could not stop receiver\n"); - - /* execute action if the arguments correctly arrived*/ -#ifndef GOTTHARDD - ret = FAIL; - strcpy(mess,"Not applicable/implemented for this detector\n"); -#else -#ifdef SLS_DETECTOR_FUNCTION_LIST - if (lockStatus==1 && differentClients==1){//necessary??? - sprintf(mess,"Detector locked by %s\n", lastClientIP); - ret=FAIL; - } - else - ret=startReceiver(0); - -#endif #endif - if(ret==OK && differentClients){ - printf("Force update\n"); - ret=FORCE_UPDATE; + + // ret could be swapped during sendData + ret1 = ret; + // send ok / fail + n = sendData(file_des,&ret1,sizeof(ret),INT32); + // send return argument + if (ret==FAIL) { + n += sendData(file_des,mess,sizeof(mess),OTHER); } - /* send answer */ - //ret could be swapped during sendData - ret1 = ret; - n = sendData(file_des,&ret1,sizeof(ret),INT32); - if(ret==FAIL) - n += sendData(file_des,mess,sizeof(mess),OTHER); - /*return ok/fail*/ + // return ok / fail return ret; } @@ -3607,49 +3804,55 @@ int stop_receiver(int file_des) { int calibrate_pedestal(int file_des){ - int ret=OK,ret1=OK; + int n=0; int retval=-1; - int n; - int frames; + sprintf(mess,"calibrate pedestal failed\n"); - sprintf(mess,"Could not calibrate pedestal\n"); - n = receiveData(file_des,&frames,sizeof(frames),INT32); - if (n < 0) { - sprintf(mess,"Error reading from socket\n"); - ret=FAIL; - } #ifndef GOTTHARDD + //to receive any arguments + while (n > 0) + n = receiveData(file_des,mess,MAX_STR_LENGTH,OTHER); ret = FAIL; - strcpy(mess,"Not applicable/implemented for this detector\n"); + sprintf(mess,"Function (Calibrate Pedestal) is not implemented for this detector\n"); + cprintf(RED, "Warning: %s", mess); #else -#ifdef SLS_DETECTOR_FUNCTION_LIST - if (ret==OK) { - if (differentClients==1 && lockStatus==1) { - ret=FAIL; - sprintf(mess,"Detector locked by %s\n",lastClientIP); - } else - ret=calibratePedestal(frames); - } -#endif -#endif - if(ret==OK){ - if (differentClients) - ret=FORCE_UPDATE; - } - /* send answer */ - /* send OK/failed */ - //ret could be swapped during sendData + // receive arguments + int frames=-1; + n = receiveData(file_des,&frames,sizeof(frames),INT32); + if (n < 0) return printSocketReadError(); + + + // execute action + if (differentClients && lockStatus) { + ret = FAIL; + sprintf(mess,"Detector locked by %s\n",lastClientIP); + cprintf(RED, "Warning: %s", mess); + } +#ifdef SLS_DETECTOR_FUNCTION_LIST + else { + ret=calibratePedestal(frames); + if (ret == FAIL) + cprintf(RED, "Warning: %s", mess); + } +#endif + if(ret==OK && differentClients) + ret=FORCE_UPDATE; +#endif + + // ret could be swapped during sendData ret1 = ret; + // send ok / fail n = sendData(file_des,&ret1,sizeof(ret),INT32); - if (ret==FAIL) + // send return argument + if (ret==FAIL) { n += sendData(file_des,mess,sizeof(mess),OTHER); - else + } else n += sendData(file_des,&retval,sizeof(retval),INT32); - /*return ok/fail*/ + // return ok / fail return ret; } @@ -3660,485 +3863,543 @@ int calibrate_pedestal(int file_des){ - int enable_ten_giga(int file_des) { - int n; - int retval=-1; int ret=OK,ret1=OK; - int arg = -1; + int n=0; + int retval=-1; + sprintf(mess,"Enabling/disabling 10GbE failed\n"); - sprintf(mess,"Can't enable/disable 10Gbe \n"); - /* receive arguments */ - n = receiveData(file_des,&arg,sizeof(arg),INT32); - if (n < 0) { - sprintf(mess,"Error reading from socket\n"); - ret=FAIL; - } - /* execute action */ + // execute action #ifndef EIGERD + //to receive any arguments + while (n > 0) + n = receiveData(file_des,mess,MAX_STR_LENGTH,OTHER); ret = FAIL; - strcpy(mess,"Not applicable/implemented for this detector\n"); + sprintf(mess,"Function (Enable 10 GbE) is not implemented for this detector\n"); + cprintf(RED, "Warning: %s", mess); #else -#ifdef VERBOSE - printf("Enabling 10Gbe :%d \n",arg); -#endif -#ifdef SLS_DETECTOR_FUNCTION_LIST - if(ret != FAIL){ + // receive arguments + int arg=-1; + n = receiveData(file_des,&arg,sizeof(arg),INT32); + if (n < 0) return printSocketReadError(); + + // execute action + if (differentClients && lockStatus && arg!=-1) { + ret = FAIL; + sprintf(mess,"Detector locked by %s\n",lastClientIP); + cprintf(RED, "Warning: %s", mess); + } +#ifdef SLS_DETECTOR_FUNCTION_LIST + else { +#ifdef VERBOSE + printf("Enabling/Disabling 10Gbe :%d \n",arg); +#endif retval=enableTenGigabitEthernet(arg); - if((arg != -1) && (retval != arg)) + if((arg != -1) && (retval != arg)) { ret=FAIL; - else if (differentClients==1) { - ret=FORCE_UPDATE; + cprintf(RED, "Warning: %s", mess); } + else if (differentClients) + ret=FORCE_UPDATE; } #endif #endif - /* send answer */ - /* send OK/failed */ - //ret could be swapped during sendData + + // ret could be swapped during sendData ret1 = ret; + // send ok / fail n = sendData(file_des,&ret1,sizeof(ret),INT32); - if (ret==FAIL) + // send return argument + if (ret==FAIL) { n += sendData(file_des,mess,sizeof(mess),OTHER); - /* send return argument */ + } n += sendData(file_des,&retval,sizeof(retval),INT32); - /*return ok/fail*/ + + // return ok / fail return ret; } + int set_all_trimbits(int file_des){ - - - int retval; - int arg; - int n; int ret=OK,ret1=OK; - - sprintf(mess,"can't set sll trimbits\n"); - - n = receiveData(file_des,&arg,sizeof(arg),INT32); - if (n < 0) { - sprintf(mess,"Error reading from socket\n"); - ret=FAIL; - } + int n=0; + int retval=-1; + sprintf(mess,"setting all trimbits failed\n"); #ifndef EIGERD + //to receive any arguments + while (n > 0) + n = receiveData(file_des,mess,MAX_STR_LENGTH,OTHER); ret = FAIL; - strcpy(mess,"Not applicable/implemented for this detector\n"); + sprintf(mess,"Function (Set All Trimbits) is not implemented for this detector\n"); + cprintf(RED, "Warning: %s", mess); #else -#ifdef VERBOSE - printf("setting all trimbits to %d\n",arg); -#endif -#ifdef SLS_DETECTOR_FUNCTION_LIST - if (differentClients==1 && lockStatus==1 && arg!=GET_READOUT_FLAGS) { - ret=FAIL; + + // receive arguments + int arg=-1; + n = receiveData(file_des,&arg,sizeof(arg),INT32); + if (n < 0) return printSocketReadError(); + + + // execute action + if (differentClients && lockStatus && arg!=-1) { + ret = FAIL; sprintf(mess,"Detector locked by %s\n",lastClientIP); - } else { + cprintf(RED, "Warning: %s", mess); + } +#ifdef SLS_DETECTOR_FUNCTION_LIST + else { +#ifdef VERBOSE + printf("setting all trimbits to %d\n",arg); +#endif if(arg < -1){ ret = FAIL; strcpy(mess,"Cant set trimbits to this value\n"); + cprintf(RED, "Warning: %s", mess); }else { - if(arg >= 0) - setAllTrimbits(arg); + if(arg >= 0){ + ret = setAllTrimbits(arg); + //changes settings to undefined + setSettings(UNDEFINED,-1); + cprintf(RED,"Settings has been changed to undefined (change all trimbits)\n"); + } retval = getAllTrimbits(); + if (arg!=-1 && arg!=retval) { + ret=FAIL; + sprintf(mess,"Could not set all trimbits: should be %d but is %d\n", arg, retval); + cprintf(RED, "Warning: %s", mess); + } } } #endif - if (ret==OK) { - if (arg!=-1 && arg!=retval) { - ret=FAIL; - sprintf(mess,"Could not set all trimbits: should be %d but is %d\n", arg, retval); - }else if (differentClients) - ret=FORCE_UPDATE; + if (ret==OK && differentClients) + ret=FORCE_UPDATE; +#endif + + // ret could be swapped during sendData + ret1 = ret; + // send ok / fail + n = sendData(file_des,&ret1,sizeof(ret),INT32); + // send return argument + if (ret==FAIL) { + n += sendData(file_des,mess,sizeof(mess),OTHER); + } else + n += sendData(file_des,&retval,sizeof(retval),INT32); + + // return ok / fail + return ret; +} + + +int set_ctb_pattern(int file_des) { + int ret=FAIL,ret1=FAIL; + int n=0; + sprintf(mess,"Function (Set CTB Pattern) is not implemented for this detector\n"); + cprintf(RED, "Error: %s", mess); + + //to receive any arguments + while (n > 0) + n = receiveData(file_des,mess,MAX_STR_LENGTH,OTHER); + + n = sendData(file_des,&ret1,sizeof(ret),INT32); + n = sendData(file_des,mess,MAX_STR_LENGTH,OTHER); + + // return ok / fail + return ret; +} + + + +int write_adc_register(int file_des) { + int ret=OK, ret1=OK; + int n=0; + int retval=-1; + sprintf(mess,"write to adc register failed\n"); + +#ifndef JUNGFRAUD + //to receive any arguments + while (n > 0) + n = receiveData(file_des,mess,MAX_STR_LENGTH,OTHER); + ret = FAIL; + sprintf(mess,"Function (Write ADC Register) is not implemented for this detector\n"); + cprintf(RED, "Warning: %s", mess); +#else + + // receive arguments + int arg[2]={-1,-1}; + n = receiveData(file_des,arg,sizeof(arg),INT32); + if (n < 0) return printSocketReadError(); + int addr=arg[0]; + int val=arg[1]; + + // execute action + if (differentClients && lockStatus) { + ret = FAIL; + sprintf(mess,"Detector locked by %s\n",lastClientIP); + cprintf(RED, "Warning: %s", mess); + } + else { +#ifdef VERBOSE + printf("writing to register 0x%x data 0x%x\n", addr, val); +#endif + setAdc(addr,val); +#ifdef VERBOSE + printf("Data set to 0x%x\n", retval); +#endif + if (ret==OK && differentClients) + ret=FORCE_UPDATE; } #endif - //ret could be swapped during sendData + // ret could be swapped during sendData ret1 = ret; + // send ok / fail n = sendData(file_des,&ret1,sizeof(ret),INT32); + // send return argument if (ret==FAIL) { - n = sendData(file_des,mess,sizeof(mess),OTHER); - } else { - n = sendData(file_des,&retval,sizeof(retval),INT32); - } + n += sendData(file_des,mess,sizeof(mess),OTHER); + } else + n += sendData(file_des,&retval,sizeof(retval),INT32); + + // return ok / fail return ret; - } - int set_counter_bit(int file_des) { - int n; - int retval = -1; int ret=OK,ret1=OK; - int arg = -1; + int n=0; + int retval=-1; + sprintf(mess,"set counter bit failed \n"); - sprintf(mess,"Can't set/rest counter bit \n"); - /* receive arguments */ - n = receiveData(file_des,&arg,sizeof(arg),INT32); - if (n < 0) { - sprintf(mess,"Error reading from socket\n"); - ret=FAIL; - } - /* execute action */ #ifndef EIGERD + //to receive any arguments + while (n > 0) + n = receiveData(file_des,mess,MAX_STR_LENGTH,OTHER); ret = FAIL; - strcpy(mess,"Not applicable/implemented for this detector\n"); + strcpy(mess,"Function (Set Counter Bit) is not implemented for this detector\n"); + cprintf(RED, "Warning: %s", mess); #else + + // receive arguments + int arg=-1; + n = receiveData(file_des,&arg,sizeof(arg),INT32); + if (n < 0) return printSocketReadError(); + + // execute action + if (differentClients && lockStatus && arg!=-1) { + ret = FAIL; + sprintf(mess,"Detector locked by %s\n",lastClientIP); + cprintf(RED, "Warning: %s", mess); + } +#ifdef SLS_DETECTOR_FUNCTION_LIST + else { #ifdef VERBOSE printf("Getting/Setting/Resetting counter bit :%d \n",arg); #endif -#ifdef SLS_DETECTOR_FUNCTION_LIST - if(ret != FAIL){ retval=setCounterBit(arg); - if((arg != -1) && (retval != arg)) + if((arg != -1) && (retval != arg)) { ret=FAIL; - else if (differentClients==1) { - ret=FORCE_UPDATE; + cprintf(RED, "Warning: %s", mess); } + if (ret==OK && differentClients) + ret=FORCE_UPDATE; } #endif #endif - /* send answer */ - /* send OK/failed */ - //ret could be swapped during sendData + + // ret could be swapped during sendData ret1 = ret; + // send ok / fail n = sendData(file_des,&ret1,sizeof(ret),INT32); - if (ret==FAIL) + // send return argument + if (ret==FAIL) { n += sendData(file_des,mess,sizeof(mess),OTHER); - /* send return argument */ + } n += sendData(file_des,&retval,sizeof(retval),INT32); - /*return ok/fail*/ + + // return ok / fail return ret; } + + int pulse_pixel(int file_des) { - int ret=OK,ret1=OK; - int n; - int arg[3]; - arg[0]=-1; arg[1]=-1; arg[2]=-1; - - + int n=0; sprintf(mess,"pulse pixel failed\n"); - n = receiveData(file_des,arg,sizeof(arg),INT32); - if (n < 0) { - sprintf(mess,"Error reading from socket\n"); - ret=FAIL; - } #ifndef EIGERD + //to receive any arguments + while (n > 0) + n = receiveData(file_des,mess,MAX_STR_LENGTH,OTHER); ret = FAIL; - strcpy(mess,"Not applicable/implemented for this detector\n"); + strcpy(mess,"Function (Pulse Pixel) is not implemented for this detector\n"); + cprintf(RED, "Warning: %s", mess); #else + + // receive arguments + int arg[3]={-1,-1,-1}; + n = receiveData(file_des,arg,sizeof(arg),INT32); + if (n < 0) return printSocketReadError(); + + // execute action + if (differentClients && lockStatus) { + ret = FAIL; + sprintf(mess,"Detector locked by %s\n",lastClientIP); + cprintf(RED, "Warning: %s", mess); + } #ifdef SLS_DETECTOR_FUNCTION_LIST - if (ret==OK) { - if (differentClients==1 && lockStatus==1) { - ret=FAIL; - sprintf(mess,"Detector locked by %s\n",lastClientIP); - } else - ret=pulsePixel(arg[0],arg[1],arg[2]); + else { + ret=pulsePixel(arg[0],arg[1],arg[2]); + if (ret == FAIL) + cprintf(RED, "Warning: %s", mess); } #endif + if (ret==OK && differentClients) + ret=FORCE_UPDATE; #endif - if(ret==OK){ - if (differentClients) - ret=FORCE_UPDATE; - } - /* send answer */ - /* send OK/failed */ - //ret could be swapped during sendData + // ret could be swapped during sendData ret1 = ret; + // send ok / fail n = sendData(file_des,&ret1,sizeof(ret),INT32); - if (ret==FAIL) + // send return argument + if (ret==FAIL) { n += sendData(file_des,mess,sizeof(mess),OTHER); + } - /*return ok/fail*/ + // return ok / fail return ret; } + + int pulse_pixel_and_move(int file_des) { - int ret=OK,ret1=OK; - int n; - int arg[3]; - arg[0]=-1; arg[1]=-1; arg[2]=-1; - - + int n=0; sprintf(mess,"pulse pixel and move failed\n"); - n = receiveData(file_des,arg,sizeof(arg),INT32); - if (n < 0) { - sprintf(mess,"Error reading from socket\n"); - ret=FAIL; - } #ifndef EIGERD + //to receive any arguments + while (n > 0) + n = receiveData(file_des,mess,MAX_STR_LENGTH,OTHER); ret = FAIL; - strcpy(mess,"Not applicable/implemented for this detector\n"); + strcpy(mess,"Function (Pulse Pixel and Move) is not implemented for this detector\n"); + cprintf(RED, "Warning: %s", mess); #else + + // receive arguments + int arg[3]={-1,-1,-1}; + n = receiveData(file_des,arg,sizeof(arg),INT32); + if (n < 0) return printSocketReadError(); + + // execute action + if (differentClients && lockStatus) { + ret = FAIL; + sprintf(mess,"Detector locked by %s\n",lastClientIP); + cprintf(RED, "Warning: %s", mess); + } #ifdef SLS_DETECTOR_FUNCTION_LIST - if (ret==OK) { - if (differentClients==1 && lockStatus==1) { - ret=FAIL; - sprintf(mess,"Detector locked by %s\n",lastClientIP); - } else - ret=pulsePixelNMove(arg[0],arg[1],arg[2]); + else { + ret=pulsePixelNMove(arg[0],arg[1],arg[2]); + if (ret == FAIL) + cprintf(RED, "Warning: %s", mess); } #endif + if(ret==OK && differentClients) + ret=FORCE_UPDATE; #endif - if(ret==OK){ - if (differentClients) - ret=FORCE_UPDATE; - } - /* send answer */ - /* send OK/failed */ - //ret could be swapped during sendData + // ret could be swapped during sendData ret1 = ret; + // send ok / fail n = sendData(file_des,&ret1,sizeof(ret),INT32); - if (ret==FAIL) + // send return argument + if (ret==FAIL) { n += sendData(file_des,mess,sizeof(mess),OTHER); + } - /*return ok/fail*/ + // return ok / fail return ret; - } + + int pulse_chip(int file_des) { - int ret=OK,ret1=OK; - int n; - int arg = -1; - - + int n=0; sprintf(mess,"pulse chip failed\n"); - n = receiveData(file_des,&arg,sizeof(arg),INT32); - if (n < 0) { - sprintf(mess,"Error reading from socket\n"); - ret=FAIL; - } #ifndef EIGERD + //to receive any arguments + while (n > 0) + n = receiveData(file_des,mess,MAX_STR_LENGTH,OTHER); ret = FAIL; - strcpy(mess,"Not applicable/implemented for this detector\n"); + strcpy(mess,"Function (Pulse Chip) is not implemented for this detector\n"); + cprintf(RED, "Warning: %s", mess); #else + + // receive arguments + int arg = -1; + n = receiveData(file_des,&arg,sizeof(arg),INT32); + if (n < 0) return printSocketReadError(); + + // execute action + if (differentClients && lockStatus) { + ret = FAIL; + sprintf(mess,"Detector locked by %s\n",lastClientIP); + cprintf(RED, "Warning: %s", mess); + } #ifdef SLS_DETECTOR_FUNCTION_LIST - if (ret==OK) { - if (differentClients==1 && lockStatus==1) { - ret=FAIL; - sprintf(mess,"Detector locked by %s\n",lastClientIP); - } else - ret=pulseChip(arg); + else { + ret=pulseChip(arg); + if (ret == FAIL) + cprintf(RED, "Warning: %s", mess); } #endif + if(ret==OK && differentClients) + ret=FORCE_UPDATE; #endif - if(ret==OK){ - if (differentClients) - ret=FORCE_UPDATE; - } - /* send answer */ - /* send OK/failed */ - //ret could be swapped during sendData + // ret could be swapped during sendData ret1 = ret; + // send ok / fail n = sendData(file_des,&ret1,sizeof(ret),INT32); - if (ret==FAIL) + // send return argument + if (ret==FAIL) { n += sendData(file_des,mess,sizeof(mess),OTHER); + } - /*return ok/fail*/ + // return ok / fail return ret; - } + int set_rate_correct(int file_des) { - int64_t tau_ns=-1; - int n; int ret=OK,ret1=OK; - - sprintf(mess,"can't set/unset rate correction\n"); - - n = receiveData(file_des,&tau_ns,sizeof(tau_ns),INT64); - if (n < 0) { - sprintf(mess,"Error reading from socket\n"); - cprintf(RED,"%s",mess); - ret=FAIL; - } + int n=0; + sprintf(mess,"Set rate correct failed\n"); #ifndef EIGERD - sprintf(mess,"Rate Correction not implemented for this detector\n"); - cprintf(RED,"%s",mess); + //to receive any arguments + while (n > 0) + n = receiveData(file_des,mess,MAX_STR_LENGTH,OTHER); ret=FAIL; -#endif + sprintf(mess,"Function (Rate Correction) is not implemented for this detector\n"); + cprintf(RED, "Warning: %s", mess); +#else + // receive arguments + int64_t tau_ns=-1; + n = receiveData(file_des,&tau_ns,sizeof(tau_ns),INT64); + if (n < 0) return printSocketReadError(); + + // execute action + if (differentClients && lockStatus) { + ret = FAIL; + sprintf(mess,"Detector locked by %s\n",lastClientIP); + cprintf(RED, "Warning: %s", mess); + } #ifdef SLS_DETECTOR_FUNCTION_LIST - - if (ret==OK) { + else { printf("Setting rate correction to %lld ns\n",tau_ns); - - if (differentClients==1 && lockStatus==1) { + //set rate + //wrong bit mode + if((setDynamicRange(-1)!=32) && (setDynamicRange(-1)!=16) && (tau_ns!=0)){ ret=FAIL; - sprintf(mess,"Detector locked by %s\n",lastClientIP); - } else { - - //tau = -1, use default tau of settings - if((ret==OK)&&(tau_ns<0)){ + strcpy(mess,"Rate correction Deactivated, must be in 32 or 16 bit mode\n"); + cprintf(RED, "Warning: %s", mess); + } + //16 or 32 bit mode + else{ + if(tau_ns < 0) tau_ns = getDefaultSettingsTau_in_nsec(); - } - //still negative (not set) - if(tau_ns < 0){ - ret = FAIL; - if(getRateCorrectionEnable()){ - setRateCorrection(0); - strcpy(mess,"Cannot set rate correction as default tau not provided. Switching off Rate Correction\n"); - }else{ - strcpy(mess,"Cannot set rate correction as default tau not provided\n"); - } - cprintf(RED,"%s",mess); + else if(tau_ns > 0){ + //changing tau to a user defined value changes settings to undefined + setSettings(UNDEFINED,-1); + cprintf(RED,"Settings has been changed to undefined (tau changed)\n"); } - //set rate - else{ - //not 32 or 16 bit mode - if((setDynamicRange(-1)!=32) && (setDynamicRange(-1)!=16) && (tau_ns!=0)){ - strcpy(mess,"Rate correction Deactivated, must be in 32 or 16 bit mode\n"); - cprintf(RED,"%s",mess); - ret=FAIL; - } - //32 bit mode - else{ - int64_t retval = setRateCorrection(tau_ns); //tau_ns will not be -1 here - if(tau_ns != retval){ - cprintf(RED,"%s",mess); - ret=FAIL; - } - } + int64_t retval = setRateCorrection(tau_ns); + if(tau_ns != retval){ + ret=FAIL; + cprintf(RED, "Warning: %s", mess); } } } #endif - if ((ret==OK) && (differentClients)) + if (ret==OK && differentClients) ret=FORCE_UPDATE; +#endif - - //ret could be swapped during sendData + // ret could be swapped during sendData ret1 = ret; + // send ok / fail n = sendData(file_des,&ret1,sizeof(ret),INT32); + // send return argument if (ret==FAIL) { n = sendData(file_des,mess,sizeof(mess),OTHER); } + // return ok / fail return ret; } + int get_rate_correct(int file_des) { - int64_t retval=-1; int ret=OK,ret1=OK; - - sprintf(mess,"can't get rate correction\n"); - + int n=0; + int64_t retval=-1; + sprintf(mess,"Get Rate correct failed\n"); #ifndef EIGERD - sprintf(mess,"Rate Correction not implemented for this detector\n"); - cprintf(RED,"%s",mess); + //to receive any arguments + while (n > 0) + n = receiveData(file_des,mess,MAX_STR_LENGTH,OTHER); ret=FAIL; -#endif - -#ifdef SLS_DETECTOR_FUNCTION_LIST - - if (ret==OK) { - retval = getCurrentTau(); - printf("Getting rate correction %lld\n",(long long int)retval); - } -#endif - if ((ret==OK) && (differentClients)) - ret=FORCE_UPDATE; - - - //ret could be swapped during sendData - ret1 = ret; - sendData(file_des,&ret1,sizeof(ret),INT32); - if (ret==FAIL) { - sendData(file_des,mess,sizeof(mess),OTHER); - } else { - sendData(file_des,&retval,sizeof(retval),INT64); - } - - return ret; -} - - - - - - -int set_activate(int file_des) { - - int arg, n; - int ret=OK,ret1=OK; - int retval; - - sprintf(mess,"can't activate/deactivate detector\n"); - - n = receiveData(file_des,&arg,sizeof(arg),INT32); - if (n < 0) { - sprintf(mess,"Error reading from socket\n"); - ret=FAIL; - } - -#ifdef VERBOSE - printf("Setting activate mode of detector to %d\n",arg); -#endif - if (ret==OK) { - - if (differentClients==1 && lockStatus==1 && arg>=0) { - ret=FAIL; - sprintf(mess,"Detector locked by %s\n",lastClientIP); - } else { -#ifdef SLS_DETECTOR_FUNCTION_LIST -#ifdef EIGERD - retval=activate(arg); + sprintf(mess,"Function (Get Rate Correction) is not implemented for this detector\n"); + cprintf(RED, "Warning: %s", mess); #else - sprintf(mess,"Deactivate/Activate Not implemented for this detector\n"); - ret=FAIL; + +#ifdef SLS_DETECTOR_FUNCTION_LIST + + // execute action + retval = getCurrentTau(); + printf("Getting rate correction %lld\n",(long long int)retval); + #endif + if (ret==OK && differentClients) + ret=FORCE_UPDATE; #endif - } - if (ret==OK){ - if ((retval!=arg) && (arg!=-1)) { - ret=FAIL; - sprintf(mess,"Could not set activate mode to %d, is set to %d\n",arg, retval); - }else if (differentClients) - ret=FORCE_UPDATE; - } - } - - - //ret could be swapped during sendData + // ret could be swapped during sendData ret1 = ret; + // send ok / fail n = sendData(file_des,&ret1,sizeof(ret),INT32); + // send return argument if (ret==FAIL) { - n = sendData(file_des,mess,sizeof(mess),OTHER); - } else { - n = sendData(file_des,&retval,sizeof(retval),INT32); - } + n += sendData(file_des,mess,sizeof(mess),OTHER); + } else + n += sendData(file_des,&retval,sizeof(retval),INT64); + + // return ok / fail return ret; } @@ -4146,79 +4407,495 @@ int set_activate(int file_des) { - - - int set_network_parameter(int file_des) { - - enum detNetworkParameter index; - enum networkParameter mode; - int value = -1; int ret=OK,ret1=OK; - int retval = -1,n; + int n=0; + int retval=-1; + sprintf(mess,"set network parameter failed\n"); - sprintf(mess,"can't set network parameter\n"); +#ifndef EIGERD + //to receive any arguments + while (n > 0) + n = receiveData(file_des,mess,MAX_STR_LENGTH,OTHER); + ret=FAIL; + sprintf(mess,"Function(Set Network Parmaeter) is not implemented for this detector\n"); + cprintf(RED, "Warning: %s", mess); +#else + + enum NETWORKINDEX index; + + // receive arguments + enum networkParameter mode=0; + int value=-1; n = receiveData(file_des,&mode,sizeof(mode),INT32); - if (n < 0) { - sprintf(mess,"Error reading from socket\n"); - ret=FAIL; - } - n = receiveData(file_des,&value,sizeof(value),INT32); - if (n < 0) { - sprintf(mess,"Error reading from socket\n"); - ret=FAIL; - } + if (n < 0) return printSocketReadError(); -#ifdef VERBOSE - printf("setting network parameter mode %d to %d\n",(int)mode,value); -#endif - if (ret==OK) { - if (differentClients==1 && lockStatus==1 && value>=0) { - ret=FAIL; - sprintf(mess,"Detector locked by %s\n",lastClientIP); - } else { + n = receiveData(file_des,&value,sizeof(value),INT32); + if (n < 0) return printSocketReadError(); + + // execute action + if (differentClients && lockStatus && value<0) { + ret = FAIL; + sprintf(mess,"Detector locked by %s\n",lastClientIP); + cprintf(RED, "Warning: %s", mess); + } #ifdef SLS_DETECTOR_FUNCTION_LIST - switch (mode) { -#ifdef EIGERD - case DETECTOR_TXN_DELAY_LEFT: - index = TXN_LEFT; - break; - case DETECTOR_TXN_DELAY_RIGHT: - index = TXN_RIGHT; - break; - case DETECTOR_TXN_DELAY_FRAME: - index = TXN_FRAME; - break; - case FLOW_CONTROL_10G: - index = FLOWCTRL_10G; - break; -#endif - default: - sprintf(mess,"unknown network parameter %d for this detector\n",mode); - ret=FAIL; - break; - } - if (ret==OK) - retval=setNetworkParameter(index, value); + else { +#ifdef VERBOSE + printf("setting network parameter mode %d to %d\n",(int)mode,value); #endif + switch (mode) { + case DETECTOR_TXN_DELAY_LEFT: + index = TXN_LEFT; + break; + case DETECTOR_TXN_DELAY_RIGHT: + index = TXN_RIGHT; + break; + case DETECTOR_TXN_DELAY_FRAME: + index = TXN_FRAME; + break; + case FLOW_CONTROL_10G: + index = FLOWCTRL_10G; + break; + default: + ret=FAIL; + sprintf(mess,"Network Parameter Index (%d) is not implemented for this detector\n",(int) mode); + cprintf(RED, "Warning: %s", mess); + break; } - if (ret==OK){ + if (ret==OK) { + retval=setNetworkParameter(index, value); if ((retval!=value) && (value>=0)) { ret=FAIL; sprintf(mess,"could not change network parameter mode %d: should be %d but is %d \n",index, value, retval); - cprintf(RED, "%s",mess); - }else if (differentClients) - ret=FORCE_UPDATE; + cprintf(RED, "Warning: %s", mess); + } } } +#endif + if (ret==OK && differentClients) + ret=FORCE_UPDATE; +#endif - //ret could be swapped during sendData + // ret could be swapped during sendData ret1 = ret; + // send ok / fail n = sendData(file_des,&ret1,sizeof(ret),INT32); - if (ret==FAIL) - n = sendData(file_des,mess,sizeof(mess),OTHER); - else - n = sendData(file_des,&retval,sizeof(retval),INT32); + // send return argument + if (ret==FAIL) { + n += sendData(file_des,mess,sizeof(mess),OTHER); + } else + n += sendData(file_des,&retval,sizeof(retval),INT32); + // return ok / fail return ret; } + + + + + + +int program_fpga(int file_des) { + int ret=OK,ret1=OK; + int n=0; + sprintf(mess,"program FPGA failed\n"); + + +#ifndef JUNGFRAUD + //to receive any arguments + while (n > 0) + n = receiveData(file_des,mess,MAX_STR_LENGTH,OTHER); + ret=FAIL; + sprintf(mess,"Function (Program FPGA) is not implemented for this detector\n"); + cprintf(RED, "Warning: %s", mess); +#else + + size_t filesize = 0; + size_t totalsize = 0; + size_t unitprogramsize = 0; + char* fpgasrc = NULL; + FILE* fp = NULL; + + // receive arguments - filesize + n = receiveData(file_des,&filesize,sizeof(filesize),INT32); + if (n < 0) return printSocketReadError(); + totalsize = filesize; +#ifdef VERY_VERBOSE + printf("\n\n Total size is:%d\n",totalsize); +#endif + + // execute action + if (differentClients && lockStatus) { + ret = FAIL; + sprintf(mess,"Detector locked by %s\n",lastClientIP); + cprintf(RED, "Warning: %s", mess); + } +#ifdef SLS_DETECTOR_FUNCTION_LIST + else { + //opening file pointer to flash and telling FPGA to not touch flash + if(startWritingFPGAprogram(&fp) != OK) { + ret=FAIL; + sprintf(mess,"Could not write to flash. Error at startup.\n"); + cprintf(RED,"%s",mess); + } + + //---------------- first ret ---------------- + // ret could be swapped during sendData + ret1 = ret; + // send ok / fail + n = sendData(file_des,&ret1,sizeof(ret),INT32); + // send return argument + if (ret==FAIL) { + n += sendData(file_des,mess,sizeof(mess),OTHER); + } + //---------------- first ret ---------------- + + if(ret!=FAIL) { + //erasing flash + eraseFlash(); + fpgasrc = (char*)malloc(MAX_FPGAPROGRAMSIZE); + } + + //writing to flash part by part + while(ret != FAIL && filesize){ + + unitprogramsize = MAX_FPGAPROGRAMSIZE; //2mb + if(unitprogramsize > filesize) //less than 2mb + unitprogramsize = filesize; + #ifdef VERY_VERBOSE + printf("unit size to receive is:%d\n",unitprogramsize); + printf("filesize:%d currentpointer:%d\n",filesize,currentPointer); + #endif + + //receive + n = receiveData(file_des,fpgasrc,unitprogramsize,OTHER); + if (n < 0) return printSocketReadError(); + + if(!(unitprogramsize - filesize)){ + fpgasrc[unitprogramsize]='\0'; + filesize-=unitprogramsize; + unitprogramsize++; + }else + filesize-=unitprogramsize; + + ret = writeFPGAProgram(fpgasrc,unitprogramsize,fp); + + //---------------- middle rets ---------------- + // ret could be swapped during sendData + ret1 = ret; + // send ok / fail + n = sendData(file_des,&ret1,sizeof(ret),INT32); + // send return argument + if (ret==FAIL) { + n += sendData(file_des,mess,sizeof(mess),OTHER); + cprintf(RED,"Failure: Breaking out of program receiving\n"); + } + //---------------- middle rets ---------------- + + if(ret != FAIL){ + //print progress + printf("Writing to Flash:%d%%\r",(int) (((double)(totalsize-filesize)/totalsize)*100) ); + fflush(stdout); + } + } + + printf("\n"); + + //closing file pointer to flash and informing FPGA + if(stopWritingFPGAprogram(fp) == FAIL){ + ret=FAIL; + sprintf(mess,"Could not write to flash. Error at end.\n"); + cprintf(RED,"%s",mess); + } + + //free resources + if(fpgasrc != NULL) + free(fpgasrc); + if(fp!=NULL) + fclose(fp); +#ifdef VERY_VERBOSE + printf("Done with program receiving command\n"); +#endif + } +#endif + if (ret==OK) + ret=FORCE_UPDATE; +#endif + + // ret could be swapped during sendData + ret1 = ret; + // send ok / fail + n = sendData(file_des,&ret1,sizeof(ret),INT32); + // send return argument + if (ret==FAIL) { + n += sendData(file_des,mess,sizeof(mess),OTHER); + } + + // return ok / fail + return ret; +} + + + + + +int reset_fpga(int file_des) { + int ret=OK,ret1=OK; + int n=0; + sprintf(mess,"Reset FPGA unsuccessful\n"); + +#ifndef JUNGFRAUD + //to receive any arguments + while (n > 0) + n = receiveData(file_des,mess,MAX_STR_LENGTH,OTHER); + ret = FAIL; + sprintf(mess,"Function (Start Readout) is not implemented for this detector\n"); + cprintf(RED, "%s", mess); +#else + + // execute action + if (differentClients && lockStatus) { + ret = FAIL; + sprintf(mess,"Detector locked by %s\n",lastClientIP); + cprintf(RED, "Warning: %s", mess); + } +#ifdef SLS_DETECTOR_FUNCTION_LIST + else { + initControlServer(); + ret = FORCE_UPDATE; + } +#endif +#endif + + // ret could be swapped during sendData + ret1 = ret; + // send ok / fail + n = sendData(file_des,&ret1,sizeof(ret),INT32); + // send return argument + if (ret==FAIL) { + n += sendData(file_des,mess,sizeof(mess),OTHER); + } + + // return ok / fail + return ret; +} + + + +int power_chip(int file_des) { + int ret=OK,ret1=OK; + int n=0; + int retval=-1; + sprintf(mess,"power chip failed\n"); + +#ifndef JUNGFRAUD + //to receive any arguments + while (n > 0) + n = receiveData(file_des,mess,MAX_STR_LENGTH,OTHER); + ret = FAIL; + sprintf(mess,"Function (Power Chip) is not implemented for this detector\n"); + cprintf(RED, "%s", mess); +#else + + // receive arguments + int arg=-1; + n = receiveData(file_des,&arg,sizeof(arg),INT32); + if (n < 0) return printSocketReadError(); + + // execute action + if (differentClients && lockStatus && arg!=-1) { + ret = FAIL; + sprintf(mess,"Detector locked by %s\n",lastClientIP); + cprintf(RED, "Warning: %s", mess); + } +#ifdef SLS_DETECTOR_FUNCTION_LIST + else { +#ifdef VERBOSE + printf("Power chip to %d\n", arg); +#endif + retval=powerChip(arg); + +#ifdef VERBOSE + printf("Chip powered: %d\n",retval); +#endif + if (retval==arg || arg<0) { + ret=OK; + } else { + ret=FAIL; + sprintf(mess,"Powering chip failed, wrote %d but read %d\n", arg, retval); + cprintf(RED, "Warning: %s", mess); + } + } +#endif + if (ret==OK && differentClients) + ret=FORCE_UPDATE; +#endif + + // ret could be swapped during sendData + ret1 = ret; + // send ok / fail + n = sendData(file_des,&ret1,sizeof(ret),INT32); + // send return argument + if (ret==FAIL) { + n += sendData(file_des,mess,sizeof(mess),OTHER); + } else + n += sendData(file_des,&retval,sizeof(retval),INT32); + + // return ok / fail + return ret; +} + + + + +int set_activate(int file_des) { + int ret=OK,ret1=OK; + int n=0; + int retval=-1; + sprintf(mess,"Activate/Deactivate failed\n"); + +#ifndef EIGERD + //to receive any arguments + while (n > 0) + n = receiveData(file_des,mess,MAX_STR_LENGTH,OTHER); + ret=FAIL; + sprintf(mess,"Function (Set Activate) is not implemented for this detector\n"); + cprintf(RED, "Warning: %s", mess); +#else + + // receive arguments + int arg=-1; + n = receiveData(file_des,&arg,sizeof(arg),INT32); + if (n < 0) return printSocketReadError(); + + // execute action + if (differentClients && lockStatus && arg!=-1) { + ret = FAIL; + sprintf(mess,"Detector locked by %s\n",lastClientIP); + cprintf(RED, "Warning: %s", mess); + } +#ifdef SLS_DETECTOR_FUNCTION_LIST + else { +#ifdef VERBOSE + printf("Setting activate mode of detector to %d\n",arg); +#endif + retval=activate(arg); + if ((retval!=arg) && (arg!=-1)) { + ret=FAIL; + sprintf(mess,"Could not set activate mode to %d, is set to %d\n",arg, retval); + cprintf(RED, "Warning: %s", mess); + } + } +#endif + if (ret==OK && differentClients) + ret=FORCE_UPDATE; +#endif + + // ret could be swapped during sendData + ret1 = ret; + // send ok / fail + n = sendData(file_des,&ret1,sizeof(ret),INT32); + // send return argument + if (ret==FAIL) { + n += sendData(file_des,mess,sizeof(mess),OTHER); + } else + n += sendData(file_des,&retval,sizeof(retval),INT32); + + // return ok / fail + return ret; +} + + + + +int prepare_acquisition(int file_des) { + int ret=OK,ret1=OK; + int n=0; + strcpy(mess,"prepare acquisition failed\n"); + +#if !defined(GOTTHARDD) && !defined(EIGERD) + //to receive any arguments + while (n > 0) + n = receiveData(file_des,mess,MAX_STR_LENGTH,OTHER); + ret = FAIL; + sprintf(mess,"Function (Prepare Acquisition) is not implemented for this detector\n"); + cprintf(RED, "Warning: %s", mess); +#else + + // execute action + if (differentClients && lockStatus) { + ret = FAIL; + sprintf(mess,"Detector locked by %s\n",lastClientIP); + cprintf(RED, "Warning: %s", mess); + } +#ifdef SLS_DETECTOR_FUNCTION_LIST + else { + ret = prepareAcquisition(); + if (ret == FAIL) + cprintf(RED, "Warning: %s", mess); + } +#endif + if(ret==OK && differentClients) + ret=FORCE_UPDATE; +#endif + + // ret could be swapped during sendData + ret1 = ret; + // send ok / fail + n = sendData(file_des,&ret1,sizeof(ret),INT32); + // send return argument + if (ret==FAIL) { + n += sendData(file_des,mess,sizeof(mess),OTHER); + } + + // return ok / fail + return ret; +} + + +int cleanup_acquisition(int file_des) { + int ret=OK,ret1=OK; + int n=0; + strcpy(mess,"prepare acquisition failed\n"); + +#ifndef GOTTHARDD + //to receive any arguments + while (n > 0) + n = receiveData(file_des,mess,MAX_STR_LENGTH,OTHER); + ret = FAIL; + sprintf(mess,"Function (Cleanup Acquisition) is not implemented for this detector\n"); + cprintf(RED, "Warning: %s", mess); +#else + + // execute action + if (differentClients && lockStatus) { + ret = FAIL; + sprintf(mess,"Detector locked by %s\n",lastClientIP); + cprintf(RED, "Warning: %s", mess); + } +#ifdef SLS_DETECTOR_FUNCTION_LIST + else {//to be implemented when used here + ret = FAIL; + sprintf(mess,"Function (Cleanup Acquisition) is not implemented for this detector\n"); + cprintf(RED, "Warning: %s", mess); + } +#endif + if(ret==OK && differentClients) + ret=FORCE_UPDATE; +#endif + + // ret could be swapped during sendData + ret1 = ret; + // send ok / fail + n = sendData(file_des,&ret1,sizeof(ret),INT32); + // send return argument + if (ret==FAIL) { + n += sendData(file_des,mess,sizeof(mess),OTHER); + } + + // return ok / fail + return ret; +} + + diff --git a/slsDetectorSoftware/slsDetectorServer/slsDetectorServer_funcs.h b/slsDetectorSoftware/slsDetectorServer/slsDetectorServer_funcs.h index 5eebc1050..68cba7e0c 100755 --- a/slsDetectorSoftware/slsDetectorServer/slsDetectorServer_funcs.h +++ b/slsDetectorSoftware/slsDetectorServer/slsDetectorServer_funcs.h @@ -1,37 +1,21 @@ #ifndef SERVER_FUNCS_H #define SERVER_FUNCS_H -#include "sls_detector_defs.h" -#include "slsDetectorServer_defs.h" - +#include "sls_receiver_defs.h" #include - - - - -//basic server functions -void checkFirmwareCompatibility(); -int init_detector(int); +// initialization functions +int printSocketReadError(); +void basictests(); +void init_detector(int); int decode_function(int); -int function_table(); -//int swap_int32(int val); -//int64_t swap_int64(int64_t val); +const char* getFunctionName(enum detFuncs func); +void function_table(); int M_nofunc(int); -int exit_server(int); + +// functions called by client int exec_command(int); - -//advnaced server functions -int lock_server(int); -int get_last_client_ip(int); -int set_port(int); -int send_update(int); -int update_client(int); -int set_master(int); -int set_synchronization(int); - -//detector specific functions -//F_GET_ERROR +int get_error(int); int get_detector_type(int); int set_number_of_modules(int); int get_max_number_of_modules(int); @@ -39,24 +23,24 @@ int set_external_signal_flag(int); int set_external_communication_mode(int); int get_id(int); int digital_test(int); -//F_ANALOG_TEST -//F_ENABLE_ANALOG_OUT -//F_CALIBRATION_PULSE +int analog_test(int); +int enable_analog_out(int); +int calibration_pulse(int); int set_dac(int); int get_adc(int); int write_register(int); int read_register(int); -//F_WRITE_MEMORY -//F_READ_MEMORY +int write_memory(int); +int read_memory(int); int set_channel(int); int get_channel(int); -//F_SET_ALL_CHANNELS +int set_all_channels(int); int set_chip(int); int get_chip(int); -//F_SET_ALL_CHIPS +int set_all_chips(int); int set_module(int); int get_module(int); -//F_SET_ALL_MODULES +int set_all_modules(int); int set_settings(int); int get_threshold_energy(int); int set_threshold_energy(int); @@ -74,22 +58,36 @@ int set_readout_flags(int); int set_roi(int); int set_speed(int); int execute_trimming(int); +int exit_server(int); +int lock_server(int); +int get_last_client_ip(int); +int set_port(int); +int update_client(int); +int send_update(int); int configure_mac(int); int load_image(int); +int set_master(int); +int set_synchronization(int); int read_counter_block(int); int reset_counter_block(int); -int start_receiver(int); -int stop_receiver(int); int calibrate_pedestal(int); int enable_ten_giga(int); int set_all_trimbits(int); +int set_ctb_pattern(int); +int write_adc_register(int); int set_counter_bit(int); int pulse_pixel(int); int pulse_pixel_and_move(int); int pulse_chip(int); int set_rate_correct(int); int get_rate_correct(int); -int set_activate(int); int set_network_parameter(int); +int program_fpga(int); +int reset_fpga(int); +int power_chip(int); +int set_activate(int); +int prepare_acquisition(int); +int cleanup_acquisition(int); + #endif diff --git a/slsDetectorSoftware/threadFiles/Makefile b/slsDetectorSoftware/threadFiles/Makefile index 19b5b40e4..a1eb27d29 100644 --- a/slsDetectorSoftware/threadFiles/Makefile +++ b/slsDetectorSoftware/threadFiles/Makefile @@ -2,20 +2,20 @@ OBJPATH=bin/obj EXAMPLEPATH=bin/example all: - g++ CondVar.cpp -lpthread -c -g -o $(OBJPATH)/CondVar.o - g++ Mutex.cpp -lpthread -c -g -o $(OBJPATH)/Mutex.o - #g++ Task.cpp -lpthread -c -g -o $(OBJPATH)/Task.o - g++ ThreadPool.cpp -lpthread -c -g -o $(OBJPATH)/ThreadPool.o - g++ Multi.cpp -lpthread -c -g -o $(OBJPATH)/Multi.o - #g++ $(OBJPATH)/CondVar.o $(OBJPATH)/Mutex.o $(OBJPATH)/Task.o $(OBJPATH)/ThreadPool.o threadpool_test.cpp Single.cpp Multi.cpp -lpthread -I . -g -o $(EXAMPLEPATH)threadpool_test - g++ $(OBJPATH)/CondVar.o $(OBJPATH)/Mutex.o $(OBJPATH)/ThreadPool.o threadpool_test.cpp Single.cpp Multi.cpp -lpthread -I . -g -o $(EXAMPLEPATH)threadpool_test + g++ CondVar.cpp -pthread -c -g -o $(OBJPATH)/CondVar.o + g++ Mutex.cpp -pthread -c -g -o $(OBJPATH)/Mutex.o + #g++ Task.cpp -pthread -c -g -o $(OBJPATH)/Task.o + g++ ThreadPool.cpp -pthread -c -g -o $(OBJPATH)/ThreadPool.o + g++ Multi.cpp -pthread -c -g -o $(OBJPATH)/Multi.o + #g++ $(OBJPATH)/CondVar.o $(OBJPATH)/Mutex.o $(OBJPATH)/Task.o $(OBJPATH)/ThreadPool.o threadpool_test.cpp Single.cpp Multi.cpp -pthread -I . -g -o $(EXAMPLEPATH)threadpool_test + g++ $(OBJPATH)/CondVar.o $(OBJPATH)/Mutex.o $(OBJPATH)/ThreadPool.o threadpool_test.cpp Single.cpp Multi.cpp -pthread -I . -g -o $(EXAMPLEPATH)threadpool_test #all: -# g++ threadpool.cpp -lpthread -fpic -c -o bin/obj/threadpool.o -# g++ -L./bin bin/obj/threadpool.o -lpthread threadpool_test.cpp -o bin/example/threadpool_test +# g++ threadpool.cpp -pthread -fpic -c -o bin/obj/threadpool.o +# g++ -L./bin bin/obj/threadpool.o -pthread threadpool_test.cpp -o bin/example/threadpool_test #threadpool: -# g++ threadpool.cpp -lpthread -fpic -c -o bin/obj/threadpool.o +# g++ threadpool.cpp -pthread -fpic -c -o bin/obj/threadpool.o # g++ -shared -fPIC bin/obj/threadpool.o -o bin/lib/libthreadpool.so #example: # g++ -L./bin/lib -lthreadpool threadpool_test.cpp -o threadpool_test diff --git a/slsDetectorSoftware/threadFiles/Task.h b/slsDetectorSoftware/threadFiles/Task.h index 785298d46..e90deb9c2 100644 --- a/slsDetectorSoftware/threadFiles/Task.h +++ b/slsDetectorSoftware/threadFiles/Task.h @@ -24,8 +24,8 @@ public: ~func00_t() {} void operator()() const {((m_ptr->*m_fn)());} private: - _Class* m_ptr; _Ret (_Class::*m_fn)(); + _Class* m_ptr; }; template @@ -36,8 +36,8 @@ public: ~func0_t() {} void operator()() const {*m_store = ((m_ptr->*m_fn)());} private: - _Class* m_ptr; _Ret (_Class::*m_fn)(); + _Class* m_ptr; _Store* m_store; }; @@ -49,8 +49,8 @@ public: ~func1_t() {} void operator()() const {*m_store = ((m_ptr->*m_fn)(m_arg1));} private: - _Class* m_ptr; _Ret (_Class::*m_fn)(_Arg1); + _Class* m_ptr; _Arg1 m_arg1; _Store* m_store; }; @@ -63,8 +63,8 @@ public: ~func2_t() {} void operator()() const {*m_store = ((m_ptr->*m_fn)(m_arg1,m_arg2));} private: - _Class* m_ptr; _Ret (_Class::*m_fn)(_Arg1,_Arg2); + _Class* m_ptr; _Arg1 m_arg1; _Arg2 m_arg2; _Store* m_store; @@ -78,8 +78,8 @@ public: ~func3_t() {} void operator()() const {*m_store = ((m_ptr->*m_fn)(m_arg1,m_arg2,m_arg3));} private: - _Class* m_ptr; _Ret (_Class::*m_fn)(_Arg1,_Arg2,_Arg3); + _Class* m_ptr; _Arg1 m_arg1; _Arg2 m_arg2; _Arg3 m_arg3; @@ -94,8 +94,8 @@ public: ~func4_t() {} void operator()() const {*m_store = ((m_ptr->*m_fn)(m_arg1,m_arg2,m_arg3,m_arg4));} private: - _Class* m_ptr; _Ret (_Class::*m_fn)(_Arg1,_Arg2,_Arg3,_Arg4); + _Class* m_ptr; _Arg1 m_arg1; _Arg2 m_arg2; _Arg3 m_arg3; @@ -106,29 +106,31 @@ private: class Task: public virtual slsDetectorDefs{ public: /* Return: int, Param: int */ - Task(func1_t * t): m1(t),m2(0),m3(0),m4(0),m5(0),m6(0),m7(0),m8(0),m9(0),m10(0),m11(0),m12(0){}; + Task(func1_t * t): m1(t),m2(0),m3(0),m4(0),m5(0),m6(0),m7(0),m8(0),m9(0),m10(0),m11(0),m12(0),m13(0){}; /* Return: int, Param: string,int */ - Task(func2_t * t): m1(0),m2(t),m3(0),m4(0),m5(0),m6(0),m7(0),m8(0),m9(0),m10(0),m11(0),m12(0){}; + Task(func2_t * t): m1(0),m2(t),m3(0),m4(0),m5(0),m6(0),m7(0),m8(0),m9(0),m10(0),m11(0),m12(0),m13(0){}; /* Return: string, Param: string */ - Task(func1_t * t): m1(0),m2(0),m3(t),m4(0),m5(0),m6(0),m7(0),m8(0),m9(0),m10(0),m11(0),m12(0){}; + Task(func1_t * t): m1(0),m2(0),m3(t),m4(0),m5(0),m6(0),m7(0),m8(0),m9(0),m10(0),m11(0),m12(0),m13(0){}; /* Return: char*, Param: char* */ - Task(func1_t * t): m1(0),m2(0),m3(0),m4(t),m5(0),m6(0),m7(0),m8(0),m9(0),m10(0),m11(0),m12(0){}; + Task(func1_t * t): m1(0),m2(0),m3(0),m4(t),m5(0),m6(0),m7(0),m8(0),m9(0),m10(0),m11(0),m12(0),m13(0){}; /* Return: detectorSettings, Param: int */ - Task(func1_t * t): m1(0),m2(0),m3(0),m4(0),m5(t),m6(0),m7(0),m8(0),m9(0),m10(0),m11(0),m12(0){}; + Task(func1_t * t): m1(0),m2(0),m3(0),m4(0),m5(t),m6(0),m7(0),m8(0),m9(0),m10(0),m11(0),m12(0),m13(0){}; /* Return: detectorSettings, Param: detectorSettings,int */ - Task(func2_t * t): m1(0),m2(0),m3(0),m4(0),m5(0),m6(t),m7(0),m8(0),m9(0),m10(0),m11(0),m12(0){}; + Task(func2_t * t): m1(0),m2(0),m3(0),m4(0),m5(0),m6(t),m7(0),m8(0),m9(0),m10(0),m11(0),m12(0),m13(0){}; /* Return: int, Param: int,int */ - Task(func2_t * t): m1(0),m2(0),m3(0),m4(0),m5(0),m6(0),m7(t),m8(0),m9(0),m10(0),m11(0),m12(0){}; - /* Return: int, Param: int,int */ - Task(func3_t * t): m1(0),m2(0),m3(0),m4(0),m5(0),m6(0),m7(0),m8(t),m9(0),m10(0),m11(0),m12(0){}; + Task(func2_t * t): m1(0),m2(0),m3(0),m4(0),m5(0),m6(0),m7(t),m8(0),m9(0),m10(0),m11(0),m12(0),m13(0){}; + /* Return: int, Param: int,int,int */ + Task(func3_t * t): m1(0),m2(0),m3(0),m4(0),m5(0),m6(0),m7(0),m8(t),m9(0),m10(0),m11(0),m12(0),m13(0){}; /* Return: int, Param: trimMode,int,int,int */ - Task(func4_t * t): m1(0),m2(0),m3(0),m4(0),m5(0),m6(0),m7(0),m8(0),m9(t),m10(0),m11(0),m12(0){}; + Task(func4_t * t): m1(0),m2(0),m3(0),m4(0),m5(0),m6(0),m7(0),m8(0),m9(t),m10(0),m11(0),m12(0),m13(0){}; /* Return: int, Param: none */ - Task(func0_t * t): m1(0),m2(0),m3(0),m4(0),m5(0),m6(0),m7(0),m8(0),m9(0),m10(t),m11(0),m12(0){}; - /* Return: char*, Param: networkParameter,string,string */ - Task(func2_t * t): m1(0),m2(0),m3(0),m4(0),m5(0),m6(0),m7(0),m8(0),m9(0),m10(0),m11(t),m12(0){}; + Task(func0_t * t): m1(0),m2(0),m3(0),m4(0),m5(0),m6(0),m7(0),m8(0),m9(0),m10(t),m11(0),m12(0),m13(0){}; + /* Return: char*, Param: networkParameter,string */ + Task(func2_t * t): m1(0),m2(0),m3(0),m4(0),m5(0),m6(0),m7(0),m8(0),m9(0),m10(0),m11(t),m12(0),m13(0){}; /* Return: void, Param: none */ - Task(func00_t * t): m1(0),m2(0),m3(0),m4(0),m5(0),m6(0),m7(0),m8(0),m9(0),m10(0),m11(0),m12(t){}; + Task(func00_t * t): m1(0),m2(0),m3(0),m4(0),m5(0),m6(0),m7(0),m8(0),m9(0),m10(0),m11(0),m12(t),m13(0){}; + /* Return: int, Param: int,int,detectorSettings */ + Task(func3_t * t): m1(0),m2(0),m3(0),m4(0),m5(0),m6(0),m7(0),m8(0),m9(0),m10(0),m11(0),m12(0),m13(t){}; @@ -147,6 +149,7 @@ public: else if(m10) (*m10)(); else if(m11) (*m11)(); else if(m12) (*m12)(); + else if(m13) (*m13)(); } private: @@ -164,16 +167,18 @@ private: func2_t * m6; /* Return: int, Param: int,int */ func2_t * m7; - /* Return: int, Param: int,int */ + /* Return: int, Param: int,int,int */ func3_t * m8; /* Return: int, Param: trimMode,int,int,int */ func4_t * m9; /* Return: int, Param: int */ func0_t * m10; - /* Return: char*, Param: networkParameter,string,string */ + /* Return: char*, Param: networkParameter,string */ func2_t * m11; /* Return: void, Param: none */ func00_t * m12; + /* Return: int, Param: int,int,detectorSettings */ + func3_t * m13; }; diff --git a/slsDetectorSoftware/threadFiles/ThreadPool.cpp b/slsDetectorSoftware/threadFiles/ThreadPool.cpp index 347a15e31..cb2a00faf 100644 --- a/slsDetectorSoftware/threadFiles/ThreadPool.cpp +++ b/slsDetectorSoftware/threadFiles/ThreadPool.cpp @@ -67,12 +67,13 @@ int ThreadPool::destroy_threadpool(){ /*cout << "Broadcasting STOP signal to all threads..." << endl;*/ m_task_cond_var.broadcast(); // notify all threads we are shttung down - int ret = -1; +// int ret = -1; for (int i = 0; i < m_pool_size; i++) { void* result; sem_post(&semStart); sem_post(&semDone); - ret = pthread_join(m_threads[i], &result); + //ret = + pthread_join(m_threads[i], &result); /*cout << "pthread_join() returned " << ret << ": " << strerror(errno) << endl;*/ m_task_cond_var.broadcast(); // try waking up a bunch of threads that are still waiting } @@ -85,7 +86,8 @@ int ThreadPool::destroy_threadpool(){ } void* ThreadPool::execute_thread(){ - int ithread = current_thread_number; +//for debugging seting ithread value +// int ithread = current_thread_number; thread_started = true; Task* task = NULL; m_tasks_loaded = false; @@ -125,6 +127,9 @@ void* ThreadPool::execute_thread(){ (*task)(); // could also do task->run(arg); /*cout << ithread <<" Done executing thread " << pthread_self() << endl;*/ + delete task; + /*cout << ithread << " task deleted" << endl;*/ + m_task_mutex.lock(); number_of_ongoing_tasks--; m_task_mutex.unlock(); @@ -136,9 +141,10 @@ void* ThreadPool::execute_thread(){ m_tasks_loaded = false; } //if(zmqthreadpool) cout<<"***"< m_tasks; volatile int m_pool_state; - bool m_tasks_loaded; - bool thread_started; + volatile bool m_tasks_loaded; + volatile bool thread_started; int current_thread_number; //volatile uint64_t tasks_done_mask;