diff --git a/slsDetectorSoftware/CMakeLists.txt b/slsDetectorSoftware/CMakeLists.txt index 7d9fa2725..69f395cc9 100644 --- a/slsDetectorSoftware/CMakeLists.txt +++ b/slsDetectorSoftware/CMakeLists.txt @@ -35,6 +35,15 @@ usersFunctions ../slsReceiverSoftware/MySocketTCP ) +add_definitions( + -DDACS_INT +) + +add_library(zmq STATIC IMPORTED ) + +set_target_properties(zmq PROPERTIES + IMPORTED_LOCATION ${CMAKE_CURRENT_SOURCE_DIR}/../slsReceiverSoftware/include/libzmq.a +) add_library(slsDetectorStatic STATIC ${SOURCES} diff --git a/slsDetectorSoftware/Makefile b/slsDetectorSoftware/Makefile index 17422ee95..eb3708d50 100644 --- a/slsDetectorSoftware/Makefile +++ b/slsDetectorSoftware/Makefile @@ -18,6 +18,9 @@ INCLUDES?= -IcommonFiles -IslsDetector -I../slsReceiverSoftware/MySocketTCP -Ius SRC_CLNT=slsDetectorAnalysis/fileIO.cpp usersFunctions/usersFunctions.cpp slsDetector/slsDetectorUtils.cpp slsDetector/slsDetectorCommand.cpp slsDetectorAnalysis/angularConversion.cpp slsDetectorAnalysis/angularConversionStatic.cpp slsDetectorAnalysis/energyConversion.cpp slsDetector/slsDetectorActions.cpp slsDetectorAnalysis/postProcessing.cpp slsDetector/slsDetector.cpp multiSlsDetector/multiSlsDetector.cpp slsDetectorAnalysis/postProcessingFuncs.cpp slsReceiverInterface/receiverInterface.cpp slsDetector/slsDetectorUsers.cpp threadFiles/CondVar.cpp threadFiles/Mutex.cpp threadFiles/ThreadPool.cpp #../slsReceiverSoftware/MySocketTCP/MySocketTCP.cpp +LIBZMQDIR = ../slsReceiverSoftware/include +LIBZMQ = -L$(LIBZMQDIR) -Wl,-rpath=$(LIBZMQDIR) -lzmq + $(info ) $(info #######################################) $(info # Compiling slsDetectorSoftware #) @@ -66,14 +69,14 @@ gotthardVirtualServer: $(SRC_MYTHEN_SVC) %.o : %.cpp %.h Makefile - $(CXX) -o $@ -c $< $(INCLUDES) $(DFLAGS) -fPIC $(EPICSFLAGS) -lpthread #$(FLAGS) + $(CXX) -o $@ -c $< $(INCLUDES) $(DFLAGS) -fPIC $(EPICSFLAGS) -lpthread -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 + $(CXX) -shared -Wl,-soname,libSlsDetector.so -o libSlsDetector.so $(OBJS) -lc $(INCLUDES) $(DFLAGS) $(FLAGS) $(EPICSFLAGS) -L/usr/lib64 -lpthread -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 535d9acf5..48aae9d30 100755 --- a/slsDetectorSoftware/commonFiles/communication_funcs.c +++ b/slsDetectorSoftware/commonFiles/communication_funcs.c @@ -137,7 +137,7 @@ int acceptConnection(int socketDescriptor) { //socklen_t address_length; - size_t address_length=sizeof(struct sockaddr_in); + socklen_t address_length=sizeof(struct sockaddr_in); if (socketDescriptor<0) return -1; diff --git a/slsDetectorSoftware/commonFiles/error_defs.h b/slsDetectorSoftware/commonFiles/error_defs.h index 89798faef..c010f26ba 100644 --- a/slsDetectorSoftware/commonFiles/error_defs.h +++ b/slsDetectorSoftware/commonFiles/error_defs.h @@ -10,16 +10,22 @@ #include +#include using namespace std; #include "sls_detector_defs.h" - +#include +#include /** Error flags */ +/*Assumption: Only upto 63 detectors */ #define CRITICAL_ERROR_MASK 0xFFFFFFFF +#define MULTI_DETECTORS_NOT_ADDED 0x8000000000000000ULL + + #define CANNOT_CONNECT_TO_DETECTOR 0x8000000000000000ULL #define CANNOT_CONNECT_TO_RECEIVER 0x4000000000000000ULL #define COULDNOT_SET_CONTROL_PORT 0x2000000000000000ULL @@ -59,9 +65,13 @@ using namespace std; #define COULD_NOT_PULSE_CHIP 0x0000000000100000ULL #define COULD_NOT_SET_RATE_CORRECTION 0x0000000000200000ULL #define DETECTOR_NETWORK_PARAMETER 0x0000000000400000ULL -#define RATE_CORRECTION_NOT_32BIT 0x0000000000800000ULL +#define RATE_CORRECTION_NOT_32or16BIT 0x0000000000800000ULL #define RATE_CORRECTION_NO_TAU_PROVIDED 0x0000000001000000ULL - +#define PROGRAMMING_ERROR 0x0000000002000000ULL +#define RECEIVER_ACTIVATE 0x0000000004000000ULL +#define DATA_STREAMING 0x0000000008000000ULL +#define RESET_ERROR 0x0000000010000000ULL +#define POWER_CHIP 0x0000000020000000ULL // 0x00000000FFFFFFFFULL /** @short class returning all error messages for error mask */ class errorDefs { @@ -70,7 +80,9 @@ class errorDefs { public: /** Constructor */ - errorDefs():errorMask(0){}; + errorDefs():errorMask(0){ + strcpy(notAddedList,""); + }; /** Gets the error message * param errorMask error mask @@ -192,15 +204,26 @@ public: if(slsErrorMask&DETECTOR_NETWORK_PARAMETER) retval.append("Could not set/get detector network parameter\n"); - if(slsErrorMask&RATE_CORRECTION_NOT_32BIT) - retval.append("Rate correction Deactivated, must be in 32 bit mode\n"); + if(slsErrorMask&RATE_CORRECTION_NOT_32or16BIT) + retval.append("Rate correction Deactivated, must be in 32 or 16 bit mode\n"); if(slsErrorMask&RATE_CORRECTION_NO_TAU_PROVIDED) retval.append("Rate correction Deactivated. No default tau provided in file\n"); + if(slsErrorMask&PROGRAMMING_ERROR) + retval.append("Could not program FPGA\n"); + if(slsErrorMask&RECEIVER_ACTIVATE) + retval.append("Could not activate/deactivate receiver\n"); + if(slsErrorMask&DATA_STREAMING) + retval.append("Could not set/reset Data Streaming\n"); + if(slsErrorMask&RESET_ERROR) + retval.append("Could not reset the FPGA\n"); + + if(slsErrorMask&POWER_CHIP) + retval.append("Could not power on/off/get the chip\n"); //------------------------------------------------------ length of message @@ -224,12 +247,31 @@ public: */ int64_t clearErrorMask(){errorMask=0;return errorMask;}; + /** Gets the not added detector list + /returns list + */ + char* getNotAddedList(){return notAddedList;}; + + /** Append the detector to not added detector list + * @param name append to the list + /returns list + */ + void appendNotAddedList(const char* name){strcat(notAddedList,name);strcat(notAddedList,"+");}; + + /** Clears not added detector list + /returns error mask + */ + void clearNotAddedList(){strcpy(notAddedList,"");}; + protected: /** Error Mask */ int64_t errorMask; + /** Detectors Not added List */ + char notAddedList[MAX_STR_LENGTH]; + }; #endif /* ERROR_DEFS_H_ */ diff --git a/slsDetectorSoftware/commonFiles/sls_detector_defs.h b/slsDetectorSoftware/commonFiles/sls_detector_defs.h index d5996d12d..e2f10656f 100755 --- a/slsDetectorSoftware/commonFiles/sls_detector_defs.h +++ b/slsDetectorSoftware/commonFiles/sls_detector_defs.h @@ -25,6 +25,9 @@ /** maximum rois */ #define MAX_ROIS 100 +/** maximum unit size of program sent to detector */ +#define MAX_FPGAPROGRAMSIZE (2 * 1024 *1024) + typedef char mystring[MAX_STR_LENGTH]; typedef double mysteps[MAX_SCAN_STEPS]; @@ -362,6 +365,8 @@ enum dacIndex { TEMPERATURE_DCDC, /**< temperature sensor (close to DCDC) */ TEMPERATURE_SODL, /**< temperature sensor (close to SODL) */ TEMPERATURE_SODR, /**< temperature sensor (close to SODR) */ + TEMPERATURE_FPGA2, /**< temperature sensor (fpga2 (eiger:febl) */ + TEMPERATURE_FPGA3, /**< temperature sensor (fpga3 (eiger:febr) */ V_POWER_A = 100, /**new chiptest board */ V_POWER_B = 101, /**new chiptest board */ V_POWER_C = 102, /**new chiptest board */ @@ -434,7 +439,10 @@ enum speedVariable { OVERSAMPLING, /**< oversampling for analog detectors */ ADC_CLOCK, /**< adc clock divider */ ADC_PHASE, /**< adc clock phase */ - ADC_PIPELINE /**< adc pipeline */ + ADC_PIPELINE, /**< adc pipeline */ + DBIT_CLOCK, /**< adc clock divider */ + DBIT_PHASE, /**< adc clock phase */ + DBIT_PIPELINE /**< adc pipeline */ }; diff --git a/slsDetectorSoftware/commonFiles/sls_detector_funcs.h b/slsDetectorSoftware/commonFiles/sls_detector_funcs.h index 6c0c88c94..c8e261617 100644 --- a/slsDetectorSoftware/commonFiles/sls_detector_funcs.h +++ b/slsDetectorSoftware/commonFiles/sls_detector_funcs.h @@ -103,9 +103,12 @@ enum { F_SET_RATE_CORRECT, /** < set/reset rate correction tau */ F_GET_RATE_CORRECT, /** < get rate correction tau */ - F_ACTIVATE, /** < activate/deactivate readout */ + F_SET_NETWORK_PARAMETER, /**< set network parameters such as transmission delay, flow control */ + F_PROGRAM_FPGA, /**< program FPGA */ + F_RESET_FPGA, /**< reset FPGA */ + F_POWER_CHIP, /**< power chip */ /* Always append functions hereafter!!! */ diff --git a/slsDetectorSoftware/eigerDetectorServer/Beb.c b/slsDetectorSoftware/eigerDetectorServer/Beb.c index d1bbcb947..a3025fea9 100644 --- a/slsDetectorSoftware/eigerDetectorServer/Beb.c +++ b/slsDetectorSoftware/eigerDetectorServer/Beb.c @@ -24,6 +24,7 @@ #include "Beb.h" +#define MAX(x, y) (((x) > (y)) ? (x) : (y)) struct BebInfo beb_infos[10]; @@ -46,6 +47,8 @@ short Beb_bit_mode; int BEB_MMAP_SIZE = 0x1000; + int Beb_activated = 1; + void BebInfo_BebInfo(struct BebInfo* bebInfo, unsigned int beb_num){ @@ -170,8 +173,117 @@ void Beb_GetModuleCopnfiguration(int* master, int* top){ } } + + +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; + + switch(tengiga){ + case 0: + addr_l_framepktcounter2 = ONE_GIGA_LEFT_PKT_SEND_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_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_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_txndelaycounter = TEN_GIGA_RIGHT_TXN_DELAY_COUNTER; + addr_r_framedelaycounter = TEN_GIGA_RIGHT_FRAME_DELAY_COUNTER; + break; + } + + + //open file pointer + int fd = Beb_open(&csp0base,XPAR_COUNTER_BASEADDR); + if(fd < 0){ + cprintf(BG_RED,"Delay read counter fail\n"); + return; + }else{ + //read data first time + l_framepktcounter2 = Beb_Read32(csp0base, addr_l_framepktcounter2); + 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_txndelaycounter = Beb_Read32(csp0base, addr_r_txndelaycounter); + r_framedelaycounter = Beb_Read32(csp0base, addr_r_framedelaycounter); +//#ifdef VERBOSE + printf("\nLeft\n" + "Framepacketcounter: %d\n" + "Txndelaycounter:%d\n" + "Framedelaycounter:%d\n" + "\nRight\n" + "Framepacketcounter: %d\n" + "Txndelaycounter:%d\n" + "Framedelaycounter:%d\n\n", + l_framepktcounter2,l_txndelaycounter,l_framedelaycounter, + r_framepktcounter2,r_txndelaycounter,r_framedelaycounter); +//#endif + + //keep comparing with previous values + int maxtimer; + while(1){ + maxtimer = MAX(MAX(l_txndelaycounter,l_framedelaycounter),MAX(r_txndelaycounter,r_framedelaycounter)); + maxtimer /= 100; + printf("Will wait for %d us\n",maxtimer); + usleep(maxtimer); + + //read new values + l_framepktcounter2_new = Beb_Read32(csp0base, addr_l_framepktcounter2); + 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_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" + "Txndelaycounter:%d\n" + "Framedelaycounter:%d\n" + "\nRight\n" + "Framepacketcounter: %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); +//#endif + + if ((l_framepktcounter2 == l_framepktcounter2_new) && (r_framepktcounter2 == r_framepktcounter2_new)) + break; + + //update old values + l_framepktcounter2 = l_framepktcounter2_new; + l_txndelaycounter = l_txndelaycounter_new; + l_framedelaycounter = l_framedelaycounter_new; + r_framepktcounter2 = r_framepktcounter2_new; + r_txndelaycounter = r_txndelaycounter_new; + r_framedelaycounter = r_framedelaycounter_new; + + } + + printf("Detector has send all data\n"); + //close file pointer + Beb_close(fd,csp0base); + } +} + + + + /* do not work at the moment */ int Beb_SetMasterViaSoftware(){ + + if(!Beb_activated) + return 0; + //mapping new memory u_int32_t* csp0base=0; u_int32_t value = 0, ret = 1; @@ -200,6 +312,10 @@ int Beb_SetMasterViaSoftware(){ /* do not work at the moment */ int Beb_SetSlaveViaSoftware(){ + + if(!Beb_activated) + return 0; + //mapping new memory u_int32_t* csp0base=0; u_int32_t value = 0, ret = 1; @@ -268,11 +384,18 @@ int Beb_Activate(int enable){ if(fd > 0) Beb_close(fd,csp0base); + Beb_activated = ret; + return ret; } int Beb_SetNetworkParameter(enum detNetworkParameter mode, int val){ + + if(!Beb_activated) + return val; + + //mapping new memory u_int32_t* csp0base=0; u_int32_t valueread = 0; @@ -325,6 +448,10 @@ int Beb_SetNetworkParameter(enum detNetworkParameter mode, int val){ int Beb_ResetToHardwareSettings(){ + + if(!Beb_activated) + return 1; + //mapping new memory u_int32_t* csp0base=0; u_int32_t value = 0, ret = 1; @@ -396,6 +523,10 @@ u_int32_t Beb_GetFirmwareSoftwareAPIVersion(){ } void Beb_ResetFrameNumber(){ + + if(!Beb_activated) + return; + //mapping new memory to read master top module configuration u_int32_t* csp0base=0; //open file pointer @@ -446,7 +577,6 @@ int Beb_InitBebInfos(){//file name at some point bebInfoSize++; - //if(!Beb_ReadSetUpFromFile("/home/root/executables/setup_beb.txt")) return 0; /* //loop through file to fill vector. BebInfo* b = new BebInfo(26); @@ -477,52 +607,6 @@ int Beb_SetBebSrcHeaderInfos(unsigned int beb_number, int ten_gig, char* src_mac } -int Beb_ReadSetUpFromFile(char* file_name){ - char line[100]; - char str[100]; - - int i0,i1; - char mac0[50],mac1[50],ip0[50],ip1[0]; - FILE* fp = fopen(file_name, "r"); - if( fp == NULL ){ - perror("Error while opening the beb setup file.\n"); - return 0; - } - - printf("Setting up beb side of detector:\n"); - while ( fgets (line , 255 , fp) != NULL ){ - if(strlen(line)<=1) - continue; - sscanf (line, "%s", str); - if (str[0]=='#') - continue; - - if(!strcmp(str,"add_beb")){ - if( sscanf (line,"%s %d %d %s %s %s %s",str,&i0,&i1,mac0,ip0,mac1,ip1) < 7){ - printf("Error adding beb from %s.\n",file_name); - exit(0); - } - - printf ("Read: %s %d %d %s %s %s %s\n", str,i0,i1,mac0,ip0,mac1,ip1); - - if(Beb_GetBebInfoIndex(i0)){ - printf("Error adding beb from %s, beb number %d already added.\n",file_name,i0); - exit(0); - } - - struct BebInfo b0; - BebInfo_BebInfo(&b0,i0); - BebInfo_SetSerialAddress(&b0,i1); - BebInfo_SetHeaderInfo(&b0,0,mac0,ip0,42000+i0); - BebInfo_SetHeaderInfo(&b0,1,mac1,ip1,52000+i0); - beb_infos[bebInfoSize] = b0; - bebInfoSize++; - } - } - fclose(fp); - return 1; -} - int Beb_CheckSourceStuffBebInfo(){ @@ -552,6 +636,10 @@ unsigned int Beb_GetBebInfoIndex(unsigned int beb_numb){ int Beb_WriteTo(unsigned int index){ + + if(!Beb_activated) + return 1; + if(index>=bebInfoSize){ printf("WriteTo index error.\n"); return 0; @@ -575,35 +663,15 @@ void Beb_SwapDataFun(int little_endian, unsigned int n, unsigned int *d){ int Beb_SetByteOrder(){ -/* - Beb_send_data_raw[0] = 0x8fff0000; - if(Local_Write(ll_beb,4,Beb_send_data_raw)!=4) return 0; - - while((Local_Read(ll_beb,Beb_recv_buffer_size*4,Beb_recv_data_raw)/4)>0) printf("\t) Cleanning buffer ...\n"); - - if(bebInfoSize<2) return 0; - - Beb_send_ndata = 3; - Beb_send_data[0] = 0x000c0000; - Beb_send_data[1] = 0; - Beb_send_data[2] = 0; - Beb_WriteTo(0); - - //using little endian for data, big endian not fully tested, swap on 16 bit boundary. - Beb_send_ndata = 3; - Beb_send_data[0] = 0x000c0000; - Beb_send_data[1] = 1; - Beb_send_data[2] = 0; - Beb_SwapDataFun(0,2,&(Beb_send_data[1])); - Beb_WriteTo(0); - - printf("\tSetting Byte Order .............. ok\n"); -*/ return 1; } int Beb_SetUpUDPHeader(unsigned int beb_number, int ten_gig, unsigned int header_number, char* dst_mac, char* dst_ip, unsigned int dst_port){ + + if(!Beb_activated) + return 1; + u_int32_t bram_phy_addr; u_int32_t* csp0base=0; /*u_int32_t* bram_ptr = NULL;*/ @@ -809,7 +877,9 @@ int Beb_SendMultiReadRequest(unsigned int beb_number, unsigned int left_right, i cprintf(GREEN, "Beb_send_data[1] Swapped:%X\n",Beb_send_data[1]); #endif - if(!Beb_WriteTo(i)) return 0; + if(Beb_activated){ + if(!Beb_WriteTo(i)) return 0; + } return 1; } @@ -828,6 +898,9 @@ int Beb_SetUpTransferParameters(short the_bit_mode){ int Beb_StopAcquisition() { + if(!Beb_activated) + return 1; + u_int32_t* csp0base=0; volatile u_int32_t valuel,valuer; //open file pointer @@ -854,6 +927,10 @@ int Beb_StopAcquisition() } int Beb_RequestNImages(unsigned int beb_number, int ten_gig, unsigned int dst_number, unsigned int nimages, int test_just_send_out_packets_no_wait){ + + if(!Beb_activated) + return 1; + if(dst_number>64) return 0; unsigned int header_size = 4; //4*64 bits diff --git a/slsDetectorSoftware/eigerDetectorServer/Beb.h b/slsDetectorSoftware/eigerDetectorServer/Beb.h index b11e11815..9431701ea 100644 --- a/slsDetectorSoftware/eigerDetectorServer/Beb.h +++ b/slsDetectorSoftware/eigerDetectorServer/Beb.h @@ -41,12 +41,13 @@ struct BebInfo{ void Beb_ClearBebInfos(); int Beb_InitBebInfos(); - int Beb_ReadSetUpFromFile(char* file_name); int Beb_CheckSourceStuffBebInfo(); unsigned int Beb_GetBebInfoIndex(unsigned int beb_numb); void Beb_GetModuleCopnfiguration(int* master, int* top); + void Beb_EndofDataSend(int tengiga); + int Beb_SetMasterViaSoftware(); int Beb_SetSlaveViaSoftware(); int Beb_Activate(int enable); diff --git a/slsDetectorSoftware/eigerDetectorServer/FebControl.c b/slsDetectorSoftware/eigerDetectorServer/FebControl.c index a07d6b2fb..a5dd9ae83 100644 --- a/slsDetectorSoftware/eigerDetectorServer/FebControl.c +++ b/slsDetectorSoftware/eigerDetectorServer/FebControl.c @@ -50,7 +50,7 @@ int64_t Feb_Control_subframe_exposure_time_in_10nsec; double Feb_Control_exposure_period_in_sec; int64_t Feb_Control_RateTable_Tau_in_nsec = -1; -int64_t Feb_Control_RateTable_Subexptime_in_nsec = -1; +int64_t Feb_Control_RateTable_Period_in_nsec = -1; unsigned int Feb_Control_trimbit_size; unsigned int* Feb_Control_last_downloaded_trimbits; @@ -65,6 +65,9 @@ int Feb_control_master = 0; unsigned int Feb_Control_rate_correction_table[1024]; double Feb_Control_rate_meas[16384]; +double ratemax=-1; +int Feb_Control_activated = 1; + void Module_Module(struct Module* mod,unsigned int number, unsigned int address_top){ unsigned int i; @@ -152,6 +155,10 @@ int Module_GetBottomDACValue(struct Module* mod,unsigned int i) +void Feb_Control_activate(int activate){ + Feb_Control_activated = activate; +} + int Feb_Control_IsBottomModule(){ if(Module_BottomAddressIsValid(&modules[Feb_Control_current_index])) return 1; @@ -186,40 +193,10 @@ int Feb_Control_Init(int master, int top, int module_num){ Feb_Control_module_number = (module_num & 0xFF); int serial = !top; - - /* - //for Gemmas modules: if master, serial 0, else 1 - int serial = 1; - if(master) - serial = 0; - switch(Feb_Control_module_number){ - case 34: serial = 0; break; //martin half - case 26: serial = 0; break; //leo - - case 31: serial = 0; break; //martin - case 32: serial = 1; break; - case 24: serial = 2; break; - case 25: serial = 3; break; - - case 15: serial = 0; break; //dhanya - case 16: serial = 1; break; - case 30: serial = 2; break; - case 38: serial = 3; break; - - case 49: serial = 0; break; // Gemma - case 48: serial = 1; break; // Gemma - }*/ printf("serial: %d\n",serial); Feb_Control_current_index = 1; - /*for(i=1;i0) - sprintf(str,"%s",str); /*sprintf(str,"mod%d::%s",module_num,str);*/ - if(!Feb_Control_SetDAC(str,f0,1)) - cprintf(RED,"Error in string: %s",str); - - } - } - fclose(fp); - printf("Done reading set up file\n"); - return 1; -} int Feb_Control_CheckSetup(int master){ @@ -675,12 +467,14 @@ int Feb_Control_SendIDelays(unsigned int dst_num, int chip_lr, unsigned int chan printf(", tracks 0x%x to: %d, %d clks and %d units.\n",channels,(((15-delay_data_valid_nclks)<<6)|ndelay_units),delay_data_valid_nclks,ndelay_units); - if(!Feb_Interface_WriteRegister(dst_num,CHIP_DATA_OUT_DELAY_REG2, 1<<31 | delay_data_valid_nclks<<16 | ndelay_units,0,0) || //the 1<<31 time enables the setting of the data valid delays - !Feb_Interface_WriteRegister(dst_num,CHIP_DATA_OUT_DELAY_REG3,set_left_delay_channels,0,0) || - !Feb_Interface_WriteRegister(dst_num,CHIP_DATA_OUT_DELAY_REG4,set_right_delay_channels,0,0) || - !Feb_Interface_WriteRegister(dst_num,CHIP_DATA_OUT_DELAY_REG_CTRL,CHIP_DATA_OUT_DELAY_SET,1,1)){ - cprintf(RED,"Warning: could not SetChipDataInputDelays(...).\n"); - return 0; + if(Feb_Control_activated){ + if(!Feb_Interface_WriteRegister(dst_num,CHIP_DATA_OUT_DELAY_REG2, 1<<31 | delay_data_valid_nclks<<16 | ndelay_units,0,0) || //the 1<<31 time enables the setting of the data valid delays + !Feb_Interface_WriteRegister(dst_num,CHIP_DATA_OUT_DELAY_REG3,set_left_delay_channels,0,0) || + !Feb_Interface_WriteRegister(dst_num,CHIP_DATA_OUT_DELAY_REG4,set_right_delay_channels,0,0) || + !Feb_Interface_WriteRegister(dst_num,CHIP_DATA_OUT_DELAY_REG_CTRL,CHIP_DATA_OUT_DELAY_SET,1,1)){ + cprintf(RED,"Warning: could not SetChipDataInputDelays(...).\n"); + return 0; + } } return 1; @@ -738,9 +532,11 @@ int Feb_Control_SendHighVoltage(unsigned int dst_num,float* value){ } unsigned int r = 0x20000000 | (b&0xff); - if(!Feb_Interface_WriteRegister(dst_num,0,r,0,0)){ - cprintf(RED,"Warning: trouble setting high voltage for dst_num %d.\n",dst_num); - return 0; + if(Feb_Control_activated){ + if(!Feb_Interface_WriteRegister(dst_num,0,r,0,0)){ + cprintf(RED,"Warning: trouble setting high voltage for dst_num %d.\n",dst_num); + return 0; + } } *value = Feb_Control_DACToVoltage(b,nsteps,vmin,vmax); @@ -752,43 +548,15 @@ int Feb_Control_SendHighVoltage(unsigned int dst_num,float* value){ int Feb_Control_DecodeDACString(char* dac_str, unsigned int* module_index, int* top, int* bottom, unsigned int* dac_ch){ char* local_s = dac_str; - //char temp[50]; *module_index = Feb_Control_current_index; - - /* - char* p1 = strstr(local_s,"mod");//size_t p1 = local_s.find("mod"); - char* p2 = strstr(local_s,"::");//size_t p2 =local_s.find("::"); - if(p1!=NULL&&p2!=NULL&&(p1+3)15){ cprintf(RED,"Warning invalid ch for SetDAC.\n"); return 0; @@ -918,9 +651,11 @@ int Feb_Control_SendDACValue(unsigned int dst_num, unsigned int ch, unsigned int unsigned int r = dac_ic<<30 | 3<<16 | dac_ch<<12 | *value; //3 write and power up - if(!Feb_Interface_WriteRegister(dst_num,0,r,1,0)){ - cprintf(RED,"Warning: trouble setting dac %d voltage.\n",ch); - return 0; + if(Feb_Control_activated){ + if(!Feb_Interface_WriteRegister(dst_num,0,r,1,0)){ + cprintf(RED,"Warning: trouble setting dac %d voltage.\n",ch); + return 0; + } } float voltage=Feb_Control_DACToVoltage(*value,4096,0,2048); @@ -929,14 +664,7 @@ int Feb_Control_SendDACValue(unsigned int dst_num, unsigned int ch, unsigned int return 1; } -/* -float GetDAC(string s){ - static unsigned int n; - if(!GetDACNumber(s,n)) return 0; - return dac[n]; -} - */ int Feb_Control_SetTrimbits(unsigned int module_num, unsigned int *trimbits){ printf("Setting Trimbits\n"); @@ -959,12 +687,15 @@ int Feb_Control_SetTrimbits(unsigned int module_num, unsigned int *trimbits){ for(l_r=0;l_r<2;l_r++){ // l_r loop //printf("\nl_r:%d\t\t",l_r); unsigned int disable_chip_mask = l_r ? DAQ_CS_BAR_LEFT : DAQ_CS_BAR_RIGHT; - if(!(Feb_Interface_WriteRegister(0xfff,DAQ_REG_STATIC_BITS,disable_chip_mask|DAQ_STATIC_BIT_PROGRAM|DAQ_STATIC_BIT_M8,0,0) - &&Feb_Control_SetCommandRegister(DAQ_SET_STATIC_BIT) - &&Feb_Control_StartDAQOnlyNWaitForFinish(5000))){ - printf("Could not select chips\n"); - return 0; + if(Feb_Control_activated){ + if(!(Feb_Interface_WriteRegister(0xfff,DAQ_REG_STATIC_BITS,disable_chip_mask|DAQ_STATIC_BIT_PROGRAM|DAQ_STATIC_BIT_M8,0,0) + &&Feb_Control_SetCommandRegister(DAQ_SET_STATIC_BIT) + &&Feb_Control_StartDAQOnlyNWaitForFinish(5000))){ + printf("Could not select chips\n"); + return 0; + } } + int row_set; for(row_set=0;row_set<16;row_set++){ //16 rows at a time //printf("row_set:%d\t\t",row_set); @@ -1020,22 +751,26 @@ int Feb_Control_SetTrimbits(unsigned int module_num, unsigned int *trimbits){ } //end row loop if(Module_TopAddressIsValid(&modules[1])){ - if(!Feb_Interface_WriteMemoryInLoops(Module_GetTopLeftAddress(&modules[Feb_Control_current_index]),0,0,1024,trimbits_to_load_l)|| - !Feb_Interface_WriteMemoryInLoops(Module_GetTopRightAddress(&modules[Feb_Control_current_index]),0,0,1024,trimbits_to_load_r)|| - //if(!Feb_Interface_WriteMemory(Module_GetTopLeftAddress(&modules[0]),0,0,1023,trimbits_to_load_r)|| - // !Feb_Interface_WriteMemory(Module_GetTopRightAddress(&modules[0]),0,0,1023,trimbits_to_load_l)|| - !Feb_Control_StartDAQOnlyNWaitForFinish(5000)){ - printf(" some errror!\n"); - return 0; + if(Feb_Control_activated){ + if(!Feb_Interface_WriteMemoryInLoops(Module_GetTopLeftAddress(&modules[Feb_Control_current_index]),0,0,1024,trimbits_to_load_l)|| + !Feb_Interface_WriteMemoryInLoops(Module_GetTopRightAddress(&modules[Feb_Control_current_index]),0,0,1024,trimbits_to_load_r)|| + //if(!Feb_Interface_WriteMemory(Module_GetTopLeftAddress(&modules[0]),0,0,1023,trimbits_to_load_r)|| + // !Feb_Interface_WriteMemory(Module_GetTopRightAddress(&modules[0]),0,0,1023,trimbits_to_load_l)|| + !Feb_Control_StartDAQOnlyNWaitForFinish(5000)){ + printf(" some errror!\n"); + return 0; + } } }else{ - if(!Feb_Interface_WriteMemoryInLoops(Module_GetBottomLeftAddress(&modules[Feb_Control_current_index]),0,0,1024,trimbits_to_load_l)|| - !Feb_Interface_WriteMemoryInLoops(Module_GetBottomRightAddress(&modules[Feb_Control_current_index]),0,0,1024,trimbits_to_load_r)|| - //if(!Feb_Interface_WriteMemory(Module_GetTopLeftAddress(&modules[0]),0,0,1023,trimbits_to_load_r)|| - // !Feb_Interface_WriteMemory(Module_GetTopRightAddress(&modules[0]),0,0,1023,trimbits_to_load_l)|| - !Feb_Control_StartDAQOnlyNWaitForFinish(5000)){ - printf(" some errror!\n"); - return 0; + if(Feb_Control_activated){ + if(!Feb_Interface_WriteMemoryInLoops(Module_GetBottomLeftAddress(&modules[Feb_Control_current_index]),0,0,1024,trimbits_to_load_l)|| + !Feb_Interface_WriteMemoryInLoops(Module_GetBottomRightAddress(&modules[Feb_Control_current_index]),0,0,1024,trimbits_to_load_r)|| + //if(!Feb_Interface_WriteMemory(Module_GetTopLeftAddress(&modules[0]),0,0,1023,trimbits_to_load_r)|| + // !Feb_Interface_WriteMemory(Module_GetTopRightAddress(&modules[0]),0,0,1023,trimbits_to_load_l)|| + !Feb_Control_StartDAQOnlyNWaitForFinish(5000)){ + printf(" some errror!\n"); + return 0; + } } } @@ -1077,14 +812,20 @@ return Module_GetTopLeftAddress(&modules[1])|Module_GetTopRightAddress(&modules[ } int Feb_Control_SetCommandRegister(unsigned int cmd){ - return Feb_Interface_WriteRegister(Feb_Control_AddressToAll(),DAQ_REG_CHIP_CMDS,cmd,0,0); + if(Feb_Control_activated) + return Feb_Interface_WriteRegister(Feb_Control_AddressToAll(),DAQ_REG_CHIP_CMDS,cmd,0,0); + else + return 1; } int Feb_Control_GetDAQStatusRegister(unsigned int dst_address, unsigned int* ret_status){ - if(!Feb_Interface_ReadRegister(dst_address,DAQ_REG_STATUS,ret_status)){ - cprintf(RED,"Error: reading status register.\n"); - return 0; + //if deactivated, should be handled earlier and should not get into this function + if(Feb_Control_activated){ + if(!Feb_Interface_ReadRegister(dst_address,DAQ_REG_STATUS,ret_status)){ + cprintf(RED,"Error: reading status register.\n"); + return 0; + } } *ret_status = (0x02FF0000 & *ret_status) >> 16; @@ -1093,11 +834,12 @@ int Feb_Control_GetDAQStatusRegister(unsigned int dst_address, unsigned int* ret int Feb_Control_StartDAQOnlyNWaitForFinish(int sleep_time_us){ - if(!Feb_Interface_WriteRegister(Feb_Control_AddressToAll(),DAQ_REG_CTRL,0,0,0)||!Feb_Interface_WriteRegister(Feb_Control_AddressToAll(),DAQ_REG_CTRL,DAQ_CTRL_START,0,0)){ - cprintf(RED,"Warning: could not start.\n"); - return 0; + if(Feb_Control_activated){ + if(!Feb_Interface_WriteRegister(Feb_Control_AddressToAll(),DAQ_REG_CTRL,0,0,0)||!Feb_Interface_WriteRegister(Feb_Control_AddressToAll(),DAQ_REG_CTRL,DAQ_CTRL_START,0,0)){ + cprintf(RED,"Warning: could not start.\n"); + return 0; + } } - return Feb_Control_WaitForFinishedFlag(sleep_time_us); } @@ -1105,6 +847,10 @@ int Feb_Control_StartDAQOnlyNWaitForFinish(int sleep_time_us){ int Feb_Control_AcquisitionInProgress(){ unsigned int status_reg_r=0,status_reg_l=0; + //deactivated should return end of acquisition + if(!Feb_Control_activated) + return 0; + int ind = Feb_Control_current_index; if(Module_BottomAddressIsValid(&modules[ind])){ @@ -1132,6 +878,10 @@ int Feb_Control_AcquisitionInProgress(){ int Feb_Control_AcquisitionStartedBit(){ unsigned int status_reg_r=0,status_reg_l=0; + //deactivated should return acquisition started/ready + if(!Feb_Control_activated) + return 1; + int ind = Feb_Control_current_index; if(Module_BottomAddressIsValid(&modules[ind])){ @@ -1172,6 +922,11 @@ int Feb_Control_WaitForFinishedFlag(int sleep_time_us){ int Feb_Control_WaitForStartedFlag(int sleep_time_us, int prev_flag){ + + //deactivated dont wait (otherwise give a toggle value back) + if(!Feb_Control_activated) + return 1; + int value = prev_flag; while(value == prev_flag){ usleep(sleep_time_us); @@ -1186,10 +941,13 @@ int Feb_Control_WaitForStartedFlag(int sleep_time_us, int prev_flag){ } -int Feb_Control_Reset(){printf("Reset daq\n"); - if(!Feb_Interface_WriteRegister(Feb_Control_AddressToAll(),DAQ_REG_CTRL,0,0,0) || !Feb_Interface_WriteRegister(Feb_Control_AddressToAll(),DAQ_REG_CTRL,DAQ_CTRL_RESET,0,0) || !Feb_Interface_WriteRegister(Feb_Control_AddressToAll(),DAQ_REG_CTRL,0,0,0)){ - cprintf(RED,"Warning: Could not reset daq, no response.\n"); - return 0; +int Feb_Control_Reset(){ + printf("Reset daq\n"); + if(Feb_Control_activated){ + if(!Feb_Interface_WriteRegister(Feb_Control_AddressToAll(),DAQ_REG_CTRL,0,0,0) || !Feb_Interface_WriteRegister(Feb_Control_AddressToAll(),DAQ_REG_CTRL,DAQ_CTRL_RESET,0,0) || !Feb_Interface_WriteRegister(Feb_Control_AddressToAll(),DAQ_REG_CTRL,0,0,0)){ + cprintf(RED,"Warning: Could not reset daq, no response.\n"); + return 0; + } } return Feb_Control_WaitForFinishedFlag(5000); @@ -1199,10 +957,12 @@ int Feb_Control_Reset(){printf("Reset daq\n"); int Feb_Control_SetStaticBits(){ - //program=1,m4=2,m8=4,test=8,rotest=16,cs_bar_left=32,cs_bar_right=64 - if(!Feb_Interface_WriteRegister(Feb_Control_AddressToAll(),DAQ_REG_STATIC_BITS,Feb_Control_staticBits,0,0) || !Feb_Control_SetCommandRegister(DAQ_SET_STATIC_BIT) || !Feb_Control_StartDAQOnlyNWaitForFinish(5000)){ - cprintf(RED,"Warning: Could not set static bits\n"); - return 0; + if(Feb_Control_activated){ + //program=1,m4=2,m8=4,test=8,rotest=16,cs_bar_left=32,cs_bar_right=64 + if(!Feb_Interface_WriteRegister(Feb_Control_AddressToAll(),DAQ_REG_STATIC_BITS,Feb_Control_staticBits,0,0) || !Feb_Control_SetCommandRegister(DAQ_SET_STATIC_BIT) || !Feb_Control_StartDAQOnlyNWaitForFinish(5000)){ + cprintf(RED,"Warning: Could not set static bits\n"); + return 0; + } } return 1; @@ -1371,6 +1131,7 @@ int Feb_Control_SetExposureTime(double the_exposure_time_in_sec){ return 1; } double Feb_Control_GetExposureTime(){return Feb_Control_exposure_time_in_sec;} +int64_t Feb_Control_GetExposureTime_in_nsec(){return (int64_t)(Feb_Control_exposure_time_in_sec*(1E9));} int Feb_Control_SetSubFrameExposureTime(int64_t the_subframe_exposure_time_in_10nsec){ Feb_Control_subframe_exposure_time_in_10nsec = the_subframe_exposure_time_in_10nsec; @@ -1447,13 +1208,7 @@ void Feb_Control_PrintAcquisitionSetup(){ } int Feb_Control_SendBitModeToBebServer(){ - /* - static int first_pass = 1; - static char buffer[1024]; - if(first_pass&&!Feb_Control_SetupSendToSocket("localhost",43212)) return 0; - else first_pass=0; - */ unsigned int just_bit_mode = (DAQ_STATIC_BIT_M4|DAQ_STATIC_BIT_M8) & Feb_Control_staticBits; unsigned int bit_mode = 16; //default if(just_bit_mode == DAQ_STATIC_BIT_M4) bit_mode = 4; @@ -1466,60 +1221,9 @@ int Feb_Control_SendBitModeToBebServer(){ return 0; } - /* - bzero(buffer,1024); - sprintf(buffer,"setbitmode %d",bit_mode); - - if(Feb_Control_WriteNRead(buffer,strlen(buffer),1024)<1||strncmp(buffer,"0",1)){ - cprintf(RED,"Error: sending bit mode ...\n"); - return 0; - } - */ return 1; } -/* -int Feb_Control_SetupSendToSocket(const char* ip_address_hostname, unsigned short int port){ - - struct hostent *server; - if((server = gethostbyname(ip_address_hostname)) == NULL){ //or look into getaddrinfo(3) - fprintf(stderr,"ERROR, no such host\n"); - return 0; - } - - //struct sockaddr_in serv_addr; - bzero((char *) &Feb_Control_serv_addr, sizeof(Feb_Control_serv_addr)); - Feb_Control_serv_addr.sin_family = AF_INET; - bcopy((char *)server->h_addr,(char *)&Feb_Control_serv_addr.sin_addr.s_addr,server->h_length); - Feb_Control_serv_addr.sin_port = htons(port); - - return 1; -} - -int Feb_Control_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 *) &Feb_Control_serv_addr,sizeof(Feb_Control_serv_addr)) < 0){ - fprintf(stderr,"ERROR connecting\n"); - return 0; - } - - int n = write(sockfd,message,length); - if(n<0) cprintf(RED,"Error writing to socket"); - - length = read(sockfd,message,max_length); - if(length<0) cprintf(RED,"Error reading to socket"); - - close(sockfd); - - return length; -} - */ int Feb_Control_PrepareForAcquisition(){//return 1; static unsigned int reg_nums[20]; @@ -1567,30 +1271,13 @@ int Feb_Control_PrepareForAcquisition(){//return 1; reg_nums[5]=DAQ_REG_SUBFRAME_EXPOSURES; reg_vals[5]= Feb_Control_subframe_exposure_time_in_10nsec; //(1 means 10ns, 100 means 1000ns) // if(!Feb_Interface_WriteRegisters((Module_GetTopLeftAddress(&modules[1])|Module_GetTopRightAddress(&modules[1])),20,reg_nums,reg_vals,0,0)){ - if(!Feb_Interface_WriteRegisters(Feb_Control_AddressToAll(),6,reg_nums,reg_vals,0,0)){ - printf("Trouble starting acquisition....\n");; - return 0; + if(Feb_Control_activated){ + if(!Feb_Interface_WriteRegisters(Feb_Control_AddressToAll(),6,reg_nums,reg_vals,0,0)){ + printf("Trouble starting acquisition....\n");; + return 0; + } } - -/* - reg_nums[0]=DAQ_REG_NEXPOSURES; - reg_vals[0]=Feb_Control_nimages; - reg_nums[1]=DAQ_REG_EXPOSURE_TIMER; - reg_vals[1]=Feb_Control_ConvertTimeToRegister(Feb_Control_exposure_time_in_sec); - reg_nums[2]=DAQ_REG_EXPOSURE_REPEAT_TIMER; - reg_vals[2]=Feb_Control_ConvertTimeToRegister(Feb_Control_exposure_period_in_sec); - reg_nums[3]=DAQ_REG_CHIP_CMDS; - reg_vals[3]=(Feb_Control_acquireNReadoutMode|Feb_Control_triggerMode|Feb_Control_externalEnableMode|Feb_Control_subFrameMode); - reg_nums[4]=DAQ_REG_SUBFRAME_EXPOSURES; - reg_vals[4]= Feb_Control_subframe_exposure_time_in_10nsec; //(1 means 10ns, 100 means 1000ns) - // if(!Feb_Interface_WriteRegisters((Module_GetTopLeftAddress(&modules[1])|Module_GetTopRightAddress(&modules[1])),20,reg_nums,reg_vals,0,0)){ - if(!Feb_Interface_WriteRegisters(Feb_Control_AddressToAll(),5,reg_nums,reg_vals,0,0)){ - printf("Trouble starting acquisition....\n");; - return 0; - } -*/ - return 1; } @@ -1611,22 +1298,13 @@ int Feb_Control_StartAcquisition(){ reg_nums[14]=DAQ_REG_CTRL; reg_vals[14]=ACQ_CTRL_START; - if(!Feb_Interface_WriteRegisters(Feb_Control_AddressToAll(),15,reg_nums,reg_vals,0,0)){ - cprintf(RED,"Trouble starting acquisition....\n");; - return 0; + if(Feb_Control_activated){ + if(!Feb_Interface_WriteRegisters(Feb_Control_AddressToAll(),15,reg_nums,reg_vals,0,0)){ + cprintf(RED,"Trouble starting acquisition....\n");; + return 0; + } } -/* - reg_nums[0]=DAQ_REG_CTRL; - reg_vals[0]=0; - reg_nums[1]=DAQ_REG_CTRL; - reg_vals[1]=ACQ_CTRL_START; - - if(!Feb_Interface_WriteRegisters(Feb_Control_AddressToAll(),2,reg_nums,reg_vals,0,0)){ - printf("Trouble starting acquisition....\n");; - return 0; - } -*/ return 1; } @@ -1705,11 +1383,13 @@ int Feb_Control_PulsePixelNMove(int npulses, int inc_x_pos, int inc_y_pos){ c |= (inc_x_pos) ? DAQ_CLK_MAIN_CLK_TO_SELECT_NEXT_PIXEL : 0; c |= (inc_y_pos) ? DAQ_CLK_ROW_CLK_TO_SELECT_NEXT_ROW : 0; - if(!Feb_Interface_WriteRegister(Feb_Control_AddressToAll(),DAQ_REG_SEND_N_TESTPULSES,npulses,0,0) || - !Feb_Control_SetCommandRegister(c) || - !Feb_Control_StartDAQOnlyNWaitForFinish(5000)){ - cprintf(RED,"Warning: could not PulsePixelNMove(...).\n"); - return 0; + if(Feb_Control_activated){ + if(!Feb_Interface_WriteRegister(Feb_Control_AddressToAll(),DAQ_REG_SEND_N_TESTPULSES,npulses,0,0) || + !Feb_Control_SetCommandRegister(c) || + !Feb_Control_StartDAQOnlyNWaitForFinish(5000)){ + cprintf(RED,"Warning: could not PulsePixelNMove(...).\n"); + return 0; + } } return 1; @@ -1717,11 +1397,13 @@ int Feb_Control_PulsePixelNMove(int npulses, int inc_x_pos, int inc_y_pos){ /**new*/ int Feb_Control_Shift32InSerialIn(unsigned int value_to_shift_in){ - if(!Feb_Control_SetCommandRegister(DAQ_SERIALIN_SHIFT_IN_32) || - !Feb_Interface_WriteRegister(Feb_Control_AddressToAll(),DAQ_REG_SHIFT_IN_32,value_to_shift_in,0,0) || - !Feb_Control_StartDAQOnlyNWaitForFinish(5000)){ - cprintf(RED,"Warning: could not shift in 32.\n"); - return 0; + if(Feb_Control_activated){ + if(!Feb_Control_SetCommandRegister(DAQ_SERIALIN_SHIFT_IN_32) || + !Feb_Interface_WriteRegister(Feb_Control_AddressToAll(),DAQ_REG_SHIFT_IN_32,value_to_shift_in,0,0) || + !Feb_Control_StartDAQOnlyNWaitForFinish(5000)){ + cprintf(RED,"Warning: could not shift in 32.\n"); + return 0; + } } return 1; } @@ -1741,11 +1423,13 @@ int Feb_Control_ClockRowClock(unsigned int ntimes){ ntimes=1023; } - if(!Feb_Control_SetCommandRegister(DAQ_CLK_ROW_CLK_NTIMES) || - !Feb_Interface_WriteRegister(Feb_Control_AddressToAll(),DAQ_REG_CLK_ROW_CLK_NTIMES,ntimes,0,0) || - !Feb_Control_StartDAQOnlyNWaitForFinish(5000)){ - cprintf(RED,"Warning: could not clock row clock.\n"); - return 0; + if(Feb_Control_activated){ + if(!Feb_Control_SetCommandRegister(DAQ_CLK_ROW_CLK_NTIMES) || + !Feb_Interface_WriteRegister(Feb_Control_AddressToAll(),DAQ_REG_CLK_ROW_CLK_NTIMES,ntimes,0,0) || + !Feb_Control_StartDAQOnlyNWaitForFinish(5000)){ + cprintf(RED,"Warning: could not clock row clock.\n"); + return 0; + } } return 1; @@ -1789,26 +1473,40 @@ int Feb_Control_PulseChip(int npulses){ int64_t Feb_Control_Get_RateTable_Tau_in_nsec(){ return Feb_Control_RateTable_Tau_in_nsec;} -int64_t Feb_Control_Get_RateTable_Subexptime_in_nsec(){ return Feb_Control_RateTable_Subexptime_in_nsec;} +int64_t Feb_Control_Get_RateTable_Period_in_nsec(){ return Feb_Control_RateTable_Period_in_nsec;} -//returns -1 if slope is too high int Feb_Control_SetRateCorrectionTau(int64_t tau_in_Nsec){ - double sub_expure_time_in_sec = (double)(Feb_Control_GetSubFrameExposureTime())/(double)1e9; + //period = exptime if 16bit, period = subexptime if 32 bit + int dr = Feb_Control_GetDynamicRange(); + double period_in_sec = (double)(Feb_Control_GetSubFrameExposureTime())/(double)1e9; + if(dr == 16) + period_in_sec = Feb_Control_GetExposureTime(); + + double tau_in_sec = (double)tau_in_Nsec/(double)1e9; + printf(" tau %lf %lf ", (double)tau_in_Nsec, (double) tau_in_sec); + unsigned int np = 16384; //max slope 16 * 1024 double b0[1024]; double m[1024]; - if(tau_in_sec<0||sub_expure_time_in_sec<0){ - printf("Error tau %f and sub_expure_time %f must be greater than 0.\n", tau_in_sec, sub_expure_time_in_sec); + if(tau_in_sec<0||period_in_sec<0){ + if(dr == 32) + printf("Error tau %lf and sub_exposure_time %lf must be greater than 0.\n", tau_in_sec, period_in_sec); + else + printf("Error tau %lf and exposure_time %lf must be greater than 0.\n", tau_in_sec, period_in_sec); return 0; } + cprintf(BLUE, "Changing Rate Correction Table tau:%0.8f sec, period:%f sec",tau_in_sec,period_in_sec); + printf("\tCalculating table for tau of %lld ns.\n", tau_in_Nsec); int i; - for(i=0;i ratemax) ratemax= Feb_Control_rate_meas[i]; + } /* b : index/address of block ram/rate correction table @@ -1827,13 +1525,11 @@ int Feb_Control_SetRateCorrectionTau(int64_t tau_in_Nsec){ */ int next_i=0; + double beforemax; b0[0] = 0; m[0] = 1; - for(i=0; i<1024; i++) - Feb_Control_rate_correction_table[i] = 65535; - - Feb_Control_rate_correction_table[0] = (((int)(m[0]+0.5)&0xf)<<14) | ((int)(b0[0]+0.5)&0x3fff); + Feb_Control_rate_correction_table[0] = (((int)(m[0]+0.5)&0xf)<<14) | ((int)(b0[0]+0.5)&0x3fff); int b=0; for(b=1;b<1024;b++){ @@ -1841,9 +1537,13 @@ int Feb_Control_SetRateCorrectionTau(int64_t tau_in_Nsec){ double s=0,sx=0,sy=0,sxx=0,sxy=0; for(;;next_i++){ if(next_i>=np){ + for(; b<1024; b++){ + if(beforemax>ratemax) b0[b] = beforemax; + else b0[b] = ratemax; + m[b] = 15; + Feb_Control_rate_correction_table[b] = (((int)(m[b]+0.5)&0xf)<<14) | ((int)(b0[b]+0.5)&0x3fff); + } b=1024; - b0[b] = 16383; - m[b] = 15; break; } @@ -1867,17 +1567,20 @@ int Feb_Control_SetRateCorrectionTau(int64_t tau_in_Nsec){ double delta = s*sxx - sx*sx; b0[b] = (sxx*sy - sx*sxy)/delta; m[b] = (s*sxy - sx*sy) /delta; - + beforemax= b0[b]; + if(m[b]<0||m[b]>15){ m[b]=15; - b0[b]=16383; + if(beforemax>ratemax) b0[b] = beforemax; + else b0[b] = ratemax; } /*printf("After Loop s: %f,\t sx: %f,\t sy: %f,\t sxx: %f,\t sxy: %f,\t " "next_i: %d,\t b: %d,\t Feb_Control_rate_meas[next_i]: %f\n", s, sx, sy, sxx, sxy, next_i, b, Feb_Control_rate_meas[next_i]);*/ // cout<ratemax) b0[b] = beforemax; + else b0[b] = ratemax; m[b] = 15; } Feb_Control_rate_correction_table[b] = (((int)(m[b]+0.5)&0xf)<<14) | ((int)(b0[b]+0.5)&0x3fff); @@ -1886,11 +1589,11 @@ int Feb_Control_SetRateCorrectionTau(int64_t tau_in_Nsec){ if(Feb_Control_SetRateCorrectionTable(Feb_Control_rate_correction_table)){ Feb_Control_RateTable_Tau_in_nsec = tau_in_Nsec; - Feb_Control_RateTable_Subexptime_in_nsec = Feb_Control_GetSubFrameExposureTime(); + Feb_Control_RateTable_Period_in_nsec = period_in_sec; return 1; }else{ Feb_Control_RateTable_Tau_in_nsec = -1; - Feb_Control_RateTable_Subexptime_in_nsec = -1; + Feb_Control_RateTable_Period_in_nsec = -1; return 0; } @@ -1919,18 +1622,22 @@ int Feb_Control_SetRateCorrectionTable(unsigned int *table){ printf("daq reset completely\n"); if(Module_TopAddressIsValid(&modules[1])){ - if(!Feb_Interface_WriteMemoryInLoops(Module_GetTopLeftAddress(&modules[Feb_Control_current_index]),1,0,1024,Feb_Control_rate_correction_table)|| - !Feb_Interface_WriteMemoryInLoops(Module_GetTopRightAddress(&modules[Feb_Control_current_index]),1,0,1024,Feb_Control_rate_correction_table)|| - !Feb_Control_StartDAQOnlyNWaitForFinish(5000)){ - cprintf(BG_RED,"Error in Top Writing to Memory ::Feb_Control_SetRateCorrectionTable\n"); - return 0; + if(Feb_Control_activated){ + if(!Feb_Interface_WriteMemoryInLoops(Module_GetTopLeftAddress(&modules[Feb_Control_current_index]),1,0,1024,Feb_Control_rate_correction_table)|| + !Feb_Interface_WriteMemoryInLoops(Module_GetTopRightAddress(&modules[Feb_Control_current_index]),1,0,1024,Feb_Control_rate_correction_table)|| + !Feb_Control_StartDAQOnlyNWaitForFinish(5000)){ + cprintf(BG_RED,"Error in Top Writing to Memory ::Feb_Control_SetRateCorrectionTable\n"); + return 0; + } } }else{ - if(!Feb_Interface_WriteMemoryInLoops(Module_GetBottomLeftAddress(&modules[Feb_Control_current_index]),1,0,1024,Feb_Control_rate_correction_table)|| - !Feb_Interface_WriteMemoryInLoops(Module_GetBottomRightAddress(&modules[Feb_Control_current_index]),1,0,1024,Feb_Control_rate_correction_table)|| - !Feb_Control_StartDAQOnlyNWaitForFinish(5000)){ - cprintf(BG_RED,"Error in Bottom Writing to Memory ::Feb_Control_SetRateCorrectionTable\n"); - return 0; + if(Feb_Control_activated){ + if(!Feb_Interface_WriteMemoryInLoops(Module_GetBottomLeftAddress(&modules[Feb_Control_current_index]),1,0,1024,Feb_Control_rate_correction_table)|| + !Feb_Interface_WriteMemoryInLoops(Module_GetBottomRightAddress(&modules[Feb_Control_current_index]),1,0,1024,Feb_Control_rate_correction_table)|| + !Feb_Control_StartDAQOnlyNWaitForFinish(5000)){ + cprintf(BG_RED,"Error in Bottom Writing to Memory ::Feb_Control_SetRateCorrectionTable\n"); + return 0; + } } } return 1; @@ -1943,7 +1650,7 @@ int Feb_Control_GetRateCorrectionVariable(){ return (Feb_Control_subFrameMode&DA void Feb_Control_SetRateCorrectionVariable(int activate_rate_correction){ if(activate_rate_correction){ Feb_Control_subFrameMode |= DAQ_NEXPOSURERS_ACTIVATE_RATE_CORRECTION; - printf("Rate correction activated. Note: the rate correction applied only when run in auto summing mode.\n"); + printf("Rate correction activated.\n"); }else{ Feb_Control_subFrameMode &= ~DAQ_NEXPOSURERS_ACTIVATE_RATE_CORRECTION; printf("Rate correction deactivated.\n"); @@ -1958,13 +1665,39 @@ int Feb_Control_PrintCorrectedValues(){ lsb = i&3; base = Feb_Control_rate_correction_table[i>>2] & 0x3fff; slope = ((Feb_Control_rate_correction_table[i>>2] & 0x3c000) >> 14); - delta = slope*lsb; - corr = delta+base; - if(base==16383 && slope==15) corr=4095; - printf("Readout Input: %d,\tBase:%d,\tSlope:%d,\tLSB:%d,\tDelta:%d\tResult:%d\tReal:%f\n", + delta = slope*lsb; + corr = delta+base; + if(slope==15) corr= 3*slope+base; + + printf("Readout Input: %d,\tBase:%d,\tSlope:%d,\tLSB:%d,\tDelta:%d\tResult:%d\tReal:%lf\n", i, base, slope, lsb, delta, corr, Feb_Control_rate_meas[i]); } return 1; } + +int Feb_Control_GetLeftFPGATemp(){ + unsigned int temperature=0; + if(Module_TopAddressIsValid(&modules[1])) + Feb_Interface_ReadRegister(Module_GetTopLeftAddress (&modules[1]),FEB_REG_STATUS, &temperature); + else + Feb_Interface_ReadRegister(Module_GetBottomLeftAddress (&modules[1]),FEB_REG_STATUS, &temperature); + temperature = temperature >> 16; + //division done in client to send int over network + return (int)temperature; +} + +int Feb_Control_GetRightFPGATemp(){ + unsigned int temperature=0; + if(Module_TopAddressIsValid(&modules[1])) + Feb_Interface_ReadRegister(Module_GetTopRightAddress (&modules[1]),FEB_REG_STATUS, &temperature); + else + Feb_Interface_ReadRegister(Module_GetBottomRightAddress (&modules[1]),FEB_REG_STATUS, &temperature); + temperature = temperature >> 16; + //division done in client to send int over network + return (int)temperature; +} + + + diff --git a/slsDetectorSoftware/eigerDetectorServer/FebControl.h b/slsDetectorSoftware/eigerDetectorServer/FebControl.h index cb87558ad..01048a4f7 100644 --- a/slsDetectorSoftware/eigerDetectorServer/FebControl.h +++ b/slsDetectorSoftware/eigerDetectorServer/FebControl.h @@ -64,6 +64,7 @@ int Module_GetBottomDACValue(struct Module* mod,unsigned int i); +void Feb_Control_activate(int activate); int Feb_Control_IsBottomModule(); int Feb_Control_GetModuleNumber(); @@ -112,8 +113,6 @@ int Feb_Control_GetModuleNumber(); void Feb_Control_FebControl(); int Feb_Control_Init(int master, int top, int module_num); - int Feb_Control_ReadSetUpFileToAddModules(char* file_name); - int Feb_Control_ReadSetUpFile(unsigned int module_num, char* file_name); int Feb_Control_CheckSetup(); unsigned int Feb_Control_GetNModules(); @@ -159,6 +158,7 @@ int Feb_Control_GetModuleNumber(); unsigned int Feb_Control_GetNExposures(); int Feb_Control_SetExposureTime(double the_exposure_time_in_sec); double Feb_Control_GetExposureTime(); + int64_t Feb_Control_GetExposureTime_in_nsec(); int Feb_Control_SetSubFrameExposureTime(int64_t the_subframe_exposure_time_in_10nsec); int64_t Feb_Control_GetSubFrameExposureTime(); int Feb_Control_SetExposurePeriod(double the_exposure_period_in_sec); @@ -185,11 +185,14 @@ int Feb_Control_GetModuleNumber(); int Feb_Control_PulseChip(int npulses); int64_t Feb_Control_Get_RateTable_Tau_in_nsec(); - int64_t Feb_Control_Get_RateTable_Subexptime_in_nsec(); + int64_t Feb_Control_Get_RateTable_Period_in_nsec(); int Feb_Control_SetRateCorrectionTau(int64_t tau_in_Nsec); int Feb_Control_SetRateCorrectionTable(unsigned int *table); int Feb_Control_GetRateCorrectionVariable(); void Feb_Control_SetRateCorrectionVariable(int activate_rate_correction); int Feb_Control_PrintCorrectedValues(); + int Feb_Control_GetLeftFPGATemp(); + int Feb_Control_GetRightFPGATemp(); + #endif diff --git a/slsDetectorSoftware/eigerDetectorServer/FebRegisterDefs.h b/slsDetectorSoftware/eigerDetectorServer/FebRegisterDefs.h index 1dbd97b59..b4b728a3d 100644 --- a/slsDetectorSoftware/eigerDetectorServer/FebRegisterDefs.h +++ b/slsDetectorSoftware/eigerDetectorServer/FebRegisterDefs.h @@ -95,6 +95,7 @@ #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 @@ -149,3 +150,49 @@ #define FRAME_NUM_RESET_OFFSET 0xA0 +//temp so far +#define FEB_REG_STATUS 0xa + +//1g counters +#define ONE_GIGA_LEFT_FRAME_SEND_COUNTER 0x04 +#define ONE_GIGA_LEFT_PKT_SEND_COUNTER 0x24 + +#define ONE_GIGA_LEFT_TXN_DELAY_COUNTER 0x104 +#define ONE_GIGA_LEFT_FRAME_DELAY_COUNTER 0x124 + +#define ONE_GIGA_RIGHT_FRAME_SEND_COUNTER 0x44 +#define ONE_GIGA_RIGHT_PKT_SEND_COUNTER 0x64 + +#define ONE_GIGA_RIGHT_TXN_DELAY_COUNTER 0x144 +#define ONE_GIGA_RIGHT_FRAME_DELAY_COUNTER 0x164 + +//10g counters +#define TEN_GIGA_LEFT_FRAME_SEND_COUNTER 0x84 +#define TEN_GIGA_LEFT_PKT_SEND_COUNTER 0xa4 + +#define TEN_GIGA_LEFT_TXN_DELAY_COUNTER 0x184 +#define TEN_GIGA_LEFT_FRAME_DELAY_COUNTER 0x1a4 + +#define TEN_GIGA_RIGHT_FRAME_SEND_COUNTER 0xc4 +#define TEN_GIGA_RIGHT_PKT_SEND_COUNTER 0xe4 + +#define TEN_GIGA_RIGHT_TXN_DELAY_COUNTER 0x1c4 +#define TEN_GIGA_RIGHT_FRAME_DELAY_COUNTER 0x1e4 + + + + + + + + + + + + + + + + + + diff --git a/slsDetectorSoftware/eigerDetectorServer/bin/eigerDetectorServerv2.0.5.14.3 b/slsDetectorSoftware/eigerDetectorServer/bin/eigerDetectorServerv2.0.5.14.3 deleted file mode 100755 index 5cc214ad1..000000000 Binary files a/slsDetectorSoftware/eigerDetectorServer/bin/eigerDetectorServerv2.0.5.14.3 and /dev/null differ diff --git a/slsDetectorSoftware/eigerDetectorServer/bin/eigerDetectorServerv2.2.0.14.0 b/slsDetectorSoftware/eigerDetectorServer/bin/eigerDetectorServerv2.2.0.14.0 new file mode 100755 index 000000000..75724eb5e Binary files /dev/null and b/slsDetectorSoftware/eigerDetectorServer/bin/eigerDetectorServerv2.2.0.14.0 differ diff --git a/slsDetectorSoftware/eigerDetectorServer/bin/eigerDetectorServerv2.2.0.14.1 b/slsDetectorSoftware/eigerDetectorServer/bin/eigerDetectorServerv2.2.0.14.1 new file mode 100755 index 000000000..0be5f404a Binary files /dev/null and b/slsDetectorSoftware/eigerDetectorServer/bin/eigerDetectorServerv2.2.0.14.1 differ diff --git a/slsDetectorSoftware/eigerDetectorServer/bin/eigerDetectorServerv2.2.0.16.0 b/slsDetectorSoftware/eigerDetectorServer/bin/eigerDetectorServerv2.2.0.16.0 new file mode 100755 index 000000000..f6dd95b75 Binary files /dev/null and b/slsDetectorSoftware/eigerDetectorServer/bin/eigerDetectorServerv2.2.0.16.0 differ diff --git a/slsDetectorSoftware/eigerDetectorServer/bin/eigerDetectorServerv2.2.0.16.1 b/slsDetectorSoftware/eigerDetectorServer/bin/eigerDetectorServerv2.2.0.16.1 new file mode 100755 index 000000000..5f58c87f9 Binary files /dev/null and b/slsDetectorSoftware/eigerDetectorServer/bin/eigerDetectorServerv2.2.0.16.1 differ diff --git a/slsDetectorSoftware/eigerDetectorServer/bin/eigerDetectorServerv2.2.0.16.2 b/slsDetectorSoftware/eigerDetectorServer/bin/eigerDetectorServerv2.2.0.16.2 new file mode 100755 index 000000000..df4901267 Binary files /dev/null and b/slsDetectorSoftware/eigerDetectorServer/bin/eigerDetectorServerv2.2.0.16.2 differ diff --git a/slsDetectorSoftware/eigerDetectorServer/gitInfo.txt b/slsDetectorSoftware/eigerDetectorServer/gitInfo.txt index b4085a0de..d4905e059 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: e9878a26ffb7e57c6e6724215e46ae5634871e64 -Revision: 231 +Repsitory UUID: 279965f286cc6364dec8bf7e2a837214d11bb296 +Revision: 258 Branch: developer Last Changed Author: Dhanya_Maliakal -Last Changed Rev: 336 -Last Changed Date: 2016-08-24 16:47:14 +0200 +Last Changed Rev: 358 +Last Changed Date: 2016-11-03 12:31:34 +0100 diff --git a/slsDetectorSoftware/eigerDetectorServer/gitInfoEiger.h b/slsDetectorSoftware/eigerDetectorServer/gitInfoEiger.h index 72d23e86b..476f77780 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 "e9878a26ffb7e57c6e6724215e46ae5634871e64" -//#define SVNREV 0x336 +#define SVNREPUUID "279965f286cc6364dec8bf7e2a837214d11bb296" +//#define SVNREV 0x358 //#define SVNKIND "" //#define SVNSCHED "" #define SVNAUTH "Dhanya_Maliakal" -#define SVNREV 0x336 -#define SVNDATE 0x20160824 +#define SVNREV 0x358 +#define SVNDATE 0x20161103 // diff --git a/slsDetectorSoftware/eigerDetectorServer/slsDetectorFunctionList.c b/slsDetectorSoftware/eigerDetectorServer/slsDetectorFunctionList.c index 9533efa17..3d904043c 100644 --- a/slsDetectorSoftware/eigerDetectorServer/slsDetectorFunctionList.c +++ b/slsDetectorSoftware/eigerDetectorServer/slsDetectorFunctionList.c @@ -130,7 +130,7 @@ int initDetector(){ detectorGain[i] = default_gain_values[(int)STANDARD]; for(i=0;i1) + if (ic>2) return -1; + if (ic==2) { + printf("dbit clock is the same as adc clk\n"); + ic=1; + + } + if (ic==1 && d>40) return -1; @@ -621,6 +627,17 @@ int phaseStep(int st){ return clkPhase[0]; } +int dbitPhaseStep(int st){ + + printf("dbit clock is the same as adc clk\n"); + return phaseStep(st); +} + + + + + + int getPhase() { return clkPhase[0]; @@ -628,10 +645,25 @@ int getPhase() { }; + +int getDbitPhase() { + + printf("dbit clock is the same as adc clk\n"); + return getPhase(); + +}; + + u_int32_t getClockDivider(int ic) { - if (ic>1) + if (ic>2) return -1; + + if (ic==2) { + printf("dbit clock is the same as adc clk\n"); + ic=1; + + } return clkDivider[ic]; @@ -667,9 +699,24 @@ u_int32_t getClockDivider(int ic) { u_int32_t adcPipeline(int d) { - if (d>=0) - bus_w(DAQ_REG, d); - return bus_r(DAQ_REG)&0xff; + u_int32_t v; + if (d>=0) { + v=bus_r(ADC_PIPELINE_REG)&0x00ff0000; + bus_w(ADC_PIPELINE_REG, d|v); + } + return bus_r(ADC_PIPELINE_REG)&0xff; +} + + +u_int32_t dbitPipeline(int d) { + u_int32_t v; + if (d>=0) { + v=bus_r(ADC_PIPELINE_REG)&0x000000ff; + bus_w(ADC_PIPELINE_REG, v|(d<<16)); + + } + v=bus_r(ADC_PIPELINE_REG)>>16; + return v&0xff; } @@ -1273,7 +1320,7 @@ int64_t set64BitReg(int64_t value, int aLSB, int aMSB){ v64=value>> 32; vMSB=v64&(0xffffffff); bus_w(aMSB,vMSB); - printf("Wreg64(%x,%x) %08x %08x %016llx\n", aLSB>>11, aMSB>>11, vLSB, vMSB, value); + // printf("Wreg64(%x,%x) %08x %08x %016llx\n", aLSB>>11, aMSB>>11, vLSB, vMSB, value); } return get64BitReg(aLSB, aMSB); @@ -1287,7 +1334,7 @@ int64_t get64BitReg(int aLSB, int aMSB){ v64=vMSB; v64=(v64<<32) | vLSB; - printf("reg64(%x,%x) %x %x %llx\n", aLSB, aMSB, vLSB, vMSB, v64); + // printf("reg64(%x,%x) %x %x %llx\n", aLSB, aMSB, vLSB, vMSB, v64); return v64; } @@ -2142,52 +2189,20 @@ u_int16_t* fifo_read_event(int ns) // printf("LAM: %08x\n",a); } - + // printf("."); a = bus_r(LOOK_AT_ME_REG); if (analogEnable) { + printf("*"); bus_w16(DUMMY_REG,1<<8); // read strobe to all fifos bus_w16(DUMMY_REG,0); - - /* for (i=0; i<32; i++) { */ - /* bus_w16(DUMMY_REG,i); */ - /* printf("%04x ",bus_r16(FIFO_STATUS_REG)); */ - /* // a = bus_r(LOOK_AT_ME_REG); */ - /* // printf("%d %08x\n",i,a); */ - /* } */ - /* printf("\n"); */ - // i=0;// -/* for (i=0; i<32; i++) { */ - -/* /\* while (((adcDisableMask&(3<<((i)*2)))>>((i)*2))==3) { *\/ */ -/* /\* i++; *\/ */ -/* /\* if (i>15) *\/ */ -/* /\* break; *\/ */ -/* /\* } *\/ */ -/* /\* if (i<16) { *\/ */ -/* bus_w16(DUMMY_REG,i); */ -/* } */ -/* val=*values; */ - //printf("sample %d ",ns); - - // bus_w16(DUMMY_REG,0); // for (i=0; i<32; i++) { - - - - if (~(mask&adcDisableMask)) { - *((u_int16_t*)now_ptr)=*values;//bus_r16(FIFO_DATA_REG);//*values;//bus_r(FIFO_DATA_REG); - - + *((u_int16_t*)now_ptr)=*values;//bus_r16(FIFO_DATA_REG); if (i!=0 || ns!=0) { a=0; while (*((u_int16_t*)now_ptr)==*((u_int16_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_int16_t*)now_ptr)=*values; - // printf(".",i); - } } now_ptr+=2; @@ -2195,15 +2210,10 @@ u_int16_t* fifo_read_event(int ns) mask=mask<<1; // if (~(mask&adcDisableMask) bus_w16(DUMMY_REG,i+1); - - // a = bus_r(LOOK_AT_ME_REG); - // printf("%d %08x\n",i,a); - //#ifdef VERBOSE - // } - // *(((u_int16_t*)(now_ptr))+i)=bus_r16(FIFO_DATA_REG); } } if (digitalEnable) { + printf("+"); bus_w16(DUMMY_REG,1<<9); // read strobe to digital fifo bus_w16(DUMMY_REG,0<<9); // read strobe to digital fifo @@ -2776,8 +2786,13 @@ int prepareADC(){ cdx=0; ddx=1; csmask=0x7c; // 1111100 +/* #define ADCREG1 0x08 */ +/* #define ADCREG2 0x14//20 */ +/* #define ADCREG3 0x4 */ +/* #define ADCREG4 0x5 */ codata=0; - writeADC(ADCREG1,0x3); writeADC(ADCREG1,0x0); + writeADC(ADCREG1,0x3); +writeADC(ADCREG1,0x0); writeADC(ADCREG3,0xf); @@ -2831,9 +2846,9 @@ int prepareADC(){ bus_w(ADC_LATCH_DISABLE_REG,0x0); // enable all ADCs - bus_w(DAQ_REG,0x12); //adc pipeline=18 + // bus_w(DAQ_REG,0x12); //adc pipeline=18 - bus_w(DAQ_REG,0xbbbbbbbb); + //bus_w(DAQ_REG,0xbbbbbbbb); // bus_w(ADC_INVERSION_REG,0x1f6170c6); return OK; @@ -3764,7 +3779,23 @@ int setPower(int ind, int val) { +int powerChip(int arg) { + //#ifndef CTB + u_int32_t preg=bus_r(POWER_ON_REG); + if (arg>=0) { + if (arg) + bus_w(POWER_ON_REG,preg|0xffff0000); + else + bus_w(POWER_ON_REG,preg&0x0000ffff); + preg=bus_r(POWER_ON_REG); + } + printf("Power register is %08x\n",preg); + if (preg&0xffff0000) + return 1; + else + return 0; +} @@ -3798,12 +3829,12 @@ int nextDac(){ valw=0xffff&(~(0x1<=0) { @@ -3892,15 +3925,15 @@ int setThisDac(int dacnum,int dacvalue){ //printf("%08x\n",codata); - for (i=1;i<25;i++) { - // printf("%d",((codata>>(24-i)))&0x1); - valw=(valw&(~(0x1<>(24-i))&0x1)<>(24-i)))&0x1); + valw=(valw&(~(0x1<>(24-i))&0x1)<>(24-i))&0x1)); - - - valw=((valw&(~(0x1< /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/firmware_funcs.c b/slsDetectorSoftware/jungfrauDetectorServer/firmware_funcs.c index 60753d4ce..71c2bc121 100755 --- a/slsDetectorSoftware/jungfrauDetectorServer/firmware_funcs.c +++ b/slsDetectorSoftware/jungfrauDetectorServer/firmware_funcs.c @@ -7,6 +7,7 @@ #include "firmware_funcs.h" #include "mcb_funcs.h" #include "registers_m.h" +#include "gitInfoJungfrau.h" //#define VERBOSE //#define VERYVERBOSE @@ -47,62 +48,58 @@ #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; + 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 -//for memory mapping + + u_int32_t CSP0BASE; - - FILE *debugfp, *datafp; - int fr; int wait_time; int *fifocntrl; - -//int *statusreg; commented out by dhanya const int nModY=1; int nModBoard; int nModX=NMAXMOD; -int dynamicRange=16;//32; +int dynamicRange=16; int nSamples=1; - -int dataBytes=NMAXMOD*NCHIP*NCHAN*2; - +size_t dataBytes=NMAXMOD*NCHIP*NCHAN*2; int storeInRAM=0; int ROI_flag=0; int adcConfigured=-1; -u_int16_t *ram_values=NULL; -char volatile *now_ptr=NULL; -u_int32_t volatile *values; 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 = 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; @@ -113,104 +110,256 @@ 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}; -int withGotthard = 0; +char mtdvalue[10]; + + -/**is not const because this value will change after initDetector, is removed from mcb_funcs.c cuz its not used anywhere - * why is this used anywhere instead of macro*/ -int nChans=NCHAN; -int nChips=NCHIP; -int nDacs=NDAC; -int nAdcs=NADC; -extern enum detectorType myDetectorType; -/** for jungfrau reinitializing macro later in server_funcs.c in initDetector*/ -extern int N_CHAN; -extern int N_CHIP; -extern int N_DAC; -extern int N_ADC; -extern int N_CHANS; int mapCSP0(void) { - printf("Mapping memory\n"); + 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"); + 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"); + 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"); + 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; - } + if ( (res=inism(SMSV))<0) { + printf("error attaching shared memory! %i",res); + return FAIL; + } #endif - printf("CSPObase is 0x%08x \n",CSP0BASE); - printf("CSPOBASE=from %08x to %08x\n",CSP0BASE,CSP0BASE+MEM_SIZE); + //printf("CSPObase is 0x%08x \n",CSP0BASE); + printf("CSPOBASE mapped from %08x to %08x\n",CSP0BASE,CSP0BASE+MEM_SIZE); - u_int32_t address; - address = FIFO_DATA_REG;//_OFF; - values=(u_int32_t*)(CSP0BASE+address*2); - printf("statusreg=%08x\n",bus_r(STATUS_REG)); - printf("\n\n"); - return OK; + 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; + 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; + 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); + 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); + 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; + volatile u_int32_t *ptr1; - ptr1=(u_int32_t*)(CSP0BASE+offset*2); - *ptr1=data; + ptr1=(u_int32_t*)(CSP0BASE+offset*2); + *ptr1=data; - return OK; + 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; + volatile u_int32_t *ptr1; + ptr1=(u_int32_t*)(CSP0BASE+offset*2); + return *ptr1; } @@ -237,102 +386,41 @@ int setPhaseShiftOnce(){ printf("Multipupose reg now:%x\n",bus_r(addr)); #endif } - return OK; } int cleanFifo(){ -/* u_int32_t addr, reg, val, adc_sync; */ -/* printf("Cleaning FIFO\n"); */ -/* addr=ADC_SYNC_REG; */ - -/* if(withGotthard) */ -/* adc_sync = GOTTHARD_ADCSYNC_VAL; */ -/* else */ -/* adc_sync = ADCSYNC_VAL; */ - - -/* reg = bus_r(addr) & CLEAN_FIFO_MASK; */ - -/* //only for start up */ -/* if(!reg) reg = adc_sync; */ - -/* // 88 3 02111 */ -/* if (ROI_flag==0) { */ -/* val=reg | ADCSYNC_CLEAN_FIFO_BITS | TOKEN_RESTART_DELAY; */ -/* bus_w(addr,val); */ -/* // 88 0 02111 */ -/* val=reg | TOKEN_RESTART_DELAY; */ -/* bus_w(addr,val); */ -/* } */ -/* else { */ -/* //1b332214 */ -/* val=reg | ADCSYNC_CLEAN_FIFO_BITS | TOKEN_RESTART_DELAY_ROI; */ -/* bus_w(addr,val); */ -/* //1b032214 */ -/* val=reg | TOKEN_RESTART_DELAY_ROI; */ -/* bus_w(addr,val); */ - -/* } */ -/* reg=bus_r(addr); */ -/* //#ifdef DDEBUG */ -/* printf("ADC SYNC reg 0x19:%x\n",reg); */ -/* //#endif */ return OK; } -int setDAQRegister() -{ -/* u_int32_t addr, reg, val; */ -/* addr=DAQ_REG; */ - -/* //depended on adcval */ -/* int packetlength=0x7f; */ -/* if(!ROI_flag) packetlength=0x13f; */ - -/* //depended on pcb rev */ -/* int tokenTiming = TOKEN_TIMING_REV2; */ -/* if((bus_r(PCB_REV_REG)&BOARD_REVISION_MASK)==1) */ -/* tokenTiming= TOKEN_TIMING_REV1; */ - - -/* val = (packetlength<<16) + tokenTiming; */ -/* //val=34+(42<<8)+(packetlength<<16); */ - -/* reg=bus_r(addr); */ -/* bus_w(addr,val); */ -/* reg=bus_r(addr); */ -/* //#ifdef VERBOSE */ -/* printf("DAQ reg 0x15:%x\n",reg); */ -/* //#endif */ - +int setDAQRegister(){ return OK; } // direct pattern output u_int32_t putout(char *s, int modnum) { - int i; - u_int32_t pat; - int addr; + int i; + u_int32_t pat; + int addr; - if (strlen(s)<16) { - fprintf(stdout," *** putout error: incorrect pattern length ***\n"); - fprintf(stdout," %s \n",s); - return FAIL; - } + if (strlen(s)<16) { + fprintf(stdout," *** putout error: incorrect pattern length ***\n"); + fprintf(stdout," %s \n",s); + return FAIL; + } - pat=0; - for (i=0;i<16;i++) { - if (s[i]=='1') pat=pat+(1<<(15-i)); - } - //addr=DAC_REG+(modnum<<4); - addr=DAC_REG;//+(modnum<2*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); + } - if (i<2) { + } else { + // if (mode==1) { + // } else { + printf("phase in %d\n",clkPhase[1]); - tot= PLL_VCO_FREQ_MHZ/clkDivider[i]; - l=tot/2; - h=l; - if (tot>2*l) { - h=l+1; - odd=1; - } - printf("Counter %d: Low is %d, High is %d\n",i, l,h); + 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= (i<<18)| (odd<<17) | l | (h<<8); + val=phase ;// | (inv<<21); + printf("**************** phase word %08x\n",val); - 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 + // 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); + 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); + // 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 - } - - - } + 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); + 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); + // 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<1) - return -1; - - if (ic==1 && d>40) - return -1; - - if (d>160) - return -1; - - if (tot>510) - return -1; - - if (tot<1) - return -1; - - - - clkDivider[ic]=d; - configurePll(ic); - - - - return clkDivider[ic]; + case FULL: + printf("Setting Half Speed (40 MHz)\n"); + /**to be done*/ + dbitPipeline(HALFSPEED_DBIT_PIPELINE); + adcPipeline(HALFSPEED_ADC_PIPELINE); + initSpeedConfGain(HALFSPEED_CONF); + adcPhase(HALFSPEED_ADC_PHASE); + break; + case HALF: + printf("Setting Half Speed (20 MHz)\n"); + dbitPipeline(HALFSPEED_DBIT_PIPELINE); + adcPipeline(HALFSPEED_ADC_PIPELINE); + initSpeedConfGain(HALFSPEED_CONF); + adcPhase(HALFSPEED_ADC_PHASE); + break; + case QUARTER: + printf("Setting Half Speed (10 MHz)\n"); + dbitPipeline(QUARTERSPEED_DBIT_PIPELINE); + adcPipeline(QUARTERSPEED_ADC_PIPELINE); + initSpeedConfGain(QUARTERSPEED_CONF); + adcPhase(QUARTERSPEED_ADC_PHASE); + break; + } + } + return getClockDivider(); } -int phaseStep(int st){ - - if (st>65535 || st<-65535) - return clkPhase[0]; + +int adcPhase(int st){ + printf("\nSetting ADC Phase to %d\n",st); + if (st>65535 || st<-65535) + return clkPhase[0]; #ifdef NEW_PLL_RECONFIG - printf("reset pll\n"); - bus_w(PLL_CNTRL_REG,((1<1) - return -1; - return clkDivider[ic]; - - -/* int ic=0; */ -/* u_int32_t val; */ -/* u_int32_t l,h; */ - -/* printf("get clk divider\n"); */ - - -/* setPllReconfigReg(PLL_MODE_REG,1,0); */ -/* getPllReconfigReg(PLL_MODE_REG,0); */ - -/* u_int32_t addr=0xa; //c0 */ -/* if (ic>0) */ -/* addr=0xb; //c1 */ - -/* val=getPllReconfigReg(PLL_N_COUNTER_REG,0); */ -/* printf("Getting N counter %08x\n",val); */ - -/* l=val&0xff; */ -/* h=(val>>8)&0xff; */ - -/* //getPllReconfigReg(PLL_STATUS_REG,0); */ -/* val=getPllReconfigReg(addr,0); */ -/* printf("Getting C counter %08x\n",val); */ - - - -/* return 800/(l+h); */ - + enum clkspeed{FULL,HALF,QUARTER}; + switch(initSpeedConfGain(-1)){ + //case FULLSPEED_CONF: + //return FULL; + case HALFSPEED_CONF: + return HALF; + case QUARTERSPEED_CONF: + return QUARTER; + default: + return -1; + } } u_int32_t adcPipeline(int d) { - if (d>=0) - bus_w(DAQ_REG, d); - return bus_r(DAQ_REG)&0xff; + if (d>=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; + return 0; } u_int32_t getSetLength() { - return 0; + return 0; } u_int32_t setOversampling(int d) { - if (d>=0 && d<=255) - bus_w(OVERSAMPLING_REG, d); + if (d>=0 && d<=255) + bus_w(OVERSAMPLING_REG, d); - return bus_r(OVERSAMPLING_REG); + return bus_r(OVERSAMPLING_REG); } u_int32_t setWaitStates(int d1) { - return 0; + return 0; } u_int32_t getWaitStates() { - return 0; + return 0; } u_int32_t setTotClockDivider(int d) { - return 0; + return 0; } u_int32_t getTotClockDivider() { - return 0; + return 0; } u_int32_t setTotDutyCycle(int d) { - return 0; + return 0; } u_int32_t getTotDutyCycle() { - return 0; + return 0; } u_int32_t setExtSignal(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}; - // int off=d*SIGNAL_OFFSET; - u_int32_t c; c=bus_r(EXT_SIGNAL_REG); @@ -754,12 +772,7 @@ u_int32_t setExtSignal(int d, enum externalSignalFlag mode) { setTiming(GET_EXTERNAL_COMMUNICATION_MODE); } - -// if (mode<=RO_TRIGGER_OUT_FALLING_EDGE && mode>=0) -// bus_w(EXT_SIGNAL_REG,((modes[mode])<=0) { + if (mode<=RO_TRIGGER_OUT_FALLING_EDGE && mode>=0) { #ifdef VERBOSE - printf("writing signal register number %d mode %04x\n",d, modes[mode]); + printf("writing signal register number %d mode %04x\n",d, modes[mode]); #endif - bus_w(EXT_SIGNAL_REG,((modes[mode])<>off); - - if (mode=0 && d<4) { #ifdef VERBOSE printf("gettings signal variable number %d value %04x\n", d, signals[d]); @@ -804,27 +807,25 @@ int getExtSignal(int d) { 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 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); + 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]; + 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]); + printf("gettings signal register number %d value %04x\n", d, modes[mode]); #endif - return modes[mode]; - } else - return -1; + return modes[mode]; + } else + return -1; } @@ -845,118 +846,122 @@ enum externalCommunicationMode{ GATE_WITH_START_TRIGGER, GATE_COINCIDENCE_WITH_INTERNAL_ENABLE }; -*/ + */ int setTiming(int ti) { + int ret=GET_EXTERNAL_COMMUNICATION_MODE; - int ret=GET_EXTERNAL_COMMUNICATION_MODE; + int g=-1, t=-1, rot=-1; - int g=-1, t=-1, rot=-1; + int i; - 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 && 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; - } + if (g>=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; + // timingMode=ret; - return ret; + return ret; } @@ -964,68 +969,69 @@ int setTiming(int ti) { int setConfigurationRegister(int d) { #ifdef VERBOSE - printf("Setting configuration register to %x",d); + printf("Setting configuration register to %x",d); #endif - if (d>=0) { - bus_w(CONFIG_REG,d); - } + if (d>=0) { + bus_w(CONFIG_REG,d); + } #ifdef VERBOSE - printf("configuration register is %x", bus_r(CONFIG_REG)); + printf("configuration register is %x", bus_r(CONFIG_REG)); #endif - return bus_r(CONFIG_REG); + return bus_r(CONFIG_REG); } int setToT(int d) { - //int ret=0; - int reg; + //int ret=0; + int reg; #ifdef VERBOSE - printf("Setting ToT to %d\n",d); + printf("Setting ToT to %d\n",d); #endif - reg=bus_r(CONFIG_REG); + reg=bus_r(CONFIG_REG); #ifdef VERBOSE - printf("Before: ToT is %x\n", reg); + 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); + 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); + printf("ToT is %x\n", reg); #endif - if (reg&TOT_ENABLE_BIT) - return 1; - else - return 0; + if (reg&TOT_ENABLE_BIT) + return 1; + else + return 0; } int setContinousReadOut(int d) { - //int ret=0; - int reg; + //int ret=0; + int reg; #ifdef VERBOSE - printf("Setting Continous readout to %d\n",d); + printf("Setting Continous readout to %d\n",d); #endif - reg=bus_r(CONFIG_REG); + reg=bus_r(CONFIG_REG); #ifdef VERBOSE - printf("Before: Continous readout is %x\n", reg); + 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); + 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); + printf("Continous readout is %x\n", reg); #endif - if (reg&CONT_RO_ENABLE_BIT) - return 1; - else - return 0; + if (reg&CONT_RO_ENABLE_BIT) + return 1; + else + return 0; } +<<<<<<< HEAD int startReceiver(int start) { u_int32_t addr=CONFIG_REG; //#ifdef VERBOSE @@ -1052,6 +1058,8 @@ int startReceiver(int start) { else return FAIL; } +======= +>>>>>>> f24459bee05f373e2830bb24388e40f0b2983d5a u_int64_t getDetectorNumber() { @@ -1072,232 +1080,212 @@ u_int64_t getDetectorNumber() { } u_int32_t getFirmwareVersion() { - return bus_r(FPGA_VERSION_REG); + return bus_r(FPGA_VERSION_REG); } u_int32_t getFirmwareSVNVersion(){ - return bus_r(FPGA_SVN_REG); + 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; - } + 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; + //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; } -// for fpga test u_int32_t testRAM(void) { - int result=OK; - - printf("TestRAM not implemented\n"); - -/* int i=0; - allocateRAM(); - // while(i<100000) { - memcpy(ram_values, values, dataBytes); - printf ("Testing RAM:\t%d: copied fifo %x to memory %x size %d\n",i++, (unsigned int)(values), (unsigned int)(ram_values), dataBytes); - // } - * -*/ - return result; + int result=OK; + printf("TestRAM not implemented\n"); + return result; } int getNModBoard() { -if(myDetectorType == JUNGFRAU) return 1; -else - return 32;//nModX; } int setNMod(int n) { - -/* printf("Writin ADC disable register %08x\n",n); */ -/* bus_w(ADC_LATCH_DISABLE_REG,n); */ - return getNMod(); + return 1; } int getNMod() { -/* u_int32_t reg; */ -/* int i; */ -/* reg=bus_r(ADC_LATCH_DISABLE_REG); */ - -/* printf("Read ADC disable register %08x\n",reg); */ -/* nModX=32; */ -/* for (i=0; i<32; i++) { */ -/* if (reg & (1<> 32; - vMSB=v64&(0xffffffff); - bus_w(aMSB,vMSB); - } - return get64BitReg(aLSB, 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; + 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); + printf("reg64(%x,%x) %x %x %llx\n", aLSB, aMSB, vLSB, vMSB, v64); - return v64; + return v64; } int64_t setFrames(int64_t value){ - return set64BitReg(value, SET_FRAMES_LSB_REG, SET_FRAMES_MSB_REG); + 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(){ - /*printf("gf");*/ - return get64BitReg(GET_FRAMES_LSB_REG, GET_FRAMES_MSB_REG); + return get64BitReg(GET_FRAMES_LSB_REG, GET_FRAMES_MSB_REG); } int64_t setExposureTime(int64_t value){ - /* time is in ns */ - if (value!=-1) - value*=(1E-3*clkDivider[0]);//(1E-9*CLK_FREQ); - return set64BitReg(value,SET_EXPTIME_LSB_REG, SET_EXPTIME_MSB_REG)/(1E-3*clkDivider[0]);//(1E-9*CLK_FREQ); + if (value!=-1){ + printf("\nSetting exptime to %lldns\n",(long long int)value); + value*=(1E-3*clockdivider); + } + int64_t retval = set64BitReg(value,SET_EXPTIME_LSB_REG, SET_EXPTIME_MSB_REG)/(1E-3*clockdivider);//(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*clkDivider[0]);//(1E-9*CLK_FREQ); + return get64BitReg(GET_EXPTIME_LSB_REG, GET_EXPTIME_MSB_REG)/(1E-3*clockdivider);//(1E-9*CLK_FREQ); } int64_t setGates(int64_t value){ - return set64BitReg(value, SET_GATES_LSB_REG, SET_GATES_MSB_REG); + 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); + return get64BitReg(GET_GATES_LSB_REG, GET_GATES_MSB_REG); } int64_t setPeriod(int64_t value){ - /* time is in ns */ - if (value!=-1) { - // value*=(1E-9*CLK_FREQ); - value*=(1E-3*clkDivider[1]); - } - if (value%2==0) { - - printf("Adding one to period: was %08llx ", value); - value+=1; - printf("now is %08llx\n ", value); + if (value!=-1){ + printf("\nSetting period to %lldns\n",(long long int)value); + value*=(1E-3*clockdivider); + } - - } else - printf("Period already even is %08llx\n ", value); - - - return set64BitReg(value,SET_PERIOD_LSB_REG, SET_PERIOD_MSB_REG)/(1E-3*clkDivider[0]);//(1E-9*CLK_FREQ); + int64_t retval = set64BitReg(value,SET_PERIOD_LSB_REG, SET_PERIOD_MSB_REG)/(1E-3*clockdivider);//(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*clkDivider[0]);//(1E-9*CLK_FREQ); + return get64BitReg(GET_PERIOD_LSB_REG, GET_PERIOD_MSB_REG)/(1E-3*clockdivider);//(1E-9*CLK_FREQ); } int64_t setDelay(int64_t value){ - /* time is in ns */ - if (value!=-1) { - value*=(1E-3*clkDivider[1]);//(1E-9*CLK_FREQ); - } - return set64BitReg(value,SET_DELAY_LSB_REG, SET_DELAY_MSB_REG)/(1E-3*clkDivider[0]);//(1E-9*CLK_FREQ); + if (value!=-1){ + printf("\nSetting delay to %lldns\n",(long long int)value); + value*=(1E-3*clockdivider); + } + + int64_t retval = set64BitReg(value,SET_DELAY_LSB_REG, SET_DELAY_MSB_REG)/(1E-3*clockdivider);//(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*clkDivider[0]);//(1E-9*CLK_FREQ); + return get64BitReg(GET_DELAY_LSB_REG, GET_DELAY_MSB_REG)/(1E-3*clockdivider);//(1E-9*CLK_FREQ); } int64_t setTrains(int64_t value){ - return set64BitReg(value, SET_CYCLES_LSB_REG, SET_CYCLES_MSB_REG); + 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); + return get64BitReg(GET_CYCLES_LSB_REG, GET_CYCLES_MSB_REG); } @@ -1313,15 +1301,12 @@ int64_t getSamples(){ int64_t setProbes(int64_t value){ - return 0; + return 0; } int64_t setProgress() { - - //????? eventually call after setting the registers - -return 0; + return 0; } @@ -1329,323 +1314,240 @@ return 0; int64_t getProgress() { - //should be done in firmware!!!! + //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); + 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); - // int64_t mask=0x8000000000000000; - // if (v & mask ) { - //#ifdef VERBOSE - // printf("no measurement time left\n"); - //#endif - // return -1E+9; - // } else - return v/(1E-9*CLK_FREQ); + 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); + 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); + printf("Frames from start data streaming %lld\n",v); + printf("Frames from start run control %lld\n",v1); - // int64_t mask=0x8000000000000000; - // if (v & mask ) { - //#ifdef VERBOSE - // printf("no measurement time left\n"); - //#endif - // return -1E+9; - // } else - return v; + return v; } ROI *setROI(int nroi,ROI* arg,int *retvalsize, int *ret) { - - if(myDetectorType == JUNGFRAU) - cprintf(RED,"ROI Not implemented for Jungfrau yet\n"); - return NULL; - - - ROI retval[MAX_ROIS]; - int i, ich; - adcDisableMask=0xfffffffff; /*warning: integer constant is too large for ‘long’ type,warning: large integer implicitly truncated to unsigned type*/ - - printf("Setting ROI\n"); - if (nroi>=0) { - if (nroi==0) { - adcDisableMask=0; - } else { - for (i=0; i=0 && ichMAX_ROIS) { - *retvalsize-=1; - break; - } - retval[*retvalsize-1].xmin=ich; - retval[*retvalsize-1].xmax=ich; - } else { - if ((adcDisableMask)&(1<<(ich-1))) { - *retvalsize+=1; - if (*retvalsize>MAX_ROIS) { - *retvalsize-=1; - break; - } - retval[*retvalsize-1].xmin=ich; - } - retval[*retvalsize-1].xmax=ich; - } - } - } - getDynamicRange(); - return retval;/*warning: function returns address of local variable*/ - + cprintf(RED,"ROI Not implemented yet\n"); + return NULL; } int loadImage(int index, short int ImageVals[]){ - printf("loadImage Not implemented yet\n"); - - /* - u_int32_t address; - switch (index) { - case DARK_IMAGE : - address = DARK_IMAGE_REG; - break; - case GAIN_IMAGE : - address = GAIN_IMAGE_REG; - break; - } - volatile u_int16_t *ptr; - ptr=(u_int16_t*)(CSP0BASE+address*2); -#ifdef VERBOSE - int i; - for(i=0;i<6;i++) - printf("%d:%d\t",i,ImageVals[i]); -#endif - memcpy(ptr,ImageVals ,dataBytes); -#ifdef VERBOSE - printf("\nLoaded x%08x address with image of index %d\n",(unsigned int)(ptr),index); -#endif - */ - return OK; } int64_t getProbes(){ - return 0; + return 0; } int setDACRegister(int idac, int val, int imod) { - u_int32_t addr, reg, mask; - int off; + 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); + 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; + 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; + if (val>=0 && val>off)&0x3ff; + //since we saved only the msb + val=val<<2; - //val=(bus_r(addr)>>off)&0x3ff; + //val=(bus_r(addr)>>off)&0x3ff; #ifdef VERBOSE - printf("Dac %d module %d register is %d\n\n",idac,imod,val); + printf("Dac %d module %d register is %d\n\n",idac,imod,val); #endif - return val; + 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; + 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); + 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 + 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 - } - } + if(i<=10){//only the first time + if(!tempSensor) + tempVal= (tempVal<<1) + (bus_r(TEMP_OUT_REG) & (1));//adc + else + tempVal= (tempVal<<1) + ((bus_r(TEMP_OUT_REG) & (2))>>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; + 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); + printf("Temperature of module:%d for the %s is %.2fC\n",imod,cTempSensor[tempSensor],val); #endif - return val; + return val; } int initHighVoltage(int val, int imod){ - - u_int32_t offw,codata; - u_int16_t valw, dacvalue; - int iru,i,ddx,csdx,cdx; - float alpha=0.55, fval=val; - 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); - + u_int32_t offw,codata; + u_int16_t valw, dacvalue; + int i,ddx,csdx,cdx; + float alpha=0.55; - - - valw=0xffff; bus_w(offw,(valw)); // start point - valw=((valw&(~(0x1<>(7-i))&0x1)<=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; - - valw=0xffff; bus_w(offw,(valw)); // stop point =start point of course */ - - - printf("Writing %d in HVDAC \n",dacvalue); - - bus_w(HV_REG,val); - } + ddx=8; csdx=10; cdx=9; + codata=((dacvalue)&0xff); - return bus_r(HV_REG); + + 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; @@ -1655,36 +1557,14 @@ int setADC(int adc){ // setDAQRegister();//token timing cleanFifo();//adc sync - //with gotthard module - if(withGotthard){ - //set packet size - ipPacketSize= DEFAULT_IP_PACKETSIZE; - udpPacketSize=DEFAULT_UDP_PACKETSIZE; - //set channel mask - nchips = GOTTHARDNCHIP; - nchans = GOTTHARDNCHAN; - mask = ACTIVE_ADC_MASK; - } - //with moench module all adc - else{/* if(adc==-1){*/ - //set packet size - ipPacketSize= DEFAULT_IP_PACKETSIZE; - udpPacketSize=DEFAULT_UDP_PACKETSIZE; - //set channel mask - nchips = N_CHIP; - nchans = N_CHANS; - mask = ACTIVE_ADC_MASK; - }/* - //with moench module 1 adc -- NOT IMPLEMENTED - else{ - ipPacketSize= ADC1_IP_PACKETSIZE; - udpPacketSize=ADC1_UDP_PACKETSIZE; - //set channel mask - nchips = NCHIPS_PER_ADC; - nchans = GOTTHARDNCHAN; - mask = 1< 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; + 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); + printf("IP checksum is 0x%lx\n",checksum); - return 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; + /*volatile u_int32_t conf= bus_r(CONFIG_REG);*/ + long int checksum=calcChecksum(sourceip, destip); +#ifdef NEW_GBE_INTERFACE + + printf("Configure interface %d\n",interface); + const int nvar=12; + uint32_t vals[nvar]; + int ivar; + int addr=0; + vals[RX_UDP_IP_ADDR]=destip; + vals[RX_UDP_PORTS_ADDR]=destport; + vals[RX_UDP_MAC_L_ADDR]=(destmac)&0xFFFFFFFF; + vals[RX_UDP_MAC_H_ADDR]=(destmac>>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 + bus_w(RX_UDPMACH_AREG,(destmac>>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); - sleep(1); - bus_w(CONTROL_REG,0); - usleep(10000); - 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); + //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)); -return 0; //any value doesnt matter - dhanya + + /* + 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 } @@ -1828,35 +1727,30 @@ 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){ - - uint32_t sourceport = 0x7e9a; // 0xE185; - int interface=0; - int ngb; -volatile u_int32_t conf= bus_r(CONFIG_REG); + //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"); + ngb=2; + printf("--------- New XGB interface\n"); #else - ngb=1; - printf("********* Old XGB interface\n"); + ngb=1; + printf("********* Old XGB interface\n"); #endif - for (interface=0; interface >>>>>> f24459bee05f373e2830bb24388e40f0b2983d5a } -u_int16_t* fifo_read_frame() -{ -#ifdef TIMEDBG - gettimeofday(&tsss,NULL); -#endif - - // u_int16_t *dum; - int ns=0; - now_ptr=(char*)ram_values; - while(ns>(ipos))&0x1; - ichan++; - } - } - break; - case 4: - for (ibyte=0; ibyte>(ipos*4))&0xf; - ichan++; - } - } - break; - case 8: - for (ichan=0; ichan>(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; @@ -2277,14 +2085,14 @@ int setDynamicRange(int dr) { 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; @@ -2294,245 +2102,164 @@ int getDynamicRange() { 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; + 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 allocateRAM(); + if (b>0) + storeInRAM=1; + else + storeInRAM=0; + return OK; } int getChannels() { - int nch=32; - int i; - for (i=0; i1) { - - clearRAM(); - ram_values=malloc(size); - // ram_values=realloc(ram_values,size)+2; - // if (ram_values) - // break; - // nSamples--; - //} - - if (ram_values) { - now_ptr=(char*)ram_values; - - //#ifdef VERBOSE - printf("ram allocated 0x%x of size %d to %x\n",(int)now_ptr,(unsigned int) size,(unsigned int)(now_ptr+size)); - //#endif - ram_size=size; - return OK; - } - - - printf("Fatal error: there must be a memory leak somewhere! You can't allocate even one frame!\n"); - return FAIL; - - - - + return OK; } int writeADC(int addr, int val) { - u_int32_t valw,codata,csmask; - int i,cdx,ddx; - cdx=0; ddx=1; - csmask=0xfc; // 1111100 - - codata=val + (addr<< 8); - printf("***** ADC SPI WRITE TO REGISTER %04X value %04X\n",addr,val); + u_int32_t valw,codata,csmask; + int i,cdx,ddx; + cdx=0; ddx=1; + csmask=0xfc; // 1111100 + + codata=val + (addr<< 8); + printf("***** ADC SPI WRITE TO REGISTER %04X value %04X\n",addr,val); // start point - valw=0xff; - bus_w16(ADC_WRITE_REG,(valw)); - - //chip sel bar down - valw=((0xffffffff&(~csmask))); - bus_w16(ADC_WRITE_REG,valw); + valw=0xff; + bus_w16(ADC_WRITE_REG,(valw)); - for (i=0;i<24;i++) { - //cldwn - valw=valw&(~(0x1<>(23-i))&0x1)<>(23-i))&0x1)<> 8); - // printf("%i: %i %i\n",a, frame[a],v); - avg[a] += ((double)frame[a])/(double)frames; - //if(frame[a] == 8191) - // printf("ch %i: %u\n",a,frame[a]); - } - // printf("********\n"); - numberFrames++; - } - - //no more data or no data - else { - if(getFrames()>-2) { - dataret=FAIL; - printf("no data and run stopped: %d frames left\n",(int)(getFrames()+2)); - - } else { - dataret=FINISHED; - printf("acquisition successfully finished\n"); - - } - printf("dataret %d\n",dataret); - } - } - - - - //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)); - } - } - - /*for(adc = 1; adc < 5; adc++){ - for(adcCh = 0; adcCh < 8; adcCh++){ - for(Ch=0 ; Ch < 32; Ch++){ - int channel = (adc+1) * 32 * 8 + adcCh * 32 + Ch; - double v2 = avg[channel]; - avg[channel] = avg[channel]/ ((double)numberFrames/(double)frames); - unsigned short v = (unsigned short)avg[channel]; - printf("setting avg for channel %i: %i (double= %f (%f))\t", channel, v,avg[channel],v2); - 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)); + avg[i] = 0.0; + } + + startStateMachine(); + + while(dataret==OK){ + //got data + waitForAcquisitionEnd(); + if (getFrames()>-2) { + dataret=FAIL; + printf("no data and run stopped: %d frames left\n",(int)(getFrames()+2)); + } else { + dataret=FINISHED; + printf("acquisition successfully finished\n"); + } } - } - } - }*/ - 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; + //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 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); + int cntrl=0; + if (addr>=MAX_PATTERN_LENGTH) + return -1; - - 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); + 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) { - if (word!=0xffffffffffffffff) { /*warning: integer constant is too large for ‘long’ type*/ - // printf("%llx %llx %lld",get64BitReg(PATTERN_IOCTRL_REG_LSB,PATTERN_IOCTRL_REG_MSB),word); - set64BitReg(word,PATTERN_IOCTRL_REG_LSB,PATTERN_IOCTRL_REG_MSB); - // printf("************ write IOCTRL (%x)\n",PATTERN_IOCTRL_REG_MSB); - } - return get64BitReg(PATTERN_IOCTRL_REG_LSB,PATTERN_IOCTRL_REG_MSB); - + return FAIL; } + uint64_t writePatternClkControl(uint64_t word) { - if (word!=0xffffffffffffffff) set64BitReg(word,PATTERN_IOCLKCTRL_REG_LSB,PATTERN_IOCLKCTRL_REG_MSB);/*warning: integer constant is too large for ‘long’ type*/ - return get64BitReg(PATTERN_IOCLKCTRL_REG_LSB,PATTERN_IOCLKCTRL_REG_MSB); - + return FAIL; } int setPatternLoop(int level, int *start, int *stop, int *n) { - int ret=OK; - int lval=0; + int ret=OK; + int lval=0; - int nreg; - int areg; + 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; - } + 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); + 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("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); + printf("lval %x\n",lval); + if (*start==-1) *start=(lval>> ASTART_OFFSET) & APATTERN_MASK; + printf("start %x\n",*start); - return ret; + 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; +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); + 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 ("%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); + // printf("AFTER *********PATTERN IOCTRL IS %llx (%x)\n",writePatternIOControl(-1), PATTERN_IOCTRL_REG_MSB); - return bus_r(reg); + return bus_r(reg); } -uint64_t setPatternWaitTime(int level, uint64_t t) { - int reglsb; - int regmsb; +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; - } + 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); + 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; - 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; + //setting int reference + offw=DAC_REG; - printf("data bit=%d, clkbit=%d, csbit=%d",ddx,cdx,csdx); - codata=((((0x6)<<4)+((0xf))<<16)+((0x0<<4)&0xfff0)); /*warning: suggest parentheses around + or - inside shift*/ - - 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<>16)&0xffff; + else + return retval&0xffff; - retval=bus_r((DAC_REG_OFF+dacnum/2)<<11); - printf("Dac register %x read %08x\n",(DAC_REG_OFF+dacnum/2)<<11,retval); - if (dacnum%2) - return (retval>>16)&0xffff; - else - return retval&0xffff; - } -int setDac(int dacnum,int dacvalue){ +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; + u_int32_t offw,codata; + u_int16_t valw; + int i,ddx,csdx,cdx; - int dacch=0; + int dacch=0; - if (dacvalue>=0) { - - //setting int reference - offw=DAC_REG; - - - ddx=0; cdx=1; - csdx=dacnum/8+2; + if (dacvalue>=0) { - dacch=dacnum%8; - - printf("data bit=%d, clkbit=%d, csbit=%d",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<>(24-i))&0x1)<>(24-i))&0x1)); + valw=((valw&(~(0x1<>(24-i))&0x1)<>(24-i))&0x1)); - - - valw=((valw&(~(0x1<dacs=detectorDacs+imod*N_DAC; - (detectorModules+imod)->adcs=detectorAdcs+imod*N_ADC; - if(myDetectorType != JUNGFRAU){ - (detectorModules+imod)->chipregs=detectorChips+imod*N_CHIP; - (detectorModules+imod)->chanregs=detectorChans+imod*N_CHIP*N_CHAN; - } - (detectorModules+imod)->ndac=N_DAC; - (detectorModules+imod)->nadc=N_ADC; - (detectorModules+imod)->nchip=N_CHIP; - (detectorModules+imod)->nchan=N_CHIP*N_CHAN; + (detectorModules+imod)->dacs=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; - /* initialize registers, dacs, retrieve sn, adc values etc */ } thisSettings=UNINITIALIZED; sChan=noneSelected; @@ -122,24 +75,6 @@ int initDetector() { sMod=noneSelected; sDac=noneSelected; sAdc=noneSelected; - - /* - setCSregister(ALLMOD); //commented out by dhanya - setSSregister(ALLMOD); - counterClear(ALLMOD); - clearSSregister(ALLMOD); - putout("0000000000000000",ALLMOD); - */ - - /* initialize dynamic range etc. */ - /* dynamicRange=getDynamicRange(); //always 16 not required commented out - nModX=setNMod(-1);*/ - - // dynamicRange=32; - // initChip(0, 0,ALLMOD); - //nModX=n; - // - allocateRAM(); return OK; } @@ -178,7 +113,7 @@ int copyChip(sls_detector_chip *destChip, sls_detector_chip *srcChip) { int copyModule(sls_detector_module *destMod, sls_detector_module *srcMod) { - int ichip, idac, ichan, iadc; + int idac, iadc; int ret=OK; @@ -198,6 +133,8 @@ int copyModule(sls_detector_module *destMod, sls_detector_module *srcMod) { /* #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; @@ -206,6 +143,8 @@ int copyModule(sls_detector_module *destMod, sls_detector_module *srcMod) { 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; @@ -218,8 +157,8 @@ int copyModule(sls_detector_module *destMod, sls_detector_module *srcMod) { #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); + //printf("Chips: src %d, dest %d\n",srcMod->nchip,destMod->nchip); + //printf("Chans: src %d, dest %d\n",srcMod->nchan,destMod->nchan); #endif @@ -227,8 +166,8 @@ int copyModule(sls_detector_module *destMod, sls_detector_module *srcMod) { destMod->ndac=srcMod->ndac; destMod->nadc=srcMod->nadc; - destMod->nchip=srcMod->nchip; - destMod->nchan=srcMod->nchan; + // destMod->nchip=srcMod->nchip; + //destMod->nchan=srcMod->nchan; if (srcMod->reg>=0) destMod->reg=srcMod->reg; #ifdef VERBOSE @@ -240,17 +179,7 @@ int copyModule(sls_detector_module *destMod, sls_detector_module *srcMod) { destMod->offset=srcMod->offset; // printf("copying gain and offset %f %f to %f %f\n",srcMod->gain,srcMod->offset,destMod->gain,destMod->offset); - - if(myDetectorType != JUNGFRAU){ - 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) @@ -267,52 +196,6 @@ int copyModule(sls_detector_module *destMod, sls_detector_module *srcMod) { -/* Register commands */ - - -/* int clearDACSregister(int imod) { */ - -/* putout("1111111111111111",imod);//reset */ -/* putout("1111111111111110",imod);//cs down */ - -/* /\* commented out by dhanya */ -/* putout("0000000001000000",imod); */ -/* putout("0000000101000000",imod); */ -/* putout("0000000101000000",imod); */ -/* putout("0000000001000000",imod); */ -/* *\/ */ -/* #ifdef DEBUG */ -/* fprintf(stdout, "Clearing DAC shiftregister\n"); */ -/* #endif */ -/* // sDac=0; */ -/* sMod=imod; */ -/* if (imod==ALLMOD) */ -/* sMod=allSelected; */ -/* return OK; */ -/* } */ - -/* int nextDAC(int imod) { */ - -/* putout("1111111111111011",imod);//cs up */ -/* putout("1111111111111001",imod);//clk down */ -/* putout("1111111111111111",imod);//reset */ - -/* /\*commented out by dhanya */ -/* putout("0000000001000000",imod); */ -/* putout("0000000001001000",imod); */ -/* putout("0000000001000000",imod); */ -/* *\/ */ -/* #ifdef DEBUG */ -/* fprintf(stdout, "Next DAC\n"); */ -/* #endif */ -/* // sDac++; */ -/* sMod=imod; */ -/* if (imod==ALLMOD) */ -/* sMod=allSelected; */ -/* return OK; */ -/* } */ - - int clearCSregister(int imod) { putout("0000000001000000",imod); @@ -461,322 +344,6 @@ int selChip(const int chip,int imod) { return 0; } -/* DACs routines */ - -/* int program_one_dac(int addr, int value, int imod) { */ - -/* #ifdef VERBOSE */ -/* printf("programming dac %d value %d module %d\n",addr, value,imod); */ -/* #endif */ - - -/* int i,im,idac,bit, control; */ -/* int v=value; */ - -/* // codata=((((0x2)<<4)+((addr)&0xf))<<16)+((value<<4)&0xfff0); */ -/* control=32+addr; */ -/* value=(value<<4) | (control<< 16); */ - -/* #ifdef DEBUGOUT */ -/* fprintf(stdout,"value=%d\n",value); */ -/* #endif */ - -/* for (i=0;i<24;i++) { */ -/* bit=value & (1<<(23-i)); */ -/* if (bit) { */ -/* putout("1111111111111100",imod);//clk down */ -/* putout("1111111111111100",imod);//write data */ -/* putout("1111111111111110",imod);//clk up */ -/* #ifdef DEBUGOUT */ -/* fprintf(stdout,"1"); */ -/* #endif */ -/* } */ -/* else */ -/* { */ -/* putout("1111111111111000",imod);//clk down */ -/* putout("1111111111111000",imod);//write data */ -/* putout("1111111111111010",imod);//clk up */ -/* #ifdef DEBUGOUT */ -/* fprintf(stdout,"0"); */ -/* #endif */ -/* } */ -/* } */ - -/* #ifdef DEBUGOUT */ -/* fprintf(stdout,"\n"); */ -/* #endif */ - -/* idac=addr;//sDac*2+addr; */ - - -/* if (detectorDacs) { */ -/* sMod=imod; */ -/* if (imod==ALLMOD) */ -/* sMod=allSelected; */ - -/* if (imod>=0 && imod=0) */ -/* initDAC(ind,val, imod); */ - -/* if (imod>=0 && imodgain,(detectorModules+imod)->offset); */ -/* #endif */ -/* if ((detectorModules+imod)->gain>0) */ -/* myg=(detectorModules+imod)->gain; */ -/* else { */ -/* if (thisSettings>=0 && thisSettings<3) */ -/* myg=g[thisSettings]; */ -/* // else */ -/* //myg=-1; */ -/* } */ - -/* if ((detectorModules+imod)->offset>0) */ -/* myo=(detectorModules+imod)->offset; */ -/* else { */ -/* if (thisSettings>=0 && thisSettings<3) */ -/* myo=o[thisSettings]; */ -/* // else */ -/* //myo=-1; */ -/* } */ - -/* if (myg>0 && myo>0) { */ -/* //ethr=(myo-detectorDacs[VTHRESH+imod*N_DAC])*1000/myg; */ - -/* ethr=(myo-setDACRegister(VDAC0,-1,imod))*1000/myg;//edited by dhanya */ -/* // else */ -/* // ethr=-1; */ - -/* } */ -/* #ifdef VERBOSE */ -/* //printf("module=%d gain=%f, offset=%f, dacu=%f\n",imod, myg, myo, detectorDacs[VTHRESH+imod*N_DAC]); */ -/* printf("module=%d gain=%f, offset=%f, dacu=%d\n",imod, myg, myo,(int)(setDACRegister(VDAC0,-1,imod)));//edited by dhanya */ -/* printf("Threshold energy of module %d is %d eV\n", imod, ethr); */ -/* #endif */ - -/* if (imod==0) */ -/* ret=ethr; */ -/* else { */ -/* if (ethr>(ret+100) || ethr<(ret-100)) */ -/* return FAIL; */ -/* } */ -/* } */ -/* } */ -/* return ret; */ -/* } */ - -/* int setThresholdEnergy(int ethr) { */ -/* double g[3]=DEFAULTGAIN; */ -/* double o[3]=DEFAULTOFFSET; */ -/* double myg=-1, myo=-1; */ -/* int dacu; */ -/* int imod; */ -/* int ret=ethr; */ - -/* setSettings(GET_SETTINGS,-1);//-1 added by dhanya */ -/* if (thisSettings>=0 || thisSettings<3){ */ -/* myg=g[thisSettings]; */ -/* myo=o[thisSettings]; */ -/* } */ -/* for (imod=0; imodgain>0) */ -/* myg=(detectorModules+imod)->gain; */ -/* else */ -/* if (thisSettings>=0 && thisSettings<3) */ -/* myg=g[thisSettings]; */ -/* else */ -/* myg=-1; */ -/* if ((detectorModules+imod)->offset>0) */ -/* myo=(detectorModules+imod)->offset; */ -/* else */ -/* if (thisSettings>=0 && thisSettings<3) */ -/* myo=o[thisSettings]; */ -/* else */ -/* myo=-1; */ -/* } else { */ -/* if (thisSettings>=0 && thisSettings<3) */ -/* myo=o[thisSettings]; */ -/* else */ -/* myo=-1; */ -/* if (thisSettings>=0 && thisSettings<3) */ -/* myg=g[thisSettings]; */ -/* else */ -/* myg=-1; */ -/* } */ -/* if (myg>0 && myo>0) { */ -/* dacu=myo-myg*((double)ethr)/1000.; */ -/* #ifdef VERBOSE */ -/* printf("module %d (%x): gain %f, off %f, energy %d eV, dac %d\n",imod,(unsigned int)((detectorModules+imod)),(detectorModules+imod)->gain,(detectorModules+imod)->offset, ethr,dacu); */ -/* #endif */ -/* } else { */ -/* dacu=ethr; */ -/* #ifdef VERBOSE */ -/* printf("could not set threshold energy for module %d, settings %d (offset is %f; gain is %f)\n",imod,thisSettings,myo,myg); */ -/* #endif */ -/* } */ -/* initDACbyIndexDACU(VDAC0, dacu, imod); ///needs to be fixed dhanya */ -/* } */ -/* return ret; */ -/* } */ - - - -/* int getDACbyIndexDACU(int ind, int imod) { */ -/* /\* */ -/* if (detectorDacs) { */ -/* if (imodndac) */ -/* return (detectorDacs[ind+imod*N_DAC]); */ -/* } */ -/* return FAIL; */ -/* *\/ */ -/* return setDACRegister(ind, -1, imod); */ -/* } */ - - -/* int initDAC(int dac_addr, int value, int imod) { */ -/* // int i; */ -/* #ifdef VERBOSE */ -/* printf("Programming dac %d with value %d\n", dac_addr, value); */ -/* #endif */ -/* clearDACSregister(imod); */ -/* program_one_dac(dac_addr,value,imod); */ -/* nextDAC(imod); */ -/* clearDACSregister(imod); */ - -/* return 0; */ -/* } */ int getTemperatureByModule(int tempSensor, int imod) { @@ -846,42 +413,12 @@ void showbits(int h) } -/* int initDACs(int* v,int imod) */ -/* { */ -/* #ifdef VERBOSE */ -/* printf("\n..inside initdacs\n"); */ -/* #endif */ -/* int iaddr; */ -/* // sDac=0; */ - -/* for (iaddr=0; iaddr<8; iaddr++) { */ -/* clearDACSregister(imod); */ -/* if (v[iaddr]>=0) { */ -/* #ifdef VERBOSE */ -/* fprintf(stdout, "voltage %d\n", *(v+iaddr)); */ -/* #endif */ -/* program_one_dac(iaddr, *(v+iaddr),imod); */ -/* } */ -/* nextDAC(imod); */ -/* } */ - - -/* clearDACSregister(imod); */ - -/* return 0; */ - -/* } */ - - - int setSettings(int i, int imod) { -#ifdef VERBOSE - if(i==-1) - printf("\nReading settings of detector...\n"); - else - printf("\ninside set settings wit settings=%d...\n",i); -#endif +//#ifdef VERBOSE + if(i!=-1) + printf("\nSetting settings wit value %d\n",i); +//#endif int isett=-1,val=-1,retval=-1; enum conf_gain { dynamic = 0x0f00, //dynamic @@ -978,7 +515,7 @@ int getChannelbyNumber(sls_detector_channel* myChan) { if (detectorChans) { if (imod=0) { if (ichip<(detectorModules+imod)->nchip && ichan<(detectorModules+imod)->nchan/(detectorModules+imod)->nchip) - myChan->reg=detectorChans[imod*N_CHAN*N_CHIP+ichip*N_CHAN+ichan]; + myChan->reg=detectorChans[imod*NCHAN*NCHIP+ichip*NCHAN+ichan]; return OK; } } @@ -990,7 +527,7 @@ 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*N_CHAN*N_CHIP+ichip*N_CHAN+ichan] & TRIM_DR); + return (detectorChans[imod*NCHAN*NCHIP+ichip*NCHAN+ichan] & TRIM_DR); } return -1; @@ -1014,8 +551,8 @@ int initChannel(int ft,int cae, int ae, int coe, int ocoe, int counts, int imod) if (sChan==allSelected) { // printf("initializing all channels ft=%d coe=%d\n",ft,coe); chanmi=0; - chanma=N_CHAN; - } else if (sChan==noneSelected || sChan>N_CHAN || sChan<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; @@ -1028,8 +565,8 @@ int initChannel(int ft,int cae, int ae, int coe, int ocoe, int counts, int imod) if (sChip==allSelected) { // printf("initializing all chips\n"); chipmi=0; - chipma=N_CHIP; - } else if (sChip==noneSelected || sChip>N_CHIP || sChip<0) { + chipma=NCHIP; + } else if (sChip==noneSelected || sChip>NCHIP || sChip<0) { // printf("initializing no chips\n"); chipmi=0; chipma=-1; @@ -1057,12 +594,12 @@ int initChannel(int ft,int cae, int ae, int coe, int ocoe, int counts, int imod) for (ichip=chipmi; ichipnchip) { - myChip->reg=detectorChips[ichip+imod*N_CHIP]; - myChip->nchan=N_CHAN; - myChip->chanregs=detectorChans+imod*N_CHAN*N_CHIP+ichip*N_CHIP; + myChip->reg=detectorChips[ichip+imod*NCHIP]; + myChip->nchan=NCHAN; + myChip->chanregs=detectorChans+imod*NCHAN*NCHIP+ichip*NCHIP; return OK; } } @@ -1278,28 +815,7 @@ int initChip(int obe, int ow,int imod){ int i; int im, ichip; int chipmi, chipma, modmi, modma; - /* switch (ow) { - case 0:; - case 1: - setDynamicRange(32); - break; - case 2: - setDynamicRange(16); - break; - case 3: - setDynamicRange(8); - break; - case 4: - setDynamicRange(4); - break; - case 5: - setDynamicRange(1); - break; - default: - setDynamicRange(32); - break; - } - */ + #ifdef DEBUGOUT printf("Initializing chip\n"); @@ -1370,8 +886,8 @@ int initChip(int obe, int ow,int imod){ if (sChip==allSelected) { chipmi=0; - chipma=N_CHIP; - } else if (sChip==noneSelected || sChip>N_CHIP || sChip<0) { + chipma=NCHIP; + } else if (sChip==noneSelected || sChip>NCHIP || sChip<0) { chipmi=0; chipma=-1; } else { @@ -1395,9 +911,9 @@ int initChip(int obe, int ow,int imod){ for (im=modmi; imN_CHIP || sChip<0) { + chipma=NCHIP; + } else if (sChip==noneSelected || sChip>NCHIP || sChip<0) { chipmi=0; chipma=-1; } else { @@ -1495,9 +1011,9 @@ int initChipWithProbes(int obe, int ow,int nprobes, int imod){ for (im=modmi; im0 && 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++; @@ -1978,7 +1464,7 @@ int testShiftStSel(int imod) { int testDataInOut(int num, int imod) { - int val[N_CHIP*nModX], result=OK; + int val[NCHIP*nModX], result=OK; int ich, ichip; setCSregister(ALLMOD); printf("Testing data in out for module %d pattern 0x%x\n", imod, num); @@ -1988,14 +1474,14 @@ int testDataInOut(int num, int imod) { setCSregister(ALLMOD); initChip(0, 0,ALLMOD); clearSSregister(ALLMOD); - for (ich=0; ich=0){ */ - -/* //clear rois */ -/* for(i=0;i=0) && (adc<=4)); */ -/* else { */ -/* printf("warning:adc value greater than 5. deleting roi\n"); */ -/* adc=-1; */ -/* } */ -/* } */ -/* } */ - - -/* //set rois for just 1 adc - take only 1st roi */ -/* if(adc!=-1){ */ -/* rois[0].xmin=adc*(GOTTHARDNCHAN*NCHIPS_PER_ADC); */ -/* rois[0].xmax=(adc+1)*(GOTTHARDNCHAN*NCHIPS_PER_ADC)-1; */ -/* rois[0].ymin=-1; */ -/* rois[0].ymax=-1; */ -/* nROI = 1; */ -/* }else */ -/* nROI = 0; */ - -/* if((arg[0].xmin!=rois[0].xmin)||(arg[0].xmax!=rois[0].xmax)||(arg[0].ymin!=rois[0].ymin)||(arg[0].ymax!=rois[0].ymax)) */ -/* *ret=FAIL; */ -/* if(n!=nROI) */ -/* *ret=FAIL; */ - -/* //set adc of interest */ -/* setADC(adc); */ -/* } */ - -/* //#ifdef VERBOSE */ -/* printf("Rois:\n"); */ -/* for( i=0;i>DETECTOR_TYPE_OFFSET) { - case MOENCH03_MODULE_ID: - myDetectorType=MOENCH; - printf("This is a MOENCH03 module %d\n",MOENCH); - break; - - case JUNGFRAU_MODULE_ID: - myDetectorType=JUNGFRAU; - printf("This is a Jungfrau module %d\n", JUNGFRAU); - break; - - case JUNGFRAU_CTB_ID: - myDetectorType=JUNGFRAUCTB; - printf("This is a Jungfrau CTB %d\n", JUNGFRAUCTB); - break; - - default: - myDetectorType=GENERIC; - printf("Unknown detector type %02x\n",(bus_r(PCB_REV_REG) & DETECTOR_TYPE_MASK)>>DETECTOR_TYPE_OFFSET); - break; - - } - printf("Detector type is %d\n", myDetectorType); - - - //control server only-- - if (b) { - 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 - printf("\nBoard Revision:0x%x\n",(bus_r(PCB_REV_REG)&BOARD_REVISION_MASK)); - if(myDetectorType == JUNGFRAU) - initDetector(); /*allocating detectorModules, detectorsDacs etc for "settings", also does allocate RAM*/ - dataBytes=NMAXMOD*N_CHIP*N_CHAN*2; /**Nchip and Nchan real values get assigned in initDetector()*/ - printf("Initializing Detector\n"); - //bus_w16(CONTROL_REG, SYNC_RESET); // reset registers -#endif - - // testFpga(); - // testRAM(); - // printf("ADC_SYNC_REG:%x\n",bus_r(ADC_SYNC_REG)); - //moench specific - // setPhaseShiftOnce(); - /*some registers set, which is in common with jungfrau, please check */ - prepareADC(); - //setADC(-1); //already does setdaqreg and clean fifo - // setSettings(GET_SETTINGS,-1); - /*some registers set, which is in common with jungfrau, please check */ - initDac(0); initDac(8); //initializes the two dacs - - if(myDetectorType==JUNGFRAU){ - /** for jungfrau reinitializing macro */ - N_CHAN=JUNGFRAU_NCHAN; - N_CHIP=JUNGFRAU_NCHIP; - N_DAC=JUNGFRAU_NDAC; - N_ADC=JUNGFRAU_NADC; - N_CHANS=JUNGFRAU_NCHANS; - - - //set dacs - int retval = -1; - int dacvalues[14][2]={ - {0, 1250}, //vout_cm - {10, 1053}, //vin_com - {1, 600}, //vb_sda - {11, 1000}, //vb_colbuf - {2, 3000}, //vb_test_cur - {3, 830}, //vcascp_pixbuf - {4, 1630}, //vcascn_pixbuf - {12, 750}, //vb_pixbuf - {6, 480}, //vref_ds - {5, 1000}, //vb_ds - {7, 400}, //vref_comp - {13, 1220}, //vb_comp - {8, 1500}, //vref_prech - {9, 3000}, //vdd_prot - }; - for(i=0;i<14;++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); - } - - //power on the chips - bus_w(POWER_ON_REG,0x1); - - //reset adc - writeADC(ADCREG1,0x3); writeADC(ADCREG1,0x0); - writeADC(ADCREG2,0x40); - writeADC(ADCREG3,0xf); - writeADC(ADCREG4,0x3f); - //vrefs - configurable? - writeADC(ADCREG_VREFS,0x2); - - - //set ADCINVERSionreg (by trial and error) - bus_w(ADC_INVERSION_REG,0x453b2a9c); - - //set adc_pipeline - bus_w(ADC_PIPELINE_REG,0x20); //same as ADC_OFFSET_REG - - //set dbit_pipeline - bus_w(DBIT_PIPELINE_REG,0x100e); - usleep(1000000);//1s - - //reset mem machine fifos fifos - bus_w(MEM_MACHINE_FIFOS_REG,0x4000); - bus_w(MEM_MACHINE_FIFOS_REG,0x0); - - //reset run control - bus_w(MEM_MACHINE_FIFOS_REG,0x0400); - bus_w(MEM_MACHINE_FIFOS_REG,0x0); - - //set default setting - setSettings(DYNAMICGAIN,-1); - } - - - //Initialization of acquistion parameters - setFrames(-1); - setTrains(-1); - setExposureTime(-1); - setPeriod(-1); - setDelay(-1); - setGates(-1); - - setTiming(GET_EXTERNAL_COMMUNICATION_MODE); - setMaster(GET_MASTER); - setSynchronization(GET_SYNCHRONIZATION_MODE); - startReceiver(0); //firmware - }//end of control server only-- - else printf("\n\n"); - - - //common for both control and stop server - strcpy(mess,"dummy message"); - strcpy(lastClientIP,"none"); - strcpy(thisClientIP,"none1"); - lockStatus=0; - // getDynamicRange(); - - /* both these functions setROI and allocateRAM should go into the control server part. */ - if(myDetectorType!=JUNGFRAU){ - int retvalsize,ret; - setROI(-1,NULL,&retvalsize,&ret); - allocateRAM(); - } - - return OK; + //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; + int fnum,n; + int retval=FAIL; #ifdef VERBOSE - printf( "receive data\n"); + printf( "receive data\n"); #endif - n = receiveDataOnly(file_des,&fnum,sizeof(fnum)); - if (n <= 0) { + 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); + printf("ERROR reading from socket %d, %d %d\n", n, fnum, file_des); #endif - return FAIL; - } + return FAIL; + } #ifdef VERBOSE - else - printf("size of data received %d\n",n); + 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)); + 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; + 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; - return OK; + 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 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 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; + 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; - } + /* 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) { + /* execute action if the arguments correctly arrived*/ + if (retval==OK) { #ifdef VERBOSE - printf("executing command %s\n", cmd); + printf("executing command %s\n", cmd); #endif - if (lockStatus==0 || differentClients==0) - sysret=system(cmd); + 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; - } + //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; - + /*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"); + int n=0; + enum detectorType ret; + int retval=OK; + + sprintf(mess,"Can't return detector type\n"); - /* receive arguments */ - /* execute action */ - ret=myDetectorType; + /* receive arguments */ + /* execute action */ + ret=myDetectorType; #ifdef VERBOSE - printf("Returning detector type %d\n",ret); + printf("Returning detector type %d\n",ret); #endif - /* send answer */ - /* send OK/failed */ - if (differentClients==1) - retval=FORCE_UPDATE; + /* 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; - 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"); + int n; + int arg[2], ret=0; + int retval=OK; + int dim, nm; - /* 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]; + sprintf(mess,"Can't set number of modules\n"); - /* 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; + /* receive arguments */ + n = receiveDataOnly(file_des,&arg,sizeof(arg)); + if (n < 0) { + sprintf(mess,"Error reading from socket %d", n); + retval=GOODBYE; } - } - } - /*} else { - if (dim==Y) { - ret=nModY; - } else if (dim==X) { - ret=setNMod(-1); - } - } - */ - - /* 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; - + 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 */ + 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); + 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; - } + 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 + printf("Max number of module in dimension %d is %d\n",arg,ret ); +#endif - if (differentClients==1 && retval==OK) { - retval=FORCE_UPDATE; - } + 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)); - } + /* 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; + /*return ok/fail*/ + return retval; } @@ -605,17 +434,14 @@ int set_external_signal_flag(int file_des) { 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 { + } else ret=FAIL; - } + if (ret==OK && differentClients!=0) ret=FORCE_UPDATE; @@ -645,7 +471,6 @@ int set_external_communication_mode(int file_des) { sprintf(mess,"Can't set external communication mode\n"); - /* receive arguments */ n = receiveDataOnly(file_des,&arg,sizeof(arg)); if (n < 0) { @@ -668,16 +493,7 @@ int set_external_communication_mode(int file_des) { */ if (retval==OK) { /* execute action */ - ret=setTiming(arg); - - /* switch(arg) { */ - /* default: */ - /* sprintf(mess,"The meaning of single signals should be set\n"); */ - /* retval=FAIL; */ - /* } */ - - #ifdef VERBOSE printf("Setting external communication mode to %d\n", arg); #endif @@ -701,336 +517,333 @@ int set_external_communication_mode(int file_des) { 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"); + // sends back 64 bits! + int64_t retval=-1; + int ret=OK; + int n=0; + enum idMode arg; - /* receive arguments */ - n = receiveDataOnly(file_des,&arg,sizeof(arg)); - if (n < 0) { - sprintf(mess,"Error reading from socket\n"); - ret=FAIL; - } + 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); + 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; -/* case DETECTOR_FIRMWARE_SVN_VERSION: - retval=getFirmwareSVNVersion(); - break;*/ - default: - printf("Required unknown id %d \n", arg); - ret=FAIL; - retval=FAIL; - break; - } - + 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); + 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)); - } + if (differentClients==1) + ret=FORCE_UPDATE; - /*return ok/fail*/ - return ret; + /* 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"); + int retval; + int ret=OK; + int imod=-1; + int n=0; + int ibit=0; + int ow; + int ival; + enum digitalTestMode arg; - n = receiveDataOnly(file_des,&arg,sizeof(arg)); - if (n < 0) { - sprintf(mess,"Error reading from socket\n"); - ret=FAIL; - } + 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 ); + 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; - } + 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); + printf("of module %d\n", imod); #endif - retval=0; + 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<= 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<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;; + 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; - } else if (ind==HV_NEW ) - retval=initHighVoltageByModule(val,imod); - else - printf("**********No dac with index %d\n",ind); + + 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; + 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 @@ -1199,7 +1012,7 @@ int get_adc(int file_des) { printf("Unknown DAC index %d\n",ind); sprintf(mess,"Unknown DAC index %d\n",ind); ret=FAIL; - break; + break; } if (ret==OK) @@ -1232,70 +1045,70 @@ int get_adc(int file_des) { } int set_channel(int file_des) { - int ret=OK; - sls_detector_channel myChan; - int retval; - int n; - + int ret=OK; + sls_detector_channel myChan; + int retval; + int n; - sprintf(mess,"Can't set channel\n"); + + sprintf(mess,"Can't set channel\n"); #ifdef VERBOSE - printf("Setting channel\n"); + printf("Setting channel\n"); #endif - ret=receiveChannel(file_des, &myChan); - if (ret>=0) - ret=OK; - else - ret=FAIL; + 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); + 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>=N_CHIP) - ret=FAIL; - if (myChan.chan>=N_CHAN) - ret=FAIL; - if (myChan.module<0) - myChan.module=ALLMOD; - } + 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 { + + 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); + retval=initChannelbyNumber(myChan); #endif - } - } - /* Maybe this is done inside the initialization funcs */ - //copyChannel(detectorChans[myChan.module][myChan.chip]+(myChan.chan), &myChan); - + } + } + /* 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)); - } + 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; - + /*return ok/fail*/ + return ret; + } @@ -1303,72 +1116,72 @@ int set_channel(int file_des) { int get_channel(int file_des) { - int ret=OK; - sls_detector_channel retval; + int ret=OK; + sls_detector_channel retval; - int arg[3]; - int ichan, ichip, imod; - int n; - - sprintf(mess,"Can't get channel\n"); + 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 && imod=0 && ichip=0 && ichan=0) - ret=OK; - else - ret=FAIL; + 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); + 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>=N_CHIP) - ret=FAIL; - } - if (differentClients==1 && lockStatus==1) { - ret=FAIL; - sprintf(mess,"Detector locked by %s\n",lastClientIP); - } else { + + 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); + retval=initChipbyNumber(myChip); #endif - } - /* Maybe this is done inside the initialization funcs */ - //copyChip(detectorChips[myChip.module]+(myChip.chip), &myChip); + } + /* 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)); - } + 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; + return ret; } + int get_chip(int file_des) { - - int ret=OK; - sls_detector_chip retval; - int arg[2]; - int ichip, imod; - int n; - + + 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 && imod=0 && ichip=0) - ret=OK; - else - ret=FAIL; + ret=receiveModuleGeneral(file_des, &myModule, 0); //0 is to receive partially (without trimbits etc.) + + 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); -#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 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; + retval=initModulebyNumber(myModule); + if(retval != myModule.reg) + ret = FAIL; #endif - } - } + } + } - if (differentClients==1 && ret==OK) - ret=FORCE_UPDATE; + if (differentClients==1 && ret==OK) + ret=FORCE_UPDATE; - /* Maybe this is done inside the initialization funcs */ - //copyChip(detectorChips[myChip.module]+(myChip.chip), &myChip); + /* 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)); - } + /* 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); + free(myDac); + if(myAdc != NULL) free(myAdc); + if(myChip != NULL) free(myChip); + if(myChan != NULL) free(myChan); - //setDynamicRange(dr); always 16 commented out + //setDynamicRange(dr); always 16 commented out - return ret; + return ret; } @@ -1630,278 +1410,250 @@ int set_module(int file_des) { int get_module(int file_des) { - int ret=OK; - int arg; - int imod; - int n; - sls_detector_module myModule; - int *myDac=malloc(N_DAC*sizeof(int)); - int *myChip=NULL; - int *myChan=NULL; - int *myAdc=NULL; - - /*not required for jungfrau. so save memory*/ - if(myDetectorType != JUNGFRAU){ - myChip=malloc(N_CHIP*sizeof(int)); - myChan=malloc(N_CHIP*N_CHAN*sizeof(int)); - myAdc=malloc(N_ADC*sizeof(int)); - } + 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; + } - 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; - myModule.adcs=NULL; - myModule.chipregs=NULL; - myModule.chanregs=NULL; - /*not required for jungfrau. so save memory*/ - if(myDetectorType != JUNGFRAU){ - 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; - } - } - myModule.ndac=N_DAC; - myModule.nchip=N_CHIP; - myModule.nchan=N_CHAN*N_CHIP; - myModule.nadc=N_ADC; - + n = receiveDataOnly(file_des,&arg,sizeof(arg)); + if (n < 0) { + sprintf(mess,"Error reading from socket\n"); + ret=FAIL; + } + imod=arg; - - 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 && 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)); -#ifdef VERYVERBOSE - printf("sending pointer %x of size %d\n",(unsigned int)(dataretval),dataBytes*nSamples); -#endif - sendDataOnly(file_des,dataretval,dataBytes*nSamples); - } else { - if (getFrames()>-1) { - dataret=FAIL; - sprintf(mess,"no data and run stopped: %d frames left\n",(int)(getFrames()+2)); - printf("%s\n",mess); - } else { - dataret=FINISHED; - sprintf(mess,"acquisition successfully finished\n"); - printf("%s\n",mess); - if (differentClients) - dataret=FORCE_UPDATE; - } -#ifdef VERBOSE - printf("Frames left %d\n",(int)(getFrames())); -#endif - sendDataOnly(file_des,&dataret,sizeof(dataret)); - sendDataOnly(file_des,mess,sizeof(mess)); - } - - - - - return dataret; - + sendDataOnly(file_des,mess,sizeof(mess)); + return dataret; } - - - - int read_all(int file_des) { - -while(read_frame(file_des)==OK) { - + while(read_frame(file_des)==OK) { #ifdef VERBOSE - printf("frame read\n"); + printf("frame read\n"); #endif - ; - } + ; + } #ifdef VERBOSE - printf("Frames finished\n"); + printf("Frames finished\n"); #endif - return OK; - - + return OK; } + + int start_and_read_all(int file_des) { - //int dataret=OK; #ifdef VERBOSE - printf("Starting and reading all frames\n"); + 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; - 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(); - - /* ret=startStateMachine(); - if (ret!=OK) { - sprintf(mess,"could not start state machine\n"); - sendDataOnly(file_des,&ret,sizeof(ret)); - sendDataOnly(file_des,mess,sizeof(mess)); - - #ifdef VERBOSE - printf("could not start state machine\n"); -#endif -} else {*/ - read_all(file_des); + } + startStateMachine(); + read_all(file_des); #ifdef VERBOSE - printf("Frames finished\n"); + printf("Frames finished\n"); #endif - //} - - - return OK; - - + 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; @@ -2199,75 +1877,73 @@ int set_timer(int file_des) { 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 moench\n"); - ret=FAIL; - break; - case CYCLES_NUMBER: - retval=setTrains(tns); - break; - case SAMPLES_JCTB: - retval=setSamples(tns); - break; - default: - ret=FAIL; - sprintf(mess,"t timer index unknown %d\n",ind); - break; - } - } - } - if (ret!=OK) { - printf(mess); - if (differentClients) - ret=FORCE_UPDATE; - } - - if (ret!=OK) { - printf(mess); - printf("set timer failed\n"); - } else if (ind==SAMPLES_JCTB) { - ret=allocateRAM(); - if (ret!=OK) - sprintf(mess, "could not allocate RAM for %lld frames\n", tns); - } - - 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))); + printf("setting timer %d to %lld ns\n",ind,tns); #endif - n = sendDataOnly(file_des,&retval,sizeof(retval)); - } + if (ret==OK) { - return ret; + 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; } @@ -2280,94 +1956,91 @@ int set_timer(int file_des) { int get_time_left(int file_des) { - enum timerIndex ind; - int n; - int64_t retval; - int ret=OK; - printf("get\n"); - 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; - } - + enum timerIndex ind; + int n; + int64_t retval; + int ret=OK; - //#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; - case SAMPLES_JCTB: - retval=getSamples(); - break; - default: - ret=FAIL; - sprintf(mess,"tl timer index unknown %d\n",ind); - break; - } - } + 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; + } - if (ret!=OK) { - printf("get time left failed\n"); - } else if (differentClients) - ret=FORCE_UPDATE; + //#ifdef VERBOSE - //#ifdef VERBOSE + printf("getting time left on timer %d \n",ind); + //#endif - printf("time left on timer %d is %lld\n",ind, retval); - //#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; + } + } - 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)); + + 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"); + printf("data sent\n"); #endif - return ret; + return ret; } @@ -2375,62 +2048,52 @@ int get_time_left(int file_des) { int set_dynamic_range(int file_des) { - - int dr; - int n; - int retval; - int ret=OK; - - printf("Set dynamic range?\n"); - 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); - } + int dr; + int n; + int retval; + int ret=OK; - //if (dr>=0 && retval!=dr) ret=FAIL; - if (ret!=OK) { - sprintf(mess,"set dynamic range failed\n"); - } else { - /* ret=allocateRAM(); */ -/* if (ret!=OK) */ -/* sprintf(mess,"Could not allocate RAM for the dynamic range selected\n"); */ -// else - if (differentClients) - ret=FORCE_UPDATE; - } + sprintf(mess,"can't set dynamic range\n"); - 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; + + 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 i; int ret=OK; int nroi=-1; int n=0; - int retvalsize=0; - ROI arg[MAX_ROIS]; - ROI* retval=0; strcpy(mess,"Could not set/get roi\n"); - // u_int32_t disable_reg=0; n = receiveDataOnly(file_des,&nroi,sizeof(nroi)); if (n < 0) { @@ -2438,41 +2101,9 @@ int set_roi(int file_des) { ret=FAIL; } - if(myDetectorType == JUNGFRAU){ - ret = FAIL; - strcpy(mess,"Not applicable/implemented for this detector\n"); - printf("Error:Set ROI-%s",mess); - } - - else{ - - if(nroi>=0){ - n = receiveDataOnly(file_des,arg,nroi*sizeof(ROI)); - if (n != (nroi*sizeof(ROI))) { - sprintf(mess,"Received wrong number of bytes for ROI\n"); - ret=FAIL; - } - - printf("Setting ROI to:"); - for( i=0;i=0) { - ret=FAIL; - sprintf(mess,"Detector locked by %s\n",lastClientIP); - } else { - switch (arg) { - case CLOCK_DIVIDER: - retval=setClockDivider(val,0); - break; - -/* case PHASE_SHIFT: */ -/* retval=phaseStep(val,0); */ -/* break; */ - - case OVERSAMPLING: - retval=setOversampling(val); - break; - - case ADC_CLOCK: - retval=setClockDivider(val,1); - break; - -/* case ADC_PHASE: */ -/* retval=phaseStep(val,1); */ -/* break; */ - - - case ADC_PIPELINE: - retval=adcPipeline(val); - break; - - - - default: - ret=FAIL; - sprintf(mess,"Unknown speed parameter %d",arg); + 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); + } + } + } + } - switch (arg) { - case CLOCK_DIVIDER: - retval=getClockDivider(0); - break; - case PHASE_SHIFT: - retval=getPhase(); - // retval=phaseStep(-1); - //ret=FAIL; - //sprintf(mess,"Cannot read phase",arg); - break; + if (ret==OK) { + switch (arg) { + case CLOCK_DIVIDER: + retval=getClockDivider(); + break; - case OVERSAMPLING: - retval=setOversampling(-1); - break; + case ADC_PHASE: + retval=getPhase(); + break; - case ADC_CLOCK: - retval=getClockDivider(1); - break; - - case ADC_PHASE: - retval=getPhase(); - break; + default: + ret=FAIL; + sprintf(mess,"Unknown speed parameter %d",arg); + } + } - case ADC_PIPELINE: - retval=adcPipeline(-1); - 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; + 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; - + enum readOutFlags arg; + int ret=FAIL; - receiveDataOnly(file_des,&arg,sizeof(arg)); - sprintf(mess,"can't set readout flags for moench\n"); - - sendDataOnly(file_des,&ret,sizeof(ret)); - sendDataOnly(file_des,mess,sizeof(mess)); + receiveDataOnly(file_des,&arg,sizeof(arg)); - return ret; + 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; } @@ -2644,55 +2229,55 @@ int set_readout_flags(int file_des) { int execute_trimming(int file_des) { - - int arg[3]; - int ret=FAIL; - enum trimMode mode; - - sprintf(mess,"can't set execute trimming for moench\n"); - - receiveDataOnly(file_des,&mode,sizeof(mode)); - receiveDataOnly(file_des,arg,sizeof(arg)); + + 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)); + sendDataOnly(file_des,&ret,sizeof(ret)); + sendDataOnly(file_des,mess,sizeof(mess)); - return ret; + 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 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; } @@ -2762,65 +2347,65 @@ int set_port(int file_des) { } 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 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(); + 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); + 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)); + retval=setTrains(tns); + n = sendDataOnly(file_des,&retval,sizeof(int64_t)); - if (lockStatus==0) { - strcpy(lastClientIP,thisClientIP); - } + if (lockStatus==0) { + strcpy(lastClientIP,thisClientIP); + } + + return ret; - return ret; - } int update_client(int file_des) { - int ret=OK; + int ret=OK; + + sendDataOnly(file_des,&ret,sizeof(ret)); + return send_update(file_des); + - sendDataOnly(file_des,&ret,sizeof(ret)); - return send_update(file_des); - - } @@ -2920,7 +2505,7 @@ int load_image(int file_des) { int ret=OK; int n; enum imageType index; - short int ImageVals[N_CHAN*N_CHIP]; + short int ImageVals[NCHAN*NCHIP]; sprintf(mess,"Loading image failed\n"); @@ -2951,7 +2536,7 @@ int load_image(int file_des) { printf("Unknown index %d\n",index); sprintf(mess,"Unknown index %d\n",index); ret=FAIL; - break; + break; } if (ret==OK) { @@ -2988,44 +2573,44 @@ int load_image(int file_des) { int set_master(int file_des) { - enum masterFlags retval=GET_MASTER; - enum masterFlags arg; - int n; - int ret=OK; - // int regret=OK; + enum masterFlags retval=GET_MASTER; + enum masterFlags arg; + int n; + int ret=OK; + // int regret=OK; - sprintf(mess,"can't set master flags\n"); + 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; - } + 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); + 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 (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; + } + 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; } @@ -3035,43 +2620,43 @@ int set_master(int file_des) { int set_synchronization(int file_des) { - enum synchronizationMode retval=GET_MASTER; - enum synchronizationMode arg; - int n; - int ret=OK; - //int regret=OK; + enum synchronizationMode retval=GET_MASTER; + enum synchronizationMode arg; + int n; + int ret=OK; + //int regret=OK; - sprintf(mess,"can't set synchronization mode\n"); + 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; - } + 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); + 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; + 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; } @@ -3085,7 +2670,7 @@ int read_counter_block(int file_des) { int n; int startACQ; //char *retval=NULL; - short int CounterVals[N_CHAN*N_CHIP]; + short int CounterVals[NCHAN*NCHIP]; sprintf(mess,"Read counter block failed\n"); @@ -3175,31 +2760,13 @@ int reset_counter_block(int file_des) { int start_receiver(int file_des) { - int ret=OK; - int n=0; - strcpy(mess,"Could not start receiver\n"); - - /* execute action if the arguments correctly arrived*/ -#ifdef MCB_FUNCS - if (lockStatus==1 && differentClients==1){//necessary??? - sprintf(mess,"Detector locked by %s\n", lastClientIP); - ret=FAIL; - } - else - ret = startReceiver(1); - -#endif - - - if(ret==OK && differentClients){ - printf("Force update\n"); - ret=FORCE_UPDATE; - } + int ret=FAIL; + int n; + strcpy(mess,"Not implemented for this detector\n"); /* send answer */ n = sendDataOnly(file_des,&ret,sizeof(ret)); - if(ret==FAIL) - n = sendDataOnly(file_des,mess,sizeof(mess)); + n = sendDataOnly(file_des,mess,sizeof(mess)); /*return ok/fail*/ return ret; } @@ -3210,32 +2777,13 @@ int start_receiver(int file_des) { int stop_receiver(int file_des) { - int ret=OK; - int n=0; - - strcpy(mess,"Could not stop receiver\n"); - - /* execute action if the arguments correctly arrived*/ -#ifdef MCB_FUNCS - if (lockStatus==1 && differentClients==1){//necessary??? - sprintf(mess,"Detector locked by %s\n", lastClientIP); - ret=FAIL; - } - else - ret=startReceiver(0); - -#endif - - - if(ret==OK && differentClients){ - printf("Force update\n"); - ret=FORCE_UPDATE; - } + int ret = FAIL; + int n; + strcpy(mess,"Not implemented for this detector\n"); /* send answer */ n = sendDataOnly(file_des,&ret,sizeof(ret)); - if(ret==FAIL) - n = sendDataOnly(file_des,mess,sizeof(mess)); + n = sendDataOnly(file_des,mess,sizeof(mess)); /*return ok/fail*/ return ret; } @@ -3287,7 +2835,7 @@ int calibrate_pedestal(int file_des){ int set_ctb_pattern(int file_des){ - int ret=OK;//FAIL; + int ret=OK;//FAIL; int retval=-1; int n; int mode; @@ -3298,146 +2846,146 @@ int set_ctb_pattern(int file_des){ sprintf(mess,"Could not set pattern\n"); - n = receiveDataOnly(file_des,&mode,sizeof(mode)); + 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; + 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); - }; + 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; + //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 - 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)); - + 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 + + 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; + */ + 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)); + 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 + + /** 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)); + */ + 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)); + break; - /** Sets the wait time in the CTB + 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; + ret=OK; - retval64=setPatternWaitTime(level,t); + 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)); + 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; + 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)); + 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; - - + 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)); - - + + + 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)); + + } @@ -3449,62 +2997,271 @@ int set_ctb_pattern(int file_des){ int write_adc_register(int file_des) { - int retval; - int ret=OK; - int arg[2]; - int addr, val; - int n; + int retval; + int ret=OK; + int arg[2]; + int addr, val; + int n; - sprintf(mess,"Can't write to register\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]; + 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); + 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 (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; - } - + if(ret!=FAIL){ + ret=writeADC(addr,val); + if (ret==OK) + retval=val; + } + #ifdef VERBOSE - printf("Data set to 0x%x\n", retval); + 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); - } + 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)); - } + /* 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; + /*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 index 2d674a1d0..0cbdd052b 100755 --- a/slsDetectorSoftware/jungfrauDetectorServer/server_funcs.h +++ b/slsDetectorSoftware/jungfrauDetectorServer/server_funcs.h @@ -23,7 +23,7 @@ int sockfd; int function_table(); int decode_function(int); -int init_detector(int,int); +int init_detector(int); int M_nofunc(int); int exit_server(int); @@ -95,4 +95,8 @@ 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/sharedmemory.c b/slsDetectorSoftware/jungfrauDetectorServer/sharedmemory.c deleted file mode 100755 index 4504cfe05..000000000 --- a/slsDetectorSoftware/jungfrauDetectorServer/sharedmemory.c +++ /dev/null @@ -1,39 +0,0 @@ -#include "sharedmemory.h" - -struct statusdata *stdata; - -int inism(int clsv) { - -static int scansmid; - - if (clsv==SMSV) { - if ( (scansmid=shmget(SMKEY,1024,IPC_CREAT | 0666 ))==-1 ) { - return -1; - } - if ( (stdata=shmat(scansmid,NULL,0))==(void*)-1) { - return -2; - } - } - - if (clsv==SMCL) { - if ( (scansmid=shmget(SMKEY,0,0) )==-1 ) { - return -3; - } - if ( (stdata=shmat(scansmid,NULL,0))==(void*)-1) { - return -4; - } - } - return 1; -} - -void write_status_sm(char *status) { - strcpy(stdata->status,status); -} - -void write_stop_sm(int v) { - stdata->stop=v; -} - -void write_runnumber_sm(int v) { - stdata->runnumber=v; -} diff --git a/slsDetectorSoftware/jungfrauDetectorServer/sharedmemory.h b/slsDetectorSoftware/jungfrauDetectorServer/sharedmemory.h deleted file mode 100755 index bdbddf719..000000000 --- a/slsDetectorSoftware/jungfrauDetectorServer/sharedmemory.h +++ /dev/null @@ -1,48 +0,0 @@ -#ifndef SM -#define SM - -#include "sls_detector_defs.h" - -#include -#include -#include -#include -#include -#include -#include -//#include -#include -#include -#include -#include -#include -#include - - -#include - -#include -#include - -/* key for shared memory */ -#define SMKEY 10001 - -#define SMSV 1 -#define SMCL 2 - - -struct statusdata { - int runnumber; - int stop; - char status[20]; -} ; - - -/* for shared memory */ - -int inism(int clsv); -void write_status_sm(char *status); -void write_stop_sm(int v); -void write_runnumber_sm(int v); - -#endif diff --git a/slsDetectorSoftware/multiSlsDetector/multiSlsDetector.cpp b/slsDetectorSoftware/multiSlsDetector/multiSlsDetector.cpp index 95e04bcf9..104f30e58 100644 --- a/slsDetectorSoftware/multiSlsDetector/multiSlsDetector.cpp +++ b/slsDetectorSoftware/multiSlsDetector/multiSlsDetector.cpp @@ -23,6 +23,8 @@ ID: $Id$ #include #include #include +#include +#include //to scan json header in zmq stream using namespace std; @@ -266,6 +268,7 @@ multiSlsDetector::multiSlsDetector(int id) : slsDetectorUtils(), shmId(-1) getNMods(); getMaxMods(); + threadStarted = false; threadpool = 0; if(createThreadPool() == FAIL) exit(-1); @@ -299,7 +302,7 @@ int multiSlsDetector::createThreadPool(){ break; default: #ifdef VERBOSE - cout << "Initialized Threadpool" << endl; + cout << "Initialized Threadpool " << threadpool << endl; #endif break; } @@ -311,7 +314,7 @@ void multiSlsDetector::destroyThreadPool(){ threadpool->destroy_threadpool(); threadpool=0; #ifdef VERBOSE - cout<<"Destroyed Threadpool"<add_task(task); } } + threadpool->startExecuting(); threadpool->wait_for_tasks_to_complete(); for(int idet=posmin; idetadd_task(task); } } + threadpool->startExecuting(); threadpool->wait_for_tasks_to_complete(); for(int idet=posmin; idetgetDetectorsType() != EIGER) - break; + /*if((detectors[id]->getDetectorsType() != EIGER)||(detectors[id]->getDetectorsType() != JUNGFRAU)) + break;*/ } p+=n/sizeof(int); } } //eiger returns only null - if(getDetectorsType() == EIGER) + detectorType types = getDetectorsType(); + if(types == EIGER || types == JUNGFRAU){ + delete [] retval; return NULL; + } if (nodatadet>=0) { for (int id=0; idnumberOfDetectors; id++) { if (id!=nodatadet) { if (detectors[id]) { -#ifdef VERBOSE +//#ifdef VERBOSE cout << "Stopping detector "<< id << endl; -#endif +//#endif detectors[id]->stopAcquisition(); if(detectors[id]->getErrorMask()) setErrorMask(getErrorMask()|(1<add_task(task); } } + threadpool->startExecuting(); threadpool->wait_for_tasks_to_complete(); for(int idet=posmin; idetmasterPosition) && (detectors[idet])){ @@ -1756,7 +1763,7 @@ int64_t multiSlsDetector::setTimer(timerIndex index, int64_t t){ if (ret1==-100) ret1=ret; else if (ret!=ret1) - ret1=FAIL; + ret1=-1; } } @@ -2229,6 +2236,7 @@ slsDetectorDefs::ROI* multiSlsDetector::getROI(int &n){ double* multiSlsDetector::decodeData(int *datain, int &nn, double *fdata) { double *dataout; + if (fdata) dataout=fdata; else { @@ -2240,12 +2248,12 @@ double* multiSlsDetector::decodeData(int *datain, int &nn, double *fdata) { nn=thisMultiDetector->numberOfChannels; } } + // int ich=0; int n; double *detp=dataout; int *datap=datain; - for (int i=0; inumberOfDetectors; i++) { if (detectors[i]) { detectors[i]->decodeData(datap, n, detp); @@ -3331,6 +3339,7 @@ char* multiSlsDetector::setNetworkParameter(networkParameter p, string s){ threadpool->add_task(task); } } + threadpool->startExecuting(); threadpool->wait_for_tasks_to_complete(); for(int idet=0; idetnumberOfDetectors; idet++){ if(detectors[idet]){ @@ -3362,6 +3371,7 @@ char* multiSlsDetector::setNetworkParameter(networkParameter p, string s){ } } + return getNetworkParameter(p); } @@ -3940,6 +3950,7 @@ int multiSlsDetector::executeTrimming(trimMode mode, int par1, int par2, int imo threadpool->add_task(task); } } + threadpool->startExecuting(); threadpool->wait_for_tasks_to_complete(); for(int idet=0; idetnumberOfDetectors; idet++){ if(detectors[idet]){ @@ -3963,6 +3974,54 @@ int multiSlsDetector::executeTrimming(trimMode mode, int par1, int par2, int imo +int multiSlsDetector::programFPGA(string fname){ + int ret=OK, ret1=OK; + + for (int i=0; inumberOfDetectors; i++) { + if (detectors[i]) { + ret=detectors[i]->programFPGA(fname); + if(detectors[i]->getErrorMask()) + setErrorMask(getErrorMask()|(1<numberOfDetectors; i++) { + if (detectors[i]) { + ret=detectors[i]->resetFPGA(); + if(detectors[i]->getErrorMask()) + setErrorMask(getErrorMask()|(1<numberOfDetectors; i++) { + if (detectors[i]) { + ret=detectors[i]->powerChip(ival); + if(detectors[i]->getErrorMask()) + setErrorMask(getErrorMask()|(1<add_task(task); } } + threadpool->startExecuting(); threadpool->wait_for_tasks_to_complete(); for(int idet=0; idetnumberOfDetectors; idet++){ if(detectors[idet]){ @@ -4065,6 +4125,7 @@ int multiSlsDetector::setAllTrimbits(int val, int imod){ threadpool->add_task(task); } } + threadpool->startExecuting(); threadpool->wait_for_tasks_to_complete(); for(int idet=0; idetnumberOfDetectors; idet++){ if(detectors[idet]){ @@ -4114,6 +4175,7 @@ int multiSlsDetector::loadCalibrationFile(string fname, int imod) { threadpool->add_task(task); } } + threadpool->startExecuting(); threadpool->wait_for_tasks_to_complete(); for(int idet=0; idetnumberOfDetectors; idet++){ if(detectors[idet]){ @@ -4268,7 +4330,7 @@ int multiSlsDetector::readConfigurationFile(string const fname){ multiSlsDetectorClient *cmd; // char ext[100]; - + setAcquiringFlag(false); string ans; string str; @@ -4357,8 +4419,12 @@ int multiSlsDetector::readConfigurationFile(string const fname){ setNumberOfModules(-1); getMaxNumberOfModules(); - if (getErrorMask()) + if (getErrorMask()){ + int c; + cprintf(RED,"\n----------------\n Error Messages\n----------------\n%s\n", + getErrorMessage(c).c_str()); return FAIL; + } return OK; @@ -4688,7 +4754,8 @@ string multiSlsDetector::checkReceiverOnline() { string multiSlsDetector::setFilePath(string s) { string ret="errorerror", ret1; - if(!s.empty()){ + //if the sls file paths are different, it should be realized by always using setfilepath even if string empty + //if(!s.empty()){ for (int idet=0; idetnumberOfDetectors; idet++) { if (detectors[idet]) { @@ -4702,7 +4769,7 @@ string multiSlsDetector::setFilePath(string s) { } } fileIO::setFilePath(ret); - } + //} return fileIO::getFilePath(); } @@ -4766,6 +4833,7 @@ int multiSlsDetector::startReceiver(){ threadpool->add_task(task); } } + threadpool->startExecuting(); threadpool->wait_for_tasks_to_complete(); for(int idet=posmin; idetmasterPosition) && (detectors[idet])){ @@ -4827,6 +4895,7 @@ int multiSlsDetector::stopReceiver(){ threadpool->add_task(task); } } + threadpool->startExecuting(); threadpool->wait_for_tasks_to_complete(); for(int idet=posmin; idetmasterPosition) && (detectors[idet])){ @@ -4909,19 +4978,30 @@ slsDetectorDefs::runStatus multiSlsDetector::getReceiverStatus(){ int multiSlsDetector::getFramesCaughtByReceiver() { - int ret=0,ret1=0; - for (int i=0; inumberOfDetectors; i++) - if (detectors[i]){ - ret1+=detectors[i]->getFramesCaughtByReceiver(); - if(detectors[i]->getErrorMask()) - setErrorMask(getErrorMask()|(1<numberOfDetectors) - return ret; - ret=(int)(ret1/thisMultiDetector->numberOfDetectors); + int ret=0,ret1=0; - return ret; + if(thisMultiDetector->numberOfDetectors>10) { + if (detectors[0]){ + ret =detectors[0]->getFramesCaughtByReceiver(); + if(detectors[0]->getErrorMask()) + setErrorMask(getErrorMask()|(1<<0)); + } + return ret; + } + + + for (int i=0; inumberOfDetectors; i++) + if (detectors[i]){ + ret1+=detectors[i]->getFramesCaughtByReceiver(); + if(detectors[i]->getErrorMask()) + setErrorMask(getErrorMask()|(1<numberOfDetectors) + return ret; + ret=(int)(ret1/thisMultiDetector->numberOfDetectors); + + return ret; } @@ -4945,6 +5025,7 @@ int multiSlsDetector::getReceiverCurrentFrameIndex() { int multiSlsDetector::resetFramesCaught() { int ret=-100, ret1; + for (int i=0; inumberOfDetectors; i++){ if (detectors[i]){ ret1=detectors[i]->resetFramesCaught(); @@ -4961,101 +5042,427 @@ int multiSlsDetector::resetFramesCaught() { } - -int* multiSlsDetector::readFrameFromReceiver(char* fName, int &acquisitionIndex, int &frameIndex, int &subFrameIndex){ - int nel=(thisMultiDetector->dataBytes)/sizeof(int); - if(nel <= 0){ - cout << "Multislsdetector databytes not valid :" << thisMultiDetector->dataBytes << endl; - acquisitionIndex = -1; - return NULL; - } - int n,complete=OK; - int i,k,offsetX, offsetY, maxX, maxY; double dr; - int* retval=new int[nel]; - int *retdet = NULL, *p=retval; - string fullFName=""; - string ext=""; - int index=-1,f_index=-1,p_index=-1,det_index=-1; - double sv0=-1,sv1=-1; - - if(getDetectorsType() == EIGER){ - maxX = thisMultiDetector->numberOfChannel[X]; - maxY = thisMultiDetector->numberOfChannel[Y]; - } +int multiSlsDetector::createReceivingDataThreads(bool destroy){ + if(!destroy) cprintf(MAGENTA,"Going to create data threads\n"); + else cprintf(MAGENTA,"Going to destroy data threads\n"); - for (int id=0; idnumberOfDetectors; id++) { - if (detectors[id]) { - n=detectors[id]->getDataBytes(); - retdet=detectors[id]->readFrameFromReceiver(fName, acquisitionIndex, frameIndex, subFrameIndex); - if(detectors[id]->getErrorMask()) - setErrorMask(getErrorMask()|(1<getDataBytes(); - if(getDetectorsType() == EIGER){ - //cout << "fname:"<getMaxNumberOfChannels()<<" n:"<getMaxNumberOfChannels(); - k=(int)(detectors[id]->getMaxNumberOfChannels(X)*dr);//bit mode - //cout << "dr:"<offsetY[id] + detectors[id]->getMaxNumberOfChannels(Y))) * maxX)*dr);//bit mode - offsetX = (int)(thisMultiDetector->offsetX[id]*dr); - //cout << "offsetY"<numberOfDetectors; + if(getDetectorsType() == EIGER) + numReadouts *= 2; - delete [] retdet; - //concatenate filenames - if(!fullFName.length()){ - //assign file prefix - fullFName.assign(fileIO::getFileName()); - if (strrchr(fName,'.')!=NULL){ - ext.assign(fName); - size_t dot = ext.rfind("."); - if(dot != string::npos) - ext = ext.erase(0,dot); - else - ext = ""; - //get variables - fileIOStatic::getVariablesFromFileName(fName,index, f_index, p_index, sv0, sv1, det_index); - //append scan and det variables - fullFName.append(fileIOStatic::getReceiverFileNameToConcatenate(fName)); - } - } - //append only if scan variables are different - if(!fileIOStatic::verifySameFrame(fName,index,f_index, p_index, sv0, sv1, det_index)){ - fullFName.append(fileIOStatic::getReceiverFileNameToConcatenate(fName)); - } - } - }else { -#ifdef VERBOSE - cout << "Receiver for detector " << id << " does not have data left " << endl; + //reset masks + killAllReceivingDataThreads = false; + + //destroy + if(destroy){ +#ifdef DEBUG + cout << "Destroying Receiving Data Thread(s)" << endl; #endif - delete [] retval; - return NULL; + killAllReceivingDataThreads = true; + for(int i = 0; i < numReadouts; ++i){ + sem_post(&sem_singlewait[i]); + pthread_join(receivingDataThreads[i],NULL); + sem_destroy(&sem_singlewait[i]); + sem_destroy(&sem_singledone[i]); +#ifdef DEBUG + cout << "." << flush << endl; +#endif + } + killAllReceivingDataThreads = false; + threadStarted = false; + + cout << "Destroyed Receiving Data Thread(s)" << endl; + } + + //create + else{ +#ifdef DEBUG + cout << "Creating Receiving Data Thread(s)" << endl; +#endif + //reset current index + currentThreadIndex = -1; + for(int i = 0; i < numReadouts; ++i){ + sem_init(&sem_singlewait[i],1,0); + sem_init(&sem_singledone[i],1,0); + threadStarted = false; + currentThreadIndex = i; + if(pthread_create(&receivingDataThreads[i], NULL,staticstartReceivingDataThread, (void*) this)){ + cprintf(RED, "Could not create receiving data thread with index %d\n",i); + return FAIL; + } + while(!threadStarted); +#ifdef DEBUG + cout << "." << flush << endl; +#endif + } + cout << "Receiving Data Thread(s) created" << endl; + } + + return OK; +} + + + +void* multiSlsDetector::staticstartReceivingDataThread(void* this_pointer){ + ((multiSlsDetector*)this_pointer)->startReceivingDataThread(); + //while(true); + + return this_pointer; +} + + +void multiSlsDetector::startReceivingDataThread(){ + + int ithread = currentThreadIndex; //set current thread value index + + char hostname[100] = "tcp://"; + char rx_hostname[100]; + strcpy(rx_hostname, detectors[ithread]->getReceiver()); + cout<<"rx_hostname:"<h_addr)); + } + strcat(hostname,":"); + //server details + //char hostname[100] = "tcp://127.0.0.1:"; + int portno = DEFAULT_ZMQ_PORTNO + ithread; + sprintf(hostname,"%s%d",hostname,portno); + + //socket details + zmq_msg_t message; + void *context; + void *zmqsocket; + context = zmq_ctx_new(); + zmqsocket = zmq_socket(context, ZMQ_PULL); + //int hwmval = 10; + //zmq_setsockopt(zmqsocket,ZMQ_RCVHWM,&hwmval,sizeof(hwmval)); //set receive HIGH WATER MARK (8-9ms slower//should not drop last packets) + cprintf(RED,"connect ret:%d\n",zmq_connect(zmqsocket, hostname)); + cout << "ZMQ Client of " << ithread << " at " << hostname << endl; + cprintf(BLUE,"%d Created socket\n",ithread); + + + //initializations + int numReadoutPerDetector = 1; + bool jungfrau = false; + int expectedsize = 1024*256;/**shouldnt work for other bit modes or anythign*/ + if(getDetectorsType() == EIGER){ + numReadoutPerDetector = 2; + expectedsize = 1024*256; + }else if(getDetectorsType() == JUNGFRAU){ + jungfrau = true; + expectedsize = 8192*128; + } + int singleDatabytes = detectors[ithread/numReadoutPerDetector]->getDataBytes(); + int nel=(singleDatabytes/numReadoutPerDetector)/sizeof(int); + int* image = new int[nel]; + int len,idet = 0; + singleframe[ithread]=NULL; + threadStarted = true; //let calling function know thread started and obtained current + + + //infinite loop, exited only (if gui restarted/ enabledatastreaming called) + while(true){ + + + sem_wait(&sem_singlewait[ithread]); //wait for it to be copied + //check to exit thread + if(killAllReceivingDataThreads) + break; + + //scan header------------------------------------------------------------------- + zmq_msg_init (&message); + len = zmq_msg_recv(&message, zmqsocket, 0); + if (len == -1) { + cprintf(BG_RED,"Could not read header for socket %d\n",ithread); + zmq_msg_close(&message); + cprintf(RED, "%d message null\n",ithread); + continue; + } + + + // error if you print it + // cout << ithread << " header len:"<numberOfChannel[X]; +// maxY = thisMultiDetector->numberOfChannel[Y]; +// } +// int numReadouts = numReadoutPerDetector * thisMultiDetector->numberOfDetectors; + +// //initializing variables +// currentFileName=""; +// currentAcquisitionIndex = -1; +// currentFrameIndex = -1; +// currentSubFrameIndex = -1; + + +// //getting values +// int slsdatabytes = 0, slsmaxchannels = 0, bytesperchannel = 0, slsmaxX = 0, slsmaxY=0; +// if(detectors[0]){ +// slsdatabytes = detectors[0]->getDataBytes(); +// slsmaxchannels = detectors[0]->getMaxNumberOfChannels(); +// bytesperchannel = slsdatabytes/slsmaxchannels; +// slsmaxX = detectors[0]->getTotalNumberOfChannels(X); +// slsmaxY = detectors[0]->getTotalNumberOfChannels(Y); +// } +// int nel=(thisMultiDetector->dataBytes)/sizeof(int); +// if(nel <= 0){ +// cprintf(RED,"Error: Multislsdetector databytes not valid : %d\n", thisMultiDetector->dataBytes); +// return; +// } +// int* multiframe=new int[nel]; +// int idet,offsetY,offsetX; +// int halfreadoutoffset = (slsmaxX/numReadoutPerDetector); +// int nx =getTotalNumberOfChannels(slsDetectorDefs::X); +// int ny =getTotalNumberOfChannels(slsDetectorDefs::Y); + +// volatile uint64_t dataThreadMask = 0x0; +// for(int i = 0; i < numReadouts; ++i) +// dataThreadMask|=(1<numberOfDetectors); //reset frame memory + +// //post all of them to start +// for(int ireadout=0; ireadoutoffsetY[idet] + slsmaxY)) * maxX * bytesperchannel; +// //the left half or right half +// if(!(ireadout%numReadoutPerDetector)) +// offsetX = thisMultiDetector->offsetX[idet]; +// else +// offsetX = thisMultiDetector->offsetX[idet] + halfreadoutoffset; +// offsetX *= bytesperchannel; +// //cprintf(BLUE,"offsetx:%d offsety:%d maxx:%d slsmaxX:%d slsmaxY:%d bytesperchannel:%d\n", +// // offsetX,offsetY,maxX,slsmaxX,slsmaxY,bytesperchannel); +// // cprintf(BLUE,"copying bytes:%d\n", (slsmaxX/numReadoutPerDetector)*bytesperchannel); +// //itnerleaving with other detectors + +// //bottom +// if(((idet+1)%2) == 0){ +// for(int i=0;idataBytes)/sizeof(int); if(nel <= 0){ cout << "Multislsdetector databytes not valid :" << thisMultiDetector->dataBytes << endl; acquisitionIndex = -1; return NULL; } int n,complete=OK; int i,k,offsetX, offsetY, maxX, maxY; double dr; int* retval=new int[nel]; int *retdet = NULL, *p=retval; string fullFName=""; string ext=""; int index=-1,f_index=-1,p_index=-1,det_index=-1; double sv0=-1,sv1=-1; if(getDetectorsType() == EIGER){ maxX = thisMultiDetector->numberOfChannel[X]; maxY = thisMultiDetector->numberOfChannel[Y]; } for (int id=0; idnumberOfDetectors; id++) { if (detectors[id]) { n=detectors[id]->getDataBytes(); retdet=detectors[id]->readFrameFromReceiver(fName, acquisitionIndex, frameIndex, subFrameIndex); if(detectors[id]->getErrorMask()) setErrorMask(getErrorMask()|(1<getDataBytes(); if(getDetectorsType() == EIGER){ + //cout << "fname:"<getMaxNumberOfChannels()<<" n:"<getMaxNumberOfChannels(); + k=(int)(detectors[id]->getMaxNumberOfChannels(X)*dr); + //bit mode + //cout << "dr:"<offsetY[id] + detectors[id]->getMaxNumberOfChannels(Y))) * maxX)*dr);//bit mode + offsetX = (int)(thisMultiDetector->offsetX[id]*dr); + //cout << "offsetY"<numberOfDetectors; idet++) { if (detectors[idet]) { //if the detector has error @@ -5225,6 +5635,7 @@ string multiSlsDetector::getErrorMessage(int &critical){ int64_t multiSlsDetector::clearAllErrorMask(){ clearErrorMask(); + clearNotAddedList(); for (int idet=0; idetnumberOfDetectors; idet++) if (detectors[idet]) detectors[idet]->clearErrorMask(); @@ -5252,7 +5663,7 @@ int multiSlsDetector::calibratePedestal(int frames){ return ret; } -int multiSlsDetector::setReadReceiverFrequency(int getFromReceiver,int i){ +int multiSlsDetector::setReadReceiverFrequency(int getFromReceiver, int freq){ int ret=-100, ret1; if(!getFromReceiver) @@ -5260,7 +5671,7 @@ int multiSlsDetector::setReadReceiverFrequency(int getFromReceiver,int i){ for (int idet=0; idetnumberOfDetectors; idet++) { if (detectors[idet]) { - ret1=detectors[idet]->setReadReceiverFrequency(getFromReceiver,i); + ret1=detectors[idet]->setReadReceiverFrequency(getFromReceiver,freq); if(detectors[idet]->getErrorMask()) setErrorMask(getErrorMask()|(1<= 0){ + + if(threadStarted != enable){ + //destroy data threads + if(threadStarted) + createReceivingDataThreads(true); + + //create data threads + if(enable > 0){ + if(createReceivingDataThreads() == FAIL){ + std::cout << "Could not create data threads in client. Aborting creating data threads in receiver" << std::endl; + //only for the first det as theres no general one + setErrorMask(getErrorMask()|(1<<0)); + detectors[0]->setErrorMask((detectors[0]->getErrorMask())|(DATA_STREAMING)); + return -1; + } + } + } + + }else enable = threadStarted; + + int ret=-100, ret1; + for (int idet=0; idetnumberOfDetectors; idet++) { + if (detectors[idet]) { + ret1=detectors[idet]->enableDataStreamingFromReceiver(enable); + if(detectors[idet]->getErrorMask()) + setErrorMask(getErrorMask()|(1<add_task(task); } } + threadpool->startExecuting(); threadpool->wait_for_tasks_to_complete(); for(int idet=0; idetnumberOfDetectors; idet++){ if(detectors[idet]){ @@ -5518,6 +5972,7 @@ int multiSlsDetector::pulsePixelNMove(int n,int x,int y) { threadpool->add_task(task); } } + threadpool->startExecuting(); threadpool->wait_for_tasks_to_complete(); for(int idet=0; idetnumberOfDetectors; idet++){ if(detectors[idet]){ @@ -5554,6 +6009,7 @@ int multiSlsDetector::pulseChip(int n) { threadpool->add_task(task); } } + threadpool->startExecuting(); threadpool->wait_for_tasks_to_complete(); for(int idet=0; idetnumberOfDetectors; idet++){ if(detectors[idet]){ diff --git a/slsDetectorSoftware/multiSlsDetector/multiSlsDetector.h b/slsDetectorSoftware/multiSlsDetector/multiSlsDetector.h index 6def8e7c5..0be2eb72a 100644 --- a/slsDetectorSoftware/multiSlsDetector/multiSlsDetector.h +++ b/slsDetectorSoftware/multiSlsDetector/multiSlsDetector.h @@ -488,6 +488,22 @@ class multiSlsDetector : public slsDetectorUtils { int decodeNMod(int i, int &idet, int &imod); + /** programs FPGA with pof file + \param fname file name + \returns OK or FAIL + */ + int programFPGA(string fname); + + /** resets FPGA + \returns OK or FAIL + */ + int resetFPGA(); + + /** power on/off the chip + \param ival on is 1, off is 0, -1 to get + \returns OK or FAIL + */ + int powerChip(int ival= -1); /** loads the modules settings/trimbits reading from a file - file name extension is automatically generated! */ int loadSettingsFile(string fname, int nmod=0); @@ -1176,19 +1192,22 @@ class multiSlsDetector : public slsDetectorUtils { /** * resets framescaught * @param index frames caught by receiver - */ + */ int resetFramesCaught(); /** - * Reads a frame from receiver - * @param fName file name of current frame() - * @param acquisitionIndex current acquisition index - * @param frameIndex current frame index (for each scan) - * @param subFrameIndex current sub frame index (for 32 bit mode for eiger) - /returns a frame read from recever - */ - int* readFrameFromReceiver(char* fName, int &acquisitionIndex, int &frameIndex, int &subFrameIndex); + * Create Receiving Data Threads + * @param destroy is true to destroy all the threads + * @return OK or FAIL + */ + int createReceivingDataThreads(bool destroy = false); + + + /** Reads frames from receiver through a constant socket + */ + //void readFrameFromReceiver(); + int* readFrameFromReceiver(char*, int&, int&, int&); /** Locks/Unlocks the connection to the receiver /param lock sets (1), usets (0), gets (-1) the lock /returns lock status of the receiver @@ -1248,14 +1267,20 @@ class multiSlsDetector : public slsDetectorUtils { int calibratePedestal(int frames = 0); /** Sets the read receiver frequency - if Receiver read upon gui request, readRxrFrequency=0, + if data required from receiver randomly readRxrFrequency=0, else every nth frame to be sent to gui @param getFromReceiver is 1 if it should ask the receiver, - 0 if it can get it from multislsdetecter - @param i is the receiver read frequency + 0 if it can get it from multi structure + @param freq is the receiver read frequency /returns read receiver frequency */ - int setReadReceiverFrequency(int getFromReceiver, int i=-1); + int setReadReceiverFrequency(int getFromReceiver, int freq=-1); + + /** Enable or disable streaming data from receiver to client + * @param enable 0 to disable 1 to enable -1 to only get the value + * @returns data streaming + */ + int enableDataStreamingFromReceiver(int enable=-1); /** updates the multidetector offsets */ void updateOffsets(); @@ -1358,11 +1383,36 @@ class multiSlsDetector : public slsDetectorUtils { bool getAcquiringFlag(); +private: + /** + * Static function - Starts Data Thread of this object + * @param this_pointer pointer to this object + */ + static void* staticstartReceivingDataThread(void *this_pointer); + /** + * Thread that receives data packets from receiver + */ + void startReceivingDataThread(); + /* synchronizing between zmq threads */ + sem_t sem_singledone[MAXDET]; + sem_t sem_singlewait[MAXDET]; + int* singleframe[MAXDET]; + /* Parameters given to the gui picked up from zmq threads*/ + int currentAcquisitionIndex; + int currentFrameIndex; + int currentSubFrameIndex; + string currentFileName; - + pthread_t receivingDataThreads[MAXDET]; + /** Ensures if threads created successfully */ + bool threadStarted; + /** Current Thread Index*/ + int currentThreadIndex; + /** Set to self-terminate data receiving threads waiting for semaphores */ + bool killAllReceivingDataThreads; protected: @@ -1380,7 +1430,6 @@ class multiSlsDetector : public slsDetectorUtils { ThreadPool* threadpool; - }; diff --git a/slsDetectorSoftware/slsDetector/gitInfoLib.h b/slsDetectorSoftware/slsDetector/gitInfoLib.h index 35c43465a..c2fbbfdcc 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 "e9878a26ffb7e57c6e6724215e46ae5634871e64" -//#define SVNREV 0x1149 +#define SVNREPUUIDLIB "a10faa8aa60e206c4a0a25ae366e9c1e6f024cbc" +//#define SVNREV 0x1297 //#define SVNKIND "" //#define SVNSCHED "" #define SVNAUTHLIB "Dhanya_Maliakal" -#define SVNREVLIB 0x1149 -#define SVNDATELIB 0x20160824 +#define SVNREVLIB 0x1297 +#define SVNDATELIB 0x20161108 // diff --git a/slsDetectorSoftware/slsDetector/slsDetector.cpp b/slsDetectorSoftware/slsDetector/slsDetector.cpp index fd3d3e266..1bd6649bb 100644 --- a/slsDetectorSoftware/slsDetector/slsDetector.cpp +++ b/slsDetectorSoftware/slsDetector/slsDetector.cpp @@ -11,7 +11,6 @@ #include #include "gitInfoLib.h" - int slsDetector::initSharedMemory(detectorType type, int id) { @@ -24,7 +23,9 @@ int slsDetector::initSharedMemory(detectorType type, int id) { int sz; //shmId=-1; +#ifdef VERBOSE cout << "init shm"<< endl; +#endif switch(type) { case MYTHEN: nch=128; // complete mythen system @@ -124,7 +125,9 @@ int slsDetector::initSharedMemory(detectorType type, int id) { std::cout<<"*** shmat error (server) ***" << std::endl; return shm_id; } - +#ifdef VERBOSE + cout <<"shm done"<myDetectorType != EIGER){ + std::cout<< "Not implemented for this detector" << std::endl; + setErrorMask((getErrorMask())|(DETECTOR_ACTIVATE)); + return -1; + } + #ifdef VERBOSE if(!enable) std::cout<< "Deactivating Detector" << std::endl; @@ -1308,11 +1318,36 @@ int slsDetector::activate(int const enable){ } } #ifdef VERBOSE - if(retval) + if(retval==1) std::cout << "Detector Activated" << std::endl; - else + else if(retval==0) std::cout << "Detector Deactivated" << std::endl; + else + std::cout << "Detector Activation unknown:" << retval << std::endl; #endif + + if(ret!=FAIL){ + if(setReceiverOnline(ONLINE_FLAG)==ONLINE_FLAG){ +#ifdef VERBOSE + std::cout << "Activating/Deactivating Receiver: " << retval << std::endl; +#endif + if (connectData() == OK) + ret=thisReceiver->sendInt(fnum,retval,retval); + disconnectData(); + if(ret==FAIL) + setErrorMask((getErrorMask())|(RECEIVER_ACTIVATE)); + } + } +#ifdef VERBOSE + if(retval==1) + std::cout << "Receiver Activated" << std::endl; + else if(retval==0) + std::cout << "Receiver Deactivated" << std::endl; + else + std::cout << "Receiver Activation unknown:" << retval << std::endl; +#endif + + return retval; } @@ -1760,7 +1795,7 @@ int slsDetector::setNumberOfModules(int n, dimension d){ thisDetector->nModMax[Y]=thisDetector->nMod[Y]; int dr=thisDetector->dynamicRange; - if (dr==24) + if ((thisDetector->myDetectorType==MYTHEN) && (dr==24)) dr=32; thisDetector->dataBytes=thisDetector->nMod[X]*thisDetector->nMod[Y]*thisDetector->nChips*thisDetector->nChans*dr/8; @@ -3678,7 +3713,6 @@ int slsDetector::startAcquisition(){ }; int slsDetector::stopAcquisition(){ - int fnum=F_STOP_ACQUISITION; int ret=FAIL; char mess[MAX_STR_LENGTH]=""; @@ -4019,7 +4053,6 @@ int64_t slsDetector::setTimer(timerIndex index, int64_t t){ int fnum=F_SET_TIMER,fnum2=F_SET_RECEIVER_TIMER; int64_t retval = -1; - int64_t ut = -2; char mess[MAX_STR_LENGTH]=""; int ret=OK; int n=0; @@ -4027,9 +4060,9 @@ int64_t slsDetector::setTimer(timerIndex index, int64_t t){ if (index!=MEASUREMENTS_NUMBER) { - //#ifdef VERBOSE +#ifdef VERBOSE std::cout<< "Setting timer "<< index << " to " << t << "ns/value" << std::endl; - //#endif +#endif if (thisDetector->onlineFlag==ONLINE_FLAG) { if (connectControl() == OK){ controlSocket->SendDataOnly(&fnum,sizeof(fnum)); @@ -4056,7 +4089,7 @@ int64_t slsDetector::setTimer(timerIndex index, int64_t t){ } else { //std::cout<< "offline " << std::endl; if (t>=0) - thisDetector->timerValue[index]=t; + thisDetector->timerValue[index]=t; if((thisDetector->myDetectorType==GOTTHARD)|| (thisDetector->myDetectorType==PROPIX)|| (thisDetector->myDetectorType==JUNGFRAU)|| @@ -4066,10 +4099,11 @@ int64_t slsDetector::setTimer(timerIndex index, int64_t t){ getTotalNumberOfChannels(); // thisDetector->dataBytes=getTotalNumberOfChannels()*thisDetector->dynamicRange/8*thisDetector->timerValue[SAMPLES_JCTB]; } + } } else { - if (t>=0) - thisDetector->timerValue[index]=t; + if (t>=0) + thisDetector->timerValue[index]=t; } #ifdef VERBOSE std::cout<< "Timer " << index << " set to "<< thisDetector->timerValue[index] << "ns" << std::endl; @@ -4089,58 +4123,88 @@ int64_t slsDetector::setTimer(timerIndex index, int64_t t){ setTotalProgress(); } - double r; - if((index == SUBFRAME_ACQUISITION_TIME) && (thisDetector->myDetectorType == EIGER) && (t>=0) && getRateCorrection(r)){ - setRateCorrection(r); + if(t!=-1){ + if ((thisDetector->myDetectorType==MYTHEN)&&(index==PROBES_NUMBER)) { + setDynamicRange(); + //cout << "Changing probes: data size = " << thisDetector->dataBytes <myDetectorType == EIGER) && + getRateCorrection(r) && + (t>=0) && + + (((index == SUBFRAME_ACQUISITION_TIME) && (thisDetector->dynamicRange == 32))|| + ((index == ACQUISITION_TIME) && (thisDetector->dynamicRange == 16))) + + && (t>=0) && getRateCorrection(r)){ + setRateCorrection(r); + } } + + + //send acquisiton period/frame number to receiver if((index==FRAME_NUMBER)||(index==FRAME_PERIOD)||(index==CYCLES_NUMBER)){ - if(ret != FAIL){ - retval = thisDetector->timerValue[index]; - if(setReceiverOnline(ONLINE_FLAG)==ONLINE_FLAG){ - int64_t args[2]; - args[1] = retval; - if((t == -1) && (ret!= FORCE_UPDATE)) args[1] = -1; - - if((index==FRAME_NUMBER)||(index==CYCLES_NUMBER)){ -#ifdef VERBOSE - std::cout << "Setting/Getting number of frames " << index <<" to/from receiver " << args[1] << std::endl; -#endif - args[0] = FRAME_NUMBER; - retval = abs(thisDetector->timerValue[FRAME_NUMBER]*thisDetector->timerValue[CYCLES_NUMBER]); - if(args[1] != -1) args[1]=retval; - }else{ -#ifdef VERBOSE - std::cout << "Setting/Getting acquisition period " << index << " to/from receiver " << args[1] << std::endl; -#endif - args[0] = FRAME_PERIOD; - //if acquisition period is zero, then #frames/buffer depends on exposure time and not acq period - if(!retval) args[1] = timerValue[ACQUISITION_TIME]; - } - + if(ret != FAIL){ + int64_t args[2]; + retval = -1; + args[0] = index; + args[1] = thisDetector->timerValue[index]; - if (connectData() == OK) - ret=thisReceiver->sendIntArray(fnum2,ut,args); - disconnectData(); - if((ut != retval)|| (ret==FAIL)){ - ret = FAIL; - if(index==FRAME_PERIOD){ - //exptime sent if acq period = 0 - if(retval){ - cout << "ERROR:Acquisition Period in receiver set incorrectly to " << ut << " instead of " << thisDetector->timerValue[index] << endl; - setErrorMask((getErrorMask())|(RECEIVER_ACQ_PERIOD_NOT_SET)); - } - }else{ - cout << "ERROR:Number of Frames (* Number of cycles) in receiver set incorrectly to " << ut << " instead of " << thisDetector->timerValue[index] << endl; - setErrorMask((getErrorMask())|(RECEIVER_FRAME_NUM_NOT_SET)); + if(setReceiverOnline(ONLINE_FLAG)==ONLINE_FLAG){ + + //set #frames, #cycles + if((index==FRAME_NUMBER)||(index==CYCLES_NUMBER)){ +#ifdef VERBOSE + std::cout << "Setting/Getting number of frames " << index <<" to/from receiver " << args[1] << std::endl; +#endif + if(thisDetector->timerValue[CYCLES_NUMBER]==0) + args[1] = thisDetector->timerValue[FRAME_NUMBER]; + else + args[1] = thisDetector->timerValue[FRAME_NUMBER]*thisDetector->timerValue[CYCLES_NUMBER]; + } + //set period + else{ +#ifdef VERBOSE + std::cout << "Setting/Getting acquisition period " << index << " to/from receiver " << args[1] << std::endl; +#endif + //if acquisition period is zero, then #frames/buffer depends on exposure time and not acq period + if(!args[1]) + args[1] = timerValue[ACQUISITION_TIME]; + } + + char mess[MAX_STR_LENGTH]=""; + if (connectData() == OK) + ret=thisReceiver->sendIntArray(fnum2,retval,args,mess); + disconnectData(); + if((args[1] != retval)|| (ret==FAIL)){ + ret = FAIL; + if(index==FRAME_PERIOD){ + //exptime sent if acq period = 0 + if(retval){ + if(strstr(mess,"receiver not idle")==NULL) + cout << "ERROR:Acquisition Period in receiver set incorrectly to " << retval << " instead of " << args[1] << endl; + setErrorMask((getErrorMask())|(RECEIVER_ACQ_PERIOD_NOT_SET)); + } + }else{ + if(strstr(mess,"receiver not idle")==NULL) + cout << "ERROR:Number of Frames (* Number of cycles) in receiver set incorrectly to " << retval << " instead of " << args[1] << endl; + setErrorMask((getErrorMask())|(RECEIVER_FRAME_NUM_NOT_SET)); + } + } + + if(ret==FORCE_UPDATE) + updateReceiver(); + } } - } - - if(ret==FORCE_UPDATE) - updateReceiver(); - } - } } return thisDetector->timerValue[index]; }; @@ -4580,7 +4644,7 @@ int slsDetector::setDynamicRange(int n){ #ifdef VERBOSE std::cout<< "Setting dynamic range to "<< n << std::endl; #endif - if (n==24) + if ((thisDetector->myDetectorType == MYTHEN) &&(n==24)) n=32; @@ -4595,8 +4659,12 @@ int slsDetector::setDynamicRange(int n){ if (rateret==FAIL) { controlSocket->ReceiveDataOnly(mess,sizeof(mess)); std::cout<< "Detector returned error: " << mess << std::endl; - if(strstr(mess,"Rate Correction")!=NULL) - setErrorMask((getErrorMask())|(RATE_CORRECTION_NOT_32BIT)); + if(strstr(mess,"Rate Correction")!=NULL){ + if(strstr(mess,"32")!=NULL) + setErrorMask((getErrorMask())|(RATE_CORRECTION_NOT_32or16BIT)); + else + setErrorMask((getErrorMask())|(COULD_NOT_SET_RATE_CORRECTION)); + } } } controlSocket->ReceiveDataOnly(&ret,sizeof(ret)); @@ -5198,7 +5266,7 @@ int slsDetector::setRateCorrection(double t){ if(strstr(mess,"default tau")!=NULL) setErrorMask((getErrorMask())|(RATE_CORRECTION_NO_TAU_PROVIDED)); if(strstr(mess,"32")!=NULL) - setErrorMask((getErrorMask())|(RATE_CORRECTION_NOT_32BIT)); + setErrorMask((getErrorMask())|(RATE_CORRECTION_NOT_32or16BIT)); else setErrorMask((getErrorMask())|(COULD_NOT_SET_RATE_CORRECTION)); } @@ -5554,7 +5622,7 @@ char* slsDetector::setDetectorMAC(string detectorMAC){ (detectorMAC[11]==':')&&(detectorMAC[14]==':')){ strcpy(thisDetector->detectorMAC,detectorMAC.c_str()); if(!strcmp(thisDetector->receiver_hostname,"none")) - std::cout << "Warning: UDP Set up failed. Receiver hostname not set." << endl; + std::cout << "Warning: Receiver hostname not set yet." << endl; else if(setUDPConnection()==FAIL) std::cout<< "Warning: UDP connection set up failed" << std::endl; }else{ @@ -5581,7 +5649,7 @@ char* slsDetector::setDetectorIP(string detectorIP){ if(result!=0){ strcpy(thisDetector->detectorIP,detectorIP.c_str()); if(!strcmp(thisDetector->receiver_hostname,"none")) - std::cout << "Warning: UDP Set up failed. Receiver hostname not set." << endl; + std::cout << "Warning: Receiver hostname not set yet." << endl; else if(setUDPConnection()==FAIL) std::cout<< "Warning: UDP connection set up failed" << std::endl; }else{ @@ -5600,6 +5668,7 @@ char* slsDetector::setReceiver(string receiverIP){ cprintf(RED,"Acquisition already running, Stopping it.\n"); stopAcquisition(); } + updateDetector(); strcpy(thisDetector->receiver_hostname,receiverIP.c_str()); @@ -5620,6 +5689,7 @@ char* slsDetector::setReceiver(string receiverIP){ std::cout << "frame number:" << thisDetector->timerValue[FRAME_NUMBER] << endl; std::cout << "dynamic range:" << thisDetector->dynamicRange << endl << endl; std::cout << "10GbE:" << thisDetector->tenGigaEnable << endl << endl; + //std::cout << "dataStreaming:" << enableDataStreamingFromReceiver(-1) << endl << endl; /** enable compresison, */ #endif if(setDetectorType()!= GENERIC){ @@ -5643,6 +5713,10 @@ char* slsDetector::setReceiver(string receiverIP){ setTimer(FRAME_PERIOD,thisDetector->timerValue[FRAME_PERIOD]); setTimer(FRAME_NUMBER,thisDetector->timerValue[FRAME_NUMBER]); setDynamicRange(thisDetector->dynamicRange); + if(thisDetector->myDetectorType == EIGER) + activate(-1); + //std::cout << "***********************************dataStreaming:" << parentDet->enableDataStreamingFromReceiver(-1) << endl << endl; + //parentDet->enableDataStreamingFromReceiver(parentDet->enableDataStreamingFromReceiver(-1)); //set scan tag setUDPConnection(); if(thisDetector->myDetectorType == EIGER) @@ -5668,7 +5742,7 @@ char* slsDetector::setReceiverUDPIP(string udpip){ }else{ strcpy(thisDetector->receiverUDPIP,udpip.c_str()); if(!strcmp(thisDetector->receiver_hostname,"none")) - std::cout << "Warning: UDP Set up failed. Receiver hostname not set." << endl; + std::cout << "Warning: Receiver hostname not set yet." << endl; else if(setUDPConnection()==FAIL){ std::cout<< "Warning: UDP connection set up failed" << std::endl; } @@ -5691,7 +5765,7 @@ char* slsDetector::setReceiverUDPMAC(string udpmac){ (udpmac[11]==':')&&(udpmac[14]==':')){ strcpy(thisDetector->receiverUDPMAC,udpmac.c_str()); if(!strcmp(thisDetector->receiver_hostname,"none")) - std::cout << "Warning: UDP Set up failed. Receiver hostname not set." << endl; + std::cout << "Warning: Receiver hostname not set yet." << endl; else if(setUDPConnection()==FAIL){ std::cout<< "Warning: UDP connection set up failed" << std::endl; } @@ -5710,7 +5784,7 @@ char* slsDetector::setReceiverUDPMAC(string udpmac){ int slsDetector::setReceiverUDPPort(int udpport){ thisDetector->receiverUDPPort = udpport; if(!strcmp(thisDetector->receiver_hostname,"none")) - std::cout << "Warning: UDP Set up failed. Receiver hostname not set." << endl; + std::cout << "Warning: Receiver hostname not set yet." << endl; else if(setUDPConnection()==FAIL){ std::cout<< "Warning: UDP connection set up failed" << std::endl; } @@ -5720,7 +5794,7 @@ int slsDetector::setReceiverUDPPort(int udpport){ int slsDetector::setReceiverUDPPort2(int udpport){ thisDetector->receiverUDPPort2 = udpport; if(!strcmp(thisDetector->receiver_hostname,"none")) - std::cout << "Warning: UDP Set up failed. Receiver hostname not set." << endl; + std::cout << "Warning: Receiver hostname not set yet." << endl; else if(setUDPConnection()==FAIL){ std::cout<< "Warning: UDP connection set up failed" << std::endl; } @@ -5774,7 +5848,7 @@ int slsDetector::setUDPConnection(){ //called before set up if(!strcmp(thisDetector->receiver_hostname,"none")){ - std::cout << "Warning: UDP Set up failed. Receiver hostname not set." << endl; + std::cout << "Warning: Receiver hostname not set yet." << endl; return FAIL; } @@ -6478,6 +6552,260 @@ int slsDetector::writeSettingsFile(string fname, int imod, int* iodelay){ +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; + + if(thisDetector->myDetectorType != JUNGFRAU){ + std::cout << "Not implemented for this detector" << std::endl; + return FAIL; + } + + + //check if it exists + struct stat st; + if(stat(fname.c_str(),&st)){ + std::cout << "Programming file does not exist" << endl; + setErrorMask((getErrorMask())|(PROGRAMMING_ERROR)); + return FAIL; + } + //create destination file name,replaces original filename with Jungfrau.rawbin + string destfname; + size_t found = fname.find_last_of("/\\"); + if(found == string::npos) + destfname = ""; + else + destfname = fname.substr(0,found+1); + destfname.append("Jungfrau_MCB.rawbin"); +#ifdef VERBOSE + std::cout << "Converting " << fname << " to " << destfname << std::endl; +#endif + int filepos,x,y,i; + FILE* src = fopen(fname.c_str(),"rb"); + FILE* dst = fopen(destfname.c_str(),"wb"); + // Remove header (0...11C) + for (filepos=0; filepos < 0x11C; filepos++) + fgetc(src); + // Write 0x80 times 0xFF (0...7F) + for (filepos=0; filepos < 0x80; filepos++) + fputc(0xFF,dst); + // Swap bits and write to file + for (filepos=0x80; filepos < 0x1000000; filepos++) { + x = fgetc(src); + if (x < 0) break; + y=0; + for (i=0; i < 8; i++) + y=y| ( (( x & (1<> i) << (7-i) ); // This swaps the bits + fputc(y,dst); + } + if (filepos < 0x1000000){ + std::cout << "Could not convert programming file. EOF before end of flash" << std::endl; + setErrorMask((getErrorMask())|(PROGRAMMING_ERROR)); + return FAIL; + } +#ifdef VERBOSE + std::cout << "File has been converted to " << destfname << std::endl; +#endif + //loading file to memory + FILE* fp = fopen(destfname.c_str(),"r"); + if(fp == NULL){ + std::cout << "Could not open rawbin file" << std::endl; + setErrorMask((getErrorMask())|(PROGRAMMING_ERROR)); + return FAIL; + } + if(fseek(fp,0,SEEK_END)){ + std::cout << "Seek error in rawbin file" << std::endl; + setErrorMask((getErrorMask())|(PROGRAMMING_ERROR)); + return FAIL; + } + filesize = ftell(fp); + if(filesize <= 0){ + std::cout << "Could not get length of rawbin file" << std::endl; + setErrorMask((getErrorMask())|(PROGRAMMING_ERROR)); + return FAIL; + } + rewind(fp); + fpgasrc = (char*)malloc(filesize+1); + if(fpgasrc == NULL){ + std::cout << "Could not allocate size of program" << std::endl; + setErrorMask((getErrorMask())|(PROGRAMMING_ERROR)); + return FAIL; + } + if(fread(fpgasrc, sizeof(char), filesize, fp) != filesize){ + std::cout << "Could not read rawbin file" << std::endl; + setErrorMask((getErrorMask())|(PROGRAMMING_ERROR)); + return FAIL; + } + + if(fclose(fp)){ + std::cout << "Could not close rawbin file" << std::endl; + setErrorMask((getErrorMask())|(PROGRAMMING_ERROR)); + return FAIL; + } +#ifdef VERBOSE + std::cout << "Successfully loaded the rawbin file to program memory" << std::endl; +#endif + + + +#ifdef VERBOSE + std::cout<< "Sending programming binary to detector " << endl; +#endif + if (setOnline(ONLINE_FLAG)==ONLINE_FLAG) { + if (connectControl() == OK){ + controlSocket->SendDataOnly(&fnum,sizeof(fnum)); + controlSocket->SendDataOnly(&filesize,sizeof(filesize)); + //check opening error + controlSocket->ReceiveDataOnly(&ret,sizeof(ret)); + if (ret==FAIL) { + controlSocket->ReceiveDataOnly(mess,sizeof(mess)); + std::cout<< "Detector returned error: " << mess << std::endl; + setErrorMask((getErrorMask())|(PROGRAMMING_ERROR)); + filesize = 0; + } + + + //erasing flash + if(ret!=FAIL){ + std::cout<< "This can take awhile. Please be patient..." << endl; + printf("Erasing Flash:%d%%\r",0); + std::cout << flush; + //erasing takes 65 seconds, printing here (otherwise need threads in server-unnecessary) + int count = 66; + while(count>0){ + usleep(1 * 1000 * 1000); + count--; + printf("Erasing Flash:%d%%\r",(int) (((double)(65-count)/65)*100)); + std::cout << flush; + } + std::cout< 0)){ + + unitprogramsize = MAX_FPGAPROGRAMSIZE; //2mb + if(unitprogramsize > filesize) //less than 2mb + unitprogramsize = filesize; +#ifdef VERBOSE + std::cout << "unitprogramsize:" << unitprogramsize << "\t filesize:" << filesize << std::endl; +#endif + controlSocket->SendDataOnly(fpgasrc+currentPointer,unitprogramsize); + controlSocket->ReceiveDataOnly(&ret,sizeof(ret)); + if (ret!=FAIL) { + filesize-=unitprogramsize; + currentPointer+=unitprogramsize; + + //print progress + printf("Writing to Flash:%d%%\r",(int) (((double)(totalsize-filesize)/totalsize)*100)); + std::cout << flush; + }else{ + controlSocket->ReceiveDataOnly(mess,sizeof(mess)); + std::cout<< "Detector returned error: " << mess << std::endl; + setErrorMask((getErrorMask())|(PROGRAMMING_ERROR)); + } + } + std::cout<ReceiveDataOnly(&ret,sizeof(ret)); + if (ret==FAIL) { + controlSocket->ReceiveDataOnly(mess,sizeof(mess)); + std::cout<< "Detector returned error: " << mess << std::endl; + setErrorMask((getErrorMask())|(PROGRAMMING_ERROR)); + } + disconnectControl(); + if (ret==FORCE_UPDATE) + updateDetector(); + } + } + + //free resources + if(fpgasrc != NULL) + free(fpgasrc); + + return ret; +} + + +int slsDetector::resetFPGA(){ + int ret=FAIL; + int fnum=F_RESET_FPGA; + char mess[MAX_STR_LENGTH]=""; + + if(thisDetector->myDetectorType != JUNGFRAU){ + std::cout << "Not implemented for this detector" << std::endl; + return FAIL; + } +#ifdef VERBOSE + std::cout<< "Sending reset to FPGA " << endl; +#endif + if (setOnline(ONLINE_FLAG)==ONLINE_FLAG) { + if (connectControl() == OK){ + controlSocket->SendDataOnly(&fnum,sizeof(fnum)); + + //check opening error + controlSocket->ReceiveDataOnly(&ret,sizeof(ret)); + if (ret==FAIL) { + controlSocket->ReceiveDataOnly(mess,sizeof(mess)); + std::cout<< "Detector returned error: " << mess << std::endl; + setErrorMask((getErrorMask())|(RESET_ERROR)); + } + + disconnectControl(); + if (ret==FORCE_UPDATE) + updateDetector(); + } + } + return ret; + +} + + + +int slsDetector::powerChip(int ival){ + int ret=FAIL; + int fnum=F_POWER_CHIP; + char mess[MAX_STR_LENGTH]=""; + int retval=-1; + + if(thisDetector->myDetectorType != JUNGFRAU && thisDetector->myDetectorType != JUNGFRAUCTB ){ + std::cout << "Not implemented for this detector" << std::endl; + return FAIL; + } +#ifdef VERBOSE + std::cout<< "Sending power on/off/get to the chip " << endl; +#endif + if (setOnline(ONLINE_FLAG)==ONLINE_FLAG) { + if (connectControl() == OK){ + controlSocket->SendDataOnly(&fnum,sizeof(fnum)); + controlSocket->SendDataOnly(&ival,sizeof(ival)); + //check opening error + controlSocket->ReceiveDataOnly(&ret,sizeof(ret)); + if (ret==FAIL) { + controlSocket->ReceiveDataOnly(mess,sizeof(mess)); + std::cout<< "Detector returned error: " << mess << std::endl; + setErrorMask((getErrorMask())|(POWER_CHIP)); + }else + controlSocket->ReceiveDataOnly(&retval,sizeof(retval)); + disconnectControl(); + if (ret==FORCE_UPDATE) + updateDetector(); + } + } + return retval; + +} int slsDetector::loadSettingsFile(string fname, int imod) { sls_detector_module *myMod=NULL; @@ -6933,8 +7261,11 @@ string slsDetector::setFilePath(string s) { if(stat(s.c_str(),&st)){ std::cout << "path does not exist" << endl; setErrorMask((getErrorMask())|(FILE_PATH_DOES_NOT_EXIST)); - }else + }else{ + pthread_mutex_lock(&ms); fileIO::setFilePath(s); + pthread_mutex_unlock(&ms); + } } } @@ -6946,8 +7277,11 @@ string slsDetector::setFilePath(string s) { if (connectData() == OK) ret=thisReceiver->sendString(fnum,retval,arg); disconnectData(); - if(ret!=FAIL) + if(ret!=FAIL){ + pthread_mutex_lock(&ms); fileIO::setFilePath(string(retval)); + pthread_mutex_unlock(&ms); + } else if(!s.empty()){ std::cout << "path does not exist" << endl; setErrorMask((getErrorMask())|(FILE_PATH_DOES_NOT_EXIST)); @@ -6956,7 +7290,11 @@ string slsDetector::setFilePath(string s) { updateReceiver(); } - return fileIO::getFilePath(); + pthread_mutex_lock(&ms); + s = fileIO::getFilePath(); + pthread_mutex_unlock(&ms); + + return s; } @@ -7001,7 +7339,11 @@ string slsDetector::setFileName(string s) { } } - return fileIO::getFileName(); + pthread_mutex_lock(&ms); + s = fileIO::getFileName(); + pthread_mutex_unlock(&ms); + + return s; } @@ -7252,65 +7594,54 @@ int slsDetector::resetFramesCaught(){ } - - - -int* slsDetector::readFrameFromReceiver(char* fName, int &acquisitionIndex, int &frameIndex, int &subFrameIndex){ - int fnum=F_READ_RECEIVER_FRAME; - int nel=thisDetector->dataBytes/sizeof(int); - int* retval=new int[nel]; - int ret=FAIL; - int n; - char mess[MAX_STR_LENGTH]="Nothing"; - - if (setReceiverOnline(ONLINE_FLAG)==ONLINE_FLAG) { -#ifdef VERBOSE - std::cout<< "slsDetector: Reading frame from receiver "<< thisDetector->dataBytes << " " <SendDataOnly(&fnum,sizeof(fnum)); - dataSocket->ReceiveDataOnly(&ret,sizeof(ret)); - - if (ret==FAIL) { - n= dataSocket->ReceiveDataOnly(mess,sizeof(mess)); - std::cout<< "Detector returned: " << mess << " " << n << std::endl; - delete [] retval; - disconnectData(); - return NULL; - } else { - n=dataSocket->ReceiveDataOnly(fName,MAX_STR_LENGTH); - n=dataSocket->ReceiveDataOnly(&acquisitionIndex,sizeof(acquisitionIndex)); - n=dataSocket->ReceiveDataOnly(&frameIndex,sizeof(frameIndex)); - if(thisDetector->myDetectorType == EIGER) - n=dataSocket->ReceiveDataOnly(&subFrameIndex,sizeof(subFrameIndex)); - n=dataSocket->ReceiveDataOnly(retval,thisDetector->dataBytes); - -#ifdef VERBOSE - std::cout<< "Received "<< n << " data bytes" << std::endl; -#endif - if (n!=thisDetector->dataBytes) { - std::cout<dataBytes << std::endl; - ret=FAIL; - delete [] retval; - disconnectData(); - return NULL; - } - - //jungfrau masking adcval - if(thisDetector->myDetectorType == JUNGFRAU){ - for(unsigned int i=0;idataBytes/sizeof(int); + int* retval=new int[nel]; + int ret=FAIL; + int n; + char mess[MAX_STR_LENGTH]="Nothing"; + if (setReceiverOnline(ONLINE_FLAG)==ONLINE_FLAG) { +#ifdef VERBOSE + std::cout<< "slsDetector: Reading frame from receiver "<< thisDetector->dataBytes << " " <SendDataOnly(&fnum,sizeof(fnum)); + dataSocket->ReceiveDataOnly(&ret,sizeof(ret)); + if (ret==FAIL) { + n= dataSocket->ReceiveDataOnly(mess,sizeof(mess)); + std::cout<< "Detector returned: " << mess << " " << n << std::endl; + delete [] retval; + disconnectData(); + return NULL; + } else { + n=dataSocket->ReceiveDataOnly(fName,MAX_STR_LENGTH); + n=dataSocket->ReceiveDataOnly(&acquisitionIndex,sizeof(acquisitionIndex)); + n=dataSocket->ReceiveDataOnly(&frameIndex,sizeof(frameIndex)); + if(thisDetector->myDetectorType == EIGER) + n=dataSocket->ReceiveDataOnly(&subFrameIndex,sizeof(subFrameIndex)); + n=dataSocket->ReceiveDataOnly(retval,thisDetector->dataBytes); +#ifdef VERBOSE + std::cout<< "Received "<< n << " data bytes" << std::endl; +#endif + if (n!=thisDetector->dataBytes) { + std::cout<dataBytes << std::endl; + ret=FAIL; + delete [] retval; + disconnectData(); + return NULL; } + //jungfrau masking adcval + if(thisDetector->myDetectorType == JUNGFRAU){ + for(unsigned int i=0;iReceiveDataOnly(&ind,sizeof(ind)); pthread_mutex_lock(&ms); fileIO::setFileIndex(ind); pthread_mutex_unlock(&ms); + 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); pthread_mutex_lock(&ms); fileIO::setFileName(path); pthread_mutex_unlock(&ms); + return OK; } @@ -7533,7 +7870,9 @@ int slsDetector::setFrameIndex(int index){ int arg = index; if(thisDetector->receiverOnlineFlag==OFFLINE_FLAG){ - fileIO::setFrameIndex(index); + pthread_mutex_lock(&ms); + fileIO::setFrameIndex(index); + pthread_mutex_unlock(&ms); } else if(setReceiverOnline(ONLINE_FLAG)==ONLINE_FLAG){ @@ -7542,14 +7881,20 @@ int slsDetector::setFrameIndex(int index){ #endif if (connectData() == OK) ret=thisReceiver->sendInt(fnum,retval,arg); - disconnectData(); - if(ret!=FAIL) + disconnectData(); + if(ret!=FAIL){ + pthread_mutex_lock(&ms); fileIO::setFrameIndex(retval); + pthread_mutex_unlock(&ms); + } if(ret==FORCE_UPDATE) updateReceiver(); } + pthread_mutex_lock(&ms); + retval = fileIO::getFrameIndex(); + pthread_mutex_unlock(&ms); - return fileIO::getFrameIndex(); + return retval; } @@ -7600,18 +7945,18 @@ int64_t slsDetector::clearAllErrorMask(){ -int slsDetector::setReadReceiverFrequency(int getFromReceiver,int i){ +int slsDetector::setReadReceiverFrequency(int getFromReceiver, int freq){ int fnum=F_READ_RECEIVER_FREQUENCY; int ret = FAIL; int retval=-1; - int arg = i; + int arg = freq; if(!getFromReceiver) return retval; if(setReceiverOnline(ONLINE_FLAG)==ONLINE_FLAG){ #ifdef VERBOSE - std::cout << "Sending read frequency to receiver " << arg << std::endl; + std::cout << "Sending read frequency to receiver " << arg << std::endl; #endif if (connectData() == OK) ret=thisReceiver->sendInt(fnum,retval,arg); @@ -7622,14 +7967,44 @@ int slsDetector::setReadReceiverFrequency(int getFromReceiver,int i){ updateReceiver(); } - if ((i > 0) && (retval != i)){ - cout << "could not set receiver read frequency:" << retval << endl; + if ((freq > 0) && (retval != freq)){ + cout << "could not set receiver read frequency to " << freq <<" Returned:" << retval << endl; setErrorMask((getErrorMask())|(RECEIVER_READ_FREQUENCY)); } return retval; } + +int slsDetector::enableDataStreamingFromReceiver(int enable){ + int fnum=F_STREAM_DATA_FROM_RECEIVER; + int ret = FAIL; + int retval=-1; + int arg = enable; + + + if(setReceiverOnline(ONLINE_FLAG)==ONLINE_FLAG){ +#ifdef VERBOSE + std::cout << "***************Sending Data Streaming in Receiver " << arg << std::endl; +#endif + if (connectData() == OK) + ret=thisReceiver->sendInt(fnum,retval,arg); + disconnectData(); + if(ret==FAIL) + retval = -1; + if(ret==FORCE_UPDATE) + updateReceiver(); + } + + if ((enable > 0) && (retval != enable)){ + cout << "could not set data streaming in receiver to " << enable <<" Returned:" << retval << endl; + setErrorMask((getErrorMask())|(DATA_STREAMING)); + } + return retval; +} + + + int slsDetector::enableReceiverCompression(int i){ int fnum=F_ENABLE_RECEIVER_COMPRESSION; int ret = FAIL; diff --git a/slsDetectorSoftware/slsDetector/slsDetector.h b/slsDetectorSoftware/slsDetector/slsDetector.h index 60260558c..84ef549c3 100644 --- a/slsDetectorSoftware/slsDetector/slsDetector.h +++ b/slsDetectorSoftware/slsDetector/slsDetector.h @@ -522,7 +522,24 @@ class slsDetector : public slsDetectorUtils, public energyConversion { }; - + /** programs FPGA with pof file + \param fname file name + \returns OK or FAIL + */ + int programFPGA(string fname); + + /** resets FPGA + \returns OK or FAIL + */ + int resetFPGA(); + + /** power on/off the chip + \param ival on is 1, off is 0, -1 to get + \returns OK or FAIL + */ + int powerChip(int ival= -1); + + /** loads the modules settings/trimbits reading from a file \param fname file name . If not specified, extension is automatically generated! \param imod module number, -1 means all modules @@ -1580,15 +1597,18 @@ class slsDetector : public slsDetectorUtils, public energyConversion { int resetFramesCaught(); /** - * Reads a frame from receiver - * @param fName file name of current frame() - * @param acquisitionIndex current acquisition index - * @param frameIndex current frame index (for each scan) - * @param subFrameIndex current sub frame index (for 32 bit mode for eiger) - /returns a frame read from recever - */ - int* readFrameFromReceiver(char* fName, int &acquisitionIndex, int &frameIndex, int &subFrameIndex); + * Create Receiving Data Threads + * @param destroy is true to destroy all the threads + * @return OK or FAIL + */ + int createReceivingDataThreads(bool destroy = false){return 0;}; + + /** Reads frames from receiver through a constant socket + */ + //void readFrameFromReceiver(){}; + + int* readFrameFromReceiver(char*, int&, int&, int&); /** Locks/Unlocks the connection to the receiver /param lock sets (1), usets (0), gets (-1) the lock /returns lock status of the receiver @@ -1688,14 +1708,20 @@ class slsDetector : public slsDetectorUtils, public energyConversion { char* setDetectorNetworkParameter(networkParameter index, int delay); /** Sets the read receiver frequency - if Receiver read upon gui request, readRxrFrequency=0, + if data required from receiver randomly readRxrFrequency=0, else every nth frame to be sent to gui @param getFromReceiver is 1 if it should ask the receiver, - 0 if it can get it from multislsdetecter - @param i is the receiver read frequency + 0 if it can get it from multi structure + @param freq is the receiver read frequency /returns read receiver frequency */ - int setReadReceiverFrequency(int getFromReceiver, int i=-1); + int setReadReceiverFrequency(int getFromReceiver, int freq=-1); + + /** Enable or disable streaming data from receiver to client + * @param enable 0 to disable 1 to enable -1 to only get the value + * @returns data streaming + */ + int enableDataStreamingFromReceiver(int enable=-1); /** enable/disable or get data compression in receiver * @param i is -1 to get, 0 to disable and 1 to enable diff --git a/slsDetectorSoftware/slsDetector/slsDetectorActions.cpp b/slsDetectorSoftware/slsDetector/slsDetectorActions.cpp index 5d0b77621..a9c3616a8 100644 --- a/slsDetectorSoftware/slsDetector/slsDetectorActions.cpp +++ b/slsDetectorSoftware/slsDetector/slsDetectorActions.cpp @@ -146,6 +146,7 @@ int slsDetectorActions::getActionMode(int iaction){ int slsDetectorActions::setScan(int iscan, string script, int nvalues, double *values, string par, int precision) { if (iscan>=0 && iscansetOnline(ONLINE_FLAG); + myDet->setReceiverOnline(ONLINE_FLAG); + + if (action==HELP_ACTION) + return helpStatus(narg,args,HELP_ACTION); + + if (action==PUT_ACTION) { + if (!sscanf(args[1],"%d",&ival)) + return string ("cannot scan datastream mode"); + myDet->enableDataStreamingFromReceiver(ival); + } + sprintf(ans,"%d",myDet->enableDataStreamingFromReceiver()); + return string(ans); +} + + +string slsDetectorCommand::helpDataStream(int narg, char *args[], int action) { + + ostringstream os; + if (action==GET_ACTION || action==HELP_ACTION) + os << string("datastream \t gets if zmq data stream from receiver is enabled. \n"); + if (action==PUT_ACTION || action==HELP_ACTION) + os << string("datastream i\t enables/disables the zmq data stream from receiver. \n"); + return os.str(); +} + + + string slsDetectorCommand::cmdFree(int narg, char *args[], int action) { #ifdef VERBOSE @@ -3894,6 +3974,10 @@ string slsDetectorCommand::cmdADC(int narg, char *args[], int action) { adc=TEMPERATURE_SODL; else if (cmd=="temp_sodr") adc=TEMPERATURE_SODR; + else if (cmd=="temp_fpgafl") + adc=TEMPERATURE_FPGA2; + else if (cmd=="temp_fpgafr") + adc=TEMPERATURE_FPGA3; else return string("cannot decode adc ")+cmd; @@ -3926,6 +4010,8 @@ string slsDetectorCommand::helpADC(int narg, char *args[], int action) { os << "temp_dcdc " << "Cannot be set" << std::endl; os << "temp_sodl " << "Cannot be set" << std::endl; os << "temp_sodr " << "Cannot be set" << std::endl; + os << "temp_fpgafl " << "Cannot be set" << std::endl; + os << "temp_fpgafr " << "Cannot be set" << std::endl; } if (action==GET_ACTION || action==HELP_ACTION) { os << "temp_adc " << "\t gets the temperature of the adc" << std::endl; @@ -3935,6 +4021,8 @@ string slsDetectorCommand::helpADC(int narg, char *args[], int action) { os << "temp_dcdc " << "\t gets the temperature close to the dc dc converter" << std::endl; os << "temp_sodl " << "\t gets the temperature close to the left so-dimm memory" << std::endl; os << "temp_sodr " << "\t gets the temperature close to the right so-dimm memory" << std::endl; + os << "temp_fpgafl " << "\t gets the temperature of the left front end board fpga" << std::endl; + os << "temp_fpgafr " << "\t gets the temperature of the left front end board fpga" << std::endl; } return os.str(); } @@ -4201,6 +4289,13 @@ string slsDetectorCommand::cmdSpeed(int narg, char *args[], int action) { index=ADC_CLOCK; else if (cmd=="adcphase") { index=ADC_PHASE; + t=100000; + } else if (cmd=="adcpipeline") + index=ADC_PIPELINE; + else if (cmd=="dbitclk") + index=DBIT_CLOCK; + else if (cmd=="dbitphase") { + index=DBIT_PHASE; t=100000; } else if (cmd=="adcpipeline") index=ADC_PIPELINE; @@ -4268,15 +4363,16 @@ string slsDetectorCommand::helpSpeed(int narg, char *args[], int action) { string slsDetectorCommand::cmdAdvanced(int narg, char *args[], int action) { -int retval; -char answer[1000]=""; + int retval; + char answer[1000]=""; - if (action==HELP_ACTION) - return helpAdvanced(narg, args, action); - - if (cmd=="flags") { + if (action==HELP_ACTION) + return helpAdvanced(narg, args, action); + + if (cmd=="flags") { + + readOutFlags flag=GET_READOUT_FLAGS; - readOutFlags flag=GET_READOUT_FLAGS; if (action==PUT_ACTION) { string sval=string(args[1]); @@ -4302,9 +4398,7 @@ char answer[1000]=""; return string("could not scan flag ")+string(args[1]); } - - myDet->setOnline(ONLINE_FLAG); - + myDet->setOnline(ONLINE_FLAG); retval = myDet->setReadOutFlags(flag); // cout << hex << flag << " " << retval << endl; @@ -4333,25 +4427,67 @@ char answer[1000]=""; return string("unknown"); - } else if (cmd=="extsig") { - externalSignalFlag flag=GET_EXTERNAL_SIGNAL_FLAG; - int is=-1; - if (sscanf(args[0],"extsig:%d",&is)) - ; - else - return string("could not scan signal number ")+string(args[0]); - - if (action==PUT_ACTION) { - flag=myDet->externalSignalType(args[1]); - if (flag==GET_EXTERNAL_SIGNAL_FLAG) - return string("could not scan external signal mode ")+string(args[1]); - } - myDet->setOnline(ONLINE_FLAG); - - return myDet->externalSignalType(myDet->setExternalSignalFlags(flag,is)); + } else if (cmd=="extsig") { + externalSignalFlag flag=GET_EXTERNAL_SIGNAL_FLAG; + int is=-1; + if (sscanf(args[0],"extsig:%d",&is)) + ; + else + return string("could not scan signal number ")+string(args[0]); - } else - return string("could not decode flag ")+cmd; + if (action==PUT_ACTION) { + flag=myDet->externalSignalType(args[1]); + if (flag==GET_EXTERNAL_SIGNAL_FLAG) + return string("could not scan external signal mode ")+string(args[1]); + } + myDet->setOnline(ONLINE_FLAG); + + return myDet->externalSignalType(myDet->setExternalSignalFlags(flag,is)); + + + } else if (cmd=="programfpga") { + if (action==GET_ACTION) + return string("cannot get"); + if(strstr(args[1],".pof")==NULL) + return string("wrong usage: programming file should have .pof extension"); + string sval=string(args[1]); +#ifdef VERBOSE + std::cout<< " programming file " << sval << std::endl; +#endif + myDet->setOnline(ONLINE_FLAG); + if(myDet->programFPGA(sval) == OK) + return string("successful"); + return string("unsuccessful"); + } + + + else if (cmd=="resetfpga") { + if (action==GET_ACTION) + return string("cannot get"); +#ifdef VERBOSE + std::cout<< " resetting fpga " << sval << std::endl; +#endif + myDet->setOnline(ONLINE_FLAG); + if(myDet->resetFPGA() == OK) + return string("successful"); + return string("unsuccessful"); + } + + + else if (cmd=="powerchip") { + char ans[100]; + myDet->setOnline(ONLINE_FLAG); + if (action==PUT_ACTION){ + int ival = -1; + if (!sscanf(args[1],"%d",&ival)) + return string("could not scan powerchip parameter " + string(args[1])); + myDet->powerChip(ival); + } + sprintf(ans,"%d",myDet->powerChip()); + return string(ans); + } + else + return string("unknown command ")+cmd; } @@ -4363,7 +4499,9 @@ string slsDetectorCommand::helpAdvanced(int narg, char *args[], int action) { os << "extsig:i mode \t sets 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 mode \t sets the readout flags to mode. can be none, storeinram, tot, continous, parallel, nonparallel, safe, digital, analog_digital, unknown" << std::endl; - + + 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; } if (action==GET_ACTION || action==HELP_ACTION) { @@ -4482,7 +4620,8 @@ string slsDetectorCommand::cmdReceiver(int narg, char *args[], int action) { if(!strcasecmp(args[1],"start")) myDet->startReceiver(); else if(!strcasecmp(args[1],"stop")){ - myDet->startReceiverReadout(); + //myDet->stopReceiver(); + // myDet->startReceiverReadout(); /*runStatus s = myDet->getReceiverStatus(); while(s != RUN_FINISHED){ usleep(50000); diff --git a/slsDetectorSoftware/slsDetector/slsDetectorCommand.h b/slsDetectorSoftware/slsDetector/slsDetectorCommand.h index 454e01f9f..dd8b4c73c 100644 --- a/slsDetectorSoftware/slsDetector/slsDetectorCommand.h +++ b/slsDetectorSoftware/slsDetector/slsDetectorCommand.h @@ -38,6 +38,7 @@ class slsDetectorCommand : public virtual slsDetectorDefs { static string helpData(int narg, char *args[], int action); static string helpFrame(int narg, char *args[], int action); static string helpStatus(int narg, char *args[], int action); + static string helpDataStream(int narg, char *args[], int action); static string helpFree(int narg, char *args[], int action); static string helpAdd(int narg, char *args[], int action); static string helpRemove(int narg, char *args[], int action); @@ -109,6 +110,7 @@ class slsDetectorCommand : public virtual slsDetectorDefs { string cmdData(int narg, char *args[], int action); string cmdFrame(int narg, char *args[], int action); string cmdStatus(int narg, char *args[], int action); + string cmdDataStream(int narg, char *args[], int action); string cmdFree(int narg, char *args[], int action); string cmdAdd(int narg, char *args[], int action); string cmdRemove(int narg, char *args[], int action); diff --git a/slsDetectorSoftware/slsDetector/slsDetectorUsers.cpp b/slsDetectorSoftware/slsDetector/slsDetectorUsers.cpp index 4e554750f..4bf4e9c90 100644 --- a/slsDetectorSoftware/slsDetector/slsDetectorUsers.cpp +++ b/slsDetectorSoftware/slsDetector/slsDetectorUsers.cpp @@ -240,7 +240,9 @@ int slsDetectorUsers::setReceiverMode(int n){ return myDetector->setReadReceiverFrequency(1,n); } - +int slsDetectorUsers::enableDataStreamingFromReceiver(int i){ + return myDetector->enableDataStreamingFromReceiver(i); +} int64_t slsDetectorUsers::getModuleFirmwareVersion(){ diff --git a/slsDetectorSoftware/slsDetector/slsDetectorUsers.h b/slsDetectorSoftware/slsDetector/slsDetectorUsers.h index 24abc2fc4..214661384 100644 --- a/slsDetectorSoftware/slsDetector/slsDetectorUsers.h +++ b/slsDetectorSoftware/slsDetector/slsDetectorUsers.h @@ -450,6 +450,15 @@ class slsDetectorUsers virtual void finalizeDataset(double *a, double *v, double *e, int &np); + + /** + Enable data streaming from receiver (zmq) + \param i 1 to set, 0 to reset and -1 to get + \returns data streaming enable + */ + int enableDataStreamingFromReceiver(int i=-1); + + /** get get Module Firmware Version \returns id diff --git a/slsDetectorSoftware/slsDetector/slsDetectorUtils.cpp b/slsDetectorSoftware/slsDetector/slsDetectorUtils.cpp index 2b3dd5a0b..190e3e2a4 100644 --- a/slsDetectorSoftware/slsDetector/slsDetectorUtils.cpp +++ b/slsDetectorSoftware/slsDetector/slsDetectorUtils.cpp @@ -8,7 +8,7 @@ #include #include #include - +#include //clock() using namespace std; slsDetectorUtils::slsDetectorUtils() { @@ -42,6 +42,8 @@ slsDetectorUtils::slsDetectorUtils() { int slsDetectorUtils::acquire(int delflag){ + struct timespec begin,end; + clock_gettime(CLOCK_REALTIME, &begin); //ensure acquire isnt started multiple times by same client if(getAcquiringFlag() == false) @@ -58,11 +60,15 @@ int slsDetectorUtils::acquire(int delflag){ }else{ //put receiver read frequency to random if no gui int ret = setReadReceiverFrequency(0); - if(ret>0 && (acquisition_finished == NULL)){ - std::cout << "Error: receiver read frequency is set to " << ret << " but should be > 0 only when using gui." << std::endl; + if(ret>0 && (dataReady == NULL)){ ret = setReadReceiverFrequency(1,0); - std::cout << "Current receiver read frequency: " << ret << std::endl; + std::cout << "No Data call back and hence receiver read frequency reset to " << ret <<" (Random)" << std::endl; } + + //start/stop data streaming threads if threads in client enabled/disabled + ret = enableDataStreamingFromReceiver(-1); + // cout<<"getting datastream:"<1) setFrameIndex(0); else @@ -279,34 +279,36 @@ int slsDetectorUtils::acquire(int delflag){ if(receiver){ - pthread_mutex_unlock(&mg);//unlock previous + pthread_mutex_unlock(&mg);//cout << "unlock"<< endl; pthread_mutex_lock(&mp); createFileName(); pthread_mutex_unlock(&mp); //send receiver file name - pthread_mutex_lock(&mg); + pthread_mutex_lock(&mg); //cout << "lock"<< endl; setFileName(fileIO::getFileName()); if(setReceiverOnline()==OFFLINE_FLAG){ stopReceiver(); *stoppedFlag=1; - pthread_mutex_unlock(&mg); + pthread_mutex_unlock(&mg);//cout << "unlock"<< endl; break; } //start receiver if(startReceiver() == FAIL) { + cout << "Start receiver failed " << endl; stopReceiver(); *stoppedFlag=1; - pthread_mutex_unlock(&mg); + pthread_mutex_unlock(&mg);//cout << "unlock"<< endl; break; } - pthread_mutex_unlock(&mg); + cout << "Receiver started " << endl; + pthread_mutex_unlock(&mg);//cout << "unlock"<< endl; } #ifdef VERBOSE cout << "Acquiring " << endl; #endif startAndReadAll(); + cout << "detector finished " << endl; #ifdef VERBOSE - cout << "finished " << endl; cout << "returned! " << endl; #endif @@ -339,56 +341,23 @@ int slsDetectorUtils::acquire(int delflag){ break; + // cout << "mglock " << endl;; + pthread_mutex_lock(&mg); //cout << "lock"<< endl; + // cout << "done " << endl;; //offline if(setReceiverOnline()==OFFLINE_FLAG){ - // wait until data processing thread has finished the data - pthread_mutex_lock(&mg); - acquiringDone = 1; - pthread_mutex_unlock(&mg); - if (*threadedProcessing) { - sem_wait(&sem_queue); - pthread_mutex_lock(&mg); - acquiringDone = 0; - pthread_mutex_unlock(&mg); + if ((getDetectorsType()==GOTTHARD) || (getDetectorsType()==MOENCH) || (getDetectorsType()==JUNGFRAU)|| (getDetectorsType()==JUNGFRAUCTB) ){ + if((*correctionMask)&(1< #include #include - +#include using namespace std; @@ -491,7 +491,22 @@ class slsDetectorUtils : public slsDetectorActions, public postProcessing { */ virtual int loadSettingsFile(string fname, int imod=-1)=0; + /** programs FPGA with pof file + \param fname file name + \returns OK or FAIL + */ + virtual int programFPGA(string fname)=0; + /** resets FPGA + \returns OK or FAIL + */ + virtual int resetFPGA()=0; + + /** power on/off the chip + \param ival on is 1, off is 0, -1 to get + \returns OK or FAIL + */ + virtual int powerChip(int ival= -1)=0; /** saves the modules settings/trimbits writing to a file \param fname file name . Axtension is automatically generated! @@ -641,16 +656,17 @@ virtual int getReceiverCurrentFrameIndex()=0; virtual int resetFramesCaught()=0; /** - * Reads a frame from receiver - * @param fName file name of current frame() - * @param acquisitionIndex current acquisition index - * @param frameIndex current frame index (for each scan) - * @param subFrameIndex current sub frame index (for 32 bit mode for eiger) - /returns a frame read from recever + * Create Receiving Data Threads + * @param destroy is true to destroy all the threads + * @return OK or FAIL + */ +virtual int createReceivingDataThreads(bool destroy = false)=0; + + +/** Reads frames from receiver through a constant socket */ -virtual int* readFrameFromReceiver(char* fName, int &acquisitionIndex, int &frameIndex, int &subFrameIndex)=0; - - +//virtual void readFrameFromReceiver()=0; +virtual int* readFrameFromReceiver(char* fName, int &acquisitionIndex, int &frameIndex, int &subFrameIndex)=0; /** Turns off the receiver server! */ @@ -693,14 +709,20 @@ virtual int setROI(int n=-1,ROI roiLimits[]=NULL)=0; virtual ROI* getROI(int &n)=0; /** Sets the read receiver frequency - if Receiver read upon gui request, readRxrFrequency=0, + if data required from receiver randomly readRxrFrequency=0, else every nth frame to be sent to gui @param getFromReceiver is 1 if it should ask the receiver, - 0 if it can get it from multislsdetecter - @param i is the receiver read frequency + 0 if it can get it from multi structure + @param freq is the receiver read frequency /returns read receiver frequency */ -virtual int setReadReceiverFrequency(int getFromReceiver, int i=-1)=0; +virtual int setReadReceiverFrequency(int getFromReceiver, int freq=-1)=0; + +/** Enable or disable streaming of data from receiver to client + * @param enable 0 to disable 1 to enable -1 to only get the value + * @returns data streaming +*/ +virtual int enableDataStreamingFromReceiver(int enable=-1)=0; /** enable/disable or get data compression in receiver @@ -824,7 +846,6 @@ virtual int setReceiverFifoDepth(int i = -1)=0; //protected: int *stoppedFlag; - int64_t *timerValue; detectorSettings *currentSettings; int *currentThresholdEV; @@ -850,6 +871,8 @@ virtual int setReceiverFifoDepth(int i = -1)=0; int (*progress_call)(double,void*); void *pProgressCallArg; + + }; diff --git a/slsDetectorSoftware/slsDetectorAnalysis/detectorData.h b/slsDetectorSoftware/slsDetectorAnalysis/detectorData.h index 79c37d93b..888993fa0 100644 --- a/slsDetectorSoftware/slsDetectorAnalysis/detectorData.h +++ b/slsDetectorSoftware/slsDetectorAnalysis/detectorData.h @@ -17,7 +17,9 @@ class detectorData { \param np number of points in x coordinate defaults to the number of detector channels (1D detector) \param ny dimension in y (1D detector) */ - detectorData(double *val=NULL, double *err=NULL, double *ang=NULL, double p_ind=-1, const char *fname="", int np=-1, int ny=1) : values(val), errors(err), angles(ang), progressIndex(p_ind), npoints(np), npy(ny){strcpy(fileName,fname);}; + detectorData(double *val=NULL, double *err=NULL, double *ang=NULL, double p_ind=-1, const char *fname="", int np=-1, int ny=1) : values(val), errors(err), angles(ang), progressIndex(p_ind), npoints(np), npy(ny){ + strcpy(fileName,fname); + }; /** @short The destructor deletes also the arrays pointing to data/errors/angles if not NULL diff --git a/slsDetectorSoftware/slsDetectorAnalysis/fileIO.cpp b/slsDetectorSoftware/slsDetectorAnalysis/fileIO.cpp index 7698aa110..7c6ba31f2 100644 --- a/slsDetectorSoftware/slsDetectorAnalysis/fileIO.cpp +++ b/slsDetectorSoftware/slsDetectorAnalysis/fileIO.cpp @@ -120,7 +120,7 @@ int fileIO::writeDataFile(void *data, int iframe) { int fileIO::closeDataFile() { - // cout << "close file...." << endl; + cout << "close file...." << endl; if (filefd) fclose(filefd); filefd=NULL; diff --git a/slsDetectorSoftware/slsDetectorAnalysis/postProcessing.cpp b/slsDetectorSoftware/slsDetectorAnalysis/postProcessing.cpp index 300f13b56..e73bfe6a5 100644 --- a/slsDetectorSoftware/slsDetectorAnalysis/postProcessing.cpp +++ b/slsDetectorSoftware/slsDetectorAnalysis/postProcessing.cpp @@ -6,6 +6,8 @@ #elif EXTPP #include "usersFunctions.h" #endif +#include + //#define VERBOSE @@ -24,6 +26,17 @@ static void* startProcessDataNoDelete(void *n){ }; +int postProcessing::kbhit(){ + struct timeval tv; + fd_set fds; + tv.tv_sec = 0; + tv.tv_usec = 0; + FD_ZERO(&fds); + FD_SET(STDIN_FILENO, &fds); //STDIN_FILENO is 0 + select(STDIN_FILENO+1, &fds, NULL, NULL, &tv); + return FD_ISSET(STDIN_FILENO, &fds); +} + postProcessing::postProcessing(): expTime(NULL), ang(NULL), val(NULL), err(NULL), numberOfChannels(0), badChannelMask(NULL){ pthread_mutex_t mp1 = PTHREAD_MUTEX_INITIALIZER; @@ -398,7 +411,9 @@ int postProcessing::fillBadChannelMask() { void* postProcessing::processData(int delflag) { + pthread_mutex_lock(&mg); if(setReceiverOnline()==OFFLINE_FLAG){ + pthread_mutex_unlock(&mg); #ifdef VERBOSE std::cout<< " ??????????????????????????????????????????? processing data - threaded mode " << *threadedProcessing << endl; @@ -465,12 +480,7 @@ void* postProcessing::processData(int delflag) { } - /** IF detector acquisition is done, let the acquire() thread know to finish up and force join thread */ - if(acquiringDone){ - sem_post(&sem_queue); - // cout << "Sem posted" << endl; - } //else - // cout << "Sem not posted" << endl; + /* IF THERE ARE NO DATA look if acquisition is finished */ if (checkJoinThread()) { if (dataQueueSize()==0) { @@ -487,115 +497,148 @@ void* postProcessing::processData(int delflag) { fdata = NULL; //cout << "delete done "<< endl; } - } - //receiver + } //receiver else{ - int nn; - - int progress = 0; - char currentfName[MAX_STR_LENGTH]=""; - int caught = -1; - int currentAcquisitionIndex = -1; - int currentFrameIndex = -1; - int currentSubFrameIndex = -1; - bool newData = false; - int nthframe = setReadReceiverFrequency(0); - int nx =getTotalNumberOfChannels(slsDetectorDefs::X); - int ny =getTotalNumberOfChannels(slsDetectorDefs::Y); - -#ifdef VERBOSE - std::cout << "receiver read freq:" << nthframe << std::endl; -#endif + + pthread_mutex_unlock(&mg); +// //cprintf(RED,"In post processing threads\n"); - //repeat forever until joined by the calling thread - while(1){ +// if(dataReady){ +// readFrameFromReceiver(); +// } - cout.flush(); - cout< 0){ -#ifdef VERY_VERY_DEBUG - if(acquiringDone == 1) cout << "acquiring seems to be done" << endl; -#endif - - - //IF GUI, check for last frames (counter upto 5) - if(dataReady){ - pthread_mutex_lock(&mg); - acquiringDone++; - pthread_mutex_unlock(&mg); -#ifdef VERY_VERY_DEBUG - cout << "acquiringDone :" << acquiringDone << endl; -#endif - } - - - //post to stopReceiver in acquire(), but continue reading frames - if (!dataReady || (acquiringDone >= 5)){ - if(!dataReady || (!nthframe) ||(!newData)){ -#ifdef VERY_VERY_DEBUG - cout << "gonna post for it to end" << endl; -#endif - sem_post(&sem_queue); -#ifdef VERY_VERY_DEBUG - cout << "Sem posted" << endl; -#endif - } - } - } - //random reads and for nthframe, checks if there is no new data - else if((!nthframe) ||(!newData)){ - //cout <<"cecking now" << endl; - if (checkJoinThread()){ - break; - } - } - - - - - - //for random reads, ask only if it has new data - if(!newData){ - if(caught > progress){ - newData = true; - - // If new data and acquiringDone>0 (= det acq over), reset to get more frames - if(dataReady && (acquiringDone > 0)){ - pthread_mutex_lock(&mg); - acquiringDone = 1; -#ifdef VERY_VERY_DEBUG - cout << "Keeping acquiringDone at 1 " << endl; -#endif - pthread_mutex_unlock(&mg); - } - - } - } - - - + //cout<<"exiting from proccessing thread"< 0){ +#ifdef VERY_VERY_DEBUG + if(acquiringDone == 1) + cout << "acquiring seems to be done" << endl; +#endif + //IF GUI, check for last frames (counter upto 5) + if(dataReady){ + pthread_mutex_lock(&mg); + acquiringDone++; + pthread_mutex_unlock(&mg); +#ifdef VERY_VERY_DEBUG + cout << "acquiringDone :" << acquiringDone << endl; +#endif + } + //post to stopReceiver in acquire(), but continue reading frames + if (!dataReady || (acquiringDone >= 5)){ + if(!dataReady || (!nthframe) ||(!newData)){ +#ifdef VERY_VERY_DEBUG + cout << "gonna post for it to end" << endl; +#endif + sem_post(&sem_queue); +#ifdef VERY_VERY_DEBUG + cout << "Sem posted" << endl; +#endif + } + } + } + //random reads and for nthframe, checks if there is no new data + else if((!nthframe) ||(!newData)){ + //cout <<"cecking now" << endl; + if (checkJoinThread()){ + break; + } + } + //for random reads, ask only if it has new data + if(!newData){ + if(caught > progress){ + newData = true; // If new data and acquiringDone>0 (= det acq over), reset to get more frames + if(dataReady && (acquiringDone > 0)){ + pthread_mutex_lock(&mg); + acquiringDone = 1; +#ifdef VERY_VERY_DEBUG + cout << "Keeping acquiringDone at 1 " << endl; +#endif + pthread_mutex_unlock(&mg); + } + } } + if(newData){ #ifdef VERY_VERY_DEBUG cout << "new data" << endl; @@ -667,6 +710,9 @@ void* postProcessing::processData(int delflag) { } } + + //cprintf(RED,"Exiting post processing thread\n"); + } return 0; diff --git a/slsDetectorSoftware/slsDetectorAnalysis/postProcessing.h b/slsDetectorSoftware/slsDetectorAnalysis/postProcessing.h index 90f00085a..02e305f4f 100644 --- a/slsDetectorSoftware/slsDetectorAnalysis/postProcessing.h +++ b/slsDetectorSoftware/slsDetectorAnalysis/postProcessing.h @@ -295,16 +295,14 @@ s queue containing the postprocessed data */ queue finalDataQueue; - /** data queue size */ int queuesize; - /** queue mutex */ - sem_t sem_queue; - - /** set when detector finishes acquiring */ - int acquiringDone; + /** queue mutex */ + sem_t sem_queue; + /** set when detector finishes acquiring */ + int acquiringDone; /** @@ -333,18 +331,24 @@ s - private: double *fdata; - int (*dataReady)(detectorData*,int, int,void*); void *pCallbackArg; - + detectorData *thisData; + + private: + int kbhit(void); + + // double *fdata; + // int (*dataReady)(detectorData*,int, int,void*); + // void *pCallbackArg; + int (*rawDataReady)(double*,int,void*); void *pRawDataArg; postProcessingFuncs *ppFun; - detectorData *thisData; + //detectorData *thisData; double *ang; @@ -374,4 +378,5 @@ s + #endif diff --git a/slsDetectorSoftware/slsDetectorClient/CMakeLists.txt b/slsDetectorSoftware/slsDetectorClient/CMakeLists.txt index 7ef30d755..0dcc2fb9a 100644 --- a/slsDetectorSoftware/slsDetectorClient/CMakeLists.txt +++ b/slsDetectorSoftware/slsDetectorClient/CMakeLists.txt @@ -18,6 +18,8 @@ add_executable(sls_detector_get target_link_libraries(sls_detector_get slsDetectorShared pthread + zmq + rt ) set_target_properties(sls_detector_get PROPERTIES RUNTIME_OUTPUT_DIRECTORY ${CMAKE_BINARY_DIR}/bin @@ -30,6 +32,8 @@ add_executable(sls_detector_put target_link_libraries(sls_detector_put slsDetectorShared pthread + zmq + rt ) set_target_properties(sls_detector_put PROPERTIES RUNTIME_OUTPUT_DIRECTORY ${CMAKE_BINARY_DIR}/bin @@ -42,6 +46,8 @@ add_executable(sls_detector_acquire target_link_libraries(sls_detector_acquire slsDetectorShared pthread + zmq + rt ) set_target_properties(sls_detector_acquire PROPERTIES RUNTIME_OUTPUT_DIRECTORY ${CMAKE_BINARY_DIR}/bin @@ -54,6 +60,8 @@ add_executable(sls_detector_help target_link_libraries(sls_detector_help slsDetectorShared pthread + zmq + rt ) set_target_properties(sls_detector_help PROPERTIES RUNTIME_OUTPUT_DIRECTORY ${CMAKE_BINARY_DIR}/bin diff --git a/slsDetectorSoftware/slsDetectorServer/slsDetectorFunctionList.h b/slsDetectorSoftware/slsDetectorServer/slsDetectorFunctionList.h index 1e1e13d40..baa0ab382 100644 --- a/slsDetectorSoftware/slsDetectorServer/slsDetectorFunctionList.h +++ b/slsDetectorSoftware/slsDetectorServer/slsDetectorFunctionList.h @@ -92,7 +92,7 @@ int startStateMachine(); int stopStateMachine(); int startReadOut(); enum runStatus getRunStatus(); -char *readFrame(int *ret, char *mess); +void readFrame(int *ret, char *mess); int64_t setTimer(enum timerIndex ind, int64_t val); diff --git a/slsDetectorSoftware/slsDetectorServer/slsDetectorServer_funcs.c b/slsDetectorSoftware/slsDetectorServer/slsDetectorServer_funcs.c index 0a423e50f..897ccf788 100755 --- a/slsDetectorSoftware/slsDetectorServer/slsDetectorServer_funcs.c +++ b/slsDetectorSoftware/slsDetectorServer/slsDetectorServer_funcs.c @@ -36,7 +36,6 @@ extern enum detectorSettings thisSettings; //global variables for optimized readout char mess[MAX_STR_LENGTH]; -char *dataretval=NULL; int dataret; //extern int dataBytes = 10; @@ -1325,9 +1324,6 @@ int get_adc(int file_des) { #endif switch (ind) { #ifdef EIGERD - case TEMPERATURE_FPGA: - iadc = TEMP_FPGA; - break; case TEMPERATURE_FPGAEXT: iadc = TEMP_FPGAEXT; break; @@ -1343,6 +1339,15 @@ int get_adc(int file_des) { case TEMPERATURE_SODR: iadc = TEMP_SODR; break; + case TEMPERATURE_FPGA: + iadc = TEMP_FPGA; + break; + case TEMPERATURE_FPGA2: + iadc = TEMP_FPGAFEBL; + break; + case TEMPERATURE_FPGA3: + iadc = TEMP_FPGAFEBR; + break; #endif #ifdef GOTTHARDD case TEMPERATURE_FPGA: @@ -1932,6 +1937,7 @@ int set_module(int file_des) { case LOWGAIN: case VERYHIGHGAIN: case VERYLOWGAIN: + case UNINITIALIZED: break; default: sprintf(mess,"This setting %d does not exist for this detector\n",myModule.reg); @@ -2520,9 +2526,8 @@ int start_and_read_all(int file_des) { int read_frame(int file_des) { - - dataret=OK; int dataret1; + if (differentClients==1 && lockStatus==1) { dataret=FAIL; sprintf(mess,"Detector locked by %s\n",lastClientIP); @@ -2531,25 +2536,28 @@ int read_frame(int file_des) { dataret1 = dataret; sendData(file_des,&dataret1,sizeof(dataret1),INT32); sendData(file_des,mess,sizeof(mess),OTHER); +#ifdef VERBOSE printf("dataret %d\n",dataret); +#endif return dataret; } #ifdef SLS_DETECTOR_FUNCTION_LIST - dataretval=readFrame(&dataret, mess); + readFrame(&dataret, mess); #endif - - //dataret could be swapped during sendData - dataret1 = dataret; - sendData(file_des,&dataret1,sizeof(dataret1),INT32); - if (dataret==FAIL) - sendData(file_des,mess,sizeof(mess),OTHER);//sizeof(mess));//sizeof(mess)); - else if(dataret==OK){printf("shouldnt be sending anything but i am\n"); - sendData(file_des,dataretval,dataBytes,OTHER);} - - printf("dataret %d\n",dataret); - return dataret; + 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; } @@ -2787,15 +2795,26 @@ int set_dynamic_range(int file_des) { #endif } if(ret == OK){ + int old_dr = setDynamicRange(-1); retval=setDynamicRange(dr); if (dr>=0 && retval!=dr) ret=FAIL; //look at rate correction only if dr change worked - if((ret==OK) && (dr!=32) && (dr!=-1) && (getRateCorrectionEnable())){ + if((ret==OK) && (dr!=32) && (dr!=16) && (dr!=-1) && (getRateCorrectionEnable())){ setRateCorrection(0); - strcpy(mess,"Switching off Rate Correction. Must be in 32 bit mode\n"); + 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()){ + strcpy(mess,"Deactivating Rate Correction. Could not set it.\n"); + cprintf(RED,"%s",mess); + ret=FAIL; + } + } } } #endif @@ -3977,9 +3996,9 @@ int set_rate_correct(int file_des) { //set rate else{ - //not 32 bit mode - if((setDynamicRange(-1)!=32) && (tau_ns!=0)){ - strcpy(mess,"Rate correction Deactivated, must be in 32 bit mode\n"); + //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; } diff --git a/slsDetectorSoftware/slsReceiverInterface/receiverInterface.cpp b/slsDetectorSoftware/slsReceiverInterface/receiverInterface.cpp index e5a5011a0..c3771e7e0 100644 --- a/slsDetectorSoftware/slsReceiverInterface/receiverInterface.cpp +++ b/slsDetectorSoftware/slsReceiverInterface/receiverInterface.cpp @@ -23,7 +23,7 @@ receiverInterface::~receiverInterface(){ int receiverInterface::sendString(int fnum, char retval[], char arg[]){ int ret = slsDetectorDefs::FAIL; - char mess[100] = ""; + char mess[MAX_STR_LENGTH] = ""; dataSocket->SendDataOnly(&fnum,sizeof(fnum)); dataSocket->SendDataOnly(arg,MAX_STR_LENGTH); @@ -42,7 +42,7 @@ int receiverInterface::sendString(int fnum, char retval[], char arg[]){ int receiverInterface::sendUDPDetails(int fnum, char retval[], char arg[3][MAX_STR_LENGTH]){ char args[3][MAX_STR_LENGTH]; int ret = slsDetectorDefs::FAIL; - char mess[100] = ""; + char mess[MAX_STR_LENGTH] = ""; dataSocket->SendDataOnly(&fnum,sizeof(fnum)); dataSocket->SendDataOnly(arg,sizeof(args)); @@ -60,7 +60,7 @@ int receiverInterface::sendUDPDetails(int fnum, char retval[], char arg[3][MAX_S int receiverInterface::sendInt(int fnum, int &retval, int arg){ int ret = slsDetectorDefs::FAIL; - char mess[100] = ""; + char mess[MAX_STR_LENGTH] = ""; dataSocket->SendDataOnly(&fnum,sizeof(fnum)); dataSocket->SendDataOnly(&arg,sizeof(arg)); @@ -78,7 +78,7 @@ int receiverInterface::sendInt(int fnum, int &retval, int arg){ int receiverInterface::getInt(int fnum, int &retval){ int ret = slsDetectorDefs::FAIL; - char mess[100] = ""; + char mess[MAX_STR_LENGTH] = ""; dataSocket->SendDataOnly(&fnum,sizeof(fnum)); dataSocket->ReceiveDataOnly(&ret,sizeof(ret)); @@ -95,7 +95,7 @@ int receiverInterface::getInt(int fnum, int &retval){ int receiverInterface::sendInt(int fnum, int64_t &retval, int64_t arg){ int ret = slsDetectorDefs::FAIL; - char mess[100] = ""; + char mess[MAX_STR_LENGTH] = ""; dataSocket->SendDataOnly(&fnum,sizeof(fnum)); dataSocket->SendDataOnly(&arg,sizeof(arg)); @@ -111,10 +111,28 @@ int receiverInterface::sendInt(int fnum, int64_t &retval, int64_t arg){ -int receiverInterface::sendIntArray(int fnum, int64_t &retval, int64_t arg[2]){ +int receiverInterface::sendIntArray(int fnum, int64_t &retval, int64_t arg[2], char mess[]){ int64_t args[2]; + char messs[MAX_STR_LENGTH]; int ret = slsDetectorDefs::FAIL; - char mess[100] = ""; + dataSocket->SendDataOnly(&fnum,sizeof(fnum)); + dataSocket->SendDataOnly(arg,sizeof(args)); + dataSocket->ReceiveDataOnly(&ret,sizeof(ret)); + if (ret==slsDetectorDefs::FAIL){ + dataSocket->ReceiveDataOnly(mess,sizeof(messs)); + std::cout<< "Receiver returned error: " << mess << std::endl; + } + dataSocket->ReceiveDataOnly(&retval,sizeof(retval)); + + return ret; +} + + + +int receiverInterface::sendIntArray(int fnum, int &retval, int arg[2]){ + int args[2]; + int ret = slsDetectorDefs::FAIL; + char mess[MAX_STR_LENGTH] = ""; dataSocket->SendDataOnly(&fnum,sizeof(fnum)); dataSocket->SendDataOnly(arg,sizeof(args)); dataSocket->ReceiveDataOnly(&ret,sizeof(ret)); diff --git a/slsDetectorSoftware/slsReceiverInterface/receiverInterface.h b/slsDetectorSoftware/slsReceiverInterface/receiverInterface.h index 27fbea6a1..0f221f171 100644 --- a/slsDetectorSoftware/slsReceiverInterface/receiverInterface.h +++ b/slsDetectorSoftware/slsReceiverInterface/receiverInterface.h @@ -91,9 +91,20 @@ public: * @param fnum function enum to determine what parameter * @param retval return value * @param arg values to send + * @param mess message returned * \returns success of operation */ - int sendIntArray(int fnum, int64_t &retval, int64_t arg[2]); + int sendIntArray(int fnum, int64_t &retval, int64_t arg[2],char mess[]); + + + /** + * Send an integer to receiver + * @param fnum function enum to determine what parameter + * @param retval return value + * @param arg values to send + * \returns success of operation + */ + int sendIntArray(int fnum, int &retval, int arg[2]); /** * Get an integer value from receiver diff --git a/slsDetectorSoftware/threadFiles/Task.h b/slsDetectorSoftware/threadFiles/Task.h index e7f8f12f8..785298d46 100644 --- a/slsDetectorSoftware/threadFiles/Task.h +++ b/slsDetectorSoftware/threadFiles/Task.h @@ -16,6 +16,18 @@ using namespace std; class slsDetector; +template +class func00_t{ +public: + func00_t(_Ret (_Class::*fn)(),_Class* ptr): + m_fn(fn),m_ptr(ptr){} + ~func00_t() {} + void operator()() const {((m_ptr->*m_fn)());} +private: + _Class* m_ptr; + _Ret (_Class::*m_fn)(); +}; + template class func0_t{ public: @@ -94,27 +106,32 @@ 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){}; + 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){}; /* 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){}; + 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){}; /* 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){}; + 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){}; /* 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){}; + 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){}; /* 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){}; + 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){}; /* 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){}; + 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){}; /* 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){}; + 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){}; + 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){}; /* 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){}; - /* Return: int, Param: int */ - 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){}; + 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){}; + /* 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){}; + 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){}; + /* 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(){} void operator()(){ @@ -129,6 +146,7 @@ public: else if(m9) (*m9)(); else if(m10) (*m10)(); else if(m11) (*m11)(); + else if(m12) (*m12)(); } private: @@ -154,6 +172,8 @@ private: func0_t * m10; /* Return: char*, Param: networkParameter,string,string */ func2_t * m11; + /* Return: void, Param: none */ + func00_t * m12; }; diff --git a/slsDetectorSoftware/threadFiles/ThreadPool.cpp b/slsDetectorSoftware/threadFiles/ThreadPool.cpp index 223983a73..347a15e31 100644 --- a/slsDetectorSoftware/threadFiles/ThreadPool.cpp +++ b/slsDetectorSoftware/threadFiles/ThreadPool.cpp @@ -7,8 +7,10 @@ ThreadPool::ThreadPool(int pool_size) : m_pool_size(pool_size){ #endif m_tasks_loaded = false; thread_started = false; + zmqthreadpool = false; current_thread_number = -1; number_of_ongoing_tasks = 0; + number_of_total_tasks = 0; } ThreadPool::~ThreadPool(){ @@ -34,6 +36,7 @@ int ThreadPool::initialize_threadpool(){ m_pool_state = STARTED; int ret = -1; sem_init(&semStart,1,0); + sem_init(&semDone,1,0); for (int i = 0; i < m_pool_size; i++) { pthread_t tid; thread_started = false; @@ -68,12 +71,15 @@ int ThreadPool::destroy_threadpool(){ for (int i = 0; i < m_pool_size; i++) { void* result; sem_post(&semStart); + sem_post(&semDone); 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 } sem_destroy(&semStart); + sem_destroy(&semDone); number_of_ongoing_tasks = 0; + number_of_total_tasks = 0; /* cout << m_pool_size << " threads exited from the thread pool" << endl;*/ return 0; } @@ -109,25 +115,28 @@ void* ThreadPool::execute_thread(){ /*cout << "Unlocking: " << pthread_self() << endl;*/ m_task_mutex.unlock(); + //if(zmqthreadpool) cout<<"***"<run(arg); /*cout << ithread <<" Done executing thread " << pthread_self() << endl;*/ - m_all_tasks_mutex.lock(); + m_task_mutex.lock(); number_of_ongoing_tasks--; - m_all_tasks_mutex.unlock(); + m_task_mutex.unlock(); + //if(zmqthreadpool) cout< m_tasks; volatile int m_pool_state; - Mutex m_all_tasks_mutex; - CondVar m_all_tasks_cond_var; bool m_tasks_loaded; bool thread_started; int current_thread_number; //volatile uint64_t tasks_done_mask; volatile int number_of_ongoing_tasks; + volatile int number_of_total_tasks; sem_t semStart; - + sem_t semDone; + bool zmqthreadpool; };