diff --git a/slsDetectorSoftware/commonFiles/sls_detector_defs.h b/slsDetectorSoftware/commonFiles/sls_detector_defs.h index d4075c0d4..31dbc6365 100755 --- a/slsDetectorSoftware/commonFiles/sls_detector_defs.h +++ b/slsDetectorSoftware/commonFiles/sls_detector_defs.h @@ -177,7 +177,8 @@ enum networkParameter { RECEIVER_HOSTNAME, /**< receiver IP/hostname */ RECEIVER_UDP_IP, /**< receiever UDP IP */ RECEIVER_UDP_PORT, /**< receiever UDP Port */ - RECEIVER_UDP_MAC /**< receiever UDP MAC */ + RECEIVER_UDP_MAC, /**< receiever UDP MAC */ + RECEIVER_UDP_PORT2 /**< receiever UDP Port of second half module for eiger */ }; /** diff --git a/slsDetectorSoftware/commonFiles/sls_detector_funcs.h b/slsDetectorSoftware/commonFiles/sls_detector_funcs.h index 87bb241aa..8bb1a84d1 100644 --- a/slsDetectorSoftware/commonFiles/sls_detector_funcs.h +++ b/slsDetectorSoftware/commonFiles/sls_detector_funcs.h @@ -90,7 +90,9 @@ enum { F_CALIBRATE_PEDESTAL, /**< starts acquistion, calibrates pedestal and write back to fpga */ F_ENABLE_TEN_GIGA, /**< enable 10Gbe */ - F_SET_ALL_TRIMBITS /** < set all trimbits to this value */ + F_SET_ALL_TRIMBITS, /** < set all trimbits to this value */ + + F_SET_CTB_PATTERN /** < loads a pattern in the CTB */ /* Always append functions hereafter!!! */ diff --git a/slsDetectorSoftware/eigerDetectorServer/Beb.c b/slsDetectorSoftware/eigerDetectorServer/Beb.c index 9558007a6..a428774a1 100644 --- a/slsDetectorSoftware/eigerDetectorServer/Beb.c +++ b/slsDetectorSoftware/eigerDetectorServer/Beb.c @@ -42,6 +42,7 @@ short Beb_bit_mode; + void BebInfo_BebInfo(struct BebInfo* bebInfo, unsigned int beb_num){ bebInfo->beb_number=beb_num; bebInfo->serial_address=0; @@ -52,6 +53,7 @@ void BebInfo_BebInfo(struct BebInfo* bebInfo, unsigned int beb_num){ bebInfo->src_port_1GbE=bebInfo->src_port_10GbE=0; } + int BebInfo_SetSerialAddress(struct BebInfo* bebInfo, unsigned int a){ //address pre shifted if(a>0xff) return 0; @@ -135,13 +137,14 @@ void Beb_Beb(int arg1){ Beb_SetByteOrder(); +/* ll_beb_new_memory = &ll_beb_new_memory_local; Local_LocalLinkInterface(ll_beb_new_memory); if(!Local_InitNewMemory(ll_beb_new_memory,XPAR_PLB_LL_NEW_MEMORY, arg1)) printf("New Memory FAIL\n"); else printf("New Memory OK\n"); - +*/ } @@ -155,6 +158,7 @@ void Beb_ClearBebInfos(){ int Beb_InitBebInfos(){//file name at some point Beb_ClearBebInfos(); + struct BebInfo b0; BebInfo_BebInfo(&b0,0); if(BebInfo_SetSerialAddress(&b0,0xff)) { //all bebs for reset and possibly get request data? @@ -172,6 +176,7 @@ int Beb_InitBebInfos(){//file name at some point beb_infos.push_back(b); */ + return Beb_CheckSourceStuffBebInfo(); } @@ -181,7 +186,7 @@ int Beb_SetBebSrcHeaderInfos(unsigned int beb_number, int ten_gig, char* src_mac //so that the values can be reset externally for now.... unsigned int i = Beb_GetBebInfoIndex(beb_number); - if(!i){ printf("returning 000\n");return 0;} //i must be greater than 0, zero is the global send + /******* if(!i) return 0;****************************/ //i must be greater than 0, zero is the global send BebInfo_SetHeaderInfo(&beb_infos[i],ten_gig,src_mac,src_ip,src_port); printf("Printing Beb info number (%d) :\n",i); @@ -253,12 +258,13 @@ int Beb_CheckSourceStuffBebInfo(){ } unsigned int Beb_GetBebInfoIndex(unsigned int beb_numb){ - if(!beb_numb) return 0; +/******************** if(!beb_numb) return 0;******************************/ unsigned int i; for(i=1;ibottom_dac[i] = mod->bottom_address_valid ? -1:0; } + +void Module_ModuleBottom(struct Module* mod,unsigned int number, unsigned int address_bottom){ + unsigned int i; + mod->module_number = number; + mod->top_address_valid = 0; + mod->top_left_address = 0; + mod->top_right_address = 0; + mod-> bottom_address_valid = 1; + mod-> bottom_left_address = 0x100 | (0xff & address_bottom); + mod-> bottom_right_address = (0x200 | (0xff & address_bottom)); + + mod->high_voltage = -1; + + for(i=0;i<4;i++) mod->idelay_top[i]=mod->idelay_bottom[i]=0; + + mod->top_dac = malloc(Module_ndacs * sizeof(int)); + mod->bottom_dac = malloc(Module_ndacs * sizeof(int)); + for(i=0;itop_dac[i] = mod->top_address_valid ? -1:0; + for(i=0;ibottom_dac[i] = mod->bottom_address_valid ? -1:0; +} + + + void Module_Module1(struct Module* mod,unsigned int number, unsigned int address_top, unsigned int address_bottom){ unsigned int i; mod->module_number = number; @@ -118,9 +143,16 @@ int Module_GetBottomDACValue(struct Module* mod,unsigned int i) +int Feb_Control_IsBottomModule(){ + if(Module_BottomAddressIsValid(&modules[Feb_Control_current_index])) + return 1; + return 0; +} - +int Feb_Control_GetModuleNumber(){ + return Feb_Control_current_mod; +} void Feb_Control_FebControl(){ @@ -130,6 +162,7 @@ void Feb_Control_FebControl(){ Feb_Control_trimbit_size=263680; Feb_Control_last_downloaded_trimbits = malloc(Feb_Control_trimbit_size * sizeof(int)); +/* printf("\nDefault Settings:\n"); Feb_Control_nimages = 1; Feb_Control_exposure_time_in_sec = 1; @@ -146,6 +179,23 @@ void Feb_Control_FebControl(){ printf("\n\n"); Feb_Control_Init(); +*/ + + + + /* + unsigned int reg_nums[1]; + unsigned int reg_vals[1]; + reg_nums[0]=DAQ_REG_CHIP_CMDS; + reg_vals[0]=(0|Feb_Control_acquireNReadoutMode|Feb_Control_triggerMode|Feb_Control_externalEnableMode|Feb_Control_subFrameMode); + + if(!Feb_Interface_WriteRegisters(Feb_Control_AddressToAll(),1,reg_nums,reg_vals,0,0)){ + printf("Trouble setting them up as slaves\n");; + } + + */ + + } @@ -159,36 +209,98 @@ void Feb_Control_ClearModules(){ int Feb_Control_Init(){ unsigned int i; Feb_Control_ClearModules(); + ///* + Feb_Control_current_mod = 0; + Feb_Control_current_index = 0; Feb_Control_AddModule(0,0xff);//global send Feb_Control_PrintModuleList(); +//*/ Feb_Control_ReadSetUpFileToAddModules("/home/root/executables/setup.txt"); + +/* printf("\nSetting detector defaults:\n"); Feb_Control_ReadSetUpFile(0,"/home/root/executables/setup.txt"); //send defaults to all - for(i=1;i0) - sprintf(str,"mod%d::%s",module_num,str); + sprintf(str,"%s",str); /*sprintf(str,"mod%d::%s",module_num,str);*/ if(!Feb_Control_SetDAC(str,f0,1)) printf("error in string: %s",str); } } fclose(fp); - +printf("Done reading set up file\n"); return 1; } int Feb_Control_CheckSetup(){ + printf("Checking Set up\n"); unsigned int i,j; int ok = 1; - for(i=0;i4095){ - printf("Waring: SetDac bad value, %d. The range is 0 to 4095.\n",v); + printf("Warning: SetDac bad value, %d. The range is 0 to 4095.\n",v); return 0; } @@ -748,9 +896,9 @@ int Feb_Control_SetDAC(char* dac_str, int value, int is_a_voltage_mv){ } if(bottom&&Module_BottomAddressIsValid(&modules[module_index])){ - if(!Feb_Control_SendDACValue(Module_GetBottomRightAddress(&modules[module_index]),dac_ch,&v)) return 0; - if(module_index!=0) Module_SetBottomDACValue(&modules[module_index],dac_ch,v); - else for(i=0;i>3)<<((7-i)*4);//upper - trimbits_to_load_r[offset+chip_sc] |= ( 0x7 & trimbits[row_set*16480+super_column_start_position_r+i])<<((7-i)*4);//low - trimbits_to_load_r[offset+chip_sc+32] |= ((0x38 & trimbits[row_set*16480+super_column_start_position_r+i])>>3)<<((7-i)*4);//upper -/* - trimbits_to_load_l[offset+chip_sc] |= ( 0x7 & trimbits[263679 - (row_set*16480+super_column_start_position_l+i)])<<((7-i)*4);//low - trimbits_to_load_l[offset+chip_sc+32] |= ((0x38 & trimbits[263679 - (row_set*16480+super_column_start_position_l+i)])>>3)<<((7-i)*4);//upper - trimbits_to_load_r[offset+chip_sc] |= ( 0x7 & trimbits[263679 - (row_set*16480+super_column_start_position_r+i)])<<((7-i)*4);//low - trimbits_to_load_r[offset+chip_sc+32] |= ((0x38 & trimbits[263679 - (row_set*16480+super_column_start_position_r+i)])>>3)<<((7-i)*4);//upper -*/ + + if(Module_TopAddressIsValid(&modules[0])){ + trimbits_to_load_l[offset+chip_sc] |= ( 0x7 & trimbits[row_set*16480+super_column_start_position_l+i])<<((7-i)*4);//low + trimbits_to_load_l[offset+chip_sc+32] |= ((0x38 & trimbits[row_set*16480+super_column_start_position_l+i])>>3)<<((7-i)*4);//upper + trimbits_to_load_r[offset+chip_sc] |= ( 0x7 & trimbits[row_set*16480+super_column_start_position_r+i])<<((7-i)*4);//low + trimbits_to_load_r[offset+chip_sc+32] |= ((0x38 & trimbits[row_set*16480+super_column_start_position_r+i])>>3)<<((7-i)*4);//upper + }else{ + trimbits_to_load_l[offset+chip_sc] |= ( 0x7 & trimbits[263679 - (row_set*16480+super_column_start_position_l+i)])<<((7-i)*4);//low + trimbits_to_load_l[offset+chip_sc+32] |= ((0x38 & trimbits[263679 - (row_set*16480+super_column_start_position_l+i)])>>3)<<((7-i)*4);//upper + trimbits_to_load_r[offset+chip_sc] |= ( 0x7 & trimbits[263679 - (row_set*16480+super_column_start_position_r+i)])<<((7-i)*4);//low + trimbits_to_load_r[offset+chip_sc+32] |= ((0x38 & trimbits[263679 - (row_set*16480+super_column_start_position_r+i)])>>3)<<((7-i)*4);//upper + + } } // end column loop i } //end supercolumn loop sc } //end row loop - - if(!Feb_Interface_WriteMemoryInLoops(Module_GetTopLeftAddress(&modules[0]),0,0,1024,trimbits_to_load_r)|| - !Feb_Interface_WriteMemoryInLoops(Module_GetTopRightAddress(&modules[0]),0,0,1024,trimbits_to_load_l)|| - //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(Module_TopAddressIsValid(&modules[0])){ + if(!Feb_Interface_WriteMemoryInLoops(Module_GetTopLeftAddress(&modules[Feb_Control_current_index]),0,0,1024,trimbits_to_load_r)|| + !Feb_Interface_WriteMemoryInLoops(Module_GetTopRightAddress(&modules[Feb_Control_current_index]),0,0,1024,trimbits_to_load_l)|| + //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_r)|| + !Feb_Interface_WriteMemoryInLoops(Module_GetBottomRightAddress(&modules[Feb_Control_current_index]),0,0,1024,trimbits_to_load_l)|| + //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; + } } } //end row_set loop (groups of 16 rows) @@ -933,9 +1094,23 @@ unsigned int* Feb_Control_GetTrimbits(){ -unsigned int Feb_Control_AddressToAll(){ +unsigned int Feb_Control_AddressToAll(){printf("in Feb_Control_AddressToAll()\n"); + + + if(moduleSize==0) return 0; - return Module_GetTopLeftAddress(&modules[0])|Module_GetTopRightAddress(&modules[0]); + + if(Module_BottomAddressIsValid(&modules[1])){ + printf("************* bottom\n"); + //if(Feb_Control_am_i_master) + return Module_GetBottomLeftAddress(&modules[1])|Module_GetBottomRightAddress(&modules[1]); + // else return 0; + } + printf("************* top\n"); + // if(Feb_Control_am_i_master) + return Module_GetTopLeftAddress(&modules[0])|Module_GetTopRightAddress(&modules[0]); + // else return 0; + } int Feb_Control_SetCommandRegister(unsigned int cmd){ @@ -978,11 +1153,23 @@ int Feb_Control_WaitForFinishedFlag(int sleep_time_us){ } int Feb_Control_AcquisitionInProgress(){ - unsigned int status_reg_r=0; + unsigned int status_reg_r=0,status_reg_l=0; - if(!(Feb_Control_GetDAQStatusRegister(Module_GetTopRightAddress(&modules[1]),&status_reg_r))) - return 0; - if(status_reg_r&DAQ_STATUS_DAQ_RUNNING) return 1; + int ind = Feb_Control_current_index; + if(Module_BottomAddressIsValid(&modules[ind])){ + + if(!(Feb_Control_GetDAQStatusRegister(Module_GetBottomRightAddress(&modules[ind]),&status_reg_r))) + {printf("ERROR: Trouble reading Status register. bottom right address\n");return 0;} + if(!(Feb_Control_GetDAQStatusRegister(Module_GetBottomLeftAddress(&modules[ind]),&status_reg_l))) + {printf("ERROR: Trouble reading Status register. bottom left address\n");return 0;} + + }else{ + if(!(Feb_Control_GetDAQStatusRegister(Module_GetTopRightAddress(&modules[ind]),&status_reg_r))) + {printf("ERROR: Trouble reading Status register. top right address\n");return 0;} + if(!(Feb_Control_GetDAQStatusRegister(Module_GetTopLeftAddress(&modules[ind]),&status_reg_l))) + {printf("ERROR: Trouble reading Status register. top left address\n");return 0;} + } + if((status_reg_r|status_reg_l)&DAQ_STATUS_DAQ_RUNNING) {/*printf("**runningggg\n");*/return 1;} /* if(!(GetDAQStatusRegister(modules[i]->Module_GetTopLeftAddress(),status_reg_r)&&GetDAQStatusRegister(modules[i]->Module_GetTopRightAddress(),status_reg_l))){ @@ -993,6 +1180,7 @@ int Feb_Control_AcquisitionInProgress(){ } */ + /*printf("**idle\n");*/ return 0; //i.e. not running (status_reg_r|status_reg_l)&DAQ_STATUS_DAQ_RUNNING; } @@ -1164,8 +1352,8 @@ int Feb_Control_SetExternalEnableMode(int use_external_enable, int polarity){ } int Feb_Control_SetNExposures(unsigned int n_images){ - if(!Feb_Control_nimages){ - printf("Warning nimages must be greater than zero.%d\n",Feb_Control_nimages); + if(!n_images){ + printf("Warning nimages must be greater than zero.%d\n",n_images); return 0; } @@ -1306,7 +1494,7 @@ int Feb_Control_WriteNRead(char* message, int length, int max_length){ } */ -int Feb_Control_StartAcquisition(){ +int Feb_Control_StartAcquisition(){printf("****** starting acquisition********* \n"); static unsigned int reg_nums[20]; static unsigned int reg_vals[20]; @@ -1319,7 +1507,7 @@ int Feb_Control_StartAcquisition(){ return 0; } - if(!Feb_Control_SetStaticBits(Feb_Control_staticBits&(DAQ_STATIC_BIT_M4|DAQ_STATIC_BIT_M8))){ + if(!Feb_Control_SetStaticBits1(Feb_Control_staticBits&(DAQ_STATIC_BIT_M4|DAQ_STATIC_BIT_M8))){ printf("Trouble setting static bits ...\n");; return 0; } @@ -1334,6 +1522,7 @@ int Feb_Control_StartAcquisition(){ return 0; } + reg_nums[0]=DAQ_REG_CTRL; reg_vals[0]=0; reg_nums[1]=DAQ_REG_NEXPOSURES; @@ -1342,6 +1531,53 @@ int Feb_Control_StartAcquisition(){ reg_vals[2]=Feb_Control_ConvertTimeToRegister(Feb_Control_exposure_time_in_sec); reg_nums[3]=DAQ_REG_EXPOSURE_REPEAT_TIMER; reg_vals[3]=Feb_Control_ConvertTimeToRegister(Feb_Control_exposure_period_in_sec); +///* + if(!Feb_Interface_WriteRegisters(Feb_Control_AddressToAll(),4,reg_nums,reg_vals,0,0)){ + printf("Trouble starting acquisition....\n");; + return 0; + } + + + unsigned int masterHalfModuleMode = 0; + + reg_nums[0]=DAQ_REG_CHIP_CMDS; + reg_vals[0]=(masterHalfModuleMode|Feb_Control_acquireNReadoutMode|Feb_Control_triggerMode|Feb_Control_externalEnableMode|Feb_Control_subFrameMode); + if(!Feb_Interface_WriteRegisters(Feb_Control_AddressToAll(),1,reg_nums,reg_vals,0,0)){ + printf("Trouble writing commands....\n");; + return 0; + } + + /* + masterHalfModuleMode = 0x80000000; + + reg_nums[0]=DAQ_REG_CHIP_CMDS; + reg_vals[0]=(masterHalfModuleMode|Feb_Control_acquireNReadoutMode|Feb_Control_triggerMode|Feb_Control_externalEnableMode|Feb_Control_subFrameMode); + if(!Feb_Interface_WriteRegisters((Module_GetTopLeftAddress(&modules[1])|Module_GetTopRightAddress(&modules[1])),1,reg_nums,reg_vals,0,0)){ + printf("Trouble writing commands....\n");; + return 0; + } +*/ + + + //if(!Feb_Interface_WriteRegisters((Module_GetTopLeftAddress(&modules[1])|Module_GetTopRightAddress(&modules[1])),1,reg_nums,reg_vals,0,0)){ + +///* + int i; + for(i=0;i<14;i++){ + reg_nums[i]=DAQ_REG_CTRL; + reg_vals[i]=0; + } + 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)){ + printf("Trouble starting acquisition....\n");; + return 0; + } + +//*/ + /* + reg_nums[4]=DAQ_REG_CHIP_CMDS; reg_vals[4]=(Feb_Control_acquireNReadoutMode|Feb_Control_triggerMode|Feb_Control_externalEnableMode|Feb_Control_subFrameMode); int i; @@ -1352,11 +1588,12 @@ int Feb_Control_StartAcquisition(){ reg_nums[19]=DAQ_REG_CTRL; reg_vals[19]=ACQ_CTRL_START; + // 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(),20,reg_nums,reg_vals,0,0)){ printf("Trouble starting acquisition....\n");; return 0; } - +*/ return 1; } diff --git a/slsDetectorSoftware/eigerDetectorServer/FebControl.h b/slsDetectorSoftware/eigerDetectorServer/FebControl.h index 63da66b8e..4ce8fd459 100644 --- a/slsDetectorSoftware/eigerDetectorServer/FebControl.h +++ b/slsDetectorSoftware/eigerDetectorServer/FebControl.h @@ -35,6 +35,7 @@ struct Module{ void Module_Module(struct Module* mod,unsigned int number, unsigned int address_top); +void Module_ModuleBottom(struct Module* mod,unsigned int number, unsigned int address_bottom); void Module_Module1(struct Module* mod,unsigned int number, unsigned int address_top, unsigned int address_bottom); unsigned int Module_GetModuleNumber(struct Module* mod); int Module_TopAddressIsValid(struct Module* mod); @@ -64,8 +65,9 @@ int Module_GetBottomDACValue(struct Module* mod,unsigned int i); - - +int Feb_Control_IsBottomModule(); +int Feb_Control_GetModuleNumber(); +void Feb_Control_Set_Master(); void Feb_Control_ClearModules(); @@ -101,7 +103,7 @@ int Module_GetBottomDACValue(struct Module* mod,unsigned int i); int Feb_Control_ResetChipCompletely(); - struct sockaddr_in Feb_Control_serv_addr; + //struct sockaddr_in Feb_Control_serv_addr; /* int Feb_Control_SetupSendToSocket(const char* ip_address_hostname, unsigned short int port); int Feb_Control_WriteNRead(char* message, int length, int max_length); diff --git a/slsDetectorSoftware/eigerDetectorServer/Makefile b/slsDetectorSoftware/eigerDetectorServer/Makefile index 7920925cb..26b190032 100755 --- a/slsDetectorSoftware/eigerDetectorServer/Makefile +++ b/slsDetectorSoftware/eigerDetectorServer/Makefile @@ -36,4 +36,4 @@ beb_debug:$(SRC_CLNT3) clean: rm -rf $(DESTDIR)/$(PROGS) *.o - \ No newline at end of file + diff --git a/slsDetectorSoftware/eigerDetectorServer/bin/eigerDetectorServer b/slsDetectorSoftware/eigerDetectorServer/bin/eigerDetectorServer index 8d96d912b..ab0168b92 100755 Binary files a/slsDetectorSoftware/eigerDetectorServer/bin/eigerDetectorServer and b/slsDetectorSoftware/eigerDetectorServer/bin/eigerDetectorServer differ diff --git a/slsDetectorSoftware/eigerDetectorServer/gitInfo.txt b/slsDetectorSoftware/eigerDetectorServer/gitInfo.txt index d75caad9c..83d4ba555 100644 --- a/slsDetectorSoftware/eigerDetectorServer/gitInfo.txt +++ b/slsDetectorSoftware/eigerDetectorServer/gitInfo.txt @@ -1,9 +1,9 @@ Path: slsDetectorsPackage/slsDetectorSoftware/eigerDetectorServer URL: origin git@gitorious.psi.ch:sls_det_software/sls_detector_software.git/eigerDetectorServer Repository Root: origin git@gitorious.psi.ch:sls_det_software/sls_detector_software.git -Repsitory UUID: c31619c88e5690230fcd389dc18f9139295c442c -Revision: 91 +Repsitory UUID: ce7cd6255b7b3abf1c046e9703ae8288ec55135a +Revision: 97 Branch: master Last Changed Author: Maliakal_Dhanya -Last Changed Rev: 280 -Last Changed Date: 2014-09-09 15:43:18 +0200 +Last Changed Rev: 282 +Last Changed Date: 2014-10-16 13:49:56 +0200 diff --git a/slsDetectorSoftware/eigerDetectorServer/gitInfoEiger.h b/slsDetectorSoftware/eigerDetectorServer/gitInfoEiger.h index e3e6ee9f0..7b83ced07 100644 --- a/slsDetectorSoftware/eigerDetectorServer/gitInfoEiger.h +++ b/slsDetectorSoftware/eigerDetectorServer/gitInfoEiger.h @@ -1,11 +1,11 @@ //#define SVNPATH "" #define SVNURL "git@gitorious.psi.ch:sls_det_software/sls_detector_software.git/eigerDetectorServer" //#define SVNREPPATH "" -#define SVNREPUUID "c31619c88e5690230fcd389dc18f9139295c442c" -//#define SVNREV 0x280 +#define SVNREPUUID "ce7cd6255b7b3abf1c046e9703ae8288ec55135a" +//#define SVNREV 0x282 //#define SVNKIND "" //#define SVNSCHED "" #define SVNAUTH "Maliakal_Dhanya" -#define SVNREV 0x280 -#define SVNDATE 0x20140909 +#define SVNREV 0x282 +#define SVNDATE 0x20141016 // diff --git a/slsDetectorSoftware/eigerDetectorServer/slsDetectorFunctionList.c b/slsDetectorSoftware/eigerDetectorServer/slsDetectorFunctionList.c index fe17b4b9b..e4ac0b885 100644 --- a/slsDetectorSoftware/eigerDetectorServer/slsDetectorFunctionList.c +++ b/slsDetectorSoftware/eigerDetectorServer/slsDetectorFunctionList.c @@ -6,6 +6,7 @@ #include + #include "slsDetectorFunctionList.h" #include "gitInfoEiger.h" /*#include "EigerHighLevelFunctions.c" @@ -49,6 +50,11 @@ unsigned int nimages_per_request=1; int on_dst=0; int dst_requested[32] = {0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0}; +int default_dac_values[16] = {0,2000,2000,1250,700,1278,500,500,2000,500,500,550,550,100,1000,775}; + + +enum masterFlags masterMode=NO_MASTER; +enum masterFlags trialMasterMode=NO_MASTER; int initDetector(){ int imod,i,n; @@ -99,16 +105,16 @@ int initDetector(){ Feb_Interface_FebInterface(); Feb_Control_FebControl(); + Feb_Control_Init(); printf("FEb control constructor done\n"); Beb_Beb(-1); printf("BEB constructor done\n"); //get dac values int retval[2]; - for(i=0;i<(detectorModules)->ndac;i++){ - setDAC((enum detDacIndex)i,-1,(detectorModules)->module,0,retval); - (detectorModules)->dacs[i] = retval[0]; - } + for(i=0;i<(detectorModules)->ndac;i++) + setDAC((enum detDacIndex)i,default_dac_values[i],(detectorModules)->module,0,retval); + /* initialize dynamic range etc. */ @@ -121,12 +127,32 @@ int initDetector(){ setThresholdEnergy(8000,0); setReadOutFlags(PARALLEL); setSpeed(0,1);//clk_devider,half speed - setHighVolage(150,0); + setHighVolage(150,0); setIODelay(675,0); setTiming(AUTO_TIMING); + //setMaster(GET_MASTER); int enable[2] = {0,1}; setExternalGating(enable);//disable external gating + + Feb_Control_SetTestModeVariable(0); + + Feb_Control_CheckSetup(); + //if(!Feb_Control_IsBottomModule()){ + //if(getDetectorNumber()==0xbeb031){ + printf("************** master ********************\n"); + trialMasterMode = IS_MASTER; + Feb_Control_Set_Master(); + //} + //else printf("************** slave ********************\n"); + + + + if(Feb_Control_IsBottomModule()) + printf("BOTTOM ***************\n"); + else + printf("TOP ***************\n"); return 1; + } @@ -287,10 +313,10 @@ void setDAC(enum detDacIndex ind, int val, int imod, int mV, int retval[]){ if(val >= 0) Feb_Control_SetDAC(iname,val,mV); int k; - Feb_Control_GetDAC(iname, &k,0); - retval[0] = k; - Feb_Control_GetDAC(iname,&k,1); - retval[1] = k; + Feb_Control_GetDAC(iname, &k,0); + retval[0] = k; + Feb_Control_GetDAC(iname,&k,1); + retval[1] = k; (detectorModules)->dacs[ind] = retval[0]; @@ -316,7 +342,7 @@ int getADC(enum detDacIndex ind, int imod){ int setIODelay(int val, int imod){ if(val!=-1){ printf(" Setting IO Delay: %d\n",val); - if(Feb_Control_SetIDelays(0,val)) + if(Feb_Control_SetIDelays(Feb_Control_GetModuleNumber(),val)) eiger_iodelay = val; } return eiger_iodelay; @@ -373,7 +399,7 @@ int setModule(sls_detector_module myMod){ } - Feb_Control_SetTrimbits(0,tt); + Feb_Control_SetTrimbits(Feb_Control_GetModuleNumber(),tt); return 0; @@ -447,34 +473,35 @@ enum detectorSettings setSettings(enum detectorSettings sett, int imod){ int startStateMachine(){ - printf("Going to start acquisition\n"); - if(Feb_Control_StartAcquisition()){ - - //RequestImages(); - int ret_val = 0; - dst_requested[0] = 1; - while(dst_requested[on_dst]){ - //waits on data - if((ret_val = (!Beb_RequestNImages(0,1,send_to_ten_gig,on_dst,nimages_per_request,0)|| - !Beb_RequestNImages(0,2,send_to_ten_gig,0x20|on_dst,nimages_per_request,0)))) - break; - dst_requested[on_dst++]=0; - on_dst%=ndsts_in_use; - } - - if(ret_val) - return FAIL; - else - return OK; +int ret; + if(trialMasterMode == IS_MASTER){ + printf("Going to start acquisition\n"); + Feb_Control_StartAcquisition(); } - return FAIL; + + //if(trialMasterMode == IS_MASTER){ + printf("requesting images\n"); + ret = startReadOut(); + //} + if(trialMasterMode == IS_MASTER){ + /*for(i=0;i<3;i++) + usleep(1000000);*/ + while(getRunStatus() == IDLE); + printf("Acquiring..\n"); + } + printf("Returning\n"); + + return ret; } int stopStateMachine(){ - printf("Going to stop acquisition\n"); - if(Feb_Control_StopAcquisition()) - return OK; + if(trialMasterMode == IS_MASTER){ + printf("Going to stop acquisition\n"); + if(Feb_Control_StopAcquisition()) + return OK; + }else return OK; + return FAIL; } @@ -485,8 +512,10 @@ int startReadOut(){ dst_requested[0] = 1; while(dst_requested[on_dst]){ //waits on data - if((ret_val = (!Beb_RequestNImages(0,1,send_to_ten_gig,on_dst,nimages_per_request,0)|| - !Beb_RequestNImages(0,2,send_to_ten_gig,0x20|on_dst,nimages_per_request,0)))) + int beb_num = 24;//Feb_Control_GetModuleNumber(); + + if((ret_val = (!Beb_RequestNImages(beb_num,1,send_to_ten_gig,on_dst,nimages_per_request,0)|| + !Beb_RequestNImages(beb_num,2,send_to_ten_gig,0x20|on_dst,nimages_per_request,0)))) break; dst_requested[on_dst++]=0; on_dst%=ndsts_in_use; @@ -496,20 +525,22 @@ int startReadOut(){ return FAIL; else return OK; - - return OK; } enum runStatus getRunStatus(){ + if(trialMasterMode == IS_MASTER){ int i = Feb_Control_AcquisitionInProgress(); if(i== 0){ - printf("IDLE\n"); + //printf("IDLE\n"); return IDLE; }else{ - printf("RUNNING\n"); + //printf("RUNNING\n"); return RUNNING; } + } + + return IDLE; } @@ -517,6 +548,8 @@ enum runStatus getRunStatus(){ char *readFrame(int *ret, char *mess){ if(!Feb_Control_WaitForFinishedFlag(5000)) printf("error in waiting for finished flag\n"); + printf("acquisition finished\n"); + *ret = (int)FINISHED; return NULL; } @@ -532,8 +565,8 @@ int64_t setTimer(enum timerIndex ind, int64_t val){ switch(ind){ case FRAME_NUMBER: if(val >= 0){ - printf(" Setting number of frames: %d\n",(unsigned int)val); - if(Feb_Control_SetNExposures((unsigned int)val)*eiger_ncycles){ + printf(" Setting number of frames: %d * %d\n",(unsigned int)val,eiger_ncycles); + if(Feb_Control_SetNExposures((unsigned int)val*eiger_ncycles)){ eiger_nexposures = val; //SetDestinationParameters(EigerGetNumberOfExposures()*EigerGetNumberOfCycles()); on_dst = 0; @@ -570,7 +603,7 @@ int64_t setTimer(enum timerIndex ind, int64_t val){ return EigerGetNumberOfExposures();*/ case CYCLES_NUMBER: if(val >= 0){ - printf(" Setting number of triggers: %d\n",(unsigned int)val); + printf(" Setting number of triggers: %d * %d\n",(unsigned int)val,eiger_nexposures); if(Feb_Control_SetNExposures((unsigned int)val*eiger_nexposures)){ eiger_ncycles = val; //SetDestinationParameters(EigerGetNumberOfExposures()*EigerGetNumberOfCycles()); @@ -609,6 +642,7 @@ int setDynamicRange(int dr){ for(i=0;i<32;i++) dst_requested[i] = 0; //clear dst requested if(Beb_SetUpTransferParameters(dr)) eiger_dynamicrange = dr; + else printf("ERROR:Could not set bit mode in the back end\n"); } } //make sure back end and front end have the same bit mode @@ -667,10 +701,9 @@ int executeTrimming(enum trimMode mode, int par1, int par2, int imod){ } -int configureMAC(int ipad, long long int macad, long long int detectormacadd, int detipad, int udpport, int ival){ +int configureMAC(int ipad, long long int macad, long long int detectormacadd, int detipad, int udpport, int udpport2, int ival){ char src_mac[50], src_ip[50],dst_mac[50], dst_ip[50]; int src_port = 0xE185; - int dst_port = udpport; sprintf(src_ip,"%d.%d.%d.%d",(detipad>>24)&0xff,(detipad>>16)&0xff,(detipad>>8)&0xff,(detipad)&0xff); sprintf(dst_ip,"%d.%d.%d.%d",(ipad>>24)&0xff,(ipad>>16)&0xff,(ipad>>8)&0xff,(ipad)&0xff); sprintf(src_mac,"%02x:%02x:%02x:%02x:%02x:%02x",(unsigned int)((detectormacadd>>40)&0xFF), @@ -686,35 +719,38 @@ int configureMAC(int ipad, long long int macad, long long int detectormacadd, in (unsigned int)((macad>>8)&0xFF), (unsigned int)((macad>>0)&0xFF)); - printf("Seting up Table Entry Left:\n"); printf("src_port:%d\n",src_port); - printf("dst_port:%d\n",dst_port); printf("src_ip:%s\n",src_ip); printf("dst_ip:%s\n",dst_ip); printf("src_mac:%s\n",src_mac); - printf("dst_mac:%s\n\n",dst_mac); + printf("dst_mac:%s\n",dst_mac); - int beb_num = 34; + + int beb_num = 24;//Feb_Control_GetModuleNumber(); int header_number = 0; + int dst_port = udpport; -int i=0; - //EigerSetupTableEntryLeft(ipad, macad, detectormacadd, detipad, udpport); + printf("dst_port:%d\n\n",dst_port); + + int i=0; /* for(i=0;i<32;i++){/** modified for Aldo*/ if(Beb_SetBebSrcHeaderInfos(beb_num,send_to_ten_gig,src_mac,src_ip,src_port) && Beb_SetUpUDPHeader(beb_num,send_to_ten_gig,header_number+i,dst_mac,dst_ip, dst_port)) printf("set up left ok\n"); else return -1; /*}*/ - //EigerSetupTableEntryRight(ipad, macad, detectormacadd, detipad, udpport); + header_number = 32; - dst_port = udpport +1; + dst_port = udpport2; + printf("dst_port:%d\n\n",dst_port); + /*for(i=0;i<32;i++){*//** modified for Aldo*/ if(Beb_SetBebSrcHeaderInfos(beb_num,send_to_ten_gig,src_mac,src_ip,src_port) && Beb_SetUpUDPHeader(beb_num,send_to_ten_gig,header_number+i,dst_mac,dst_ip, dst_port)) - printf("set up right ok\n"); + printf("set up right ok\n\n"); else return -1; /*}*/ - //SetDestinationParameters(EigerGetNumberOfExposures()*EigerGetNumberOfCycles()); + on_dst = 0; for(i=0;i<32;i++) dst_requested[i] = 0; //clear dst requested @@ -879,6 +915,9 @@ void setExternalGating(int enable[]){ enum masterFlags setMaster(enum masterFlags arg){ + //if(arg != GET_MASTER) + // masterMode = arg; + return NO_MASTER; } diff --git a/slsDetectorSoftware/gitInfo.txt b/slsDetectorSoftware/gitInfo.txt index 40e3bf8fa..3098c814c 100644 --- a/slsDetectorSoftware/gitInfo.txt +++ b/slsDetectorSoftware/gitInfo.txt @@ -1,9 +1,9 @@ Path: slsDetectorsPackage/slsDetectorSoftware URL: origin git@gitorious.psi.ch:sls_det_software/sls_detector_software.git Repository Root: origin git@gitorious.psi.ch:sls_det_software/sls_detector_software.git -Repsitory UUID: c31619c88e5690230fcd389dc18f9139295c442c -Revision: 852 +Repsitory UUID: ce7cd6255b7b3abf1c046e9703ae8288ec55135a +Revision: 865 Branch: master Last Changed Author: Maliakal_Dhanya -Last Changed Rev: 852 -Last Changed Date: 2014-09-09 15:43:18 +0200 +Last Changed Rev: 865 +Last Changed Date: 2014-10-16 13:49:56 +0200 diff --git a/slsDetectorSoftware/gotthardDetectorServer/gitInfo.txt b/slsDetectorSoftware/gotthardDetectorServer/gitInfo.txt index 047932789..4b8c1aa5c 100644 --- a/slsDetectorSoftware/gotthardDetectorServer/gitInfo.txt +++ b/slsDetectorSoftware/gotthardDetectorServer/gitInfo.txt @@ -1,9 +1,9 @@ Path: slsDetectorsPackage/slsDetectorSoftware/gotthardDetectorServer URL: origin git@gitorious.psi.ch:sls_det_software/sls_detector_software.git/gotthardDetectorServer Repository Root: origin git@gitorious.psi.ch:sls_det_software/sls_detector_software.git -Repsitory UUID: c31619c88e5690230fcd389dc18f9139295c442c -Revision: 173 +Repsitory UUID: ce7cd6255b7b3abf1c046e9703ae8288ec55135a +Revision: 175 Branch: master Last Changed Author: Maliakal_Dhanya -Last Changed Rev: 280 -Last Changed Date: 2014-09-09 15:43:18 +0200 +Last Changed Rev: 282 +Last Changed Date: 2014-10-16 13:49:56 +0200 diff --git a/slsDetectorSoftware/gotthardDetectorServer/gitInfoGotthard.h b/slsDetectorSoftware/gotthardDetectorServer/gitInfoGotthard.h index 8875fcb86..13990b080 100644 --- a/slsDetectorSoftware/gotthardDetectorServer/gitInfoGotthard.h +++ b/slsDetectorSoftware/gotthardDetectorServer/gitInfoGotthard.h @@ -1,11 +1,11 @@ //#define SVNPATH "" #define SVNURL "git@gitorious.psi.ch:sls_det_software/sls_detector_software.git/gotthardDetectorServer" //#define SVNREPPATH "" -#define SVNREPUUID "c31619c88e5690230fcd389dc18f9139295c442c" -//#define SVNREV 0x280 +#define SVNREPUUID "ce7cd6255b7b3abf1c046e9703ae8288ec55135a" +//#define SVNREV 0x282 //#define SVNKIND "" //#define SVNSCHED "" #define SVNAUTH "Maliakal_Dhanya" -#define SVNREV 0x280 -#define SVNDATE 0x20140909 +#define SVNREV 0x282 +#define SVNDATE 0x20141016 // diff --git a/slsDetectorSoftware/gotthardDetectorServer/server_funcs.c b/slsDetectorSoftware/gotthardDetectorServer/server_funcs.c index 897c6bcad..0fa60e7e7 100755 --- a/slsDetectorSoftware/gotthardDetectorServer/server_funcs.c +++ b/slsDetectorSoftware/gotthardDetectorServer/server_funcs.c @@ -2547,7 +2547,7 @@ int update_client(int file_des) { int configure_mac(int file_des) { int ret=OK; - char arg[5][50]; + char arg[6][50]; int n; int imod=0;//should be in future sent from client as -1, arg[2] @@ -2572,7 +2572,7 @@ int configure_mac(int file_des) { sscanf(arg[2], "%x", &udpport); sscanf(arg[3], "%llx", &idetectormacadd); sscanf(arg[4], "%x", &detipad); - + //arg[5] is udpport2 for eiger #ifdef VERBOSE int i; printf("\ndigital_test_bit in server %d\t",digitalTestBit); diff --git a/slsDetectorSoftware/jungfrauDetectorServer/.target-makefrag b/slsDetectorSoftware/jungfrauDetectorServer/.target-makefrag new file mode 100755 index 000000000..ce093ecac --- /dev/null +++ b/slsDetectorSoftware/jungfrauDetectorServer/.target-makefrag @@ -0,0 +1 @@ +AXIS_BUILDTYPE ?= cris-axis-linux-gnu diff --git a/slsDetectorSoftware/jungfrauDetectorServer/Makefile b/slsDetectorSoftware/jungfrauDetectorServer/Makefile new file mode 100755 index 000000000..af9c684c4 --- /dev/null +++ b/slsDetectorSoftware/jungfrauDetectorServer/Makefile @@ -0,0 +1,48 @@ +# $Id: Makefile,v 1.1.1.1 2006/02/04 03:35:01 freza Exp $ +# first compile +# make cris-axis-linux-gnu + + +CROSS = bfin-uclinux- +CC = $(CROSS)gcc + +CFLAGS += -Wall -DMOENCHD -DMCB_FUNCS -DDACS_INT -DDEBUG #-DVERBOSE #-DVERYVERBOSE #-DVIRTUAL #-DDACS_INT_CSERVER + + +PROGS= jungfrauDetectorServer +INSTDIR= /tftpboot +INSTMODE= 0777 + + + +BINS = testlib_sharedlibc +SRCS = server.c server_funcs.c communication_funcs.c firmware_funcs.c mcb_funcs.c trimming_funcs.c sharedmemory.c +OBJS = $(SRCS:%.c=%.o) + + + +all: clean $(PROGS) + +boot: $(OBJS) + +$(PROGS): $(OBJS) + echo $(OBJS) + $(CC) $(CFLAGS) -o $@ $^ $(LDLIBS_$@) $(LDFLAGS_$@) + + +install: $(PROGS) + $(INSTALL) -d $(INSTDIR) + $(INSTALL) -m $(INSTMODE) $(PROGS) $(INSTDIR) + + +romfs: + $(ROMFSINST) /bin/$(PROGS) + +clean: + rm -rf $(PROGS) *.o *.gdb + + + + + + diff --git a/slsDetectorSoftware/jungfrauDetectorServer/Makefile.virtual b/slsDetectorSoftware/jungfrauDetectorServer/Makefile.virtual new file mode 100755 index 000000000..38dd2537c --- /dev/null +++ b/slsDetectorSoftware/jungfrauDetectorServer/Makefile.virtual @@ -0,0 +1,30 @@ + +DESTDIR ?= ./ + +CC = gcc +CFLAGS += -Wall -DMOENCHD -DMCB_FUNCS -DDACS_INT -DDEBUG -DVIRTUAL + + +PROGS= $(DESTDIR)/moenchVirtualServer + + +SRCS = server.c server_funcs.c communication_funcs.c firmware_funcs.c mcb_funcs.c trimming_funcs.c sharedmemory.c +OBJS = $(SRCS:%.c=%.o) + +moenchVirtualServer = $(PROGS) + +all: clean $(PROGS) + + +$(PROGS): $(OBJS) + $(CC) $(CFLAGS) -o $@ $^ $(LDLIBS_$@) $(LDFLAGS_$@) + + +clean: + rm -rf $(PROGS) *.o *.gdb + + + + + + diff --git a/slsDetectorSoftware/jungfrauDetectorServer/communication_funcs.c b/slsDetectorSoftware/jungfrauDetectorServer/communication_funcs.c new file mode 120000 index 000000000..87a4f95d1 --- /dev/null +++ b/slsDetectorSoftware/jungfrauDetectorServer/communication_funcs.c @@ -0,0 +1 @@ +../commonFiles/communication_funcs.c \ No newline at end of file diff --git a/slsDetectorSoftware/jungfrauDetectorServer/communication_funcs.h b/slsDetectorSoftware/jungfrauDetectorServer/communication_funcs.h new file mode 120000 index 000000000..f220903b2 --- /dev/null +++ b/slsDetectorSoftware/jungfrauDetectorServer/communication_funcs.h @@ -0,0 +1 @@ +../commonFiles/communication_funcs.h \ No newline at end of file diff --git a/slsDetectorSoftware/jungfrauDetectorServer/firmware_funcs.c b/slsDetectorSoftware/jungfrauDetectorServer/firmware_funcs.c new file mode 100755 index 000000000..be5511b74 --- /dev/null +++ b/slsDetectorSoftware/jungfrauDetectorServer/firmware_funcs.c @@ -0,0 +1,2732 @@ + +#include "server_defs.h" +#include "firmware_funcs.h" +#include "mcb_funcs.h" +#include "registers_m.h" + +#ifdef SHAREDMEMORY +#include "sharedmemory.h" +#endif + +#include +#include +#include + +#include + +//for memory mapping +u_int64_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 dataBytes=NMAXMOD*NCHIP*NCHAN*2; +int storeInRAM=0; +int ROI_flag=0; +int adcConfigured=-1; +u_int32_t *ram_values=NULL; +volatile char *now_ptr=NULL; +volatile u_int16_t *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 ififostart, ififostop, ififostep, ififo; + +int masterMode=NO_MASTER, syncMode=NO_SYNCHRONIZATION, timingMode=AUTO_TIMING; + +enum externalSignalFlag signals[4]={EXT_SIG_OFF, EXT_SIG_OFF, EXT_SIG_OFF, EXT_SIG_OFF}; + +int withGotthard = 0; + +#ifdef MCB_FUNCS +extern const int nChans; +extern const int nChips; +//extern const int nDacs; +//extern const int nAdcs; +#endif +#ifndef MCB_FUNCS + +const int nChans=NCHAN; +const int nChips=NCHIP; +const int nDacs=NDAC; +const int nAdcs=NADC; +#endif + + + + +/** + ENEt conf structs +*/ +typedef struct mac_header_struct{ + u_int8_t mac_dest_mac2; + u_int8_t mac_dest_mac1; + u_int8_t mac_dummy1; + u_int8_t mac_dummy2; + u_int8_t mac_dest_mac6; + u_int8_t mac_dest_mac5; + u_int8_t mac_dest_mac4; + u_int8_t mac_dest_mac3; + u_int8_t mac_src_mac4; + u_int8_t mac_src_mac3; + u_int8_t mac_src_mac2; + u_int8_t mac_src_mac1; + u_int16_t mac_ether_type; + u_int8_t mac_src_mac6; + u_int8_t mac_src_mac5; +} mac_header; + +typedef struct ip_header_struct { + u_int16_t ip_len; + u_int8_t ip_tos; + u_int8_t ip_ihl:4 ,ip_ver:4; + u_int16_t ip_offset:13,ip_flag:3; + u_int16_t ip_ident; + u_int16_t ip_chksum; + u_int8_t ip_protocol; + u_int8_t ip_ttl; + u_int32_t ip_sourceip; + u_int32_t ip_destip; +} ip_header; + +typedef struct udp_header_struct{ + u_int16_t udp_destport; + u_int16_t udp_srcport; + u_int16_t udp_chksum; + u_int16_t udp_len; +} udp_header; + +typedef struct mac_conf_struct{ + mac_header mac; + ip_header ip; + udp_header udp; + u_int32_t npack; + u_int32_t lpack; + u_int32_t npad; + u_int32_t cdone; +} mac_conf; + +typedef struct tse_conf_struct{ + u_int32_t rev; //0x0 + u_int32_t scratch; + u_int32_t command_config; + u_int32_t mac_0; //0x3 + u_int32_t mac_1; + u_int32_t frm_length; + u_int32_t pause_quant; + u_int32_t rx_section_empty; //0x7 + u_int32_t rx_section_full; + u_int32_t tx_section_empty; + u_int32_t tx_section_full; + u_int32_t rx_almost_empty; //0xB + u_int32_t rx_almost_full; + u_int32_t tx_almost_empty; + u_int32_t tx_almost_full; + u_int32_t mdio_addr0; //0xF + u_int32_t mdio_addr1; +}tse_conf; + + + +int mapCSP0(void) { + printf("Mapping memory\n"); +#ifndef VIRTUAL + int fd; + fd = open("/dev/mem", O_RDWR | O_SYNC, 0); + if (fd == -1) { + printf("\nCan't find /dev/mem!\n"); + return FAIL; + } + printf("/dev/mem opened\n"); + + CSP0BASE = (u_int32_t)mmap(0, MEM_SIZE, PROT_READ|PROT_WRITE, MAP_FILE|MAP_SHARED, fd, CSP0); + if (CSP0BASE == (u_int32_t)MAP_FAILED) { + printf("\nCan't map memmory area!!\n"); + return FAIL; + } + printf("CSP0 mapped\n"); + +#endif +#ifdef VIRTUAL + CSP0BASE = malloc(MEM_SIZE); + printf("memory allocated\n"); +#endif +#ifdef SHAREDMEMORY + if ( (res=inism(SMSV))<0) { + printf("error attaching shared memory! %i",res); + return FAIL; + } +#endif + printf("CSPObase is 0x%x \n",CSP0BASE); + printf("CSPOBASE=from %08x to %x\n",CSP0BASE,CSP0BASE+MEM_SIZE); + + u_int32_t address; + address = FIFO_DATA_REG_OFF; + values=(u_int16_t*)(CSP0BASE+address*2); + printf("statusreg=%08x\n",bus_r(STATUS_REG)); + printf("\n\n"); + return OK; +} + +u_int16_t bus_r16(u_int32_t offset){ + volatile u_int16_t *ptr1; + ptr1=(u_int16_t*)(CSP0BASE+offset*2); + return *ptr1; +} + +u_int16_t bus_w16(u_int32_t offset, u_int16_t data) { + volatile u_int16_t *ptr1; + ptr1=(u_int16_t*)(CSP0BASE+offset*2); + *ptr1=data; + return OK; +} + +/** ramType is DARK_IMAGE_REG or GAIN_IMAGE_REG */ +u_int16_t ram_w16(u_int32_t ramType, int adc, int adcCh, int Ch, u_int16_t data) { + unsigned int adr = (ramType | adc << 8 | adcCh << 5 | Ch ); + // printf("Writing to addr:%x\n",adr); + return bus_w16(adr,data); +} + +/** ramType is DARK_IMAGE_REG or GAIN_IMAGE_REG */ +u_int16_t ram_r16(u_int32_t ramType, int adc, int adcCh, int Ch){ + unsigned int adr = (ramType | adc << 8 | adcCh << 5 | Ch ); + // printf("Reading from addr:%x\n",adr); + return bus_r16(adr); +} + +u_int32_t bus_w(u_int32_t offset, u_int32_t data) { + volatile u_int32_t *ptr1; + + ptr1=(u_int32_t*)(CSP0BASE+offset*2); + *ptr1=data; + + return OK; +} + + +u_int32_t bus_r(u_int32_t offset) { + volatile u_int32_t *ptr1; + + ptr1=(u_int32_t*)(CSP0BASE+offset*2); + return *ptr1; +} + + +int setPhaseShiftOnce(){ + u_int32_t addr, reg; + int i; + addr=MULTI_PURPOSE_REG; + reg=bus_r(addr); +#ifdef VERBOSE + printf("Multipurpose reg:%x\n",reg); +#endif + + //Checking if it is power on(negative number) + // if(((reg&0xFFFF0000)>>16)>0){ + //bus_w(addr,0x0); //clear the reg + + if(reg==0){ + printf("\nImplementing phase shift of %d\n",phase_shift); + for (i=1;i0) { + bus_w(PLL_CNTRL_REG, 1);//reset PLL + bus_w(PLL_CNTRL_REG, 0); + phase_shift=0; + for (i=0;i1) nc=d;// nc=161/d; + else return -1; + + if (nc>255) + return -1; + + int addr, addr1, addr0; + u_int32_t pat,pat1,pat0; + + addr= PLL_PARAM_REG; + addr0= PLL_PARAM_OUT_REG; + addr1=PLL_CNTRL_REG; + pat1=0x10; + + + //write high count c0 +/* pat=(1<<12)|(7<<9)|nc; */ +/* bus_w(addr, pat); */ +/* bus_w(addr1, pat1); */ +/* bus_w(addr1, 0); */ +/* usleep (1000); */ +/* pat=bus_r(addr0); */ +/* bus_w(addr1, 0x4); */ +/* bus_w(addr1, 0); */ +/* pat=bus_r(addr0); */ +/* printf("M nominal count read %x (%d)\n",pat,(pat&0x1ff)); */ + + + + //write low count c0 + pat=(nc-1)|(4<<12)|(1<<9); + bus_w(addr, pat); + bus_w(addr1, pat1); + bus_w(addr1, 0); + pat0=bus_r(PLL_PARAM_OUT_REG); + usleep (1000); + printf("C0 low count status %x\n",pat0); + + //write high count c0 + pat=(nc)|(4<<12)|(0<<9); + bus_w(addr, pat); + bus_w(addr1, pat1); + bus_w(addr1, 0); + pat0=bus_r(PLL_PARAM_OUT_REG); + printf("C0 high count status %x\n",pat0); + usleep (1000); + + //write low count c1 + pat=(nc-1)|(5<<12)|(1<<9); + bus_w(addr, pat); + bus_w(addr1, pat1); + bus_w(addr1, 0); + pat0=bus_r(PLL_PARAM_OUT_REG); + printf("C1 high count status %x\n",pat0); + usleep (1000); + + //write high count c1 + pat=(nc)|(5<<12)|(0<<9); + bus_w(addr, pat); + bus_w(addr1, pat1); + bus_w(addr1, 0); + pat0=bus_r(PLL_PARAM_OUT_REG); + printf("C1 low count status %x\n",pat0); + usleep (1000); + + //reconfigure pll + pat1=0x8; + bus_w(addr1, pat1); + bus_w(addr1, 0); + pat0=bus_r(PLL_PARAM_OUT_REG); + printf("configure status %d\n",pat0); + sleep (1); + printf("finish status %x\n",pat0); + + + bus_w(PLL_CNTRL_REG, 1); //reset PLL + bus_w(PLL_CNTRL_REG, 0); + + return 0; +} + + + + +u_int32_t getClockDivider() { + + + + int ic=0; + + //reset pll_reconfig to initial values + bus_w(PLL_CNTRL_REG,(1<=0 && d<=255) + bus_w(OVERSAMPLING_REG, d); + + return bus_r(OVERSAMPLING_REG); +} + + +u_int32_t setWaitStates(int d1) { + return 0; +} + +u_int32_t getWaitStates() { + return 0; +} + + +u_int32_t setTotClockDivider(int d) { + return 0; +} + +u_int32_t getTotClockDivider() { + return 0; +} + + +u_int32_t setTotDutyCycle(int d) { + return 0; +} + +u_int32_t getTotDutyCycle() { + return 0; +} + + +u_int32_t setExtSignal(int d, enum externalSignalFlag mode) { + + //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); + + if (d>=0 && d<4) { + signals[d]=mode; +#ifdef VERBOSE + printf("settings signal variable number %d to value %04x\n", d, signals[d]); +#endif + + // if output signal, set it! + + switch (mode) { + case GATE_IN_ACTIVE_HIGH: + case GATE_IN_ACTIVE_LOW: + if (timingMode==GATE_FIX_NUMBER || timingMode==GATE_WITH_START_TRIGGER) + setFPGASignal(d,mode); + else + setFPGASignal(d,SIGNAL_OFF); + break; + case TRIGGER_IN_RISING_EDGE: + case TRIGGER_IN_FALLING_EDGE: + if (timingMode==TRIGGER_EXPOSURE || timingMode==GATE_WITH_START_TRIGGER) + setFPGASignal(d,mode); + else + setFPGASignal(d,SIGNAL_OFF); + break; + case RO_TRIGGER_IN_RISING_EDGE: + case RO_TRIGGER_IN_FALLING_EDGE: + if (timingMode==TRIGGER_READOUT) + setFPGASignal(d,mode); + else + setFPGASignal(d,SIGNAL_OFF); + break; + case MASTER_SLAVE_SYNCHRONIZATION: + setSynchronization(syncMode); + break; + default: + setFPGASignal(d,mode); + break; + } + + setTiming(GET_EXTERNAL_COMMUNICATION_MODE); + } + + +// if (mode<=RO_TRIGGER_OUT_FALLING_EDGE && mode>=0) +// bus_w(EXT_SIGNAL_REG,((modes[mode])<=0) { +#ifdef VERBOSE + 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]); +#endif + return signals[d]; + } else + return -1; + + +} + + +int getFPGASignal(int d) { + + int modes[]={SIGNAL_OFF, GATE_IN_ACTIVE_HIGH, GATE_IN_ACTIVE_LOW,TRIGGER_IN_RISING_EDGE, TRIGGER_IN_FALLING_EDGE,RO_TRIGGER_IN_RISING_EDGE, RO_TRIGGER_IN_FALLING_EDGE, GATE_OUT_ACTIVE_HIGH, GATE_OUT_ACTIVE_LOW, TRIGGER_OUT_RISING_EDGE, TRIGGER_OUT_FALLING_EDGE, RO_TRIGGER_OUT_RISING_EDGE,RO_TRIGGER_OUT_FALLING_EDGE}; + + int off=d*SIGNAL_OFFSET; + int mode=((bus_r(EXT_SIGNAL_REG)&(SIGNAL_MASK<>off); + + if (mode<=RO_TRIGGER_OUT_FALLING_EDGE) { + if (modes[mode]!=SIGNAL_OFF && signals[d]!=MASTER_SLAVE_SYNCHRONIZATION) + signals[d]=modes[mode]; +#ifdef VERYVERBOSE + printf("gettings signal register number %d value %04x\n", d, modes[mode]); +#endif + return modes[mode]; + } else + return -1; + +} + + + + + +/* +enum externalCommunicationMode{ + GET_EXTERNAL_COMMUNICATION_MODE, + AUTO, + TRIGGER_EXPOSURE_SERIES, + TRIGGER_EXPOSURE_BURST, + TRIGGER_READOUT, + TRIGGER_COINCIDENCE_WITH_INTERNAL_ENABLE, + GATE_FIX_NUMBER, + GATE_FIX_DURATION, + GATE_WITH_START_TRIGGER, + GATE_COINCIDENCE_WITH_INTERNAL_ENABLE +}; +*/ + + +int setTiming(int ti) { + + + int ret=GET_EXTERNAL_COMMUNICATION_MODE; + + int g=-1, t=-1, rot=-1; + + int i; + + switch (ti) { + case AUTO_TIMING: + timingMode=ti; + // disable all gates/triggers in except if used for master/slave synchronization + for (i=0; i<4; i++) { + if (getFPGASignal(i)>0 && getFPGASignal(i)=0 && t>=0 && rot<0) { + ret=GATE_WITH_START_TRIGGER; + } else if (g<0 && t>=0 && rot<0) { + ret=TRIGGER_EXPOSURE; + } else if (g>=0 && t<0 && rot<0) { + ret=GATE_FIX_NUMBER; + } else if (g<0 && t<0 && rot>0) { + ret=TRIGGER_READOUT; + } else if (g<0 && t<0 && rot<0) { + ret=AUTO_TIMING; + } + + // timingMode=ret; + + return ret; + +} + + + +int setConfigurationRegister(int d) { +#ifdef VERBOSE + printf("Setting configuration register to %x",d); +#endif + if (d>=0) { + bus_w(CONFIG_REG,d); + } +#ifdef VERBOSE + printf("configuration register is %x", bus_r(CONFIG_REG)); +#endif + return bus_r(CONFIG_REG); +} + +int setToT(int d) { + //int ret=0; + int reg; +#ifdef VERBOSE + printf("Setting ToT to %d\n",d); +#endif + reg=bus_r(CONFIG_REG); +#ifdef VERBOSE + printf("Before: ToT is %x\n", reg); +#endif + if (d>0) { + bus_w(CONFIG_REG,reg|TOT_ENABLE_BIT); + } else if (d==0) { + bus_w(CONFIG_REG,reg&(~TOT_ENABLE_BIT)); + } + reg=bus_r(CONFIG_REG); +#ifdef VERBOSE + printf("ToT is %x\n", reg); +#endif + if (reg&TOT_ENABLE_BIT) + return 1; + else + return 0; +} + +int setContinousReadOut(int d) { + //int ret=0; + int reg; +#ifdef VERBOSE + printf("Setting Continous readout to %d\n",d); +#endif + reg=bus_r(CONFIG_REG); +#ifdef VERBOSE + printf("Before: Continous readout is %x\n", reg); +#endif + if (d>0) { + bus_w(CONFIG_REG,reg|CONT_RO_ENABLE_BIT); + } else if (d==0) { + bus_w(CONFIG_REG,reg&(~CONT_RO_ENABLE_BIT)); + } + reg=bus_r(CONFIG_REG); +#ifdef VERBOSE + printf("Continous readout is %x\n", reg); +#endif + if (reg&CONT_RO_ENABLE_BIT) + return 1; + else + return 0; +} + + +int startReceiver(int start) { + u_int32_t addr=CONFIG_REG; +#ifdef VERBOSE + if(start) + printf("Setting up detector to send to Receiver\n"); + else + printf("Setting up detector to send to CPU\n"); +#endif + int reg=bus_r(addr); + //for start recever, write 0 and for stop, write 1 + if (!start) + bus_w(CONFIG_REG,reg|CPU_OR_RECEIVER_BIT); + else + bus_w(CONFIG_REG,reg&(~CPU_OR_RECEIVER_BIT)); + + reg=bus_r(addr); +//#ifdef VERBOSE + printf("Config Reg %x\n", reg); +//#endif + int d =reg&CPU_OR_RECEIVER_BIT; + if(d!=0) d=1; + if(d!=start) + return OK; + else + return FAIL; +} + + +u_int64_t getDetectorNumber() { + char output[255],mac[255]=""; + u_int64_t res=0; + FILE* sysFile = popen("ifconfig eth0 | grep HWaddr | cut -d \" \" -f 11", "r"); + fgets(output, sizeof(output), sysFile); + pclose(sysFile); + //getting rid of ":" + char * pch; + pch = strtok (output,":"); + while (pch != NULL){ + strcat(mac,pch); + pch = strtok (NULL, ":"); + } + sscanf(mac,"%llx",&res); + return res; +} + +u_int32_t getFirmwareVersion() { + return bus_r(FPGA_VERSION_REG); +} + +u_int32_t getFirmwareSVNVersion(){ + return bus_r(FPGA_SVN_REG); +} + + +// for fpga test +u_int32_t testFpga(void) { + printf("Testing FPGA:\n"); + volatile u_int32_t val,addr,val2; + int result=OK,i; + //fixed pattern + val=bus_r(FIX_PATT_REG); + if (val==FIXED_PATT_VAL) { + printf("fixed pattern ok!! %08x\n",val); + } else { + printf("fixed pattern wrong!! %08x\n",val); + result=FAIL; + } + + //dummy register + addr = DUMMY_REG; + for(i=0;i<1000000;i++) + { + val=0x5A5A5A5A-i; + bus_w(addr, val); + val=bus_r(addr); + if (val!=0x5A5A5A5A-i) { + printf("ATTEMPT:%d:\tFPGA dummy register wrong!! %x instead of %x \n",i,val,0x5A5A5A5A-i); + result=FAIL; + } + val=(i+(i<<10)+(i<<20)); + bus_w(addr, val); + val2=bus_r(addr); + if (val2!=val) { + printf("ATTEMPT:%d:\tFPGA dummy register wrong!! read %x instead of %x.\n",i,val2,val); + result=FAIL; + } + val=0x0F0F0F0F; + bus_w(addr, val); + val=bus_r(addr); + if (val!=0x0F0F0F0F) { + printf("ATTEMPT:%d:\tFPGA dummy register wrong!! %x instead of 0x0F0F0F0F \n",i,val); + result=FAIL; + } + val=0xF0F0F0F0; + bus_w(addr, val); + val=bus_r(addr); + if (val!=0xF0F0F0F0) { + printf("ATTEMPT:%d:\tFPGA dummy register wrong!! %x instead of 0xF0F0F0F0 \n\n",i,val); + result=FAIL; + } + } + if(result==OK) + { + printf("----------------------------------------------------------------------------------------------"); + printf("\nATTEMPT 1000000: FPGA DUMMY REGISTER OK!!!\n"); + printf("----------------------------------------------------------------------------------------------"); + } + printf("\n"); + return result; +} + + +// for fpga test +u_int32_t testRAM(void) { + int result=OK; + 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 getNModBoard() { + return nModX; +} + +int setNMod(int n) { + return nModX; +} + + +// fifo test +int testFifos(void) { + printf("Fifo test not implemented!\n"); + bus_w16(CONTROL_REG, START_FIFOTEST_BIT); + bus_w16(CONTROL_REG, 0x0); + return OK; +} + + + +// program dacq settings + +int64_t set64BitReg(int64_t value, int aLSB, int aMSB){ + int64_t v64; + u_int32_t vLSB,vMSB; + if (value!=-1) { + vLSB=value&(0xffffffff); + bus_w(aLSB,vLSB); + v64=value>> 32; + vMSB=v64&(0xffffffff); + bus_w(aMSB,vMSB); + } + return get64BitReg(aLSB, aMSB); + +} + +int64_t get64BitReg(int aLSB, int aMSB){ + int64_t v64; + u_int32_t vLSB,vMSB; + vLSB=bus_r(aLSB); + vMSB=bus_r(aMSB); + v64=vMSB; + v64=(v64<<32) | vLSB; + + printf("reg64(%x,%x) %x %x %llx\n", aLSB, aMSB, vLSB, vMSB, v64); + + return v64; +} + +int64_t setFrames(int64_t value){ + return set64BitReg(value, SET_FRAMES_LSB_REG, SET_FRAMES_MSB_REG); +} + +int64_t getFrames(){ + printf("gf"); + 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-9*CLK_FREQ); + return set64BitReg(value,SET_EXPTIME_LSB_REG, SET_EXPTIME_MSB_REG)/(1E-9*CLK_FREQ); +} + +int64_t getExposureTime(){ + return get64BitReg(GET_EXPTIME_LSB_REG, GET_EXPTIME_MSB_REG)/(1E-9*CLK_FREQ); +} + +int64_t setGates(int64_t value){ + return set64BitReg(value, SET_GATES_LSB_REG, SET_GATES_MSB_REG); +} + +int64_t getGates(){ + 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); + } + + + + return set64BitReg(value,SET_PERIOD_LSB_REG, SET_PERIOD_MSB_REG)/(1E-9*CLK_FREQ); +} + +int64_t getPeriod(){ + return get64BitReg(GET_PERIOD_LSB_REG, GET_PERIOD_MSB_REG)/(1E-9*CLK_FREQ); +} + +int64_t setDelay(int64_t value){ + /* time is in ns */ + if (value!=-1) { + value*=(1E-9*CLK_FREQ); + } + return set64BitReg(value,SET_DELAY_LSB_REG, SET_DELAY_MSB_REG)/(1E-9*CLK_FREQ); +} + +int64_t getDelay(){ + return get64BitReg(GET_DELAY_LSB_REG, GET_DELAY_MSB_REG)/(1E-9*CLK_FREQ); +} + +int64_t setTrains(int64_t value){ + return set64BitReg(value, SET_CYCLES_LSB_REG, SET_CYCLES_MSB_REG); +} + +int64_t getTrains(){ + return get64BitReg(GET_CYCLES_LSB_REG, GET_CYCLES_MSB_REG); +} + + +int64_t setProbes(int64_t value){ + return 0; +} + + +int64_t setProgress() { + + //????? eventually call after setting the registers + +return 0; + +} + + +int64_t getProgress() { + + + //should be done in firmware!!!! + + return 0; + +} + +int64_t getActualTime(){ + return get64BitReg(GET_ACTUAL_TIME_LSB_REG, GET_ACTUAL_TIME_MSB_REG)/(1E-9*CLK_FREQ); +} + +int64_t getMeasurementTime(){ + int64_t v=get64BitReg(GET_MEASUREMENT_TIME_LSB_REG, GET_MEASUREMENT_TIME_MSB_REG); + 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); +} + + + + +int loadImage(int index, short int ImageVals[]){ + 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; +} + + +int setDACRegister(int idac, int val, int imod) { + u_int32_t addr, reg, mask; + int off; +#ifdef VERBOSE + if(val==-1) + printf("Getting dac register%d module %d\n",idac,imod); + else + printf("Setting dac register %d module %d to %d\n",idac,imod,val); +#endif + + switch(idac){ + case 0: + case 1: + case 2: + addr=MOD_DACS1_REG; + break; + case 3: + case 4: + case 5: + addr=MOD_DACS2_REG; + break; + case 6: + case 7: + addr=MOD_DACS3_REG; + break; + default: + printf("weird idac value %d\n",idac); + return -1; + break; + } + //saving only the msb + val=val>>2; + + off=(idac%3)*10; + mask=~((0x3ff)<=0 && val>off)&0x3ff; + //since we saved only the msb + val=val<<2; + + //val=(bus_r(addr)>>off)&0x3ff; + + +#ifdef VERBOSE + printf("Dac %d module %d register is %d\n\n",idac,imod,val); +#endif + return val; +} + + +int getTemperature(int tempSensor, int imod){ + int val; + imod=0;//ignoring more than 1 mod for now + int i,j,repeats=6; + u_int32_t tempVal=0; +#ifdef VERBOSE + char cTempSensor[2][100]={"ADCs/ASICs","VRs/FPGAs"}; + printf("Getting Temperature of module:%d for the %s for tempsensor:%d\n",imod,cTempSensor[tempSensor],tempSensor); +#endif + bus_w(TEMP_IN_REG,(T1_CLK_BIT)|(T1_CS_BIT)|(T2_CLK_BIT)|(T2_CS_BIT));//standby + bus_w(TEMP_IN_REG,((T1_CLK_BIT)&~(T1_CS_BIT))|(T2_CLK_BIT));//high clk low cs + + for(i=0;i<20;i++) { + //repeats is number of register writes for delay + for(j=0;j>1);//fpga + } + } + + bus_w(TEMP_IN_REG,(T1_CLK_BIT)|(T1_CS_BIT)|(T2_CLK_BIT)|(T2_CS_BIT));//standby + val=((int)tempVal)/4.0; + +#ifdef VERBOSE + printf("Temperature of module:%d for the %s is %.2fC\n",imod,cTempSensor[tempSensor],val); +#endif + return val; +} + + + +int initHighVoltage(int val, int imod){ +#ifdef VERBOSE + printf("Setting/Getting High Voltage of module:%d with val:%d\n",imod,val); +#endif + volatile u_int32_t addr=HV_REG; + int writeVal,writeVal2; + switch(val){ + case -1: break; + case 0: writeVal=0x0; writeVal2=0x0; break; + case 90: writeVal=0x0; writeVal2=0x1; break; + case 110:writeVal=0x2; writeVal2=0x3; break; + case 120:writeVal=0x4; writeVal2=0x5; break; + case 150:writeVal=0x6; writeVal2=0x7; break; + case 180:writeVal=0x8; writeVal2=0x9; break; + case 200:writeVal=0xA; writeVal2=0xB; break; + default :printf("Invalid voltage\n");return -2;break; + } + //to set value + if(val!=-1){ + //set value to converted value + bus_w(addr,writeVal); + bus_w(addr,writeVal2); +#ifdef VERBOSE + printf("Value sent is %d and then %d\n",writeVal,writeVal2); +#endif + } + //read value and return the converted value + val=bus_r(addr); +#ifdef VERBOSE + printf("Value read from reg is %d\n",val); +#endif + switch(val){ + case 0x0:val=0;break; + case 0x1:val=90;break; + case 0x3:val=110;break; + case 0x5:val=120;break; + case 0x7:val=150;break; + case 0x9:val=180;break; + case 0xB:val=200;break; + default:printf("Weird value read:%d\n",val);return -3;break; + } +#ifdef VERBOSE + printf("High voltage of module:%d is %d\n",imod,val); +#endif + return val; +} + + + +int initConfGain(int isettings,int val,int imod){ + int retval; + u_int32_t addr=GAIN_REG; + + if(val!=-1){ +#ifdef VERBOSE + printf("Setting Gain of module:%d with val:%d\n",imod,val); +#endif + bus_w(addr,((val<>SETTINGS_OFFSET); +#ifdef VERBOSE + printf("Settings read from reg is %d\n",retval); +#endif + if((isettings!=-1)&&(retval!=isettings)){ + printf("\n\nSettings r\n\n"); + return -1; + } + + return retval; +} + + + +int setADC(int adc){ + int reg,nchips,mask,nchans; + + if(adc==-1) ROI_flag=0; + else ROI_flag=1; + + setDAQRegister();//token timing + cleanFifo();//adc sync + + //with 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 = NCHIP; + nchans = NCHANS; + 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<mac.mac_dest_mac1 =((macad>>(8*5))&0xFF);// 0x00; //pc7060 + mac_conf_regs->mac.mac_dest_mac2 =((macad>>(8*4))&0xFF);// 0x19; //pc7060 + mac_conf_regs->mac.mac_dest_mac3 =((macad>>(8*3))&0xFF);// 0x99; //pc7060 + mac_conf_regs->mac.mac_dest_mac4 =((macad>>(8*2))&0xFF);// 0x24; //pc7060 + mac_conf_regs->mac.mac_dest_mac5 =((macad>>(8*1))&0xFF);// 0xEB; //pc7060 + mac_conf_regs->mac.mac_dest_mac6 =((macad>>(8*0))&0xFF);// 0xEE; //pc7060 + + /* + mac_conf_regs->mac.mac_src_mac1 = 0x00; + mac_conf_regs->mac.mac_src_mac2 = 0xAA; + mac_conf_regs->mac.mac_src_mac3 = 0xBB; + mac_conf_regs->mac.mac_src_mac4 = 0xCC; + mac_conf_regs->mac.mac_src_mac5 = 0xDD; + mac_conf_regs->mac.mac_src_mac6 = 0xEE; + */ + mac_conf_regs->mac.mac_src_mac1 =((detectormacad>>(8*5))&0xFF); + mac_conf_regs->mac.mac_src_mac2 =((detectormacad>>(8*4))&0xFF); + mac_conf_regs->mac.mac_src_mac3 =((detectormacad>>(8*3))&0xFF); + mac_conf_regs->mac.mac_src_mac4 =((detectormacad>>(8*2))&0xFF); + mac_conf_regs->mac.mac_src_mac5 =((detectormacad>>(8*1))&0xFF); + mac_conf_regs->mac.mac_src_mac6 =((detectormacad>>(8*0))&0xFF); + mac_conf_regs->mac.mac_ether_type = 0x0800; //ipv4 + + + + mac_conf_regs->ip.ip_ver = 0x4; + mac_conf_regs->ip.ip_ihl = 0x5; + mac_conf_regs->ip.ip_tos = 0x0; + mac_conf_regs->ip.ip_len = ipPacketSize;//0x0522; // was 0x0526; + mac_conf_regs->ip.ip_ident = 0x0000; + mac_conf_regs->ip.ip_flag = 0x2; + mac_conf_regs->ip.ip_offset = 0x00; + mac_conf_regs->ip.ip_ttl = 0x70; + mac_conf_regs->ip.ip_protocol = 0x11; + mac_conf_regs->ip.ip_chksum = 0x0000 ; //6E42 now is automatically computed + mac_conf_regs->ip.ip_sourceip = detipad; //0x8181CA2E;129.129.202.46 + mac_conf_regs->ip.ip_destip = ipad; //CA57 + + //#ifdef VERBOSE + printf("mac_dest:%llx %x:%x:%x:%x:%x:%x\n", + macad, + mac_conf_regs->mac.mac_dest_mac1, + mac_conf_regs->mac.mac_dest_mac2, + mac_conf_regs->mac.mac_dest_mac3, + mac_conf_regs->mac.mac_dest_mac4, + mac_conf_regs->mac.mac_dest_mac5, + mac_conf_regs->mac.mac_dest_mac6); + printf("mac_src:%llx %x:%x:%x:%x:%x:%x\n", + detectormacad, + mac_conf_regs->mac.mac_src_mac1, + mac_conf_regs->mac.mac_src_mac2, + mac_conf_regs->mac.mac_src_mac3, + mac_conf_regs->mac.mac_src_mac4, + mac_conf_regs->mac.mac_src_mac5, + mac_conf_regs->mac.mac_src_mac6); + printf("ip_ttl:%x\n",mac_conf_regs->ip.ip_ttl); + printf("det_ip: %x %x\n",detipad, mac_conf_regs->ip.ip_sourceip); + printf("dest_ip: %x %x\n",ipad, mac_conf_regs->ip.ip_destip); + + //#endif + + //checksum + count=sizeof(mac_conf_regs->ip); + addr=&(mac_conf_regs->ip); + 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; + mac_conf_regs->ip.ip_chksum = checksum; + //#ifdef VERBOSE + printf("IP header checksum is 0x%x s\n",(unsigned int)(checksum)); + //#endif + + mac_conf_regs->udp.udp_srcport = 0xE185; + mac_conf_regs->udp.udp_destport = udpport;//0xC351; + mac_conf_regs->udp.udp_len = udpPacketSize;//0x050E; //was 0x0512; + mac_conf_regs->udp.udp_chksum = 0x0000; + +#ifdef VERBOSE + printf("Configuring TSE\n"); +#endif + tse_conf_regs->rev = 0xA00; + tse_conf_regs->scratch = 0xCCCCCCCC; + tse_conf_regs->command_config = 0xB; + tse_conf_regs->mac_0 = 0x17231C00; + tse_conf_regs->mac_1 = 0xCB4A; + tse_conf_regs->frm_length = 0x5DC; //max frame length (1500 bytes) (was 0x41C) + tse_conf_regs->pause_quant = 0x0; + tse_conf_regs->rx_section_empty = 0x7F0; + tse_conf_regs->rx_section_full = 0x10; + tse_conf_regs->tx_section_empty = 0x3F8; //was 0x7F0; + tse_conf_regs->tx_section_full = 0x16; + tse_conf_regs->rx_almost_empty = 0x8; + tse_conf_regs->rx_almost_full = 0x8; + tse_conf_regs->tx_almost_empty = 0x8; + tse_conf_regs->tx_almost_full = 0x3; + tse_conf_regs->mdio_addr0 = 0x12; + tse_conf_regs->mdio_addr1 = 0x0; + + mac_conf_regs->cdone = 0xFFFFFFFF; + + + if(ival) + bus_w(addrr,(INT_RSTN_BIT|ENET_RESETN_BIT|WRITE_BACK_BIT|DIGITAL_TEST_BIT)); //0x2840,write shadow regs.. + else + bus_w(addrr,(INT_RSTN_BIT|ENET_RESETN_BIT|WRITE_BACK_BIT)); //0x2840,write shadow regs.. + + val=bus_r(addrr); +#ifdef VERBOSE + printf("Value read from Multi-purpose Reg:%x\n",val); +#endif + // if(val!=0x2840) return -1; + + usleep(100000); + + if(ival) + bus_w(addrr,(INT_RSTN_BIT|ENET_RESETN_BIT|SW1_BIT|DIGITAL_TEST_BIT)); //0x2820,write shadow regs.. + else + bus_w(addrr,(INT_RSTN_BIT|ENET_RESETN_BIT|SW1_BIT)); //0x2820,write shadow regs.. + + val=bus_r(addrr); +#ifdef VERBOSE + printf("Value read from Multi-purpose Reg:%x\n",val); +#endif + // if(val!=0x2820) return -1; + + + + + return adcConfigured; +} + + +int getAdcConfigured(){ + return adcConfigured; +} + +u_int32_t runBusy(void) { + u_int32_t s = bus_r(STATUS_REG) & 1; +#ifdef VERBOSE + printf("status %04x\n",s); +#endif + return s; +} + +u_int32_t dataPresent(void) { + return bus_r(LOOK_AT_ME_REG); +} + +u_int32_t runState(void) { + int s=bus_r(STATUS_REG); +#ifdef SHAREDMEMORY + if (s&RUN_BUSY_BIT) + write_status_sm("Running"); + else + write_status_sm("Stopped"); +#endif +#ifdef VERBOSE + printf("status %04x\n",s); +#endif + +/* if (s==0x62001) + exit(-1);*/ + return s; +} + + +// State Machine + +int startStateMachine(){ +int i; +//#ifdef VERBOSE + printf("*******Starting State Machine*******\n"); +//#endif + cleanFifo(); + // fifoReset(); + now_ptr=(char*)ram_values; +#ifdef SHAREDMEMORY + write_stop_sm(0); + write_status_sm("Started"); +#endif + + + for(i=0;i<100;i++){ + //start state machine + bus_w16(CONTROL_REG, START_ACQ_BIT | START_EXPOSURE_BIT); + bus_w16(CONTROL_REG, 0x0); + //verify + if(bus_r(STATUS_REG) & RUN_BUSY_BIT) + break; + else + usleep(5000); + } + if(i!=0) + printf("tried to start state machine %d times\n",i); + if(i==100){ + printf("\n***********COULD NOT START STATE MACHINE***************\n"); + return FAIL; + } + + printf("statusreg=%08x\n",bus_r(STATUS_REG)); + return OK; +} + + + + +int stopStateMachine(){ + int i; +//#ifdef VERBOSE + printf("*******Stopping State Machine*******\n"); +//#endif +#ifdef SHAREDMEMORY + write_stop_sm(1); + write_status_sm("Stopped"); +#endif + for(i=0;i<100;i++){ + //stop state machine + bus_w16(CONTROL_REG, STOP_ACQ_BIT); + bus_w16(CONTROL_REG, 0x0); + usleep(5000); + //verify + if(!(bus_r(STATUS_REG)&RUNMACHINE_BUSY_BIT)) + break; + } + if(i!=0) + printf("tried to stop state machine %d times\n",i); + if(i==100){ + printf("\n***********COULD NOT STOP STATE MACHINE***************\n"); + return FAIL; + } + +/* + usleep(5000); + // if (!runBusy()) + if(!(bus_r(STATUS_REG)&RUNMACHINE_BUSY_BIT)) + return OK; + else + return FAIL; + */ + printf("statusreg=%08x\n",bus_r(STATUS_REG)); + return OK; +} + + +int startReadOut(){ + u_int32_t status; +#ifdef VERBOSE + printf("Starting State Machine Readout\n"); +#endif + status=bus_r(STATUS_REG)&RUN_BUSY_BIT; +#ifdef DEBUG + printf("State machine status is %08x\n",bus_r(STATUS_REG)); +#endif + bus_w16(CONTROL_REG, START_ACQ_BIT |START_READOUT_BIT); // start readout + bus_w16(CONTROL_REG, 0x0); + return OK; +} + + +// fifo routines + +u_int32_t fifoReset(void) { + return -1; +} + + +u_int32_t setNBits(u_int32_t n) { + return -1; +} + +u_int32_t getNBits(){ + return -1; +} + + +u_int32_t fifoReadCounter(int fifonum){ + return -1; +} + +u_int32_t fifoReadStatus() +{ + // reads from the global status register + + return bus_r(STATUS_REG)&(SOME_FIFO_FULL_BIT | ALL_FIFO_EMPTY_BIT); +} + +u_int32_t fifo_full(void) +{ + // checks fifo empty flag returns 1 if fifo is empty + // otherwise 0 + return bus_r(STATUS_REG)&SOME_FIFO_FULL_BIT; +} + + +u_int32_t* fifo_read_event() +{ + + int i=0; + +#ifdef VIRTUAL + return NULL; +#endif + +#ifdef VERBOSE + printf("before looping\n"); +#endif + volatile u_int32_t t = bus_r(LOOK_AT_ME_REG); + +#ifdef VERBOSE + printf("lookatmereg=x%x\n",t); +#endif +/* + while ((t&0x1)==0) + { + t = bus_r(LOOK_AT_ME_REG); + if (!runBusy()){ + return NULL; + } + } +*/ + + while((t&0x1)==0) { +#ifdef VERYVERBOSE + printf("before readout %08x %08x\n", runState(), bus_r(LOOK_AT_ME_REG)); +#endif +#ifdef VERYVERBOSE + printf("look at me reg:%08x\n",bus_r(LOOK_AT_ME_REG)); +#endif + if (runBusy()==0) { + t = bus_r(LOOK_AT_ME_REG); +#ifdef VERYVERBOSE + printf("status should be idle!..look at me reg:%08x\n",bus_r(LOOK_AT_ME_REG)); +#endif + if ((t&0x1)==0) { +#ifdef VERBOSE + printf("no frame found - exiting\n"); + printf("%08x %08x\n", runState(), bus_r(LOOK_AT_ME_REG)); +#endif +#ifdef VERYVERBOSE + printf("returning null\n"); +#endif + printf("lookatmereg=x%x\n",t); + return NULL; + } else { +#ifdef VERBOSE + printf("no frame found %x status %x\n", bus_r(LOOK_AT_ME_REG),runState()); +#endif + break; + } + } + t = bus_r(LOOK_AT_ME_REG); +#ifdef VERYVERBOSE + printf("before starting while loop again: look at me reg:%08x\n\n",bus_r(LOOK_AT_ME_REG)); +#endif + if (i%1000==0) + printf("%08x %08x\n", runState(), bus_r(LOOK_AT_ME_REG)); + i++; + } +#ifdef VERYVERBOSE + printf(" out of while loop!\n"); +#endif +#ifdef VERYVERBOSE + printf("before readout %08x %08x\n", runState(), bus_r(LOOK_AT_ME_REG)); +#endif + + dma_memcpy(now_ptr,values ,dataBytes); + + +#ifdef VERYVERBOSE + int a; + for (a=0;a<8; a=a+2) + printf("\n%d %d: x%04x x%04x ",a+1,a,*(now_ptr+a+1),*(now_ptr+a) ); + for (a=2554;a<2560; a=a+2) + printf("\n%d %d: x%04x x%04x ",a+1,a,*(now_ptr+a+1),*(now_ptr+a) ); + printf("********\n"); + //memcpy(now_ptr, values, dataBytes); +#endif +#ifdef VERYVERBOSE + printf("Copying to ptr %08x %d\n",(unsigned int)(now_ptr), dataBytes); + printf("after readout %08x %08x\n", runState(), bus_r(LOOK_AT_ME_REG)); +#endif + + if (storeInRAM>0) { + now_ptr+=dataBytes; + } + printf("lookatmereg=x%x\n",t); + return ram_values; +} + + + +u_int32_t* decode_data(int *datain) +{ + u_int32_t *dataout; + // const char one=1; + const int bytesize=8; + char *ptr=(char*)datain; + //int nbits=dynamicRange; + int ipos=0, ichan=0;; + //int nch, boff=0; + int ibyte;//, ibit; + char iptr; + +#ifdef VERBOSE + printf("Decoding data for DR %d\n",dynamicRange); +#endif + dataout=malloc(nChans*nChips*nModX*4); + ichan=0; + switch (dynamicRange) { + case 1: + for (ibyte=0; ibyte>(ipos))&0x1; + ichan++; + } + } + break; + case 4: + for (ibyte=0; ibyte>(ipos*4))&0xf; + ichan++; + } + } + break; + case 8: + for (ichan=0; ichan0) + storeInRAM=1; + else + storeInRAM=0; + return allocateRAM(); +} + + +int allocateRAM() { + size_t size; + u_int32_t nt, nf; + nt=setTrains(-1); + nf=setFrames(-1); + if (nt==0) nt=1; + if (nf==0) nf=1; + // ret=clearRAM(); + if (storeInRAM) { + size=dataBytes*nf*nt; + if (size>(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)); + } + } + } + }*/ + + + + 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 writePatternWord(int addr, uint64_t word) { + + int cntrl=0; + if (addr>=MAX_PATTERN_LENGTH) + return -1; + + 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); + bus_w(PATTERN_CNTRL_REG, cntrl | (1<< PATTERN_CTRL_WRITE_BIT) ); + bus_w(PATTERN_CNTRL_REG, cntrl); + } + return word; +} +uint64_t writePatternIOControl(uint64_t word) { + if (word>=0)set64BitReg(word,PATTERN_IOCTRL_REG_LSB,PATTERN_IOCTRL_REG_MSB); + return get64BitReg(PATTERN_IOCTRL_REG_LSB,PATTERN_IOCTRL_REG_MSB); + +} +uint64_t writePatternClkControl(uint64_t word) { + if (word>=0)set64BitReg(word,PATTERN_IOCLKCTRL_REG_LSB,PATTERN_IOCLKCTRL_REG_MSB); + return get64BitReg(PATTERN_IOCLKCTRL_REG_LSB,PATTERN_IOCLKCTRL_REG_MSB); + +} + +int setPatternLoop(int level, int *start, int *stop, int *n) { + int ret=OK; + int lval=0; + + + switch (level) { + case 0: + if (*n>=0) bus_w(*n,PATTERN_N_LOOP0_REG); + *n=bus_r(PATTERN_N_LOOP0_REG); + lval=bus_r(PATTERN_LOOP0_AREG); + if (*start==-1) *start=(lval>> ASTART_OFFSET) & APATTERN_MASK; + if (*stop==-1) *start=(lval>> ASTOP_OFFSET) & APATTERN_MASK; + lval= ((*start & APATTERN_MASK) << ASTART_OFFSET) | ((*stop & APATTERN_MASK) << ASTOP_OFFSET); + bus_w(lval, PATTERN_LOOP0_AREG); + break; + case 1: + if (*n>=0) bus_w(*n,PATTERN_N_LOOP1_REG); + *n=bus_r(PATTERN_N_LOOP1_REG); + lval=bus_r(PATTERN_LOOP1_AREG); + if (*start==-1) *start=(lval>> ASTART_OFFSET) & APATTERN_MASK; + if (*stop==-1) *start=(lval>> ASTOP_OFFSET) & APATTERN_MASK; + lval= ((*start & APATTERN_MASK) << ASTART_OFFSET) | ((*stop & APATTERN_MASK) << ASTOP_OFFSET); + bus_w(lval, PATTERN_LOOP1_AREG); + + break; + case 2: + if (*n>=0) bus_w(*n,PATTERN_N_LOOP2_REG); + *n=bus_r(PATTERN_N_LOOP2_REG); + lval=bus_r(PATTERN_LOOP2_AREG); + if (*start==-1) *start=(lval>> ASTART_OFFSET) & APATTERN_MASK; + if (*stop==-1) *start=(lval>> ASTOP_OFFSET) & APATTERN_MASK; + lval= ((*start & APATTERN_MASK) << ASTART_OFFSET) | ((*stop & APATTERN_MASK) << ASTOP_OFFSET); + bus_w(lval, PATTERN_LOOP2_AREG); + + break; + case -1: + + lval=bus_r(PATTERN_LIMITS_AREG); + if (*start==-1) start=(lval>> ASTART_OFFSET) & APATTERN_MASK; + if (*stop==-1) start=(lval>> ASTOP_OFFSET) & APATTERN_MASK; + lval= ((*start & APATTERN_MASK) << ASTART_OFFSET) | ((*stop & APATTERN_MASK) << ASTOP_OFFSET); + bus_w(lval, PATTERN_LIMITS_AREG); + break; + default: + ret=FAIL; + + + + + } + + return ret; +} + + +int setPatternWaitAddress(int level, int addr) { + int ret=-1; + switch (level) { + case 0: + if (addr>=0) bus_w(addr,PATTERN_WAIT0_AREG); + return bus_r(PATTERN_WAIT0_AREG); + case 1: + if (addr>=0) bus_w(addr,PATTERN_WAIT1_AREG); + return bus_r(PATTERN_WAIT1_AREG); + case 2: + if (addr>=0) bus_w(addr,PATTERN_WAIT2_AREG); + return bus_r(PATTERN_WAIT2_AREG); + }; + + return ret; +} + + +uint64_t setPatternWaitTime(int level, uint64_t t) { + uint64_t ret=-1; + switch (level) { + case 0: + if (t>=0) set64BitReg(t,PATTERN_WAIT0_TIME_REG_LSB,PATTERN_WAIT0_TIME_REG_MSB); + return get64BitReg(PATTERN_WAIT0_TIME_REG_LSB,PATTERN_WAIT0_TIME_REG_MSB); + case 1: + if (t>=0) set64BitReg(t,PATTERN_WAIT1_TIME_REG_LSB,PATTERN_WAIT1_TIME_REG_MSB); + return get64BitReg(PATTERN_WAIT1_TIME_REG_LSB,PATTERN_WAIT1_TIME_REG_MSB); + case 2: + if (t>=0) set64BitReg(t,PATTERN_WAIT2_TIME_REG_LSB,PATTERN_WAIT2_TIME_REG_MSB); + return get64BitReg(PATTERN_WAIT2_TIME_REG_LSB,PATTERN_WAIT2_TIME_REG_MSB); + } + return ret; +} + + + diff --git a/slsDetectorSoftware/jungfrauDetectorServer/firmware_funcs.h b/slsDetectorSoftware/jungfrauDetectorServer/firmware_funcs.h new file mode 100755 index 000000000..29babf8fa --- /dev/null +++ b/slsDetectorSoftware/jungfrauDetectorServer/firmware_funcs.h @@ -0,0 +1,187 @@ +#ifndef FIRMWARE_FUNCS_H +#define FIRMWARE_FUNCS_H + + +#include "sls_detector_defs.h" + + +#include +#include +#include +#include +#include +#include +#include +//#include +#include +#include +#include +#include +#include +#include + + +int mapCSP0(void); + +u_int16_t bus_r16(u_int32_t offset); +u_int16_t bus_w16(u_int32_t offset, u_int16_t data);//aldos function +u_int32_t bus_w(u_int32_t offset, u_int32_t data); +u_int32_t bus_r(u_int32_t offset); + +int setPhaseShiftOnce(); +int phaseStep(int st); +int cleanFifo(); +int setDAQRegister(); + +u_int32_t putout(char *s, int modnum); +u_int32_t readin(int modnum); +u_int32_t setClockDivider(int d); +u_int32_t getClockDivider(); +u_int32_t setSetLength(int d); +u_int32_t getSetLength(); +u_int32_t setWaitStates(int d); +u_int32_t getWaitStates(); +u_int32_t setTotClockDivider(int d); +u_int32_t getTotClockDivider(); +u_int32_t setTotDutyCycle(int d); +u_int32_t getTotDutyCycle(); +u_int32_t setOversampling(int d); + +u_int32_t setExtSignal(int d, enum externalSignalFlag mode); +int getExtSignal(int d); + +u_int32_t setFPGASignal(int d, enum externalSignalFlag mode); +int getFPGASignal(int d); + +int setTiming(int t); + + +int setConfigurationRegister(int d); +int setToT(int d); +int setContinousReadOut(int d); +int startReceiver(int d); + +int setDACRegister(int idac, int val, int imod); + +int getTemperature(int tempSensor,int imod); +int initHighVoltage(int val,int imod); +int initConfGain(int isettings,int val,int imod); + +int setADC(int adc); +int configureMAC(int ipad, long long int macad, long long int detectormacadd, int detipad, int ival, int udpport); +int getAdcConfigured(); + + +u_int64_t getDetectorNumber(); +u_int32_t getFirmwareVersion(); +int testFifos(void); +u_int32_t testFpga(void); +u_int32_t testRAM(void); +int testBus(void); +int setDigitalTestBit(int ival); + +int64_t set64BitReg(int64_t value, int aLSB, int aMSB); +int64_t get64BitReg(int aLSB, int aMSB); + +int64_t setFrames(int64_t value); +int64_t getFrames(); + +int64_t setExposureTime(int64_t value); +int64_t getExposureTime(); + +int64_t setGates(int64_t value); +int64_t getGates(); + +int64_t setDelay(int64_t value); +int64_t getDelay(); + +int64_t setPeriod(int64_t value); +int64_t getPeriod(); + +int64_t setTrains(int64_t value); +int64_t getTrains(); + +int64_t setProbes(int64_t value); +int64_t getProbes(); + +int64_t getProgress(); +int64_t setProgress(); + +int64_t getActualTime(); +int64_t getMeasurementTime(); + + +u_int32_t runBusy(void); +u_int32_t runState(void); +u_int32_t dataPresent(void); + + +int startStateMachine(); +int stopStateMachine(); +int startReadOut(); +u_int32_t fifoReset(void); +u_int32_t fifoReadCounter(int fifonum); +u_int32_t fifoReadStatus(); + + +u_int32_t fifo_full(void); + + + +u_int32_t* fifo_read_event(); +u_int32_t* decode_data(int* datain); +//u_int32_t move_data(u_int64_t* datain, u_int64_t* dataout); +int setDynamicRange(int dr); +int getDynamicRange(); +int getNModBoard(); +int setNMod(int n); +int setStoreInRAM(int b); +int allocateRAM(); +int clearRAM(); + + +int setMaster(int f); +int setSynchronization(int s); + +int loadImage(int index, short int ImageVals[]); +int readCounterBlock(int startACQ, short int CounterVals[]); +int resetCounterBlock(int startACQ); + +int calibratePedestal(int frames); + +uint64_t writePatternWord(int addr, uint64_t word); +uint64_t writePatternIOControl(uint64_t word); +uint64_t writePatternClkControl(uint64_t word); +int setPatternLoop(int level, int *start, int *stop, int *n); +int setPatternWaitAddress(int level, int addr); +uint64_t setPatternWaitTime(int level, uint64_t t); + + + + +/* + +u_int32_t setNBits(u_int32_t); +u_int32_t getNBits(); +*/ + +/* +//move to mcb_funcs? + +int readOutChan(int *val); +u_int32_t getModuleNumber(int modnum); +int testShiftIn(int imod); +int testShiftOut(int imod); +int testShiftStSel(int imod); +int testDataInOut(int num, int imod); +int testExtPulse(int imod); +int testExtPulseMux(int imod, int ow); +int testDataInOutMux(int imod, int ow, int num); +int testOutMux(int imod); +int testFpgaMux(int imod); +int calibration_sensor(int num, int *values, int *dacs) ; +int calibration_chip(int num, int *values, int *dacs); +*/ + + +#endif diff --git a/slsDetectorSoftware/jungfrauDetectorServer/gitInfo.txt b/slsDetectorSoftware/jungfrauDetectorServer/gitInfo.txt new file mode 100644 index 000000000..921890a70 --- /dev/null +++ b/slsDetectorSoftware/jungfrauDetectorServer/gitInfo.txt @@ -0,0 +1,9 @@ +Path: slsDetectorsPackage/slsDetectorSoftware/moenchDetectorServer +URL: origin git@gitorious.psi.ch:sls_det_software/sls_detector_software.git/moenchDetectorServer +Repository Root: origin git@gitorious.psi.ch:sls_det_software/sls_detector_software.git +Repsitory UUID: 046a469b1e6582c4c55bd6eaeb4818b618d0a9a9 +Revision: 55 +Branch: separate_receiver +Last Changed Author: Maliakal_Dhanya +Last Changed Rev: 14 +Last Changed Date: 2014-06-03 12:26:45 +0200 diff --git a/slsDetectorSoftware/jungfrauDetectorServer/gitInfoMoench.h b/slsDetectorSoftware/jungfrauDetectorServer/gitInfoMoench.h new file mode 100644 index 000000000..270653967 --- /dev/null +++ b/slsDetectorSoftware/jungfrauDetectorServer/gitInfoMoench.h @@ -0,0 +1,11 @@ +//#define SVNPATH "" +#define SVNURL "git@gitorious.psi.ch:sls_det_software/sls_detector_software.git/moenchDetectorServer" +//#define SVNREPPATH "" +#define SVNREPUUID "046a469b1e6582c4c55bd6eaeb4818b618d0a9a9" +//#define SVNREV 0x14 +//#define SVNKIND "" +//#define SVNSCHED "" +#define SVNAUTH "Maliakal_Dhanya" +#define SVNREV 0x14 +#define SVNDATE 0x20140603 +// diff --git a/slsDetectorSoftware/jungfrauDetectorServer/gitInfoMoenchTmp.h b/slsDetectorSoftware/jungfrauDetectorServer/gitInfoMoenchTmp.h new file mode 100644 index 000000000..58e48f497 --- /dev/null +++ b/slsDetectorSoftware/jungfrauDetectorServer/gitInfoMoenchTmp.h @@ -0,0 +1,11 @@ +//#define SVNPATH "" +#define SVNURL "" +//#define SVNREPPATH "" +#define SVNREPUUID "" +//#define SVNREV "" +//#define SVNKIND "" +//#define SVNSCHED "" +#define SVNAUTH "" +#define SVNREV "" +#define SVNDATE "" +// diff --git a/slsDetectorSoftware/jungfrauDetectorServer/jungfrauDetectorServer b/slsDetectorSoftware/jungfrauDetectorServer/jungfrauDetectorServer new file mode 100755 index 000000000..ee798a145 Binary files /dev/null and b/slsDetectorSoftware/jungfrauDetectorServer/jungfrauDetectorServer differ diff --git a/slsDetectorSoftware/jungfrauDetectorServer/jungfrauDetectorServer.gdb b/slsDetectorSoftware/jungfrauDetectorServer/jungfrauDetectorServer.gdb new file mode 100755 index 000000000..25a3cc706 Binary files /dev/null and b/slsDetectorSoftware/jungfrauDetectorServer/jungfrauDetectorServer.gdb differ diff --git a/slsDetectorSoftware/jungfrauDetectorServer/mcb_funcs.c b/slsDetectorSoftware/jungfrauDetectorServer/mcb_funcs.c new file mode 100755 index 000000000..88cd7a138 --- /dev/null +++ b/slsDetectorSoftware/jungfrauDetectorServer/mcb_funcs.c @@ -0,0 +1,2649 @@ +#ifdef MCB_FUNCS + +#include +#include +#include +#include +#include +#include "registers_m.h" + +#ifndef PICASSOD +#include "server_defs.h" +#else +#include "picasso_defs.h" +#endif +#include "firmware_funcs.h" +#include "mcb_funcs.h" + + +/* global variables */ +#undef DEBUG +#undef DEBUGOUT + +extern int nModX; +//extern int dataBytes; +extern int dynamicRange; +const int nChans=NCHAN; +const int nChips=NCHIP; +const int nDacs=NDAC; +const int nAdcs=NADC; +enum detectorSettings thisSettings; + +int sChan, sChip, sMod, sDac, sAdc; +const int allSelected=-2; +const int noneSelected=-1; + + +sls_detector_module *detectorModules=NULL; +int *detectorChips=NULL; +int *detectorChans=NULL; +int *detectorDacs=NULL; +int *detectorAdcs=NULL; +//int numberOfProbes; + +ROI rois[MAX_ROIS]; +int nROI=0; + + +int initDetector() { + + int imod; + // sls_detector_module *myModule; + int n=getNModBoard(); + nModX=n; + +#ifdef VERBOSE + printf("Board is for %d modules\n",n); +#endif + detectorModules=malloc(n*sizeof(sls_detector_module)); + detectorChips=malloc(n*NCHIP*sizeof(int)); + detectorChans=malloc(n*NCHIP*NCHAN*sizeof(int)); + detectorDacs=malloc(n*NDAC*sizeof(int)); + detectorAdcs=malloc(n*NADC*sizeof(int)); +#ifdef VERBOSE + printf("modules from 0x%x to 0x%x\n",(unsigned int)(detectorModules), (unsigned int)(detectorModules+n)); + printf("chips from 0x%x to 0x%x\n",(unsigned int)(detectorChips), (unsigned int)(detectorChips+n*NCHIP)); + printf("chans from 0x%x to 0x%x\n",(unsigned int)(detectorChans), (unsigned int)(detectorChans+n*NCHIP*NCHAN)); + printf("dacs from 0x%x to 0x%x\n",(unsigned int)(detectorDacs), (unsigned int)(detectorDacs+n*NDAC)); + printf("adcs from 0x%x to 0x%x\n",(unsigned int)(detectorAdcs), (unsigned int)(detectorAdcs+n*NADC)); +#endif + for (imod=0; imoddacs=detectorDacs+imod*NDAC; + (detectorModules+imod)->adcs=detectorAdcs+imod*NADC; + (detectorModules+imod)->chipregs=detectorChips+imod*NCHIP; + (detectorModules+imod)->chanregs=detectorChans+imod*NCHIP*NCHAN; + (detectorModules+imod)->ndac=NDAC; + (detectorModules+imod)->nadc=NADC; + (detectorModules+imod)->nchip=NCHIP; + (detectorModules+imod)->nchan=NCHIP*NCHAN; + (detectorModules+imod)->module=imod; + (detectorModules+imod)->gain=0; + (detectorModules+imod)->offset=0; + (detectorModules+imod)->reg=0; + /* initialize registers, dacs, retrieve sn, adc values etc */ + } + thisSettings=UNINITIALIZED; + sChan=noneSelected; + sChip=noneSelected; + 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);*/ + + //dataBytes=nModX*NCHIP*NCHAN*4; + // dynamicRange=32; + // initChip(0, 0,ALLMOD); + //nModX=n; + // + allocateRAM(); + + + return OK; +} + + + + +int copyChannel(sls_detector_channel *destChan, sls_detector_channel *srcChan) { + destChan->chan=srcChan->chan; + destChan->chip=srcChan->chip; + destChan->module=srcChan->module; + destChan->reg=srcChan->reg; + return OK; +} + + +int copyChip(sls_detector_chip *destChip, sls_detector_chip *srcChip) { + + int ichan; + int ret=OK; + if ((srcChip->nchan)>(destChip->nchan)) { + printf("Number of channels of source is larger than number of channels of destination\n"); + return FAIL; + } + + destChip->nchan=srcChip->nchan; + destChip->reg=srcChip->reg; + destChip->chip=srcChip->chip; + destChip->module=srcChip->module; + for (ichan=0; ichan<(srcChip->nchan); ichan++) { + *((destChip->chanregs)+ichan)=*((srcChip->chanregs)+ichan); + } + return ret; +} + + +int copyModule(sls_detector_module *destMod, sls_detector_module *srcMod) { + + int ichip, idac, ichan, iadc; + + int ret=OK; + +#ifdef VERBOSE + printf("Copying module %x to module %x\n",(unsigned int)(srcMod),(unsigned int)(destMod)); +#endif + + if (srcMod->module>=0) { +#ifdef VERBOSE + printf("Copying module number %d to module number %d\n",srcMod->module,destMod->module); +#endif + destMod->module=srcMod->module; + } + if (srcMod->serialnumber>=0){ +/* #ifdef VERBOSE */ +/* printf("Copying module serial number %x to module serial number %x\n",srcMod->serialnumber,destMod->serialnumber); */ +/* #endif */ + destMod->serialnumber=srcMod->serialnumber; + } + if ((srcMod->nchip)>(destMod->nchip)) { + printf("Number of chip of source is larger than number of chips of destination\n"); + return FAIL; + } + if ((srcMod->nchan)>(destMod->nchan)) { + printf("Number of channels of source is larger than number of channels of destination\n"); + return FAIL; + } + if ((srcMod->ndac)>(destMod->ndac)) { + printf("Number of dacs of source is larger than number of dacs of destination\n"); + return FAIL; + } + if ((srcMod->nadc)>(destMod->nadc)) { + printf("Number of dacs of source is larger than number of dacs of destination\n"); + return FAIL; + } + +#ifdef VERBOSE + printf("DACs: src %d, dest %d\n",srcMod->ndac,destMod->ndac); + printf("ADCs: src %d, dest %d\n",srcMod->nadc,destMod->nadc); + printf("Chips: src %d, dest %d\n",srcMod->nchip,destMod->nchip); + printf("Chans: src %d, dest %d\n",srcMod->nchan,destMod->nchan); + +#endif + + + + destMod->ndac=srcMod->ndac; + destMod->nadc=srcMod->nadc; + destMod->nchip=srcMod->nchip; + destMod->nchan=srcMod->nchan; + if (srcMod->reg>=0) + destMod->reg=srcMod->reg; +#ifdef VERBOSE + printf("Copying register %x (%x)\n",destMod->reg,srcMod->reg ); +#endif + if (srcMod->gain>=0) + destMod->gain=srcMod->gain; + if (srcMod->offset>=0) + destMod->offset=srcMod->offset; + + // printf("copying gain and offset %f %f to %f %f\n",srcMod->gain,srcMod->offset,destMod->gain,destMod->offset); + + for (ichip=0; ichip<(srcMod->nchip); ichip++) { + if (*((srcMod->chipregs)+ichip)>=0) + *((destMod->chipregs)+ichip)=*((srcMod->chipregs)+ichip); + } + for (ichan=0; ichan<(srcMod->nchan); ichan++) { + if (*((srcMod->chanregs)+ichan)>=0) + *((destMod->chanregs)+ichan)=*((srcMod->chanregs)+ichan); + } + for (idac=0; idac<(srcMod->ndac); idac++) { + if (*((srcMod->dacs)+idac)>=0) + *((destMod->dacs)+idac)=*((srcMod->dacs)+idac); + } + for (iadc=0; iadc<(srcMod->nadc); iadc++) { + if (*((srcMod->adcs)+iadc)>=0) + *((destMod->adcs)+iadc)=*((srcMod->adcs)+iadc); + } + return ret; +} + + + +/* 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); + putout("0000100001000000",imod); + putout("0000100001000000",imod); + putout("0000000001000000",imod); +#ifdef DEBUG + fprintf(stdout, "Clearing CS shiftregister\n"); +#endif + /* + sChan=noneSelected; + sMod=noneSelected; + sDac=noneSelected; + sAdc=noneSelected; + */ + sChip=noneSelected; + sMod=imod; + if (imod==ALLMOD) + sMod=allSelected; + //putout("0000000000000000",imod); + return 0; +} + +int setCSregister(int imod){ + + putout("0000000001000000",imod); + putout("0001000001000000",imod); + putout("0001000001000000",imod); + putout("0000000001000000",imod); +#ifdef DEBUG + fprintf(stdout, "Setting CS shiftregister\n"); +#endif + putout("0000000000000000",imod); + sChip=allSelected; + sMod=imod; + if (imod==ALLMOD) + sMod=allSelected; + return 0; +} + +int nextChip(int imod){ + + putout("0000000001000000",imod); + putout("0010000001000000",imod); + putout("0000000001000000",imod); +#ifdef DEBUG + fprintf(stdout, "Next Chip\n"); +#endif + sChip++; + sMod=imod; + if (imod==ALLMOD) + sMod=allSelected; + return 0; +} + +int firstChip(int imod){ + + putout("0100000001000000",imod); + putout("0110000001000000",imod); + putout("0100000001000000",imod); +#ifdef DEBUG + fprintf(stdout, "First Chip\n"); +#endif + sChip=0; + sMod=imod; + if (imod==ALLMOD) + sMod=allSelected; + return 0; +} + +int clearSSregister(int imod){ + int i; + putout("0000011000000000",imod); + for (i=0; i<10; i++) + putout("0000111000000000",imod); + putout("0000011000000000",imod); +#ifdef DEBUG + fprintf(stdout,"Clearing SS shiftregister\n"); +#endif + putout("0000000000000000",imod); + sChan=noneSelected; + sMod=imod; + if (imod==ALLMOD) + sMod=allSelected; + return 0; +} + +int setSSregister(int imod){ + int i; + putout("0000011000000000",imod); + for (i=0; i<10; i++) + putout("0001011000000000",imod); + putout("0000011000000000",imod); +#ifdef DEBUG + fprintf(stdout,"Setting SS shiftregister\n"); +#endif + putout("0000000000000000",imod); + sChan=allSelected; + sMod=imod; + if (imod==ALLMOD) + sMod=allSelected; + return 0; +} + +int nextStrip(int imod){ + putout("0000011000000000",imod); + putout("0010011000000000",imod); + putout("0000011000000000",imod); +#ifdef DEBUG + fprintf(stdout,"|-"); +#endif + sChan++; + sMod=imod; + if (imod==ALLMOD) + sMod=allSelected; + return 0; +} + +int selChannel(const int strip,int imod) { + int istrip; + clearSSregister(imod); + nextStrip(imod); + for (istrip=0; istrip=0 && imod=0) + 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*NDAC])*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*NDAC]); + 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*NDAC]); + } + 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) +{ + int im; + //for the particular module + if (imod>=0 && imod=0 && imod=0 && imod=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 + int confgain[] = CONF_GAIN; + int isett=-2,retval; + + //reading settings + if(i==GET_SETTINGS){ + retval=initConfGainByModule(i,i,imod); + if(retval==i) + isett=UNDEFINED; + } + //writing settings + else{ + retval=initConfGainByModule(i,confgain[i],imod); + if(retval!=i) + isett=UNDEFINED; + } + //if error while read/writing + if(isett==UNDEFINED) + printf("Error:Weird Value read back from the Gain/Settings Reg\n"); + else{ + //validating the settings read back + if((retval>=HIGHGAIN)&&(retval<=VERYHIGHGAIN)) + isett=retval; + else{ + isett=UNDEFINED; + printf("Error:Wrong Settings Read out:%d\n",retval); + } + } + thisSettings=isett; +#ifdef VERBOSE + printf("detector settings are %d\n",thisSettings); +#endif + return thisSettings; +} + + + + +/* Initialization*/ + +int initChannelbyNumber(sls_detector_channel myChan) { + int reg=myChan.reg; + int ft=reg & TRIM_DR; + int cae=(reg>>(NTRIMBITS))&1; + int ae=(reg>>(NTRIMBITS+1))&1; + int coe=(reg>>(NTRIMBITS+2))&1; + int ocoe=(reg>>(NTRIMBITS+3))&1; + int counts=(reg>>(NTRIMBITS+4)); +#ifdef VERBOSE + printf("Initializing channel %d chip %d module %d reg %x\n",myChan.chan,myChan.chip,myChan.module, reg); + printf("trim %d, cae %d, ae %d, coe %d, ocoe %d, counts %d\n",ft, cae, ae, coe, ocoe, counts); +#endif + + if (myChan.chip<0) + setCSregister(myChan.module); + else + selChip(myChan.chip,myChan.module); + + if (myChan.chan<0) + setSSregister(myChan.module); + else + selChannel(myChan.chan,myChan.module); + + initChannel(ft,cae,ae, coe, ocoe, counts,myChan.module); + + setDynamicRange(dynamicRange); + + setCSregister(ALLMOD); + clearSSregister(ALLMOD); + putout("0000000000000000",ALLMOD); + + return myChan.reg; + +} + +int getChannelbyNumber(sls_detector_channel* myChan) { + int imod, ichip, ichan; + imod=myChan->module; + ichip=myChan->chip; + ichan=myChan->chan; + + if (detectorChans) { + if (imod=0) { + if (ichip<(detectorModules+imod)->nchip && ichan<(detectorModules+imod)->nchan/(detectorModules+imod)->nchip) + myChan->reg=detectorChans[imod*NCHAN*NCHIP+ichip*NCHAN+ichan]; + return OK; + } + } + return FAIL; + +} + +int getTrimbit(int imod, int ichip, int ichan) { + if (detectorChans) { + if (imod=0) + if (ichip<(detectorModules+imod)->nchip && ichan<(detectorModules+imod)->nchan/(detectorModules+imod)->nchip) + return (detectorChans[imod*NCHAN*NCHIP+ichip*NCHAN+ichan] & TRIM_DR); + } + + return -1; +} + +int initChannel(int ft,int cae, int ae, int coe, int ocoe, int counts, int imod){ + + int ibit, bit, i, im, ichip, ichan; + int chanmi, chanma, chipmi, chipma, modmi, modma; + + + + sMod=imod; + // printf("initializing module %d\n",sMod); + if (imod==ALLMOD) { + sMod=allSelected; + + // printf("initializing all modules\n"); + } + + if (sChan==allSelected) { + // printf("initializing all channels ft=%d coe=%d\n",ft,coe); + chanmi=0; + chanma=NCHAN; + } else if (sChan==noneSelected || sChan>NCHAN || sChan<0) { + // printf("initializing no channels ft=%d coe=%d\n",ft,coe); + chanmi=0; + chanma=-1; + } else { + // printf("initializing channel %d ft=%d coe=%d\n",sChan, ft,coe); + chanmi=sChan; + chanma=sChan+1; + } + + if (sChip==allSelected) { + // printf("initializing all chips\n"); + chipmi=0; + chipma=NCHIP; + } else if (sChip==noneSelected || sChip>NCHIP || sChip<0) { + // printf("initializing no chips\n"); + chipmi=0; + chipma=-1; + } else { + // printf("initializing chip %d\n",sChip); + chipmi=sChip; + chipma=sChip+1; + } + + + if (sMod==allSelected) { + modmi=0; + modma=nModX;//getNModBoard(); + } else if (sMod==noneSelected || sMod>nModX || sMod<0) {//(sMod==noneSelected || sMod>getNModBoard() || sMod<0) { + modmi=0; + modma=-1; + return 1; + } else { + modmi=sMod; + modma=sMod+1; + } + + if (detectorChans) { + for (im=modmi; im63 || ft<0) { + fprintf(stdout,"Fine Threshold is %d while should be between 0 and 63!",ft); + return 1; + } + /*cal_enable*/ + if (cae) { + putout("0100000000000000",imod); + putout("0110000000000000",imod); + } else { + putout("0000000000000000",imod); + putout("0010000000000000",imod); + } + /*n_an_enable*/ + if (ae) { + putout("0000000000000000",imod); + putout("0010000000000000",imod); + putout("0000000000000000",imod); + } else { + putout("0100000000000000",imod); + putout("0110000000000000",imod); + putout("0100000000000000",imod); + } + /*trb5*/ + ibit=5; + bit=ft & (1<>1; + int nchan, ichan; + int ft, cae, ae, coe, ocoe, counts, chanreg; + + + + nchan=myChip.nchan; + if (ichip<0) + setCSregister(imod); + else + selChip(ichip,imod); + + clearSSregister(imod); + for (ichan=0; ichan>(NTRIMBITS+1))&1; + ae=(chanreg>>(NTRIMBITS+2))&1; + coe=((chanreg)>>(NTRIMBITS+3))&1; + ocoe=((chanreg)>>(NTRIMBITS+4))&1; + counts=((chanreg)>>(NTRIMBITS+5)); + nextStrip(imod); + initChannel(ft,cae,ae, coe, ocoe, counts,imod); + } + initChip(obe,ow,imod); + return myChip.reg; + +} + +int getChipbyNumber(sls_detector_chip* myChip){ + int imod, ichip; + imod=myChip->module; + ichip=myChip->chip; + + if (detectorChips) { + if (imodnchip) { + myChip->reg=detectorChips[ichip+imod*NCHIP]; + myChip->nchan=NCHAN; + myChip->chanregs=detectorChans+imod*NCHAN*NCHIP+ichip*NCHIP; + return OK; + } + } + return FAIL; + +} + + + +int initChip(int obe, int ow,int imod){ + int i; + int im, ichip; + int chipmi, chipma, modmi, modma; + /* 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"); +#endif + putout("0000000000000000",imod); +#ifdef DEBUGOUT + printf("Output mode= %d\n", ow); +#endif + + /* clearing shift in register */ + for (i=0; i<10; i++) + putout("0000100000000000",imod); + putout("0000000000000000",imod); + + if (ow>0) { + putout("0100000000000000",imod); + putout("0110000000000000",imod); + putout("0100000000000000",imod); + for (i=0; i<(OUTMUX_OFFSET-1); i++) { + putout("0000000000000000",imod); + putout("0010000000000000",imod); + putout("0000000000000000",imod); + } + if (ow>1) { + putout("0000000000000000",imod); + putout("0010000000000000",imod); + putout("0000000000000000",imod); + } + if (ow>2) { + putout("0000000000000000",imod); + putout("0010000000000000",imod); + putout("0000000000000000",imod); + } + if (ow>3) { + putout("0000000000000000",imod); + putout("0010000000000000",imod); + putout("0000000000000000",imod); + } + if (ow>4) { + putout("0000000000000000",imod); + putout("0010000000000000",imod); + putout("0000000000000000",imod); + } + } +#ifdef DEBUGOUT + printf("Output buffer enable= %d\n", obe); +#endif + if (obe) { + putout("0100000000000000",imod); + putout("0110000000000000",imod); + putout("0100000000000000",imod); + } else { + putout("0000000000000000",imod); + putout("0010000000000000",imod); + putout("0000000000000000",imod); + } + /*}*/ + putout("0000000000000000",imod); + + + + + + sMod=imod; + if (imod==ALLMOD) + sMod=allSelected; + + + if (sChip==allSelected) { + chipmi=0; + chipma=NCHIP; + } else if (sChip==noneSelected || sChip>NCHIP || sChip<0) { + chipmi=0; + chipma=-1; + } else { + chipmi=sChip; + chipma=sChip+1; + } + + + if (sMod==allSelected) { + modmi=0; + modma=nModX;//getNModBoard(); + } else if (sMod==noneSelected || sMod>nModX || sMod<0) {//(sMod==noneSelected || sMod>getNModBoard() || sMod<0) { + modmi=0; + modma=-1; + } else { + modmi=sMod; + modma=sMod+1; + } + + if (detectorChips) { + for (im=modmi; imNCHIP || sChip<0) { + chipmi=0; + chipma=-1; + } else { + chipmi=sChip; + chipma=sChip+1; + } + + + if (sMod==allSelected) { + modmi=0; + modma=nModX;//getNModBoard(); + } else if (sMod==noneSelected || sMod>nModX || sMod<0) {//(sMod==noneSelected || sMod>getNModBoard() || sMod<0) { + modmi=0; + modma=-1; + } else { + modmi=sMod; + modma=sMod+1; + } + + if (detectorChips) { + for (im=modmi; imnModX || sMod<0) {//(sMod==noneSelected || sMod>getNModBoard() || sMod<0) { + modmi=0; + modma=-1; + } else { + modmi=sMod; + modma=sMod+1; + } + + if (detectorModules) { + for (im=modmi; imreg)=cm; +#ifdef VERBOSE + printf("imod=%d reg=%d (%x)\n",im,(detectorModules+im)->reg,(unsigned int)((detectorModules+im))); +#endif + } + } + return 0; +} + +int initModulebyNumber(sls_detector_module myMod) { + + printf("\ninside initmoduleynumber..\n"); + + int nchip,nchan;//int ichip, nchip, ichan, nchan; + int im, modmi,modma; + // int ft, cae, ae, coe, ocoe, counts, chanreg; + int imod; + // int obe; + // int ow; + int v[NDAC]; + + + nchip=myMod.nchip; + nchan=(myMod.nchan)/nchip; + + imod=myMod.module; + sMod=imod; + + if (sMod==ALLMOD) + sMod=allSelected; + + if (sMod==allSelected) { + modmi=0; + modma=nModX;//getNModBoard(); + } else if (sMod==noneSelected || sMod>nModX || sMod<0) {// (sMod==noneSelected || sMod>getNModBoard() || sMod<0) { + modmi=0; + modma=-1; + } else { + modmi=sMod; + modma=sMod+1; + } + + + /* + for (idac=0; idacmodule; +#ifdef VERBOSE + printf("Getting module %d\n",imod); +#endif + if (detectorModules) { + copyModule(myMod,detectorModules+imod); + ; + } else + return FAIL; + + return OK; +} + +/* To chips */ +int clearCounter(int imod){ + int i; +#ifdef DEBUG + printf("Clearing counter with contclear\n"); +#endif + putout("0000000000000000",imod); + for (i=0; i<10; i++) + putout("0000000000010000",imod); + putout("0000000000000000",imod); + + return 0; +} + +int clearOutReg(int imod){ + int i; +#ifdef DEBUG + printf("Clearing output register\n"); +#endif + putout("0000010000000000",imod); + for (i=0; i<10; i++) + putout("0000110000000000",imod); + putout("0000010000000000",imod); + return 0; +} +int setOutReg(int imod){ + int i; +#ifdef DEBUG + printf("Setting output register\n"); +#endif + putout("0000010000000000",imod); + for (i=0; i<10; i++) + putout("0001010000000000",imod); + putout("0000010000000000",imod); + return 0; +} + + +int extPulse(int ncal, int imod) { + int ical; +#ifdef DEBUG + printf("Giving a clock pulse to the counter\n"); +#endif + for (ical=0; ical0 && i%2==0) { + printf("Shift in: module %d chip %i bit %d read %d instead of %d \n",k,j,i,val & 1<< j, i%2); + result++; + } + if (i%2>0 && (val & 1<0 && (dum & (1<0) { + printf("Shift out: module %d chip %i bit %d read %d instead of %d \n",k,j,i,val & 1<< j, (dum &1<0 && i%2==0) { + printf("Shift stsel: module %d chip %i bit %d read %d instead of %d \n",k,j,i,val & 1<< j, i%2); + result++; + } + if (i%2>0 && (val & 1<> 1; + + + putout("0000000000000000",ALLMOD); + putout("0010000000000000",ALLMOD); //change mux setting + putout("0000000000000000",ALLMOD); + } + + printf("Test FpgaMux module %d : %d errors\n", imod,result); + if (result) + return 1; + else + return 0; +} + + + + + + + + + +int calibration_sensor(int num, int *v, int *dacs) { + int ich, ichip, imod; + int val[10]; + + + printf("calibrating sensor..."); + for (imod=0; imod=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 + + +extern int sockfd; +extern int phase_shift; + + + +void error(char *msg) +{ + perror(msg); +} + +int main(int argc, char *argv[]) +{ + int portno, b; + char cmd[500]; + int retval=OK; + int sd, fd; + int iarg; + int checkType = 1; + + + for(iarg=1; iarg 2) && (!strcasecmp(argv[2],"stopserver"))){ + portno = DEFAULT_PORTNO+1; + if ( sscanf(argv[1],"%d",&portno) ==0) { + printf("could not open stop server: unknown port\n"); + return 1; + } + b=0; + printf("\n\nStop Server\nOpening stop server on port %d\n",portno); + checkType=0; + + } + + //control server + else { + portno = DEFAULT_PORTNO; + if(checkType) + sprintf(cmd,"%s %d stopserver &",argv[0],DEFAULT_PORTNO+1); + else + sprintf(cmd,"%s %d stopserver -test with_gotthard &",argv[0],DEFAULT_PORTNO+1); + printf("\n\nControl Server\nOpening control server on port %d\n",portno ); + + //printf("\n\ncmd:%s\n",cmd); + system(cmd); + b=1; + checkType=1; + + } + + + + + + init_detector(b, checkType); + + + sd=bindSocket(portno); + sockfd=sd; + if (getServerError(sd)) { + printf("server error!\n"); + return -1; + } + + /* assign function table */ + function_table(); +#ifdef VERBOSE + printf("function table assigned \n"); +#endif + + + /* waits for connection */ + while(retval!=GOODBYE) { +#ifdef VERBOSE + printf("\n"); +#endif +#ifdef VERY_VERBOSE + printf("Waiting for client call\n"); +#endif + fd=acceptConnection(sockfd); +#ifdef VERY_VERBOSE + printf("Conenction accepted\n"); +#endif + retval=decode_function(fd); +#ifdef VERY_VERBOSE + printf("function executed\n"); +#endif + closeConnection(fd); +#ifdef VERY_VERBOSE + printf("connection closed\n"); +#endif + } + + exitServer(sockfd); + printf("Goodbye!\n"); + + return 0; +} + diff --git a/slsDetectorSoftware/jungfrauDetectorServer/server_defs.h b/slsDetectorSoftware/jungfrauDetectorServer/server_defs.h new file mode 100755 index 000000000..850533266 --- /dev/null +++ b/slsDetectorSoftware/jungfrauDetectorServer/server_defs.h @@ -0,0 +1,63 @@ +#ifndef SERVER_DEFS_H +#define SERVER_DEFS_H + +#include "sls_detector_defs.h" + +#include + + +// Hardware definitions + +#define NCHAN (160*160) +#define NCHIP 1 +#define NMAXMODX 1 +#define NMAXMODY 1 +#define NMAXMOD (NMAXMODX*NMAXMODY) +#define NDAC 8 +#define NADC 1 + +/**when moench readout tested with gotthard module*/ +#define GOTTHARDNCHAN 128 +#define GOTTHARDNCHIP 10 + + + + +#define NCHANS (NCHAN*NCHIP*NMAXMOD) +#define NDACS (NDAC*NMAXMOD) + +#define NTRIMBITS 6 +#define NCOUNTBITS 24 + +#define NCHIPS_PER_ADC 2 + +//#define TRIM_DR ((2**NTRIMBITS)-1) +//#define COUNT_DR ((2**NCOUNTBITS)-1) +#define TRIM_DR (((int)pow(2,NTRIMBITS))-1) +#define COUNT_DR (((int)pow(2,NCOUNTBITS))-1) + + +#define ALLMOD 0xffff +#define ALLFIFO 0xffff + +#define GOTTHARD_ADCSYNC_VAL 0x32214 +#define ADCSYNC_VAL 0x02111 +#define TOKEN_RESTART_DELAY 0x88000000 +#define TOKEN_RESTART_DELAY_ROI 0x1b000000 +#define TOKEN_TIMING_REV1 0x1f16 +#define TOKEN_TIMING_REV2 0x1f0f + +#define DEFAULT_PHASE_SHIFT 0 // 120 +#define DEFAULT_IP_PACKETSIZE 0x0522 +#define DEFAULT_UDP_PACKETSIZE 0x050E +#define ADC1_IP_PACKETSIZE 256*2+14+20 +#define ADC1_UDP_PACKETSIZE 256*2+4+8+2 + +#ifdef VIRTUAL +#define DEBUGOUT +#endif + +#define CLK_FREQ 65.6E+6 + + +#endif diff --git a/slsDetectorSoftware/jungfrauDetectorServer/server_funcs.c b/slsDetectorSoftware/jungfrauDetectorServer/server_funcs.c new file mode 100755 index 000000000..71cf5c0d0 --- /dev/null +++ b/slsDetectorSoftware/jungfrauDetectorServer/server_funcs.c @@ -0,0 +1,3244 @@ +#include "sls_detector_defs.h" +#include "server_funcs.h" +#ifndef PICASSOD +#include "server_defs.h" +#else +#include "picasso_defs.h" +#endif +#include "firmware_funcs.h" +#include "mcb_funcs.h" +#include "trimming_funcs.h" +#include "registers_m.h" +#include "gitInfoMoench.h" + +#define FIFO_DATA_REG_OFF 0x50<<11 +//#define CONTROL_REG 0x24<<11 +// Global variables + + +int (*flist[256])(int); + + +//defined in the detector specific file +#ifdef MYTHEND +const enum detectorType myDetectorType=MYTHEN; +#elif GOTTHARDD +const enum detectorType myDetectorType=GOTTHARD; +#elif EIGERD +const enum detectorType myDetectorType=EIGER; +#elif PICASSOD +const enum detectorType myDetectorType=PICASSO; +#elif MOENCHD +const enum detectorType myDetectorType=MOENCH; +#else +const enum detectorType myDetectorType=GENERIC; +#endif + + +extern int nModX; +extern int nModY; +extern int dataBytes; +extern int dynamicRange; +extern int storeInRAM; + +extern int lockStatus; +extern char lastClientIP[INET_ADDRSTRLEN]; +extern char thisClientIP[INET_ADDRSTRLEN]; +extern int differentClients; + +/* global variables for optimized readout */ +extern unsigned int *ram_values; +char *dataretval=NULL; +int nframes, iframes, dataret; +char mess[1000]; + +int digitalTestBit = 0; + +extern int withGotthard; + + +int init_detector(int b, int checkType) { + + int i; + if (mapCSP0()==FAIL) { printf("Could not map memory\n"); + exit(1); + } + + // + + printf("v: 0x%x\n",bus_r(FPGA_VERSION_REG)); + printf("fp: 0x%x\n",bus_r(FIX_PATT_REG)); + + if (checkType) { + 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)) + printf("ERROR: wrote 0x%x, read 0x%x\n",i*100,bus_r(SET_DELAY_LSB_REG)); + } + printf("Finished\n"); + } + return 0; + + bus_w16(CONTROL_REG, SYNC_RESET); + bus_w16(CONTROL_REG, 0x0); + + + //confirm if it is really moench + if(((bus_r(PCB_REV_REG) & DETECTOR_TYPE_MASK)>>DETECTOR_TYPE_OFFSET) != MOENCH_MODULE ){ + if(checkType){ + printf("This is a Gotthard detector. Exiting Moench Server.\n\n"); + exit(-1); + } + //no check required as specified in command line arguments + else if(b){ + printf("***This is a GOTTHARD detector with %d chips per module***\n",GOTTHARDNCHIP); + printf("***Assuming this to be a MOENCH detector***\n"); + } + withGotthard = 1; + } else if(b){ + printf("***This is a MOENCH detector with %d chips per module***\n",NCHIP); + } + + if (b) { +#ifdef MCB_FUNCS + printf("\nBoard Revision:0x%x\n",(bus_r(PCB_REV_REG)&BOARD_REVISION_MASK)); + 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(); //firmware.h + + + prepareADC(); // server_funcs + setADC(-1); //already does setdaqreg and clean fifo + setSettings(GET_SETTINGS,-1); + + //Initialization + setFrames(1); + setTrains(1); + setExposureTime(1e3); + setPeriod(1E6); + setDelay(0); + setGates(0); + + setTiming(GET_EXTERNAL_COMMUNICATION_MODE); + setMaster(GET_MASTER); + setSynchronization(GET_SYNCHRONIZATION_MODE); + startReceiver(0); //firmware + } + strcpy(mess,"dummy message"); + strcpy(lastClientIP,"none"); + strcpy(thisClientIP,"none1"); + lockStatus=0; + return OK; +} + + +int decode_function(int file_des) { + int fnum,n; + int retval=FAIL; +#ifdef VERBOSE + printf( "receive data\n"); +#endif + n = receiveDataOnly(file_des,&fnum,sizeof(fnum)); + if (n <= 0) { +#ifdef VERBOSE + printf("ERROR reading from socket %d, %d %d\n", n, fnum, file_des); +#endif + return FAIL; + } +#ifdef VERBOSE + else + printf("size of data received %d\n",n); +#endif + +#ifdef VERBOSE + printf( "calling function fnum = %d %x\n",fnum,(unsigned int)(flist[fnum])); +#endif + if (fnum<0 || fnum>255) + fnum=255; + retval=(*flist[fnum])(file_des); + if (retval==FAIL) + printf( "Error executing the function = %d \n",fnum); + return retval; +} + + +int function_table() { + int i; + for (i=0;i<256;i++){ + flist[i]=&M_nofunc; + } + flist[F_EXIT_SERVER]=&exit_server; + flist[F_EXEC_COMMAND]=&exec_command; + flist[F_GET_DETECTOR_TYPE]=&get_detector_type; + flist[F_SET_NUMBER_OF_MODULES]=&set_number_of_modules; + flist[F_GET_MAX_NUMBER_OF_MODULES]=&get_max_number_of_modules; + flist[F_SET_EXTERNAL_SIGNAL_FLAG]=&set_external_signal_flag; + flist[F_SET_EXTERNAL_COMMUNICATION_MODE]=&set_external_communication_mode; + flist[F_GET_ID]=&get_id; + flist[F_DIGITAL_TEST]=&digital_test; + flist[F_WRITE_REGISTER]=&write_register; + flist[F_READ_REGISTER]=&read_register; + flist[F_SET_DAC]=&set_dac; + flist[F_GET_ADC]=&get_adc; + flist[F_SET_CHANNEL]=&set_channel; + flist[F_SET_CHIP]=&set_chip; + flist[F_SET_MODULE]=&set_module; + flist[F_GET_CHANNEL]=&get_channel; + flist[F_GET_CHIP]=&get_chip; + flist[F_GET_MODULE]=&get_module; + flist[F_GET_THRESHOLD_ENERGY]=&get_threshold_energy; + flist[F_SET_THRESHOLD_ENERGY]=&set_threshold_energy; + flist[F_SET_SETTINGS]=&set_settings; + flist[F_START_ACQUISITION]=&start_acquisition; + flist[F_STOP_ACQUISITION]=&stop_acquisition; + flist[F_START_READOUT]=&start_readout; + flist[F_GET_RUN_STATUS]=&get_run_status; + flist[F_READ_FRAME]=&read_frame; + flist[F_READ_ALL]=&read_all; + flist[F_START_AND_READ_ALL]=&start_and_read_all; + flist[F_SET_TIMER]=&set_timer; + flist[F_GET_TIME_LEFT]=&get_time_left; + flist[F_SET_DYNAMIC_RANGE]=&set_dynamic_range; + flist[F_SET_ROI]=&set_roi; + flist[F_SET_SPEED]=&set_speed; + flist[F_SET_READOUT_FLAGS]=&set_readout_flags; + flist[F_EXECUTE_TRIMMING]=&execute_trimming; + flist[F_LOCK_SERVER]=&lock_server; + flist[F_SET_PORT]=&set_port; + flist[F_GET_LAST_CLIENT_IP]=&get_last_client_ip; + flist[F_UPDATE_CLIENT]=&update_client; + flist[F_CONFIGURE_MAC]=&configure_mac; + flist[F_LOAD_IMAGE]=&load_image; + flist[F_SET_MASTER]=&set_master; + flist[F_SET_SYNCHRONIZATION_MODE]=&set_synchronization; + flist[F_READ_COUNTER_BLOCK]=&read_counter_block; + flist[F_RESET_COUNTER_BLOCK]=&reset_counter_block; + flist[F_START_RECEIVER]=&start_receiver; + flist[F_STOP_RECEIVER]=&stop_receiver; + flist[F_CALIBRATE_PEDESTAL]=&calibrate_pedestal; + flist[F_SET_CTB_PATTERN]=&set_ctb_pattern; + return OK; +} + + +int M_nofunc(int file_des){ + + int ret=FAIL; + sprintf(mess,"Unrecognized Function\n"); + printf(mess); + + sendDataOnly(file_des,&ret,sizeof(ret)); + sendDataOnly(file_des,mess,sizeof(mess)); + return GOODBYE; +} + + +int exit_server(int file_des) { + int retval=FAIL; + sendDataOnly(file_des,&retval,sizeof(retval)); + printf("closing server."); + sprintf(mess,"closing server"); + sendDataOnly(file_des,mess,sizeof(mess)); + return GOODBYE; +} + +int exec_command(int file_des) { + char cmd[MAX_STR_LENGTH]; + char answer[MAX_STR_LENGTH]; + int retval=OK; + int sysret=0; + int n=0; + + /* receive arguments */ + n = receiveDataOnly(file_des,cmd,MAX_STR_LENGTH); + if (n < 0) { + sprintf(mess,"Error reading from socket\n"); + retval=FAIL; + } + + /* execute action if the arguments correctly arrived*/ + if (retval==OK) { +#ifdef VERBOSE + printf("executing command %s\n", cmd); +#endif + if (lockStatus==0 || differentClients==0) + sysret=system(cmd); + + //should be replaced by popen + if (sysret==0) { + sprintf(answer,"Succeeded\n"); + if (lockStatus==1 && differentClients==1) + sprintf(answer,"Detector locked by %s\n", lastClientIP); + } else { + sprintf(answer,"Failed\n"); + retval=FAIL; + } + } else { + sprintf(answer,"Could not receive the command\n"); + } + + /* send answer */ + n = sendDataOnly(file_des,&retval,sizeof(retval)); + n = sendDataOnly(file_des,answer,MAX_STR_LENGTH); + if (n < 0) { + sprintf(mess,"Error writing to socket"); + retval=FAIL; + } + + + /*return ok/fail*/ + return retval; + +} + + + +int get_detector_type(int file_des) { + int n=0; + enum detectorType ret; + int retval=OK; + + sprintf(mess,"Can't return detector type\n"); + + + /* receive arguments */ + /* execute action */ + ret=myDetectorType; + +#ifdef VERBOSE + printf("Returning detector type %d\n",ret); +#endif + + /* send answer */ + /* send OK/failed */ + if (differentClients==1) + retval=FORCE_UPDATE; + + n += sendDataOnly(file_des,&retval,sizeof(retval)); + if (retval!=FAIL) { + /* send return argument */ + n += sendDataOnly(file_des,&ret,sizeof(ret)); + } else { + n += sendDataOnly(file_des,mess,sizeof(mess)); + } + /*return ok/fail*/ + return retval; + + +} + + +int set_number_of_modules(int file_des) { + int n; + int arg[2], ret=0; + int retval=OK; + int dim, nm; + + sprintf(mess,"Can't set number of modules\n"); + + /* receive arguments */ + n = receiveDataOnly(file_des,&arg,sizeof(arg)); + if (n < 0) { + sprintf(mess,"Error reading from socket %d", n); + retval=GOODBYE; + } + if (retval==OK) { + dim=arg[0]; + nm=arg[1]; + + /* execute action */ +#ifdef VERBOSE + printf("Setting the number of modules in dimension %d to %d\n",dim,nm ); +#endif + + //if (nm!=GET_FLAG) { + if (dim!=X && nm!=GET_FLAG) { + retval=FAIL; + sprintf(mess,"Can't change module number in dimension %d\n",dim); + } else { + if (lockStatus==1 && differentClients==1 && nm!=GET_FLAG) { + sprintf(mess,"Detector locked by %s\n", lastClientIP); + retval=FAIL; + } else { + ret=setNMod(nm); + if (nModX==nm || nm==GET_FLAG) { + retval=OK; + if (differentClients==1) + retval=FORCE_UPDATE; + } else + retval=FAIL; + } + } + } + /*} 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; + +} + + +int get_max_number_of_modules(int file_des) { + int n; + int ret; + int retval=OK; + enum dimension arg; + + sprintf(mess,"Can't get max number of modules\n"); + /* receive arguments */ + n = receiveDataOnly(file_des,&arg,sizeof(arg)); + if (n < 0) { + sprintf(mess,"Error reading from socket\n"); + retval=FAIL; + } + /* execute action */ +#ifdef VERBOSE + printf("Getting the max number of modules in dimension %d \n",arg); +#endif + + + switch (arg) { + case X: + ret=getNModBoard(); + break; + case Y: + ret=NMAXMODY; + break; + default: + ret=FAIL; + retval=FAIL; + break; + } +#ifdef VERBOSE + printf("Max number of module in dimension %d is %d\n",arg,ret ); +#endif + + + + if (differentClients==1 && retval==OK) { + retval=FORCE_UPDATE; + } + + /* send answer */ + /* send OK/failed */ + n = sendDataOnly(file_des,&retval,sizeof(retval)); + if (retval!=FAIL) { + /* send return argument */ + n += sendDataOnly(file_des,&ret,sizeof(ret)); + } else { + n += sendDataOnly(file_des,mess,sizeof(mess)); + } + + + + /*return ok/fail*/ + return retval; +} + + +//index 0 is in gate +//index 1 is in trigger +//index 2 is out gate +//index 3 is out trigger + +int set_external_signal_flag(int file_des) { + int n; + int arg[2]; + int ret=OK; + int signalindex; + enum externalSignalFlag flag, retval; + + sprintf(mess,"Can't set external signal flag\n"); + + /* receive arguments */ + n = receiveDataOnly(file_des,&arg,sizeof(arg)); + if (n < 0) { + sprintf(mess,"Error reading from socket\n"); + ret=FAIL; + } + retval=SIGNAL_OFF; + if (ret==OK) { + signalindex=arg[0]; + flag=arg[1]; + /* execute action */ + switch (flag) { + case GET_EXTERNAL_SIGNAL_FLAG: + retval=getExtSignal(signalindex); + break; + + default: + if (differentClients==0 || lockStatus==0) { + retval=setExtSignal(signalindex,flag); + } else { + if (lockStatus!=0) { + ret=FAIL; + sprintf(mess,"Detector locked by %s\n", lastClientIP); + } + } + + } + +#ifdef VERBOSE + printf("Setting external signal %d to flag %d\n",signalindex,flag ); + printf("Set to flag %d\n",retval); +#endif + + } else { + ret=FAIL; + } + + if (ret==OK && differentClients!=0) + ret=FORCE_UPDATE; + + + /* send answer */ + /* send OK/failed */ + n = sendDataOnly(file_des,&ret,sizeof(ret)); + if (ret!=FAIL) { + /* send return argument */ + n += sendDataOnly(file_des,&retval,sizeof(retval)); + } else { + n += sendDataOnly(file_des,mess,sizeof(mess)); + } + + + /*return ok/fail*/ + return ret; + +} + + +int set_external_communication_mode(int file_des) { + int n; + enum externalCommunicationMode arg, ret=GET_EXTERNAL_COMMUNICATION_MODE; + int retval=OK; + + sprintf(mess,"Can't set external communication mode\n"); + + + /* receive arguments */ + n = receiveDataOnly(file_des,&arg,sizeof(arg)); + if (n < 0) { + sprintf(mess,"Error reading from socket\n"); + retval=FAIL; + } + /* + enum externalCommunicationMode{ + GET_EXTERNAL_COMMUNICATION_MODE, + AUTO, + TRIGGER_EXPOSURE_SERIES, + TRIGGER_EXPOSURE_BURST, + TRIGGER_READOUT, + TRIGGER_COINCIDENCE_WITH_INTERNAL_ENABLE, + GATE_FIX_NUMBER, + GATE_FIX_DURATION, + GATE_WITH_START_TRIGGER, + GATE_COINCIDENCE_WITH_INTERNAL_ENABLE + }; + */ + if (retval==OK) { + /* execute action */ + + ret=setTiming(arg); + + /* 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 + } else + ret=FAIL; + + /* send answer */ + /* send OK/failed */ + n = sendDataOnly(file_des,&retval,sizeof(retval)); + if (retval!=FAIL) { + /* send return argument */ + n += sendDataOnly(file_des,&ret,sizeof(ret)); + } else { + n += sendDataOnly(file_des,mess,sizeof(mess)); + } + + /*return ok/fail*/ + return retval; +} + + + +int get_id(int file_des) { + // sends back 64 bits! + int64_t retval=-1; + int ret=OK; + int n=0; + enum idMode arg; + + sprintf(mess,"Can't return id\n"); + + /* receive arguments */ + n = receiveDataOnly(file_des,&arg,sizeof(arg)); + if (n < 0) { + sprintf(mess,"Error reading from socket\n"); + ret=FAIL; + } + +#ifdef VERBOSE + printf("Getting id %d\n", arg); +#endif + + switch (arg) { + case DETECTOR_SERIAL_NUMBER: + retval=getDetectorNumber(); + break; + case DETECTOR_FIRMWARE_VERSION: + retval=getFirmwareSVNVersion(); + retval=(retval <<32) | getFirmwareVersion(); + break; + case DETECTOR_SOFTWARE_VERSION: + retval= SVNREV; + retval= (retval <<32) | SVNDATE; + break; +/* case DETECTOR_FIRMWARE_SVN_VERSION: + retval=getFirmwareSVNVersion(); + break;*/ + default: + printf("Required unknown id %d \n", arg); + ret=FAIL; + retval=FAIL; + break; + } + +#ifdef VERBOSE + printf("Id is %llx\n", retval); +#endif + + if (differentClients==1) + ret=FORCE_UPDATE; + + /* send answer */ + /* send OK/failed */ + n = sendDataOnly(file_des,&ret,sizeof(ret)); + if (ret!=FAIL) { + /* send return argument */ + n += sendDataOnly(file_des,&retval,sizeof(retval)); + } else { + n += sendDataOnly(file_des,mess,sizeof(mess)); + } + + /*return ok/fail*/ + return ret; + +} + +int digital_test(int file_des) { + + int retval; + int ret=OK; + int imod=-1; + int n=0; + int ibit=0; + int ow; + int ival; + enum digitalTestMode arg; + + sprintf(mess,"Can't send digital test\n"); + + n = receiveDataOnly(file_des,&arg,sizeof(arg)); + if (n < 0) { + sprintf(mess,"Error reading from socket\n"); + ret=FAIL; + } + +#ifdef VERBOSE + printf("Digital test mode %d\n",arg ); +#endif + + switch (arg) { + case CHIP_TEST: + n = receiveDataOnly(file_des,&imod,sizeof(imod)); + if (n < 0) { + sprintf(mess,"Error reading from socket\n"); + retval=FAIL; + } +#ifdef VERBOSE + printf("of module %d\n", imod); +#endif + retval=0; +#ifdef MCB_FUNCS + if (differentClients==1 && lockStatus==1) { + ret=FAIL; + sprintf(mess,"Detector locked by %s\n",lastClientIP); + break; + } + if (imod >= nModX) { + ret=FAIL; + sprintf(mess,"Module %d disabled\n",imod); + break; + } + if (testShiftIn(imod)) retval|=(1<<(ibit)); + ibit++; + if (testShiftOut(imod)) retval|=(1<<(ibit)); + ibit++; + if (testShiftStSel(imod)) retval|=(1<<(ibit)); + ibit++; + //if ( testDataInOut(0x123456, imod)) retval|=(1<<(ibit++)); + //if ( testExtPulse(imod)) retval|=(1<<(ibit++)); + // for (ow=0; ow<6; ow++) + // ow=1; + //#ifndef PICASSOD + for (ow=0; ow<5; ow++) { + //#endif + if (testDataInOutMux(imod, ow, 0x789abc)) retval|=(1<=getNModBoard()) + ret=FAIL; + if (imod<0) + imod=ALLMOD; + +#ifdef MCB_FUNCS + switch (ind) { + case V_DAC0 : + idac=VDAC0; + break; + case V_DAC1: + idac=VDAC1; + break; + case V_DAC2: + idac=VDAC2; + break; + case V_DAC3: + idac=VDAC3; + break; + case V_DAC4: + idac=VDAC4; + break; + case V_DAC5: + idac=VDAC5; + break; + case V_DAC6: + idac=VDAC6; + break; + case V_DAC7: + idac=VDAC7; + break; + case HV_POT: + idac=HIGH_VOLTAGE; + break; + + default: + printf("Unknown DAC index %d for Moench\n",ind); + sprintf(mess,"Unknown DAC index %d for Moench\n",ind); + ret=FAIL; + break; + } + + if (ret==OK) { + if (differentClients==1 && lockStatus==1) { + ret=FAIL; + sprintf(mess,"Detector locked by %s\n",lastClientIP); + } else{ + if(idac==HIGH_VOLTAGE) + retval=initHighVoltageByModule(val,imod); + else + retval=initDACbyIndexDACU(idac,val,imod); + } + } + if(ret==OK){ + ret=FAIL; + if(idac==HIGH_VOLTAGE){ + if(retval==-2) + strcpy(mess,"Invalid Voltage.Valid values are 0,90,110,120,150,180,200"); + else if(retval==-3) + strcpy(mess,"Weird value read back or it has not been set yet\n"); + else + ret=OK; + }//since v r saving only msb + else if ((retval-val)<=3 || val==-1) + ret=OK; + } +#endif + +#ifdef VERBOSE + printf("DAC set to %d V\n", retval); +#endif + + if(ret==FAIL) + printf("Setting dac %d of module %d: wrote %d but read %d\n", ind, imod, val, retval); + else{ + if (differentClients) + ret=FORCE_UPDATE; + } + + + /* send answer */ + /* send OK/failed */ + n = sendDataOnly(file_des,&ret,sizeof(ret)); + if (ret!=FAIL) { + /* send return argument */ + n += sendDataOnly(file_des,&retval,sizeof(retval)); + } else { + n += sendDataOnly(file_des,mess,sizeof(mess)); + } + + + /*return ok/fail*/ + return ret; + +} + + + +int get_adc(int file_des) { + //default: mod 0 + int retval; + int ret=OK; + int arg[2]; + enum dacIndex ind; + int imod; + int n; + int idac=0; + + sprintf(mess,"Can't read ADC\n"); + + + n = receiveDataOnly(file_des,arg,sizeof(arg)); + if (n < 0) { + sprintf(mess,"Error reading from socket\n"); + ret=FAIL; + } + ind=arg[0]; + imod=arg[1]; + +#ifdef VERBOSE + printf("Getting ADC %d of module %d\n", ind, imod); +#endif + + if (imod>=getNModBoard() || imod<0) + ret=FAIL; + +#ifdef MCB_FUNCS + switch (ind) { + case TEMPERATURE_FPGA: + idac=TEMP_FPGA; + break; + case TEMPERATURE_ADC: + idac=TEMP_ADC; + break; + default: + printf("Unknown DAC index %d\n",ind); + sprintf(mess,"Unknown DAC index %d\n",ind); + ret=FAIL; + break; + } + + if (ret==OK) + retval=getTemperatureByModule(idac,imod); +#endif + +#ifdef VERBOSE + printf("ADC is %d V\n", retval); +#endif + if (ret==FAIL) { + printf("Getting adc %d of module %d failed\n", ind, imod); + } + + if (differentClients) + ret=FORCE_UPDATE; + + /* send answer */ + /* send OK/failed */ + n = sendDataOnly(file_des,&ret,sizeof(ret)); + if (ret!=FAIL) { + /* send return argument */ + n += sendDataOnly(file_des,&retval,sizeof(retval)); + } else { + n += sendDataOnly(file_des,mess,sizeof(mess)); + } + + /*return ok/fail*/ + return ret; + +} + +int set_channel(int file_des) { + int ret=OK; + sls_detector_channel myChan; + int retval; + int n; + + + sprintf(mess,"Can't set channel\n"); + +#ifdef VERBOSE + printf("Setting channel\n"); +#endif + ret=receiveChannel(file_des, &myChan); + if (ret>=0) + ret=OK; + else + ret=FAIL; +#ifdef VERBOSE + printf("channel number is %d, chip number is %d, module number is %d, register is %lld\n", myChan.chan,myChan.chip, myChan.module, myChan.reg); +#endif + + if (ret==OK) { + if (myChan.module>=getNModBoard()) + ret=FAIL; + if (myChan.chip>=NCHIP) + ret=FAIL; + if (myChan.chan>=NCHAN) + ret=FAIL; + if (myChan.module<0) + myChan.module=ALLMOD; + } + + + if (ret==OK) { + if (differentClients==1 && lockStatus==1) { + ret=FAIL; + sprintf(mess,"Detector locked by %s\n",lastClientIP); + } else { +#ifdef MCB_FUNCS + retval=initChannelbyNumber(myChan); +#endif + } + } + /* Maybe this is done inside the initialization funcs */ + //copyChannel(detectorChans[myChan.module][myChan.chip]+(myChan.chan), &myChan); + + + + if (differentClients==1 && ret==OK) + ret=FORCE_UPDATE; + + /* send answer */ + /* send OK/failed */ + n = sendDataOnly(file_des,&ret,sizeof(ret)); + if (ret!=FAIL) { + /* send return argument */ + n += sendDataOnly(file_des,&retval,sizeof(retval)); + } else { + n += sendDataOnly(file_des,mess,sizeof(mess)); + } + + + /*return ok/fail*/ + return ret; + +} + + + + +int get_channel(int file_des) { + + int ret=OK; + sls_detector_channel retval; + + int arg[3]; + int ichan, ichip, imod; + int n; + + sprintf(mess,"Can't get channel\n"); + + + + n = receiveDataOnly(file_des,arg,sizeof(arg)); + if (n < 0) { + sprintf(mess,"Error reading from socket\n"); + ret=FAIL; + } + ichan=arg[0]; + ichip=arg[1]; + imod=arg[2]; + + if (ret==OK) { + ret=FAIL; + if (imod>=0 && imod=0 && ichip=0 && ichan=0) + ret=OK; + else + ret=FAIL; +#ifdef VERBOSE + printf("chip number is %d, module number is %d, register is %d, nchan %d\n",myChip.chip, myChip.module, myChip.reg, myChip.nchan); +#endif + + if (ret==OK) { + if (myChip.module>=getNModBoard()) + ret=FAIL; + if (myChip.module<0) + myChip.module=ALLMOD; + if (myChip.chip>=NCHIP) + ret=FAIL; + } + if (differentClients==1 && lockStatus==1) { + ret=FAIL; + sprintf(mess,"Detector locked by %s\n",lastClientIP); + } else { +#ifdef MCB_FUNCS + retval=initChipbyNumber(myChip); +#endif + } + /* Maybe this is done inside the initialization funcs */ + //copyChip(detectorChips[myChip.module]+(myChip.chip), &myChip); + + if (differentClients && ret==OK) + ret=FORCE_UPDATE; + /* send answer */ + /* send OK/failed */ + n = sendDataOnly(file_des,&ret,sizeof(ret)); + if (ret!=FAIL) { + /* send return argument */ + n += sendDataOnly(file_des,&retval,sizeof(retval)); + } else { + n += sendDataOnly(file_des,mess,sizeof(mess)); + } + + + return ret; +} + +int get_chip(int file_des) { + + + int ret=OK; + sls_detector_chip retval; + int arg[2]; + int ichip, imod; + int n; + + + + n = receiveDataOnly(file_des,arg,sizeof(arg)); + if (n < 0) { + sprintf(mess,"Error reading from socket\n"); + ret=FAIL; + } + ichip=arg[0]; + imod=arg[1]; + if (ret==OK) { + ret=FAIL; + if (imod>=0 && imod=0 && ichip=0) + ret=OK; + else + ret=FAIL; + + +#ifdef VERBOSE + printf("module number is %d,register is %d, nchan %d, nchip %d, ndac %d, nadc %d, gain %f, offset %f\n",myModule.module, myModule.reg, myModule.nchan, myModule.nchip, myModule.ndac, myModule.nadc, myModule.gain,myModule.offset); +#endif + + if (ret==OK) { + if (myModule.module>=getNModBoard()) { + ret=FAIL; + printf("Module number is too large %d\n",myModule.module); + } + if (myModule.module<0) + myModule.module=ALLMOD; + } + + if (ret==OK) { + if (differentClients==1 && lockStatus==1) { + ret=FAIL; + sprintf(mess,"Detector locked by %s\n",lastClientIP); + } else { +#ifdef MCB_FUNCS + retval=initModulebyNumber(myModule); +#endif + } + } + + if (differentClients==1 && ret==OK) + ret=FORCE_UPDATE; + + /* Maybe this is done inside the initialization funcs */ + //copyChip(detectorChips[myChip.module]+(myChip.chip), &myChip); + + /* send answer */ + /* send OK/failed */ + n = sendDataOnly(file_des,&ret,sizeof(ret)); + if (ret!=FAIL) { + /* send return argument */ + n += sendDataOnly(file_des,&retval,sizeof(retval)); + } else { + n += sendDataOnly(file_des,mess,sizeof(mess)); + } + free(myChip); + free(myChan); + free(myDac); + free(myAdc); + + // setDynamicRange(dr); always 16 commented out + + + return ret; +} + + + + +int get_module(int file_des) { + + + int ret=OK; + + + int arg; + int imod; + int n; + + + + sls_detector_module myModule; + int *myChip=malloc(NCHIP*sizeof(int)); + int *myChan=malloc(NCHIP*NCHAN*sizeof(int)); + int *myDac=malloc(NDAC*sizeof(int));/**dhanya*/ + int *myAdc=malloc(NADC*sizeof(int));/**dhanya*/ + + + if (myDac) + myModule.dacs=myDac; + else { + sprintf(mess,"could not allocate dacs\n"); + ret=FAIL; + } + if (myAdc) + myModule.adcs=myAdc; + else { + sprintf(mess,"could not allocate adcs\n"); + ret=FAIL; + } + if (myChip) + myModule.chipregs=myChip; + else { + sprintf(mess,"could not allocate chips\n"); + ret=FAIL; + } + if (myChan) + myModule.chanregs=myChan; + else { + sprintf(mess,"could not allocate chans\n"); + ret=FAIL; + } + + myModule.ndac=NDAC; + myModule.nchip=NCHIP; + myModule.nchan=NCHAN*NCHIP; + myModule.nadc=NADC; + + + + + + n = receiveDataOnly(file_des,&arg,sizeof(arg)); + if (n < 0) { + sprintf(mess,"Error reading from socket\n"); + ret=FAIL; + } + imod=arg; + + if (ret==OK) { + ret=FAIL; + if (imod>=0 && imod-2) { + 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); + } +#ifdef VERYVERBOSE + printf("%d %d %x %s\n",(int)(sizeof(mess)),(int)(strlen(mess)),(unsigned int)( mess),mess); +#endif + sendDataOnly(file_des,&dataret,sizeof(dataret)); + sendDataOnly(file_des,mess,sizeof(mess)); +#ifdef VERYVERBOSE + printf("message sent %s\n",mess); +#endif + printf("dataret %d\n",dataret); + return dataret; + } + } else { + nframes=0; + while(fifo_read_event()) { + nframes++; + } + dataretval=(char*)ram_values; + dataret=OK; +#ifdef VERBOSE + printf("sending data of %d frames\n",nframes); +#endif + for (iframes=0; iframes-2) { + 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)); + printf("dataret %d\n",dataret); + return dataret; + } + printf("dataret %d\n",dataret); + return dataret; +} + + + + + + + + +int read_all(int file_des) { + +while(read_frame(file_des)==OK) { + +#ifdef VERBOSE + printf("frame read\n"); +#endif + ; + } +#ifdef VERBOSE + printf("Frames finished\n"); +#endif + return OK; + + +} + +int start_and_read_all(int file_des) { + //int dataret=OK; +#ifdef VERBOSE + printf("Starting and reading all frames\n"); +#endif + + if (differentClients==1 && lockStatus==1) { + dataret=FAIL; + sprintf(mess,"Detector locked by %s\n",lastClientIP); + sendDataOnly(file_des,&dataret,sizeof(dataret)); + sendDataOnly(file_des,mess,sizeof(mess)); + return dataret; + + } + + startStateMachine(); + + /* 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); +#ifdef VERBOSE + printf("Frames finished\n"); +#endif + //} + + + return OK; + + +} + +int set_timer(int file_des) { + enum timerIndex ind; + int64_t tns; + int n; + int64_t retval; + int ret=OK; + + + sprintf(mess,"can't set timer\n"); + + n = receiveDataOnly(file_des,&ind,sizeof(ind)); + if (n < 0) { + sprintf(mess,"Error reading from socket\n"); + ret=FAIL; + } + + n = receiveDataOnly(file_des,&tns,sizeof(tns)); + if (n < 0) { + sprintf(mess,"Error reading from socket\n"); + ret=FAIL; + } + + if (ret!=OK) { + printf(mess); + } + +#ifdef VERBOSE + printf("setting timer %d to %lld ns\n",ind,tns); +#endif + if (ret==OK) { + + if (differentClients==1 && lockStatus==1 && tns!=-1) { + ret=FAIL; + sprintf(mess,"Detector locked by %s\n",lastClientIP); + } else { + switch(ind) { + case FRAME_NUMBER: + retval=setFrames(tns); + break; + case ACQUISITION_TIME: + retval=setExposureTime(tns); + break; + case FRAME_PERIOD: + retval=setPeriod(tns); + break; + case DELAY_AFTER_TRIGGER: + retval=setDelay(tns); + break; + case GATES_NUMBER: + retval=setGates(tns); + break; + case PROBES_NUMBER: + sprintf(mess,"can't set timer for moench\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) { + printf(mess); + if (differentClients) + ret=FORCE_UPDATE; + } + + if (ret!=OK) { + printf(mess); + printf("set timer failed\n"); + } else if (ind==FRAME_NUMBER) { + 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))); +#endif + + n = sendDataOnly(file_des,&retval,sizeof(retval)); + } + + return ret; + +} + + + + + + + + +int get_time_left(int file_des) { + + enum timerIndex ind; + int n; + int64_t retval; + int ret=OK; + + sprintf(mess,"can't get timer\n"); + n = receiveDataOnly(file_des,&ind,sizeof(ind)); + if (n < 0) { + sprintf(mess,"Error reading from socket\n"); + ret=FAIL; + } + + + //#ifdef VERBOSE + + printf("getting time left on timer %d \n",ind); + //#endif + + if (ret==OK) { + switch(ind) { + case FRAME_NUMBER: + printf("getting frames \n"); + retval=getFrames(); + break; + case ACQUISITION_TIME: + retval=getExposureTime(); + break; + case FRAME_PERIOD: + retval=getPeriod(); + break; + case DELAY_AFTER_TRIGGER: + retval=getDelay(); + break; + case GATES_NUMBER: + retval=getGates(); + break; + case PROBES_NUMBER: + retval=getProbes(); + break; + case CYCLES_NUMBER: + retval=getTrains(); + break; + case PROGRESS: + retval=getProgress(); + break; + case ACTUAL_TIME: + retval=getActualTime(); + break; + case MEASUREMENT_TIME: + retval=getMeasurementTime(); + break; + default: + ret=FAIL; + sprintf(mess,"timer index unknown %d\n",ind); + break; + } + } + + + if (ret!=OK) { + printf("get time left failed\n"); + } else if (differentClients) + ret=FORCE_UPDATE; + + //#ifdef VERBOSE + + printf("time left on timer %d is %lld\n",ind, retval); + //#endif + + n = sendDataOnly(file_des,&ret,sizeof(ret)); + if (ret!=OK) { + n += sendDataOnly(file_des,mess,sizeof(mess)); + } else { + n = sendDataOnly(file_des,&retval,sizeof(retval)); + } +#ifdef VERBOSE + + printf("data sent\n"); +#endif + + return ret; + + +} + +int set_dynamic_range(int file_des) { + + + + int dr; + int n; + int retval; + int ret=OK; + + + sprintf(mess,"can't set dynamic range\n"); + + + n = receiveDataOnly(file_des,&dr,sizeof(dr)); + if (n < 0) { + sprintf(mess,"Error reading from socket\n"); + ret=FAIL; + } + + + if (differentClients==1 && lockStatus==1 && dr>=0) { + ret=FAIL; + sprintf(mess,"Detector locked by %s\n",lastClientIP); + } else { + retval=setDynamicRange(dr); + } + + //if (dr>=0 && retval!=dr) ret=FAIL; + if (ret!=OK) { + sprintf(mess,"set dynamic range failed\n"); + } else { + ret=allocateRAM(); + if (ret!=OK) + sprintf(mess,"Could not allocate RAM for the dynamic range selected\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"); + + + n = receiveDataOnly(file_des,&nroi,sizeof(nroi)); + if (n < 0) { + sprintf(mess,"Error reading from socket\n"); + ret=FAIL; + } + + if(nroi!=-1){ + 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; + } +//#ifdef VERBOSE + /* + printf("Setting ROI to:"); + for( i=0;i=0) { + if (differentClients==1 && lockStatus==1 && val>=0) { + ret=FAIL; + sprintf(mess,"Detector locked by %s\n",lastClientIP); + } else { + switch (arg) { + case CLOCK_DIVIDER: + retval=setClockDivider(val); + break; + + case PHASE_SHIFT: + retval=phaseStep(val); + break; + + case OVERSAMPLING: + retval=setOversampling(val); + break; + + default: + ret=FAIL; + sprintf(mess,"Unknown speed parameter %d",arg); + } + } + } + + + switch (arg) { + case CLOCK_DIVIDER: + retval=getClockDivider(); + break; + + case PHASE_SHIFT: + retval=phaseStep(-1); + break; + + case OVERSAMPLING: + retval=setOversampling(-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; +} + + + +int set_readout_flags(int file_des) { + + enum readOutFlags arg; + int n; + 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)); + + return ret; +} + + + + + +int execute_trimming(int file_des) { + + int arg[3]; + int ret=FAIL; + enum trimMode mode; + + sprintf(mess,"can't set execute trimming for moench\n"); + + receiveDataOnly(file_des,&mode,sizeof(mode)); + receiveDataOnly(file_des,arg,sizeof(arg)); + + + sendDataOnly(file_des,&ret,sizeof(ret)); + sendDataOnly(file_des,mess,sizeof(mess)); + + return ret; +} + + +int lock_server(int file_des) { + + + int n; + int ret=OK; + + int lock; + n = receiveDataOnly(file_des,&lock,sizeof(lock)); + if (n < 0) { + sprintf(mess,"Error reading from socket\n"); + printf("Error reading from socket (lock)\n"); + ret=FAIL; + } + if (lock>=0) { + if (lockStatus==0 || strcmp(lastClientIP,thisClientIP)==0 || strcmp(lastClientIP,"none")==0) + lockStatus=lock; + else { + ret=FAIL; + sprintf(mess,"Server already locked by %s\n", lastClientIP); + } + } + if (differentClients && ret==OK) + ret=FORCE_UPDATE; + + n = sendDataOnly(file_des,&ret,sizeof(ret)); + if (ret==FAIL) { + n = sendDataOnly(file_des,mess,sizeof(mess)); + } else + n = sendDataOnly(file_des,&lockStatus,sizeof(lockStatus)); + + return ret; + +} + +int set_port(int file_des) { + int n; + int ret=OK; + int sd=-1; + + enum portType p_type; /** data? control? stop? Unused! */ + int p_number; /** new port number */ + + n = receiveDataOnly(file_des,&p_type,sizeof(p_type)); + if (n < 0) { + sprintf(mess,"Error reading from socket\n"); + printf("Error reading from socket (ptype)\n"); + ret=FAIL; + } + + n = receiveDataOnly(file_des,&p_number,sizeof(p_number)); + if (n < 0) { + sprintf(mess,"Error reading from socket\n"); + printf("Error reading from socket (pnum)\n"); + ret=FAIL; + } + if (differentClients==1 && lockStatus==1 ) { + ret=FAIL; + sprintf(mess,"Detector locked by %s\n",lastClientIP); + } else { + if (p_number<1024) { + sprintf(mess,"Too low port number %d\n", p_number); + printf("\n"); + ret=FAIL; + } + + printf("set port %d to %d\n",p_type, p_number); + + sd=bindSocket(p_number); + } + if (sd>=0) { + ret=OK; + if (differentClients ) + ret=FORCE_UPDATE; + } else { + ret=FAIL; + sprintf(mess,"Could not bind port %d\n", p_number); + printf("Could not bind port %d\n", p_number); + if (sd==-10) { + sprintf(mess,"Port %d already set\n", p_number); + printf("Port %d already set\n", p_number); + + } + } + + n = sendDataOnly(file_des,&ret,sizeof(ret)); + if (ret==FAIL) { + n = sendDataOnly(file_des,mess,sizeof(mess)); + } else { + n = sendDataOnly(file_des,&p_number,sizeof(p_number)); + closeConnection(file_des); + exitServer(sockfd); + sockfd=sd; + + } + + return ret; + +} + +int get_last_client_ip(int file_des) { + int ret=OK; + int n; + if (differentClients ) + ret=FORCE_UPDATE; + n = sendDataOnly(file_des,&ret,sizeof(ret)); + n = sendDataOnly(file_des,lastClientIP,sizeof(lastClientIP)); + + return ret; + +} + + +int send_update(int file_des) { + + int ret=OK; + enum detectorSettings t; + int n;//int thr, n; + //int it; + int64_t retval, tns=-1; + n = sendDataOnly(file_des,lastClientIP,sizeof(lastClientIP)); + n = sendDataOnly(file_des,&nModX,sizeof(nModX)); + n = sendDataOnly(file_des,&nModY,sizeof(nModY)); + n = sendDataOnly(file_des,&dynamicRange,sizeof(dynamicRange)); + n = sendDataOnly(file_des,&dataBytes,sizeof(dataBytes)); + t=setSettings(GET_SETTINGS,-1); + n = sendDataOnly(file_des,&t,sizeof(t)); +/* thr=getThresholdEnergy(); + n = sendDataOnly(file_des,&thr,sizeof(thr));*/ + retval=setFrames(tns); + n = sendDataOnly(file_des,&retval,sizeof(int64_t)); + retval=setExposureTime(tns); + n = sendDataOnly(file_des,&retval,sizeof(int64_t)); + retval=setPeriod(tns); + n = sendDataOnly(file_des,&retval,sizeof(int64_t)); + retval=setDelay(tns); + n = sendDataOnly(file_des,&retval,sizeof(int64_t)); + retval=setGates(tns); + n = sendDataOnly(file_des,&retval,sizeof(int64_t)); +/* retval=setProbes(tns); + n = sendDataOnly(file_des,&retval,sizeof(int64_t));*/ + retval=setTrains(tns); + n = sendDataOnly(file_des,&retval,sizeof(int64_t)); + + if (lockStatus==0) { + strcpy(lastClientIP,thisClientIP); + } + + return ret; + + +} +int update_client(int file_des) { + + int ret=OK; + + sendDataOnly(file_des,&ret,sizeof(ret)); + return send_update(file_des); + + + +} + + +int configure_mac(int file_des) { + + int ret=OK; + char arg[5][50]; + int n; + + int imod=0;//should be in future sent from client as -1, arg[2] + int ipad; + long long int imacadd; + long long int idetectormacadd; + int udpport; + int detipad; + int retval=-100; + + sprintf(mess,"Can't configure MAC\n"); + + + n = receiveDataOnly(file_des,arg,sizeof(arg)); + if (n < 0) { + sprintf(mess,"Error reading from socket\n"); + ret=FAIL; + } + + sscanf(arg[0], "%x", &ipad); + sscanf(arg[1], "%llx", &imacadd); + sscanf(arg[2], "%x", &udpport); + sscanf(arg[3], "%llx", &idetectormacadd); + sscanf(arg[4], "%x", &detipad); + +#ifdef VERBOSE + int i; + printf("\ndigital_test_bit in server %d\t",digitalTestBit); + printf("\nipadd %x\t",ipad); + printf("destination ip is %d.%d.%d.%d = 0x%x \n",(ipad>>24)&0xff,(ipad>>16)&0xff,(ipad>>8)&0xff,(ipad)&0xff,ipad); + printf("macad:%llx\n",imacadd); + for (i=0;i<6;i++) + printf("mac adress %d is 0x%x \n",6-i,(unsigned int)(((imacadd>>(8*i))&0xFF))); + printf("udp port:0x%x\n",udpport); + printf("detector macad:%llx\n",idetectormacadd); + for (i=0;i<6;i++) + printf("detector mac adress %d is 0x%x \n",6-i,(unsigned int)(((idetectormacadd>>(8*i))&0xFF))); + printf("detipad %x\n",detipad); + printf("\n"); +#endif + + + + if (imod>=getNModBoard()) + ret=FAIL; + if (imod<0) + imod=ALLMOD; + + //#ifdef VERBOSE + printf("Configuring MAC of module %d at port %x\n", imod, udpport); + //#endif +#ifdef MCB_FUNCS + if (ret==OK){ + if(runBusy()){ + ret=stopStateMachine(); + if(ret==FAIL) + strcpy(mess,"could not stop detector acquisition to configure mac"); + } + + if(ret==OK) + configureMAC(ipad,imacadd,idetectormacadd,detipad,digitalTestBit,udpport); + retval=getAdcConfigured(); + } +#endif + if (ret==FAIL) + printf("configuring MAC of mod %d failed\n", imod); + else + printf("Configuremac successful of mod %d and adc %d\n",imod,retval); + + if (differentClients) + ret=FORCE_UPDATE; + + /* send answer */ + /* send OK/failed */ + n = sendDataOnly(file_des,&ret,sizeof(ret)); + if (ret==FAIL) + n += sendDataOnly(file_des,mess,sizeof(mess)); + else + n += sendDataOnly(file_des,&retval,sizeof(retval)); + /*return ok/fail*/ + return ret; + +} + + + +int load_image(int file_des) { + int retval; + int ret=OK; + int n; + enum imageType index; + short int ImageVals[NCHAN*NCHIP]; + + sprintf(mess,"Loading image failed\n"); + + n = receiveDataOnly(file_des,&index,sizeof(index)); + if (n < 0) { + sprintf(mess,"Error reading from socket\n"); + ret=FAIL; + } + + n = receiveDataOnly(file_des,ImageVals,dataBytes); + if (n < 0) { + sprintf(mess,"Error reading from socket\n"); + ret=FAIL; + } + + switch (index) { + case DARK_IMAGE : +#ifdef VERBOSE + printf("Loading Dark image\n"); +#endif + break; + case GAIN_IMAGE : +#ifdef VERBOSE + printf("Loading Gain image\n"); +#endif + break; + default: + printf("Unknown index %d\n",index); + sprintf(mess,"Unknown index %d\n",index); + ret=FAIL; + break; + } + + if (ret==OK) { + if (differentClients==1 && lockStatus==1) { + ret=FAIL; + sprintf(mess,"Detector locked by %s\n",lastClientIP); + } else{ + retval=loadImage(index,ImageVals); + if (retval==-1) + ret = FAIL; + } + } + + if(ret==OK){ + if (differentClients) + ret=FORCE_UPDATE; + } + + /* send answer */ + /* send OK/failed */ + n = sendDataOnly(file_des,&ret,sizeof(ret)); + if (ret!=FAIL) { + /* send return argument */ + n += sendDataOnly(file_des,&retval,sizeof(retval)); + } else { + n += sendDataOnly(file_des,mess,sizeof(mess)); + } + + /*return ok/fail*/ + return ret; +} + + + +int set_master(int file_des) { + + enum masterFlags retval=GET_MASTER; + enum masterFlags arg; + int n; + int ret=OK; + // int regret=OK; + + + sprintf(mess,"can't set master flags\n"); + + + n = receiveDataOnly(file_des,&arg,sizeof(arg)); + if (n < 0) { + sprintf(mess,"Error reading from socket\n"); + ret=FAIL; + } + + +#ifdef VERBOSE + printf("setting master flags to %d\n",arg); +#endif + + if (differentClients==1 && lockStatus==1 && arg!=GET_READOUT_FLAGS) { + ret=FAIL; + sprintf(mess,"Detector locked by %s\n",lastClientIP); + } else { + retval=setMaster(arg); + + } + if (retval==GET_MASTER) { + ret=FAIL; + } + n = sendDataOnly(file_des,&ret,sizeof(ret)); + if (ret==FAIL) { + n = sendDataOnly(file_des,mess,sizeof(mess)); + } else { + n = sendDataOnly(file_des,&retval,sizeof(retval)); + } + return ret; +} + + + + + + +int set_synchronization(int file_des) { + + enum synchronizationMode retval=GET_MASTER; + enum synchronizationMode arg; + int n; + int ret=OK; + //int regret=OK; + + + sprintf(mess,"can't set synchronization mode\n"); + + + n = receiveDataOnly(file_des,&arg,sizeof(arg)); + if (n < 0) { + sprintf(mess,"Error reading from socket\n"); + ret=FAIL; + } +#ifdef VERBOSE + printf("setting master flags to %d\n",arg); +#endif + + if (differentClients==1 && lockStatus==1 && arg!=GET_READOUT_FLAGS) { + ret=FAIL; + sprintf(mess,"Detector locked by %s\n",lastClientIP); + } else { + //ret=setStoreInRAM(0); + // initChipWithProbes(0,0,0, ALLMOD); + retval=setSynchronization(arg); + } + if (retval==GET_SYNCHRONIZATION_MODE) { + ret=FAIL; + } + n = sendDataOnly(file_des,&ret,sizeof(ret)); + if (ret==FAIL) { + n = sendDataOnly(file_des,mess,sizeof(mess)); + } else { + n = sendDataOnly(file_des,&retval,sizeof(retval)); + } + return ret; +} + + + + + + +int read_counter_block(int file_des) { + + int ret=OK; + int n; + int startACQ; + //char *retval=NULL; + short int CounterVals[NCHAN*NCHIP]; + + sprintf(mess,"Read counter block failed\n"); + + n = receiveDataOnly(file_des,&startACQ,sizeof(startACQ)); + if (n < 0) { + sprintf(mess,"Error reading from socket\n"); + ret=FAIL; + } + + if (ret==OK) { + if (differentClients==1 && lockStatus==1) { + ret=FAIL; + sprintf(mess,"Detector locked by %s\n",lastClientIP); + } else{ + ret=readCounterBlock(startACQ,CounterVals); +#ifdef VERBOSE + int i; + for(i=0;i<6;i++) + printf("%d:%d\t",i,CounterVals[i]); +#endif + } + } + + if(ret!=FAIL){ + if (differentClients) + ret=FORCE_UPDATE; + } + + /* send answer */ + /* send OK/failed */ + n = sendDataOnly(file_des,&ret,sizeof(ret)); + if (ret!=FAIL) { + /* send return argument */ + n += sendDataOnly(file_des,CounterVals,dataBytes);//1280*2 + } else { + n += sendDataOnly(file_des,mess,sizeof(mess)); + } + + /*return ok/fail*/ + return ret; +} + + + + + +int reset_counter_block(int file_des) { + + int ret=OK; + int n; + int startACQ; + + sprintf(mess,"Reset counter block failed\n"); + + n = receiveDataOnly(file_des,&startACQ,sizeof(startACQ)); + if (n < 0) { + sprintf(mess,"Error reading from socket\n"); + ret=FAIL; + } + + if (ret==OK) { + if (differentClients==1 && lockStatus==1) { + ret=FAIL; + sprintf(mess,"Detector locked by %s\n",lastClientIP); + } else + ret=resetCounterBlock(startACQ); + } + + if(ret==OK){ + if (differentClients) + ret=FORCE_UPDATE; + } + + /* send answer */ + /* send OK/failed */ + n = sendDataOnly(file_des,&ret,sizeof(ret)); + if (ret==FAIL) + n += sendDataOnly(file_des,mess,sizeof(mess)); + + /*return ok/fail*/ + return ret; +} + + + + + + +int start_receiver(int file_des) { + int ret=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; + } + + /* send answer */ + n = sendDataOnly(file_des,&ret,sizeof(ret)); + if(ret==FAIL) + n = sendDataOnly(file_des,mess,sizeof(mess)); + /*return ok/fail*/ + return ret; +} + + + + + + +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; + } + + /* send answer */ + n = sendDataOnly(file_des,&ret,sizeof(ret)); + if(ret==FAIL) + n = sendDataOnly(file_des,mess,sizeof(mess)); + /*return ok/fail*/ + return ret; +} + + + + + +int calibrate_pedestal(int file_des){ + + int ret=OK; + int retval=-1; + int n; + int frames; + + sprintf(mess,"Could not calibrate pedestal\n"); + + n = receiveDataOnly(file_des,&frames,sizeof(frames)); + if (n < 0) { + sprintf(mess,"Error reading from socket\n"); + ret=FAIL; + } + + if (ret==OK) { + if (differentClients==1 && lockStatus==1) { + ret=FAIL; + sprintf(mess,"Detector locked by %s\n",lastClientIP); + } else + ret=calibratePedestal(frames); + } + + if(ret==OK){ + if (differentClients) + ret=FORCE_UPDATE; + } + + /* send answer */ + /* send OK/failed */ + n = sendDataOnly(file_des,&ret,sizeof(ret)); + if (ret==FAIL) + n += sendDataOnly(file_des,mess,sizeof(mess)); + else + n += sendDataOnly(file_des,&retval,sizeof(retval)); + + /*return ok/fail*/ + return ret; +} + + +int set_ctb_pattern(int file_des){ + + int ret=FAIL; + int retval=-1; + int n; + int mode; + uint64_t word, retval64, t; + int addr; + int level, start, stop, nl; + + sprintf(mess,"Could not set pattern\n"); + + n = receiveDataOnly(file_des,&mode,sizeof(mode)); + switch (mode) { + + case 0: //sets word + n = receiveDataOnly(file_des,&addr,sizeof(addr)); + n = receiveDataOnly(file_des,&word,sizeof(word)); + ret=OK; + + switch (addr) { + case -1: + retval64=writePatternIOControl(word); + break; + case -2: + retval64=writePatternClkControl(word); + break; + default: + retval64=writePatternWord(addr,word); + }; + + + //write word; + //@param addr address of the word, -1 is I/O control register, -2 is clk control register + //@param word 64bit word to be written, -1 gets + + n = sendDataOnly(file_des,&ret,sizeof(ret)); + if (ret==FAIL) + n += sendDataOnly(file_des,mess,sizeof(mess)); + else + n += sendDataOnly(file_des,&retval64,sizeof(retval64)); + break; + + case 1: //pattern loop + n = receiveDataOnly(file_des,&level,sizeof(level)); + n = receiveDataOnly(file_des,&start,sizeof(start)); + n = receiveDataOnly(file_des,&stop,sizeof(stop)); + n = receiveDataOnly(file_des,&nl,sizeof(nl)); + + + /** Sets the pattern or loop limits in the CTB + @param level -1 complete pattern, 0,1,2, loop level + @param start start address if >=0 + @param stop stop address if >=0 + @param n number of loops (if level >=0) + @returns OK/FAIL + */ + ret=setPatternLoop(level, &start, &stop, &nl); + + n = sendDataOnly(file_des,&ret,sizeof(ret)); + if (ret==FAIL) + n += sendDataOnly(file_des,mess,sizeof(mess)); + else { + n += sendDataOnly(file_des,&start,sizeof(start)); + n += sendDataOnly(file_des,&stop,sizeof(stop)); + n += sendDataOnly(file_des,&nl,sizeof(nl)); + } + break; + + + + case 2: //wait address + n = receiveDataOnly(file_des,&level,sizeof(level)); + n = receiveDataOnly(file_des,&addr,sizeof(addr)); + + + + /** Sets the wait address in the CTB + @param level 0,1,2, wait level + @param addr wait address, -1 gets + @returns actual value + */ + retval=setPatternWaitAddress(level,addr); + ret=OK; + if (ret==FAIL) + n += sendDataOnly(file_des,mess,sizeof(mess)); + else { + n += sendDataOnly(file_des,&retval,sizeof(retval)); + + } + + + break; + + + case 3: //wait time + n = receiveDataOnly(file_des,&level,sizeof(level)); + n = receiveDataOnly(file_des,&t,sizeof(t)); + + + /** Sets the wait time in the CTB + @param level 0,1,2, wait level + @param t wait time, -1 gets + @returns actual value + */ + + ret=OK; + + retval64=setPatternWaitTime(level,t); + + n = sendDataOnly(file_des,&ret,sizeof(ret)); + if (ret==FAIL) + n += sendDataOnly(file_des,mess,sizeof(mess)); + else + n += sendDataOnly(file_des,&retval64,sizeof(retval64)); + + break; + + + default: + ret=FAIL; + sprintf(mess,"%s - wrong mode %d\n",mess, mode); + n = sendDataOnly(file_des,&ret,sizeof(ret)); + n += sendDataOnly(file_des,mess,sizeof(mess)); + + + + } + + + /*return ok/fail*/ + return ret; +} + + diff --git a/slsDetectorSoftware/jungfrauDetectorServer/server_funcs.h b/slsDetectorSoftware/jungfrauDetectorServer/server_funcs.h new file mode 100755 index 000000000..29e5a3032 --- /dev/null +++ b/slsDetectorSoftware/jungfrauDetectorServer/server_funcs.h @@ -0,0 +1,98 @@ +#ifndef SERVER_FUNCS_H +#define SERVER_FUNCS_H + + +#include "sls_detector_defs.h" + + +#include +/* +#include +#include +#include +*/ +#include "communication_funcs.h" + + + + +#define GOODBYE -200 + +int sockfd; + +int function_table(); + +int decode_function(int); +int init_detector(int,int); + +int M_nofunc(int); +int exit_server(int); + + + + +// General purpose functions +int get_detector_type(int); +int set_number_of_modules(int); +int get_max_number_of_modules(int); + + +int exec_command(int); +int set_external_signal_flag(int); +int set_external_communication_mode(int); +int get_id(int); +int digital_test(int); +int write_register(int); +int read_register(int); +int set_dac(int); +int get_adc(int); +int set_channel(int); +int set_chip(int); +int set_module(int); +int get_channel(int); +int get_chip(int); +int get_module(int); + +int get_threshold_energy(int); +int set_threshold_energy(int); +int set_settings(int); +int start_acquisition(int); +int stop_acquisition(int); +int start_readout(int); +int get_run_status(int); +int read_frame(int); +int read_all(int); +int start_and_read_all(int); +int set_timer(int); +int get_time_left(int); +int set_dynamic_range(int); +int set_roi(int); +int get_roi(int); +int set_speed(int); +void prepareADC(void); +int set_readout_flags(int); +int execute_trimming(int); +int lock_server(int); +int set_port(int); +int get_last_client_ip(int); +int set_master(int); +int set_synchronization(int); + +int update_client(int); +int send_update(int); +int configure_mac(int); + +int load_image(int); +int read_counter_block(int); +int reset_counter_block(int); + +int start_receiver(int); +int stop_receiver(int); + + +int calibrate_pedestal(int); + +int set_roi(int); +int set_ctb_pattern(int); + +#endif diff --git a/slsDetectorSoftware/jungfrauDetectorServer/sharedmemory.c b/slsDetectorSoftware/jungfrauDetectorServer/sharedmemory.c new file mode 100755 index 000000000..4504cfe05 --- /dev/null +++ b/slsDetectorSoftware/jungfrauDetectorServer/sharedmemory.c @@ -0,0 +1,39 @@ +#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 new file mode 100755 index 000000000..bdbddf719 --- /dev/null +++ b/slsDetectorSoftware/jungfrauDetectorServer/sharedmemory.h @@ -0,0 +1,48 @@ +#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/jungfrauDetectorServer/sls_detector_defs.h b/slsDetectorSoftware/jungfrauDetectorServer/sls_detector_defs.h new file mode 120000 index 000000000..c5062e03f --- /dev/null +++ b/slsDetectorSoftware/jungfrauDetectorServer/sls_detector_defs.h @@ -0,0 +1 @@ +../commonFiles/sls_detector_defs.h \ No newline at end of file diff --git a/slsDetectorSoftware/jungfrauDetectorServer/sls_detector_funcs.h b/slsDetectorSoftware/jungfrauDetectorServer/sls_detector_funcs.h new file mode 120000 index 000000000..844b67129 --- /dev/null +++ b/slsDetectorSoftware/jungfrauDetectorServer/sls_detector_funcs.h @@ -0,0 +1 @@ +../commonFiles/sls_detector_funcs.h \ No newline at end of file diff --git a/slsDetectorSoftware/jungfrauDetectorServer/sls_receiver_defs.h b/slsDetectorSoftware/jungfrauDetectorServer/sls_receiver_defs.h new file mode 120000 index 000000000..a07bf98e7 --- /dev/null +++ b/slsDetectorSoftware/jungfrauDetectorServer/sls_receiver_defs.h @@ -0,0 +1 @@ +../../slsReceiverSoftware/includes/sls_receiver_defs.h \ No newline at end of file diff --git a/slsDetectorSoftware/jungfrauDetectorServer/sls_receiver_funcs.h b/slsDetectorSoftware/jungfrauDetectorServer/sls_receiver_funcs.h new file mode 120000 index 000000000..67df52bf4 --- /dev/null +++ b/slsDetectorSoftware/jungfrauDetectorServer/sls_receiver_funcs.h @@ -0,0 +1 @@ +../../slsReceiverSoftware/includes/sls_receiver_funcs.h \ No newline at end of file diff --git a/slsDetectorSoftware/jungfrauDetectorServer/stop_server.c b/slsDetectorSoftware/jungfrauDetectorServer/stop_server.c new file mode 100755 index 000000000..e3c8ff7e1 --- /dev/null +++ b/slsDetectorSoftware/jungfrauDetectorServer/stop_server.c @@ -0,0 +1,46 @@ +/* A simple server in the internet domain using TCP + The port number is passed as an argument */ + + +#include "sls_detector_defs.h" + + +#include "communication_funcs.h" +#include "firmware_funcs.h" + + +int sockfd; + +int main(int argc, char *argv[]) +{ + int portno; + int retval=0; + + portno = DEFAULT_PORTNO; + + + bindSocket(portno); + if (getServerError()) + return -1; + + + + /* waits for connection */ + while(retval!=GOODBYE) { +#ifdef VERBOSE + printf("\n"); +#endif +#ifdef VERY_VERBOSE + printf("Stop server: waiting for client call\n"); +#endif + acceptConnection(); + retval=stopStateMachine(); + closeConnection(); + } + + exitServer(); + printf("Goodbye!\n"); + + return 0; +} + diff --git a/slsDetectorSoftware/jungfrauDetectorServer/trimming_funcs.c b/slsDetectorSoftware/jungfrauDetectorServer/trimming_funcs.c new file mode 100755 index 000000000..9a28b9b4a --- /dev/null +++ b/slsDetectorSoftware/jungfrauDetectorServer/trimming_funcs.c @@ -0,0 +1,749 @@ +#ifndef PICASSOD +#include "server_defs.h" +#else +#include "picasso_defs.h" +#endif +#include "trimming_funcs.h" +#include "mcb_funcs.h" +#include "firmware_funcs.h" +#include + + + +extern int nModX; +//extern int *values; + +extern const int nChans; +extern const int nChips; +extern const int nDacs; +extern const int nAdcs; + + +int trim_fixed_settings(int countlim, int par2, int im) +{ + + int retval=OK; +#ifdef VERBOSE + printf("Trimming with fixed settings\n"); +#endif +#ifdef VIRTUAL + return OK; +#endif + + if (par2<=0) + retval=trim_with_level(countlim, im); + else + retval=trim_with_median(countlim,im); + + + return retval; +} + + +int trim_with_noise(int countlim, int nsigma, int im) +{ + + + int retval=OK, retval1=OK, retval2=OK; +#ifdef VERBOSE + printf("Trimming using noise\n"); +#endif +#ifdef VIRTUAL + return OK; +#endif + + /* threshold scan */ + +#ifdef VERBOSE + printf("chosing vthresh and vtrim....."); +#endif + retval1=choose_vthresh_and_vtrim(countlim,nsigma, im); + +#ifdef VERBOSE + printf("trimming with noise.....\n"); +#endif + retval2=trim_with_level(countlim, im); + +#ifdef DEBUGOUT + printf("done\n"); +#endif + if (retval1==OK && retval2==OK) + retval=OK; + else + retval=FAIL; + + return retval; + +} + +int trim_with_beam(int countlim, int nsigma, int im) //rpc +{ + + + int retval=OK, retval1=OK, retval2=OK; + + printf("Trimming using beam\n"); + //return OK; +#ifdef VIRTUAL + printf("Trimming using beam\n"); + return OK; +#endif + /* threshold scan */ +#ifdef DEBUGOUT + printf("chosing vthresh and vtrim....."); +#endif + + retval1=choose_vthresh_and_vtrim(countlim,nsigma,im); + retval2=trim_with_median(TRIM_DR, im); + +#ifdef DEBUGOUT + printf("done\n"); +#endif + + if (retval1==OK && retval2==OK) + retval=OK; + else + retval=FAIL; + + return retval; + +} + + +int trim_improve(int maxit, int par2, int im) //rpc +{ + + int retval=OK, retval1=OK, retval2=OK; + + +#ifdef VERBOSE + printf("Improve the trimming\n"); +#endif +#ifdef VIRTUAL + return OK; +#endif + + + if (par2!=0 && im==ALLMOD) + retval1=choose_vthresh(); + + retval2=trim_with_median(2*maxit+1, im); +#ifdef DEBUGOUT + printf("done\n"); +#endif + if (retval1==OK && retval2==OK) + retval=OK; + else + retval=FAIL; + + return retval; + +} + +int calcthr_from_vcal(int vcal) { + int thrmin; + //thrmin=140+3*vcal/5; + thrmin=180+3*vcal/5; + return thrmin; +} + +int calccal_from_vthr(int vthr) { + int vcal; + vcal=5*(vthr-140)/3; + return vcal; +} + +int choose_vthresh_and_vtrim(int countlim, int nsigma, int im) { + int retval=OK; +#ifdef MCB_FUNCS + int modma, modmi, nm; + int thr, thrstep=5, nthr=31; + + int *fifodata; + + double vthreshmean, vthreshSTDev; + int *thrmi, *thrma; + double c; + double b=BVTRIM; + double a=AVTRIM; + int *trim; + int ich, imod, ichan; + int nvalid=0; + u_int32_t *scan; + int ithr; + sls_detector_channel myChan; + + + + setFrames(1); + // setNMod(getNModBoard()); + + if (im==ALLMOD){ + modmi=0; + modma=nModX; + } else { + modmi=im; + modma=im+1; + } + nm=modma-modmi; + + trim=malloc(sizeof(int)*nChans*nChips*nModX); + thrmi=malloc(sizeof(int)*nModX); + thrma=malloc(sizeof(int)*nModX); + + + for (ich=0; ichcountlim && trim[ich]==-1) { +//commented out by dhanya trim[ich]=getDACbyIndexDACU(VTHRESH,imod); +#ifdef VERBOSE + // printf("yes: %d %d %d\n",ich,ithr,scan[ich]); +#endif + } +#ifdef VERBOSE + /* else { + printf("no: %d %d %d\n",ich,ithr,scan[ich]); + }*/ +#endif + } + } + free(scan); + } + + for (imod=modmi; imodthrmi[imod] && trim[ich]0) { + vthreshmean=vthreshmean/nvalid; + //commented out by dhanya vthreshSTDev=sqrt((vthreshSTDev/nvalid)-vthreshmean*vthreshmean); + } else { + vthreshmean=thrmi[imod]; + vthreshSTDev=nthr*thrstep; + printf("No valid channel for module %d\n",imod); + retval=FAIL; + } + +#ifdef DEBUGOUT + printf("module= %d nvalid = %d mean=%f RMS=%f\n",imod, nvalid, vthreshmean,vthreshSTDev); +#endif + // *vthresh=round(vthreshmean-nsigma*vthreshSTDev); + thr=(int)(vthreshmean-nsigma*vthreshSTDev); + if (thr<0 || thr>(DAC_DR-1)) { + thr=thrmi[imod]/2; + printf("Can't find correct threshold for module %d\n",imod); + retval=FAIL; + } +//commented out by dhanya initDACbyIndexDACU(VTHRESH,thr,imod); +#ifdef VERBOSE + printf("vthresh=%d \n",thr); +#endif + c=CVTRIM-2.*nsigma*vthreshSTDev/63.; + //commented out by dhanya thr=(int)((-b-sqrt(b*b-4*a*c))/(2*a)); + if (thr<500 || thr>(DAC_DR-1)) { + thr=750; + printf("Can't find correct trimbit size for module %d\n",imod); + retval=FAIL; + } + + //commented out by dhanya initDACbyIndexDACU(VTRIM,thr,imod); + +#ifdef VERBOSE + printf("vtrim=%d \n",thr); +#endif + + } + free(trim); + free(thrmi); + free(thrma); + +#endif + return retval; +} + + + + + +int trim_with_level(int countlim, int im) { + int ich, itrim, ichan, ichip, imod; + u_int32_t *scan; + int *inttrim; + int modma, modmi, nm; + int retval=OK; + int *fifodata; + sls_detector_channel myChan; + printf("trimming module number %d", im); + + +#ifdef MCB_FUNCS + setFrames(1); + // setNMod(getNModBoard()); + + if (im==ALLMOD){ + modmi=0; + modma=nModX; + } else { + modmi=im; + modma=im+1; + } + nm=modma-modmi; + + inttrim=malloc(sizeof(int)*nChips*nChans*nModX); + printf("countlim=%d\n",countlim); + for (ich=0; ichcountlim){ + inttrim[ich]=itrim; + if (scan[ich]>2*countlim && itrim>0) { + //if (scan[ich]>2*countlim || itrim==0) { + inttrim[ich]=itrim-1; + } +#ifdef VERBOSE + printf("Channel %d trimbit %d counted %d (%08x) countlim %d\n",ich,itrim,scan[ich],fifodata[ich],countlim); +#endif + } + } +#ifdef VERBOSE + /* else + printf("Channel %d trimbit %d counted %d countlim %d\n",ich,itrim,scan[ich],countlim);*/ +#endif + } + } + free(scan); + } + + for (imod=modmi; imod0) + direction[ichan]=1; + else + direction[ichan]=-1; + } + //commented out by dhanya vthresh=getDACbyIndexDACU(VTHRESH,imod); + if ( direction[ichan]!=-3) { + if (abs(diff)>abs(olddiff[ichan])) { + vthresh=vthresh-direction[ichan]; + if (vthresh>(DAC_DR-1)) { + vthresh=(DAC_DR-1); + printf("can't equalize threshold for module %d\n", ichan); + retval=FAIL; + } + if (vthresh<0) { + vthresh=0; + printf("can't equalize threshold for module %d\n", ichan); + retval=FAIL; + } + direction[ichan]=-3; + } else { + vthresh=vthresh+direction[ichan]; + olddiff[ichan]=diff; + change_flag=1; + } +//commented out by dhanya initDACbyIndex(VTHRESH,vthresh, ichan); + } + } + iteration++; + free(scan); + free(scan1); + } +#endif + return retval; +} + + + + + +int trim_with_median(int stop, int im) { + + + int retval=OK; + +#ifdef MCB_FUNCS + int ichan, imod, ichip, ich; + u_int32_t *scan, *scan1; + int *olddiff, *direction; + int med, diff; + int change_flag=1; + int iteration=0; + int me[nModX], me1[nModX]; + int modma, modmi, nm; + int trim; + int *fifodata; + + setFrames(1); + // setNMod(getNModBoard()); + + if (im==ALLMOD){ + modmi=0; + modma=nModX; + } else { + modmi=im; + modma=im+1; + } + nm=modma-modmi; + + olddiff=malloc(4*nModX*nChips*nChans); + direction=malloc(4*nModX*nChips*nChans); + for (imod=modmi; imod0) { + direction[ichan]=1; + } else { + direction[ichan]=-1; + } + } + if ( direction[ichan]!=-3) { + if (abs(diff)>abs(olddiff[ichan])) { + trim=getTrimbit(imod,ichip,ich)+direction[ichan]; + printf("%d old diff %d < new diff %d %d - trimbit %d\n",ichan, olddiff[ichan], diff, direction[ichan], trim); + direction[ichan]=-3; + } else { + trim=getTrimbit(imod,ichip,ich)-direction[ichan]; + olddiff[ichan]=diff; + change_flag=1; + } + if (trim>TRIM_DR) { + trim=63; + printf("can't trim channel %d chip %d module %d to trim %d\n",ich, ichip, imod, trim); + retval=FAIL; + } + if (trim<0) { + printf("can't trim channel %d chip %d module %d to trim %d\n",ich, ichip, imod, trim); + trim=0; + retval=FAIL; + } + initChannel(trim,0,0,1,0,0,imod); + } + } + } + } + iteration++; + free(scan); + free(scan1); + } + free(olddiff); + free(direction); +#endif + return retval; +} diff --git a/slsDetectorSoftware/jungfrauDetectorServer/trimming_funcs.h b/slsDetectorSoftware/jungfrauDetectorServer/trimming_funcs.h new file mode 100755 index 000000000..42ecea24a --- /dev/null +++ b/slsDetectorSoftware/jungfrauDetectorServer/trimming_funcs.h @@ -0,0 +1,20 @@ +#ifndef TRIMMING_FUNCS_H +#define TRIMMING_FUNCS_H + +#include "sls_detector_defs.h" + +int trim_fixed_settings(int countlim, int par2, int imod); +int trim_with_noise(int countlim, int nsigma, int imod); +int trim_with_beam(int countlim, int nsigma, int imod); +int trim_improve(int maxit, int par2, int imod); +int calcthr_from_vcal(int vcal); +int calccal_from_vthr(int vthr); +int choose_vthresh_and_vtrim(int countlim, int nsigma, int imod); + +int choose_vthresh(); +int trim_with_level(int countlim, int imod); +int trim_with_median(int stop, int imod); +int calcthr_from_vcal(int vcal); +int calccal_from_vthr(int vthr); + +#endif diff --git a/slsDetectorSoftware/moenchDetectorServer/gitInfo.txt b/slsDetectorSoftware/moenchDetectorServer/gitInfo.txt index 2b8b24fce..256e019d7 100644 --- a/slsDetectorSoftware/moenchDetectorServer/gitInfo.txt +++ b/slsDetectorSoftware/moenchDetectorServer/gitInfo.txt @@ -1,9 +1,9 @@ Path: slsDetectorsPackage/slsDetectorSoftware/moenchDetectorServer URL: origin git@gitorious.psi.ch:sls_det_software/sls_detector_software.git/moenchDetectorServer Repository Root: origin git@gitorious.psi.ch:sls_det_software/sls_detector_software.git -Repsitory UUID: c31619c88e5690230fcd389dc18f9139295c442c -Revision: 58 +Repsitory UUID: ce7cd6255b7b3abf1c046e9703ae8288ec55135a +Revision: 62 Branch: master Last Changed Author: Maliakal_Dhanya -Last Changed Rev: 280 -Last Changed Date: 2014-09-09 15:43:18 +0200 +Last Changed Rev: 282 +Last Changed Date: 2014-10-16 13:49:56 +0200 diff --git a/slsDetectorSoftware/moenchDetectorServer/gitInfoMoench.h b/slsDetectorSoftware/moenchDetectorServer/gitInfoMoench.h index a7ca6266d..2940f7e04 100644 --- a/slsDetectorSoftware/moenchDetectorServer/gitInfoMoench.h +++ b/slsDetectorSoftware/moenchDetectorServer/gitInfoMoench.h @@ -1,11 +1,11 @@ //#define SVNPATH "" #define SVNURL "git@gitorious.psi.ch:sls_det_software/sls_detector_software.git/moenchDetectorServer" //#define SVNREPPATH "" -#define SVNREPUUID "c31619c88e5690230fcd389dc18f9139295c442c" -//#define SVNREV 0x280 +#define SVNREPUUID "ce7cd6255b7b3abf1c046e9703ae8288ec55135a" +//#define SVNREV 0x282 //#define SVNKIND "" //#define SVNSCHED "" #define SVNAUTH "Maliakal_Dhanya" -#define SVNREV 0x280 -#define SVNDATE 0x20140909 +#define SVNREV 0x282 +#define SVNDATE 0x20141016 // diff --git a/slsDetectorSoftware/moenchDetectorServer/server_funcs.c b/slsDetectorSoftware/moenchDetectorServer/server_funcs.c index d047802ef..b0d8d56ab 100755 --- a/slsDetectorSoftware/moenchDetectorServer/server_funcs.c +++ b/slsDetectorSoftware/moenchDetectorServer/server_funcs.c @@ -2629,7 +2629,7 @@ int update_client(int file_des) { int configure_mac(int file_des) { int ret=OK; - char arg[5][50]; + char arg[6][50]; int n; int imod=0;//should be in future sent from client as -1, arg[2] @@ -2654,7 +2654,7 @@ int configure_mac(int file_des) { sscanf(arg[2], "%x", &udpport); sscanf(arg[3], "%llx", &idetectormacadd); sscanf(arg[4], "%x", &detipad); - +//arg[5] is for eiger #ifdef VERBOSE int i; printf("\ndigital_test_bit in server %d\t",digitalTestBit); diff --git a/slsDetectorSoftware/multiSlsDetector/multiSlsDetector.cpp b/slsDetectorSoftware/multiSlsDetector/multiSlsDetector.cpp index ab6d85ba8..19ce49714 100644 --- a/slsDetectorSoftware/multiSlsDetector/multiSlsDetector.cpp +++ b/slsDetectorSoftware/multiSlsDetector/multiSlsDetector.cpp @@ -351,56 +351,71 @@ int multiSlsDetector::addSlsDetector(int id, int pos) { void multiSlsDetector::updateOffsets(){ - int offsetX=0,offsetY=0,numX,numY; - int maxChanX = thisMultiDetector->maxNumberOfChannelsPerDetector[X]; - int maxChanY = thisMultiDetector->maxNumberOfChannelsPerDetector[Y]; - cout << "Updating multi detector offsets" << endl; - thisMultiDetector->numberOfChannel[X] = 0; - thisMultiDetector->maxNumberOfChannel[X] = 0; - thisMultiDetector->numberOfChannel[Y] = 0; - thisMultiDetector->maxNumberOfChannel[Y] = 0; - for (int i=0; inumberOfDetectors; i++) { - if (detectors[i]) { - thisMultiDetector->offsetX[i] = offsetX; - thisMultiDetector->offsetY[i] = offsetY; + cout << endl << "Updating multi detector offsets" << endl; - cout << "Detector at position: " << i << " x offset:" << offsetX << " y offset:" << offsetY << endl; + int offsetX=0, offsetY=0, numX=0, numY=0, maxX=0, maxY=0; + int maxChanX = thisMultiDetector->maxNumberOfChannelsPerDetector[X]; + int maxChanY = thisMultiDetector->maxNumberOfChannelsPerDetector[Y]; + thisMultiDetector->numberOfChannel[X] = 0; + thisMultiDetector->maxNumberOfChannel[X] = 0; + thisMultiDetector->numberOfChannel[Y] = 0; + thisMultiDetector->maxNumberOfChannel[Y] = 0; - numX = detectors[i]->getMaxNumberOfChannels(X); - numY = detectors[i]->getMaxNumberOfChannels(Y); + //0th position + if (detectors[0]){ + offsetX = thisMultiDetector->offsetX[0] = 0; + offsetY = thisMultiDetector->offsetY[0] = 0; + numX = thisMultiDetector->numberOfChannel[X] = detectors[0]->getTotalNumberOfChannels(X); + numY = thisMultiDetector->numberOfChannel[Y] = detectors[0]->getTotalNumberOfChannels(Y); + maxX = thisMultiDetector->maxNumberOfChannel[X] = detectors[0]->getMaxNumberOfChannels(X); + maxY = thisMultiDetector->maxNumberOfChannel[Y] = detectors[0]->getMaxNumberOfChannels(Y); - offsetX += numX; - if ((maxChanX == -1) || ((maxChanX > 0) && (offsetX < maxChanX))){ - thisMultiDetector->numberOfChannel[X] += detectors[i]->getTotalNumberOfChannels(X); - thisMultiDetector->maxNumberOfChannel[X] += numX; - //the first time y should be added but offset not increased - if (thisMultiDetector->numberOfChannel[Y] == 0){ - if ((maxChanY == -1) || ((maxChanY > 0) && (numY < maxChanY))){ - thisMultiDetector->numberOfChannel[Y] += detectors[i]->getTotalNumberOfChannels(Y); - thisMultiDetector->maxNumberOfChannel[Y] += numY; - }else{ - cout<<"Detector at position " << i << "exceeds maximum channels allowed for complete detector set in y dimension also!" << endl; - thisMultiDetector->numberOfChannel[Y] += detectors[i]->getTotalNumberOfChannels(Y); - thisMultiDetector->maxNumberOfChannel[Y] += numY; - } - } - }else{ - offsetX = 0; - thisMultiDetector->numberOfChannel[X] = 0; - thisMultiDetector->maxNumberOfChannel[X] = 0; - offsetY += numY; - if ((maxChanY == -1) || ((maxChanY > 0) && (offsetY < maxChanY))){ - thisMultiDetector->numberOfChannel[Y] += detectors[i]->getTotalNumberOfChannels(Y); - thisMultiDetector->maxNumberOfChannel[Y] += numY; - }else{ - cout<<"Detector at position " << i << "exceeds maximum channels allowed for complete detector set in y dimension also!" << endl; - thisMultiDetector->numberOfChannel[Y] += detectors[i]->getTotalNumberOfChannels(Y); - thisMultiDetector->maxNumberOfChannel[Y] += numY; - } - } - } - } + cout << "Detector at position 0: x offset:" << offsetX << " y offset:" << offsetY << endl; + } + + for (int i=1; inumberOfDetectors; i++) { + if (detectors[i]) { + //incrementing in x direction + if ((maxChanX == -1) || ((maxChanX > 0) && ((offsetX + numX) < maxChanX))){ + offsetX += detectors[i]->getMaxNumberOfChannels(X); + maxX += detectors[i]->getMaxNumberOfChannels(X); + numX += detectors[i]->getTotalNumberOfChannels(X); + } + //incrementing in y direction + else{ + offsetX = 0; + numX = 0; + maxX = 0; + thisMultiDetector->maxNumberOfChannel[X] = 0; + offsetY += detectors[i]->getMaxNumberOfChannels(Y); + if ((maxChanY == -1) || ((maxChanY > 0) && (offsetY <= maxChanY))){ + numY += detectors[i]->getTotalNumberOfChannels(Y); + maxY += detectors[i]->getMaxNumberOfChannels(Y); + }else{ + cout<<"Detector at position " << i << "exceeds maximum channels allowed for complete detector set in y dimension also!" << endl; + numY += detectors[i]->getTotalNumberOfChannels(Y); + maxY += detectors[i]->getMaxNumberOfChannels(Y); + } + } + + thisMultiDetector->offsetX[i] = offsetX; + thisMultiDetector->offsetY[i] = offsetY; + cout << "Detector at position: " << i << " x offset:" << thisMultiDetector->offsetX[i] << " y offset:" << thisMultiDetector->offsetY[i] << endl; + if(numX > thisMultiDetector->numberOfChannel[X]) + thisMultiDetector->numberOfChannel[X] = numX; + if(numY > thisMultiDetector->numberOfChannel[Y]) + thisMultiDetector->numberOfChannel[Y] = numY; + if(maxX > thisMultiDetector->maxNumberOfChannel[X]) + thisMultiDetector->maxNumberOfChannel[X] = maxX; + if(maxY > thisMultiDetector->maxNumberOfChannel[Y]) + thisMultiDetector->maxNumberOfChannel[Y] = maxY; + } + } + + + cout << "Number of Channels in X direction:" << thisMultiDetector->numberOfChannel[X] << endl; + cout << "Number of Channels in Y direction:" << thisMultiDetector->numberOfChannel[Y] << endl << endl; } string multiSlsDetector::setHostname(const char* name, int pos){ @@ -1182,6 +1197,7 @@ int multiSlsDetector::startAcquisition(){ int i=0; int ret=OK, ret1=OK; + for (i=0; inumberOfDetectors; i++) { if (i!=thisMultiDetector->masterPosition) if (detectors[i]) { @@ -1213,6 +1229,8 @@ int multiSlsDetector::stopAcquisition(){ int i=0; int ret=OK, ret1=OK; + + i=thisMultiDetector->masterPosition; if (thisMultiDetector->masterPosition>=0) { @@ -1447,7 +1465,7 @@ int* multiSlsDetector::startAndReadAll(){ if (detectors[id]) { detectors[id]->disconnectControl(); } - } + } } @@ -1488,6 +1506,7 @@ int multiSlsDetector::startAndReadAllNoWait(){ ret1=FAIL; } } + return ret1; } @@ -1509,20 +1528,16 @@ slsDetectorDefs::runStatus multiSlsDetector::getRunStatus() { return s; } - if (detectors[0]){ - s=detectors[0]->getRunStatus(); - if(detectors[0]->getErrorMask()) - setErrorMask(getErrorMask()|(1<<0)); - } - - for (int i=1; inumberOfDetectors; i++) { + for (int i=0; inumberOfDetectors; i++) { s1=detectors[i]->getRunStatus(); if(detectors[i]->getErrorMask()) setErrorMask(getErrorMask()|(1<numberOfChannels=0; for (int id=0; id< thisMultiDetector->numberOfDetectors; id++) thisMultiDetector->numberOfChannels+=detectors[id]->getTotalNumberOfChannels(); return thisMultiDetector->numberOfChannels;}; - int multiSlsDetector::getTotalNumberOfChannels(dimension d){thisMultiDetector->numberOfChannel[d]=0; for (int id=0; id< thisMultiDetector->numberOfDetectors; id++) thisMultiDetector->numberOfChannel[d]+=detectors[id]->getTotalNumberOfChannels(d); return thisMultiDetector->numberOfChannel[d];}; + //int multiSlsDetector::getTotalNumberOfChannels(dimension d){thisMultiDetector->numberOfChannel[d]=0; for (int id=0; id< thisMultiDetector->numberOfDetectors; id++) thisMultiDetector->numberOfChannel[d]+=detectors[id]->getTotalNumberOfChannels(d); return thisMultiDetector->numberOfChannel[d];}; + int multiSlsDetector::getTotalNumberOfChannels(dimension d){updateOffsets();return thisMultiDetector->numberOfChannel[d];}; int multiSlsDetector::getMaxNumberOfChannels(){thisMultiDetector->maxNumberOfChannels=0; for (int id=0; id< thisMultiDetector->numberOfDetectors; id++) thisMultiDetector->maxNumberOfChannels+=detectors[id]->getMaxNumberOfChannels();return thisMultiDetector->maxNumberOfChannels;}; - int multiSlsDetector::getMaxNumberOfChannels(dimension d){thisMultiDetector->maxNumberOfChannel[d]=0; for (int id=0; id< thisMultiDetector->numberOfDetectors; id++) thisMultiDetector->maxNumberOfChannel[d]+=detectors[id]->getMaxNumberOfChannels(d);return thisMultiDetector->maxNumberOfChannel[d];}; + // int multiSlsDetector::getMaxNumberOfChannels(dimension d){thisMultiDetector->maxNumberOfChannel[d]=0; for (int id=0; id< thisMultiDetector->numberOfDetectors; id++) thisMultiDetector->maxNumberOfChannel[d]+=detectors[id]->getMaxNumberOfChannels(d);return thisMultiDetector->maxNumberOfChannel[d];}; + int multiSlsDetector::getMaxNumberOfChannels(dimension d){updateOffsets();return thisMultiDetector->maxNumberOfChannel[d];}; @@ -4814,3 +4831,126 @@ int multiSlsDetector::enableTenGigabitEthernet(int i){ } return ret; } + + + + + /** opens pattern file and sends pattern to CTB + @param fname pattern file to open + @returns OK/FAIL + */ +int multiSlsDetector::setCTBPattern(string fname) { + + + + + +} + + + /** Writes a pattern word to the CTB + @param addr address of the word, -1 is I/O control register, -2 is clk control register + @param word 64bit word to be written, -1 gets + @returns actual value + */ +uint64_t multiSlsDetector::setCTBWord(int addr,uint64_t word) { + uint64_t ret=-100,ret1; + for (int idet=0; idetnumberOfDetectors; idet++) + if (detectors[idet]){ + ret1=detectors[idet]->setCTBWord(addr, word); + if(detectors[idet]->getErrorMask()) + setErrorMask(getErrorMask()|(1<=0 + @param stop stop address if >=0 + @param n number of loops (if level >=0) + @returns OK/FAIL + */ +int multiSlsDetector::setCTBPatLoops(int level,int &start, int &stop, int &n) { + + + int ret=-100,ret1; + for (int idet=0; idetnumberOfDetectors; idet++) + if (detectors[idet]){ + ret1=detectors[idet]->setCTBPatLoops(level, start, stop, n); + if(detectors[idet]->getErrorMask()) + setErrorMask(getErrorMask()|(1<numberOfDetectors; idet++) + if (detectors[idet]){ + ret1=detectors[idet]->setCTBPatWaitAddr(level, addr); + if(detectors[idet]->getErrorMask()) + setErrorMask(getErrorMask()|(1<numberOfDetectors; idet++) + if (detectors[idet]){ + ret1=detectors[idet]->setCTBPatWaitTime(level,t); + if(detectors[idet]->getErrorMask()) + setErrorMask(getErrorMask()|(1<=0 + @param stop stop address if >=0 + @param n number of loops (if level >=0) + @returns OK/FAIL + */ + int setCTBPatLoops(int level,int &start, int &stop, int &n); + + + /** Sets the wait address in the CTB + @param level 0,1,2, wait level + @param addr wait address, -1 gets + @returns actual value + */ + int setCTBPatWaitAddr(int level, int addr=-1); + + /** Sets the wait time in the CTB + @param level 0,1,2, wait level + @param t wait time, -1 gets + @returns actual value + */ + int setCTBPatWaitTime(int level, uint64_t t=-1); + + + + + + + + + + + + + + protected: diff --git a/slsDetectorSoftware/mythenDetectorServer/gitInfo.txt b/slsDetectorSoftware/mythenDetectorServer/gitInfo.txt index 6f4d00d95..54d7cdf89 100644 --- a/slsDetectorSoftware/mythenDetectorServer/gitInfo.txt +++ b/slsDetectorSoftware/mythenDetectorServer/gitInfo.txt @@ -1,9 +1,9 @@ Path: slsDetectorsPackage/slsDetectorSoftware/mythenDetectorServer URL: origin git@gitorious.psi.ch:sls_det_software/sls_detector_software.git/mythenDetectorServer Repository Root: origin git@gitorious.psi.ch:sls_det_software/sls_detector_software.git -Repsitory UUID: c31619c88e5690230fcd389dc18f9139295c442c -Revision: 90 +Repsitory UUID: ce7cd6255b7b3abf1c046e9703ae8288ec55135a +Revision: 91 Branch: master Last Changed Author: Maliakal_Dhanya -Last Changed Rev: 280 -Last Changed Date: 2014-09-09 15:43:18 +0200 +Last Changed Rev: 282 +Last Changed Date: 2014-10-16 13:49:56 +0200 diff --git a/slsDetectorSoftware/mythenDetectorServer/gitInfoMythen.h b/slsDetectorSoftware/mythenDetectorServer/gitInfoMythen.h index cf8494ed2..2ac5f41bf 100644 --- a/slsDetectorSoftware/mythenDetectorServer/gitInfoMythen.h +++ b/slsDetectorSoftware/mythenDetectorServer/gitInfoMythen.h @@ -1,11 +1,11 @@ //#define SVNPATH "" #define SVNURL "git@gitorious.psi.ch:sls_det_software/sls_detector_software.git/mythenDetectorServer" //#define SVNREPPATH "" -#define SVNREPUUID "c31619c88e5690230fcd389dc18f9139295c442c" -//#define SVNREV 0x280 +#define SVNREPUUID "ce7cd6255b7b3abf1c046e9703ae8288ec55135a" +//#define SVNREV 0x282 //#define SVNKIND "" //#define SVNSCHED "" #define SVNAUTH "Maliakal_Dhanya" -#define SVNREV 0x280 -#define SVNDATE 0x20140909 +#define SVNREV 0x282 +#define SVNDATE 0x20141016 // diff --git a/slsDetectorSoftware/patternGenerator/generate.sh b/slsDetectorSoftware/patternGenerator/generate.sh new file mode 100755 index 000000000..ca44e565c --- /dev/null +++ b/slsDetectorSoftware/patternGenerator/generate.sh @@ -0,0 +1,20 @@ +if [ "$#" -eq 0 ]; then + echo "Wrong number of arguments: usage should be $0 patname" + exit 1 +fi +infile=$1 +outfile=$infile"at" +if [ "$#" -ge 2 ]; then + outfile=$2 +fi +exe=$infile"exe" +if [ "$#" -ge 3 ]; then + exe=$3 +fi + +if [ -f "$infile" ] +then +gcc -DINFILE="\"$infile\"" -DOUTFILE="\"$outfile\"" -o $exe generator.c ; ./$exe ; rm $exe +else + echo "$infile not found." +fi diff --git a/slsDetectorSoftware/patternGenerator/generator.c b/slsDetectorSoftware/patternGenerator/generator.c new file mode 100755 index 000000000..6c66cda92 --- /dev/null +++ b/slsDetectorSoftware/patternGenerator/generator.c @@ -0,0 +1,160 @@ +/**************************************************************************** +usage to generate a patter test.pat from test.p + +gcc -DINFILE="\"test.p\"" -DOUTFILE="\"test.pat\"" -o test.exe generator.c ; ./test.exe ; rm test.exe + + +*************************************************************************/ + +#include /* exit() */ +#include /* exit() */ +#include /* memset(), memcpy() */ +#include /* uname() */ +#include +#include /* fork(), write(), close() */ +#include +#include +#include +#include +#include +#include +#include +#include +#include +//#include + +#define MAXLOOPS 3 +#define MAXTIMERS 3 +#define MAXWORDS 1024 + + + +uint64_t pat=0; +uint64_t iopat=0; +uint64_t clkpat=0; + +int iaddr=0; +int waitaddr[3]={-1,-1,-1}; +int startloopaddr[3]={-1,-1,-1}; +int stoploopaddr[3]={-1,-1,-1}; +int start=0, stop=0; +uint64_t waittime[3]={0,0,0}; +int nloop[3]={0,0,0}; + +char infile[10000], outfile[10000]; + +FILE *fd; + +int i,ii,iii,j,jj,jjj,pixx,pixy,memx,memy,muxout,memclk,colclk,rowclk,muxclk,memcol,memrow,loopcounter; +//int W[33]; +//u_int32_t W; + +void setstart() { + start=iaddr; +} + +void setstop() { + stop=iaddr; +} + +void setinput(int bit) { + uint64_t mask=1; + mask=mask<>bit; +} + +void setstartloop(int iloop) { + if (iloop>=0 && iloop=0 && iloop=0 && iloop=0 && iloop=0 && iloop=MAXWORDS) printf("ERROR: too many word in the pattern (%d instead of %d)!",iaddr, MAXWORDS); +} + +main(void) { + int iloop=0; + fd=fopen(OUTFILE,"w"); + +#include INFILE + + fprintf(fd,"patctrl %016llx\n",iopat); + fprintf(fd,"patclkctrl %016llx\n",clkpat); + fprintf(fd,"patlimits %04x %04x\n",start, stop); + + for (iloop=0; iloopreceiverTCPPort=DEFAULT_PORTNO+2; /** set receiver udp port */ thisDetector->receiverUDPPort=DEFAULT_UDP_PORTNO; + /** set receiver udp port for Eiger */ + thisDetector->receiverUDPPort2=DEFAULT_UDP_PORTNO+1; /** set receiver ip address/hostname */ strcpy(thisDetector->receiver_hostname,"none"); /** set receiver udp ip address */ @@ -4838,6 +4840,15 @@ char* slsDetector::setNetworkParameter(networkParameter index, string value) { sscanf(value.c_str(),"%d",&i); setReceiverUDPPort(i); return getReceiverUDPPort(); + case RECEIVER_UDP_PORT2: + sscanf(value.c_str(),"%d",&i); + if(thisDetector->myDetectorType == EIGER) + setReceiverUDPPort2(i); + else + setReceiverUDPPort(i); + if(thisDetector->myDetectorType == EIGER) + return getReceiverUDPPort2(); + return getReceiverUDPPort(); default: return ("unknown network parameter"); } @@ -4867,6 +4878,9 @@ char* slsDetector::getNetworkParameter(networkParameter index) { case RECEIVER_UDP_PORT: return getReceiverUDPPort(); break; + case RECEIVER_UDP_PORT2: + return getReceiverUDPPort2(); + break; default: return ("unknown network parameter"); } @@ -5012,14 +5026,17 @@ int slsDetector::setReceiverUDPPort(int udpport){ return thisDetector->receiverUDPPort; } - +int slsDetector::setReceiverUDPPort2(int udpport){ + thisDetector->receiverUDPPort2 = udpport; + return thisDetector->receiverUDPPort2; +} int slsDetector::setUDPConnection(){ int ret = FAIL; int fnum = F_SETUP_RECEIVER_UDP; - char args[2][MAX_STR_LENGTH]; + char args[3][MAX_STR_LENGTH]; char retval[MAX_STR_LENGTH]=""; @@ -5043,9 +5060,11 @@ int slsDetector::setUDPConnection(){ //copy arguments to args[][] strcpy(args[0],thisDetector->receiverUDPIP); sprintf(args[1],"%d",thisDetector->receiverUDPPort); + sprintf(args[2],"%d",thisDetector->receiverUDPPort2); #ifdef VERBOSE std::cout << "Receiver udp ip address: " << thisDetector->receiverUDPIP << std::endl; std::cout << "Receiver udp port: " << thisDetector->receiverUDPPort << std::endl; + std::cout << "Receiver udp port2: " << thisDetector->receiverUDPPort2 << std::endl; #endif //set up receiver for UDP Connection and get receivermac address @@ -5084,7 +5103,7 @@ int slsDetector::configureMAC(){ int ret=FAIL; int fnum=F_CONFIGURE_MAC,fnum2=F_RECEIVER_SHORT_FRAME; char mess[100]; - char arg[5][50]; + char arg[6][50]; char cword[50]="", *pcword; string sword; int retval=-1; @@ -5112,6 +5131,7 @@ int slsDetector::configureMAC(){ sprintf(arg[2],"%x",thisDetector->receiverUDPPort); strcpy(arg[3],thisDetector->detectorMAC); strcpy(arg[4],thisDetector->detectorIP); + sprintf(arg[5],"%x",thisDetector->receiverUDPPort2); #ifdef VERBOSE std::cout<< "Configuring MAC"<< std::endl; @@ -5174,6 +5194,9 @@ int slsDetector::configureMAC(){ #ifdef VERBOSE std::cout<<"detector ip:"<onlineFlag==ONLINE_FLAG) { @@ -6769,3 +6792,233 @@ int slsDetector::enableTenGigabitEthernet(int i){ thisDetector->tenGigaEnable=retval; return retval; } + + + + /******** CTB funcs */ + + /** opens pattern file and sends pattern to CTB + @param fname pattern file to open + @returns OK/FAIL + */ +int slsDetector::setCTBPattern(string fname) { + + + int fnum=F_SET_CTB_PATTERN; + int ret = FAIL; + char retval[MAX_STR_LENGTH]=""; + + +// if(setReceiverOnline(ONLINE_FLAG)==ONLINE_FLAG){ +// #ifdef VERBOSE +// std::cout << "Sending detector hostname to Receiver " << thisDetector->hostname << std::endl; +// #endif +// if (connectData() == OK) +// ret=thisReceiver->sendString(fnum,retval,thisDetector->hostname); +// if((ret==FAIL) || (strcmp(retval,thisDetector->hostname))) +// setErrorMask((getErrorMask())|(RECEIVER_DET_HOSTNAME_NOT_SET)); +// } + + return ret; + + +} + + + /** Writes a pattern word to the CTB + @param addr address of the word, -1 is I/O control register, -2 is clk control register + @param word 64bit word to be written, -1 gets + @returns actual value + */ +uint64_t slsDetector::setCTBWord(int addr,uint64_t word) { + + //uint64_t ret; + + int ret=FAIL; + uint64_t retval=-1; + int fnum=F_SET_CTB_PATTERN; + int mode=0; //sets word + + char mess[100]; + +#ifdef VERBOSE + std::cout<<"Setting CTB word" <onlineFlag==ONLINE_FLAG) { + if (connectControl() == OK){ + controlSocket->SendDataOnly(&fnum,sizeof(fnum)); + controlSocket->SendDataOnly(&mode,sizeof(mode)); + controlSocket->SendDataOnly(&addr,sizeof(addr)); + controlSocket->SendDataOnly(&word,sizeof(word)); + controlSocket->ReceiveDataOnly(&ret,sizeof(ret)); + if (ret!=FAIL) + controlSocket->ReceiveDataOnly(&retval,sizeof(retval)); + else { + controlSocket->ReceiveDataOnly(mess,sizeof(mess)); + std::cout<< "Detector returned error: " << mess << std::endl; + } + controlSocket->Disconnect(); + if (ret==FORCE_UPDATE) + updateDetector(); + } + } + + return retval; + + +} + + /** 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 + */ +int slsDetector::setCTBPatLoops(int level,int &start, int &stop, int &n) { + + + int retval[3], args[4]; + + args[0]=level; + args[1]=start; + args[2]=stop; + args[3]=n; + + + int ret=FAIL; + int fnum=F_SET_CTB_PATTERN; + int mode=1; //sets loop + + char mess[100]; + +#ifdef VERBOSE + std::cout<<"Setting CTB word" <onlineFlag==ONLINE_FLAG) { + if (connectControl() == OK){ + controlSocket->SendDataOnly(&fnum,sizeof(fnum)); + controlSocket->SendDataOnly(&mode,sizeof(mode)); + controlSocket->SendDataOnly(&args,sizeof(args)); + controlSocket->ReceiveDataOnly(&ret,sizeof(ret)); + if (ret!=FAIL) { + controlSocket->ReceiveDataOnly(&retval,sizeof(retval)); + start=retval[0]; + stop=retval[1]; + n=retval[2]; + } else { + controlSocket->ReceiveDataOnly(mess,sizeof(mess)); + std::cout<< "Detector returned error: " << mess << std::endl; + } + controlSocket->Disconnect(); + if (ret==FORCE_UPDATE) + updateDetector(); + } + } + + return ret; + + +} + + + /** Sets the wait address in the CTB + @param level 0,1,2, wait level + @param addr wait address, -1 gets + @returns actual value + */ +int slsDetector::setCTBPatWaitAddr(int level, int addr) { + + + + + int retval=-1; + + + int ret=FAIL; + int fnum=F_SET_CTB_PATTERN; + int mode=3; //sets loop + + char mess[100]; + +#ifdef VERBOSE + std::cout<<"Setting CTB word" <onlineFlag==ONLINE_FLAG) { + if (connectControl() == OK){ + controlSocket->SendDataOnly(&fnum,sizeof(fnum)); + controlSocket->SendDataOnly(&mode,sizeof(mode)); + controlSocket->SendDataOnly(&level,sizeof(level)); + controlSocket->SendDataOnly(&addr,sizeof(addr)); + controlSocket->ReceiveDataOnly(&ret,sizeof(ret)); + if (ret!=FAIL) { + controlSocket->ReceiveDataOnly(&retval,sizeof(retval)); + } else { + controlSocket->ReceiveDataOnly(mess,sizeof(mess)); + std::cout<< "Detector returned error: " << mess << std::endl; + } + controlSocket->Disconnect(); + if (ret==FORCE_UPDATE) + updateDetector(); + } + } + + return retval; + + + +} + + /** Sets the wait time in the CTB + @param level 0,1,2, wait level + @param t wait time, -1 gets + @returns actual value + */ +int slsDetector::setCTBPatWaitTime(int level, uint64_t t) { + + + + + + uint64_t retval=-1; + + + int ret=FAIL; + // uint64_t retval=-1; + int fnum=F_SET_CTB_PATTERN; + int mode=4; //sets loop + + char mess[100]; + +#ifdef VERBOSE + std::cout<<"Setting CTB word" <onlineFlag==ONLINE_FLAG) { + if (connectControl() == OK){ + controlSocket->SendDataOnly(&fnum,sizeof(fnum)); + controlSocket->SendDataOnly(&mode,sizeof(mode)); + controlSocket->SendDataOnly(&level,sizeof(level)); + controlSocket->SendDataOnly(&t,sizeof(t)); + controlSocket->ReceiveDataOnly(&ret,sizeof(ret)); + if (ret!=FAIL) { + controlSocket->ReceiveDataOnly(&retval,sizeof(retval)); + } else { + controlSocket->ReceiveDataOnly(mess,sizeof(mess)); + std::cout<< "Detector returned error: " << mess << std::endl; + } + controlSocket->Disconnect(); + if (ret==FORCE_UPDATE) + updateDetector(); + } + } + + return retval; + + +} + + diff --git a/slsDetectorSoftware/slsDetector/slsDetector.h b/slsDetectorSoftware/slsDetector/slsDetector.h index 6ffb42c04..593834a60 100644 --- a/slsDetectorSoftware/slsDetector/slsDetector.h +++ b/slsDetectorSoftware/slsDetector/slsDetector.h @@ -240,6 +240,8 @@ class slsDetector : public slsDetectorUtils, public energyConversion { int receiverTCPPort; /** is the port used to communicate between detector and the receiver*/ int receiverUDPPort; + /** is the port used to communicate between second half module of Eiger detector and the receiver*/ + int receiverUDPPort2; /** ip address of the receiver for the detector to send packets to**/ char receiverUDPIP[MAX_STR_LENGTH]; /** mac address of receiver for the detector to send packets to **/ @@ -1603,6 +1605,8 @@ class slsDetector : public slsDetectorUtils, public energyConversion { char* getReceiverUDPMAC() {return thisDetector->receiverUDPMAC;}; /** returns the receiver UDP IP address \sa sharedSlsDetector */ char* getReceiverUDPPort() {char *c= new char[MAX_STR_LENGTH];sprintf(c,"%d",thisDetector->receiverUDPPort); return c;}; + /** returns the receiver UDP2 for Eiger IP address \sa sharedSlsDetector */ + char* getReceiverUDPPort2() {char *c= new char[MAX_STR_LENGTH];sprintf(c,"%d",thisDetector->receiverUDPPort2); return c;}; /** validates the format of detector MAC address and sets it \sa sharedSlsDetector */ char* setDetectorMAC(string detectorMAC); @@ -1616,6 +1620,8 @@ class slsDetector : public slsDetectorUtils, public energyConversion { char* setReceiverUDPMAC(string udpmac); /** sets the receiver udp port \sa sharedSlsDetector */ int setReceiverUDPPort(int udpport); + /** sets the receiver udp port2 for Eiger \sa sharedSlsDetector */ + int setReceiverUDPPort2(int udpport); /** Sets the read receiver frequency if Receiver read upon gui request, readRxrFrequency=0, @@ -1644,6 +1650,48 @@ class slsDetector : public slsDetectorUtils, public energyConversion { */ int enableTenGigabitEthernet(int i = -1); + + /******** CTB funcs */ + + /** opens pattern file and sends pattern to CTB + @param fname pattern file to open + @returns OK/FAIL + */ + int setCTBPattern(string fname); + + + /** Writes a pattern word to the CTB + @param addr address of the word, -1 is I/O control register, -2 is clk control register + @param word 64bit word to be written, -1 gets + @returns actual value + */ + uint64_t setCTBWord(int addr,uint64_t word=-1); + + /** Sets the pattern or loop limits in the CTB + @param level -1 complete pattern, 0,1,2, loop level + @param start start address if >=0 + @param stop stop address if >=0 + @param n number of loops (if level >=0) + @returns OK/FAIL + */ + int setCTBPatLoops(int level,int &start, int &stop, int &n); + + + /** Sets the wait address in the CTB + @param level 0,1,2, wait level + @param addr wait address, -1 gets + @returns actual value + */ + int setCTBPatWaitAddr(int level, int addr=-1); + + /** Sets the wait time in the CTB + @param level 0,1,2, wait level + @param t wait time, -1 gets + @returns actual value + */ + int setCTBPatWaitTime(int level, uint64_t t=-1); + + protected: diff --git a/slsDetectorSoftware/slsDetector/slsDetectorBase.h b/slsDetectorSoftware/slsDetector/slsDetectorBase.h index d543b0281..554adeefe 100644 --- a/slsDetectorSoftware/slsDetector/slsDetectorBase.h +++ b/slsDetectorSoftware/slsDetector/slsDetectorBase.h @@ -519,6 +519,8 @@ class slsDetectorBase : public virtual slsDetectorDefs, public virtual errorDef case GOTTHARD: return string("Gotthard"); \ case AGIPD: return string("Agipd"); \ case MOENCH: return string("Moench"); \ + case JUNGFRAU: return string("Jungfrau"); \ + case JUNGFRAUCTB: return string("JungfrauCTB"); \ default: return string("Unknown"); \ }}; @@ -533,6 +535,8 @@ class slsDetectorBase : public virtual slsDetectorDefs, public virtual errorDef if (type=="Gotthard") return GOTTHARD; \ if (type=="Agipd") return AGIPD; \ if (type=="Moench") return MOENCH; \ + if (type=="Jungfrau") return JUNGFRAU; \ + if (type=="JungfrauCTB") return JUNGFRAUCTB; \ return GENERIC;}; diff --git a/slsDetectorSoftware/slsDetector/slsDetectorCommand.cpp b/slsDetectorSoftware/slsDetector/slsDetectorCommand.cpp index cee4a387c..33faa40c9 100644 --- a/slsDetectorSoftware/slsDetector/slsDetectorCommand.cpp +++ b/slsDetectorSoftware/slsDetector/slsDetectorCommand.cpp @@ -344,6 +344,10 @@ slsDetectorCommand::slsDetectorCommand(slsDetectorUtils *det) { descrToFuncMap[i].m_pFuncPtr=&slsDetectorCommand::cmdNetworkParameter; i++; + descrToFuncMap[i].m_pFuncName="rx_udpport2"; // + descrToFuncMap[i].m_pFuncPtr=&slsDetectorCommand::cmdNetworkParameter; + i++; + descrToFuncMap[i].m_pFuncName="detectormac"; // descrToFuncMap[i].m_pFuncPtr=&slsDetectorCommand::cmdNetworkParameter; i++; @@ -865,6 +869,97 @@ slsDetectorCommand::slsDetectorCommand(slsDetectorUtils *det) { i++; + /* pattern generator */ + + + descrToFuncMap[i].m_pFuncName="pattern"; // + descrToFuncMap[i].m_pFuncPtr=&slsDetectorCommand::cmdPattern; + i++; + + + descrToFuncMap[i].m_pFuncName="patword"; // + descrToFuncMap[i].m_pFuncPtr=&slsDetectorCommand::cmdPattern; + i++; + + + descrToFuncMap[i].m_pFuncName="patioctrl"; // + descrToFuncMap[i].m_pFuncPtr=&slsDetectorCommand::cmdPattern; + i++; + + + descrToFuncMap[i].m_pFuncName="patclkctrl"; // + descrToFuncMap[i].m_pFuncPtr=&slsDetectorCommand::cmdPattern; + i++; + + + descrToFuncMap[i].m_pFuncName="patlimits"; // + descrToFuncMap[i].m_pFuncPtr=&slsDetectorCommand::cmdPattern; + i++; + + descrToFuncMap[i].m_pFuncName="patloop0"; // + descrToFuncMap[i].m_pFuncPtr=&slsDetectorCommand::cmdPattern; + i++; + + + descrToFuncMap[i].m_pFuncName="patnloop0"; // + descrToFuncMap[i].m_pFuncPtr=&slsDetectorCommand::cmdPattern; + i++; + + + descrToFuncMap[i].m_pFuncName="patwait0"; // + descrToFuncMap[i].m_pFuncPtr=&slsDetectorCommand::cmdPattern; + i++; + + + descrToFuncMap[i].m_pFuncName="patwaittime0"; // + descrToFuncMap[i].m_pFuncPtr=&slsDetectorCommand::cmdPattern; + i++; + + + descrToFuncMap[i].m_pFuncName="patloop1"; // + descrToFuncMap[i].m_pFuncPtr=&slsDetectorCommand::cmdPattern; + i++; + + + descrToFuncMap[i].m_pFuncName="patnloop1"; // + descrToFuncMap[i].m_pFuncPtr=&slsDetectorCommand::cmdPattern; + i++; + + + descrToFuncMap[i].m_pFuncName="patwait1"; // + descrToFuncMap[i].m_pFuncPtr=&slsDetectorCommand::cmdPattern; + i++; + + + descrToFuncMap[i].m_pFuncName="patwaittime1"; // + descrToFuncMap[i].m_pFuncPtr=&slsDetectorCommand::cmdPattern; + i++; + + + descrToFuncMap[i].m_pFuncName="patloop2"; // + descrToFuncMap[i].m_pFuncPtr=&slsDetectorCommand::cmdPattern; + i++; + + + descrToFuncMap[i].m_pFuncName="patnloop2"; // + descrToFuncMap[i].m_pFuncPtr=&slsDetectorCommand::cmdPattern; + i++; + + + descrToFuncMap[i].m_pFuncName="patwait2"; // + descrToFuncMap[i].m_pFuncPtr=&slsDetectorCommand::cmdPattern; + i++; + + + descrToFuncMap[i].m_pFuncName="patwaittime2"; // + descrToFuncMap[i].m_pFuncPtr=&slsDetectorCommand::cmdPattern; + i++; + + + + + + numberOfCommands=i; // #ifdef VERBOSE @@ -2464,6 +2559,12 @@ string slsDetectorCommand::cmdNetworkParameter(int narg, char *args[], int actio if (!(sscanf(args[1],"%d",&i))) return ("cannot parse argument") + string(args[1]); } + } else if (cmd=="rx_udpport2") { + t=RECEIVER_UDP_PORT2; + if (action==PUT_ACTION){ + if (!(sscanf(args[1],"%d",&i))) + return ("cannot parse argument") + string(args[1]); + } } else return ("unknown network parameter")+cmd; if (action==PUT_ACTION) @@ -2485,6 +2586,7 @@ string slsDetectorCommand::helpNetworkParameter(int narg, char *args[], int acti os << "rx_udpip ip \n sets receiver udp ip to ip"<< std::endl; os << "rx_udpmac mac \n sets receiver udp mac to mac"<< std::endl; os << "rx_udpport port \n sets receiver udp port to port"<< std::endl; + os << "rx_udpport2 port \n sets receiver udp port to port. For Eiger, it is the second half module and for other detectors, same as rx_udpport"<< std::endl; } if (action==GET_ACTION || action==HELP_ACTION) { os << "detectormac \n gets detector mac "<< std::endl; @@ -2492,6 +2594,8 @@ string slsDetectorCommand::helpNetworkParameter(int narg, char *args[], int acti os << "rx_hostname \n gets receiver ip "<< std::endl; os << "rx_udpmac \n gets receiver udp mac "<< std::endl; os << "rx_udpport \n gets receiver udp port "<< std::endl; + os << "rx_udpport2 \n gets receiver udp port. For Eiger, it is the second half module and for other detectors, same as rx_udpport"<< std::endl; + } return os.str(); @@ -4140,10 +4244,11 @@ string slsDetectorCommand::cmdReceiver(int narg, char *args[], int action) { string slsDetectorCommand::helpReceiver(int narg, char *args[], int action) { ostringstream os; - if (action==PUT_ACTION || action==HELP_ACTION) + if (action==PUT_ACTION || action==HELP_ACTION) { os << "receiver [status] \t starts/stops the receiver to listen to detector packets. - can be start or stop" << std::endl; os << "r_readfreq \t sets the gui read frequency of the receiver, 0 if gui requests frame, >0 if receiver sends every nth frame to gui" << std::endl; os << "tengiga \t sets system to be configure for 10Gbe if set to 1, else 1Gbe if set to 0" << std::endl; + } if (action==GET_ACTION || action==HELP_ACTION){ os << "receiver \t returns the status of receiver - can be running or idle" << std::endl; os << "framescaught \t returns the number of frames caught by receiver(average for multi)" << std::endl; @@ -4160,4 +4265,82 @@ string slsDetectorCommand::helpReceiver(int narg, char *args[], int action) { +} + +string slsDetectorCommand::helpPattern(int narg, char *args[], int action) { + + ostringstream os; + if (action==PUT_ACTION || action==HELP_ACTION) { + os << "pattern fname \t loads pattern file" << std::endl; + os << "patword addr word \t writes pattern word - only very advanced users!" << std::endl; + os << "patioctrl reg\t configures inputs/outputs of the chiptest board - only advanced users!" << std::endl; + os << "patclkctrl reg\t configures output clk enable of the chiptest board- only advanced users! " << std::endl; + os << "patlimits addr1 addr2\t defines pattern limits between addr1 and addr2" << std::endl; + os << "patloop0 addr1 adrr2 \t configures the limits of the 0 loop " << std::endl; + os << "patloop1 addr1 adrr2 \t configures the limits of the 1 loop " << std::endl; + os << "patloop2 addr1 adrr2 \t configures the limits of the 2 loop " << std::endl; + os << "patnloop0 n \t sets number of cycles of the 0 loop " << std::endl; + os << "patnloop1 n \t sets number of cycles of the 1 loop " << std::endl; + os << "patnloop2 n \t sets number of cycles of the 2 loop " << std::endl; + os << "patwait0 addr \t configures pattern wait 0 address " << std::endl; + os << "patwait1 addr \t configures pattern wait 1 address " << std::endl; + os << "patwait2 addr \t configures pattern wait 2 address " << std::endl; + os << "patwaittime0 nclk \t sets wait 0 waiting time in clock number " << std::endl; + os << "patwaittime1 nclk \t sets wait 1 waiting time in clock number " << std::endl; + os << "patwaittime2 nclk \t sets wait 2 waiting time in clock number " << std::endl; + } + if (action==GET_ACTION || action==HELP_ACTION){ + os << "pattern \t cannot get" << std::endl; + os << "patword \t cannot get" << std::endl; + os << "patioctrl \t returns inputs/outputs of the chiptest board - only advanced users!" << std::endl; + os << "patclkctrl\t returns output clk enable of the chiptest board- only advanced users! " << std::endl; + os << "patlimits \t returns pattern limits between addr1 and addr2" << std::endl; + os << "patloop0 \t returns the limits of the 0 loop " << std::endl; + os << "patloop1 \t returns the limits of the 1 loop " << std::endl; + os << "patloop2 \t returns the limits of the 2 loop " << std::endl; + os << "patnloop0 \t returns the number of cycles of the 0 loop " << std::endl; + os << "patnloop1 \t returns the number of cycles of the 1 loop " << std::endl; + os << "patnloop2 \t returns the number of cycles of the 2 loop " << std::endl; + os << "patwait0 \t returns the pattern wait 0 address " << std::endl; + os << "patwait1 \t returns the pattern wait 1 address " << std::endl; + os << "patwait2 \t returns the pattern wait 2 address " << std::endl; + os << "patwaittime0 \t returns the wait 0 waiting time in clock number " << std::endl; + os << "patwaittime1 \t returns the wait 1 waiting time in clock number " << std::endl; + os << "patwaittime2 \t returns the wait 2 waiting time in clock number " << std::endl; + + } + return os.str(); + +} + + +string slsDetectorCommand::cmdPattern(int narg, char *args[], int action) { + + /******** + + Must implement set ctb functions in slsDetector and multiSlsDetector + + **********/ + ostringstream os; + if (cmd=="pattern") ; + else if (cmd=="patword") ; + else if (cmd=="patioctrl") ; + else if (cmd=="patclkctrl") ; + else if (cmd=="patlimits") ; + else if (cmd=="patloop0") ; + else if (cmd=="patloop1") ; + else if (cmd=="patloop2") ; + else if (cmd=="patnloop0") ; + else if (cmd=="patnloop1") ; + else if (cmd=="patnloop2") ; + else if (cmd=="patwait0") ; + else if (cmd=="patwait1") ; + else if (cmd=="patwait2") ; + else if (cmd=="patwaittime0") ; + else if (cmd=="patwaittime1") ; + else if (cmd=="patwaittime2") ; + else return helpPattern(narg, args, action); + + return os.str(); + } diff --git a/slsDetectorSoftware/slsDetector/slsDetectorCommand.h b/slsDetectorSoftware/slsDetector/slsDetectorCommand.h index f6a791eab..22888c462 100644 --- a/slsDetectorSoftware/slsDetector/slsDetectorCommand.h +++ b/slsDetectorSoftware/slsDetector/slsDetectorCommand.h @@ -84,6 +84,7 @@ class slsDetectorCommand : public virtual slsDetectorDefs { static string helpEnablefwrite(int narg, char *args[], int action); static string helpOverwrite(int narg, char *args[], int action); static string helpReceiver(int narg, char *args[], int action); + static string helpPattern(int narg, char *args[], int action); @@ -155,6 +156,7 @@ class slsDetectorCommand : public virtual slsDetectorDefs { string cmdEnablefwrite(int narg, char *args[], int action); string cmdOverwrite(int narg, char *args[], int action); string cmdReceiver(int narg, char *args[], int action); + string cmdPattern(int narg, char *args[], int action); int numberOfCommands; diff --git a/slsDetectorSoftware/slsDetector/slsDetectorUtils.h b/slsDetectorSoftware/slsDetector/slsDetectorUtils.h index c2d50008f..46bf60726 100644 --- a/slsDetectorSoftware/slsDetector/slsDetectorUtils.h +++ b/slsDetectorSoftware/slsDetector/slsDetectorUtils.h @@ -702,12 +702,77 @@ virtual int enableReceiverCompression(int i = -1)=0; /returns if 10Gbe is enabled */ virtual int enableTenGigabitEthernet(int i = -1)=0; + + + + /******** CTB funcs */ + + /** opens pattern file and sends pattern to CTB + @param fname pattern file to open + @returns OK/FAIL + */ + virtual int setCTBPattern(string fname)=0; + + + /** Writes a pattern word to the CTB + @param addr address of the word, -1 is I/O control register, -2 is clk control register + @param word 64bit word to be written, -1 gets + @returns actual value + */ + virtual uint64_t setCTBWord(int addr,uint64_t word=-1)=0; + + /** 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 + */ + virtual int setCTBPatLoops(int level,int &start, int &stop, int &n)=0; + + + /** Sets the wait address in the CTB + @param level 0,1,2, wait level + @param addr wait address, -1 gets + @returns actual value + */ + virtual int setCTBPatWaitAddr(int level, int addr=-1)=0; + + /** Sets the wait time in the CTB + @param level 0,1,2, wait level + @param t wait time, -1 gets + @returns actual value + */ + virtual int setCTBPatWaitTime(int level, uint64_t t=-1)=0; + + + + + + + + + + + + + + + + + + + + + + + protected: - static const int64_t thisSoftwareVersion=0x20120124; + static const int64_t thisSoftwareVersion=0x20141013; diff --git a/slsDetectorSoftware/slsDetectorServer/slsDetectorFunctionList.h b/slsDetectorSoftware/slsDetectorServer/slsDetectorFunctionList.h index e21e69ded..cbe43b571 100644 --- a/slsDetectorSoftware/slsDetectorServer/slsDetectorFunctionList.h +++ b/slsDetectorSoftware/slsDetectorServer/slsDetectorFunctionList.h @@ -95,7 +95,7 @@ int executeTrimming(enum trimMode mode, int par1, int par2, int imod); #ifndef MYTHEND -int configureMAC(int ipad, long long int macad, long long int detectormacadd, int detipad, int udpport, int ival); +int configureMAC(int ipad, long long int macad, long long int detectormacadd, int detipad, int udpport, int udpport2, int ival); #endif #ifdef GOTTHARDD diff --git a/slsDetectorSoftware/slsDetectorServer/slsDetectorServer_funcs.c b/slsDetectorSoftware/slsDetectorServer/slsDetectorServer_funcs.c index f87a7d389..7737e2418 100755 --- a/slsDetectorSoftware/slsDetectorServer/slsDetectorServer_funcs.c +++ b/slsDetectorSoftware/slsDetectorServer/slsDetectorServer_funcs.c @@ -54,8 +54,8 @@ int init_detector(int b) { #endif }else{ Feb_Interface_FebInterface(); - Feb_Control_FebControl(); - printf("FEb control constructor done\n"); + Feb_Control_Init(); + // printf("FEb control constructor done\n"); /* Beb_Beb(-1); printf("BEB constructor done\n");*/ } @@ -2275,9 +2275,9 @@ int get_run_status(int file_des) { enum runStatus s; sprintf(mess,"getting run status\n"); -//#ifdef VERBOSE +#ifdef VERBOSE printf("Getting status\n"); -//#endif +#endif #ifdef SLS_DETECTOR_FUNCTION_LIST s= getRunStatus();printf("status:%d\n"); #endif @@ -2967,7 +2967,7 @@ int configure_mac(int file_des) { int retval=-100; int ret=OK,ret1=OK; - char arg[5][50]; + char arg[6][50]; int n; #ifndef MYTHEND @@ -2976,6 +2976,7 @@ int configure_mac(int file_des) { long long int imacadd; long long int idetectormacadd; int udpport; + int udpport2; int detipad; #endif @@ -2996,7 +2997,7 @@ int configure_mac(int file_des) { sscanf(arg[2], "%x", &udpport); sscanf(arg[3], "%llx", &idetectormacadd); sscanf(arg[4], "%x", &detipad); - + sscanf(arg[5], "%x", &udpport2); #ifdef SLS_DETECTOR_FUNCTION_LIST @@ -3006,7 +3007,7 @@ int configure_mac(int file_des) { printf("mess:%s\n",mess); } #endif -#ifdef VERBOSE + //#ifdef VERBOSE int i; /*printf("\ndigital_test_bit in server %d\t",digitalTestBit);for gotthard*/ printf("\nipadd %x\t",ipad); @@ -3019,9 +3020,10 @@ int configure_mac(int file_des) { for (i=0;i<6;i++) printf("detector mac adress %d is 0x%x \n",6-i,(unsigned int)(((idetectormacadd>>(8*i))&0xFF))); printf("detipad %x\n",detipad); + printf("udp port2:0x%x\n",udpport2); printf("\n"); printf("Configuring MAC of module %d at port %x\n", imod, udpport); -#endif + //#endif #ifdef SLS_DETECTOR_FUNCTION_LIST if (ret==OK) { @@ -3029,7 +3031,7 @@ int configure_mac(int file_des) { stopStateMachine(); } - retval=configureMAC(ipad,imacadd,idetectormacadd,detipad,udpport,0); /*digitalTestBit);*/ + retval=configureMAC(ipad,imacadd,idetectormacadd,detipad,udpport,udpport2,0); /*digitalTestBit);*/ if(retval==-1) ret=FAIL; } #endif diff --git a/slsDetectorSoftware/slsReceiverInterface/receiverInterface.cpp b/slsDetectorSoftware/slsReceiverInterface/receiverInterface.cpp index 3a1eaa384..b244cdadc 100644 --- a/slsDetectorSoftware/slsReceiverInterface/receiverInterface.cpp +++ b/slsDetectorSoftware/slsReceiverInterface/receiverInterface.cpp @@ -40,8 +40,8 @@ int receiverInterface::sendString(int fnum, char retval[], char arg[]){ -int receiverInterface::sendUDPDetails(int fnum, char retval[], char arg[2][MAX_STR_LENGTH]){ - char args[2][MAX_STR_LENGTH]; +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] = ""; diff --git a/slsDetectorSoftware/slsReceiverInterface/receiverInterface.h b/slsDetectorSoftware/slsReceiverInterface/receiverInterface.h index 2dd2221d2..27fbea6a1 100644 --- a/slsDetectorSoftware/slsReceiverInterface/receiverInterface.h +++ b/slsDetectorSoftware/slsReceiverInterface/receiverInterface.h @@ -56,7 +56,7 @@ public: * @param arg value to send * \returns success of operation */ - int sendUDPDetails(int fnum, char retval[], char arg[2][MAX_STR_LENGTH]); + int sendUDPDetails(int fnum, char retval[], char arg[3][MAX_STR_LENGTH]); /**