diff --git a/slsDetectorServers/eigerDetectorServer/Beb.c b/slsDetectorServers/eigerDetectorServer/Beb.c index dc4e139fa..7c20c2b40 100644 --- a/slsDetectorServers/eigerDetectorServer/Beb.c +++ b/slsDetectorServers/eigerDetectorServer/Beb.c @@ -1,12 +1,8 @@ - -/** - * @author Ian Johnson - * @version 1.0 - */ - - -//return reversed 1 means good, 0 means failed - +#include "xfs_types.h" +#include "xparameters.h" +#include "FebRegisterDefs.h" +#include "logger.h" +#include "Beb.h" #include @@ -14,46 +10,40 @@ #include #include #include - - - -#include "xfs_types.h" -#include "xparameters.h" -#include "FebRegisterDefs.h" - -#include "Beb.h" +#include +#include #define MAX(x, y) (((x) > (y)) ? (x) : (y)) - struct BebInfo beb_infos[10]; - int bebInfoSize = 0; +struct BebInfo beb_infos[10]; +int bebInfoSize = 0; - struct LocalLinkInterface ll_beb_local,* ll_beb; +struct LocalLinkInterface ll_beb_local,* ll_beb; - struct udp_header_type udp_header; +struct udp_header_type udp_header; - int Beb_send_ndata; - unsigned int Beb_send_buffer_size; - unsigned int* Beb_send_data_raw; - unsigned int* Beb_send_data; +int Beb_send_ndata; +unsigned int Beb_send_buffer_size; +unsigned int* Beb_send_data_raw; +unsigned int* Beb_send_data; - int Beb_recv_ndata; - unsigned int Beb_recv_buffer_size; - unsigned int* Beb_recv_data_raw; - unsigned int* Beb_recv_data; +int Beb_recv_ndata; +unsigned int Beb_recv_buffer_size; +unsigned int* Beb_recv_data_raw; +unsigned int* Beb_recv_data; - short Beb_bit_mode; - int BEB_MMAP_SIZE = 0x1000; +short Beb_bit_mode; +int BEB_MMAP_SIZE = 0x1000; - int Beb_activated = 1; +int Beb_activated = 1; - uint32_t Beb_detid = 0; - int Beb_top =0; +uint32_t Beb_detid = 0; +int Beb_top =0; -void BebInfo_BebInfo(struct BebInfo* bebInfo, unsigned int beb_num){ +void BebInfo_BebInfo(struct BebInfo* bebInfo, unsigned int beb_num) { bebInfo->beb_number=beb_num; bebInfo->serial_address=0; strcpy(bebInfo->src_mac_1GbE,""); @@ -64,18 +54,18 @@ void BebInfo_BebInfo(struct BebInfo* bebInfo, unsigned int beb_num){ } -int BebInfo_SetSerialAddress(struct BebInfo* bebInfo, unsigned int a){ - //address pre shifted - if(a>0xff) return 0; - bebInfo->serial_address = 0x04000000 | ((a&0xff)<<16); - return 1; +int BebInfo_SetSerialAddress(struct BebInfo* bebInfo, unsigned int a) { + //address pre shifted + if (a>0xff) return 0; + bebInfo->serial_address = 0x04000000 | ((a&0xff)<<16); + return 1; } -int BebInfo_SetHeaderInfo(struct BebInfo* bebInfo, int ten_gig, char* src_mac, char* src_ip, unsigned int src_port){ - if(ten_gig){ strcpy(bebInfo->src_mac_10GbE,src_mac); strcpy(bebInfo->src_ip_10GbE,src_ip); bebInfo->src_port_10GbE = src_port;} - else { strcpy(bebInfo->src_mac_1GbE,src_mac); strcpy(bebInfo->src_ip_1GbE,src_ip); bebInfo->src_port_1GbE = src_port;} - return 1; +int BebInfo_SetHeaderInfo(struct BebInfo* bebInfo, int ten_gig, char* src_mac, char* src_ip, unsigned int src_port) { + if (ten_gig) { strcpy(bebInfo->src_mac_10GbE,src_mac); strcpy(bebInfo->src_ip_10GbE,src_ip); bebInfo->src_port_10GbE = src_port;} + else { strcpy(bebInfo->src_mac_1GbE,src_mac); strcpy(bebInfo->src_ip_1GbE,src_ip); bebInfo->src_port_1GbE = src_port;} + return 1; } @@ -87,20 +77,29 @@ char* BebInfo_GetSrcIP(struct BebInfo* bebInfo, int ten_gig) {return ten_gig unsigned int BebInfo_GetSrcPort(struct BebInfo* bebInfo, int ten_gig) {return ten_gig ? bebInfo->src_port_10GbE : bebInfo->src_port_1GbE;} -void BebInfo_Print(struct BebInfo* bebInfo){ - printf("\t%d) Beb Info.\n",bebInfo->beb_number); - printf("\t\tSerial Add: 0x%x\n",bebInfo->serial_address); - printf("\t\tMAC 1GbE: %s\n",bebInfo->src_mac_1GbE); - printf("\t\tIP 1GbE: %s\n",bebInfo->src_ip_1GbE); - printf("\t\tport 1GbE: %d\n",bebInfo->src_port_1GbE); - printf("\t\tMAC 10GbE: %s\n",bebInfo->src_mac_10GbE); - printf("\t\tIP 10GbE: %s\n",bebInfo->src_ip_10GbE); - printf("\t\tport 10GbE: %d\n",bebInfo->src_port_10GbE); +void BebInfo_Print(struct BebInfo* bebInfo) { + FILE_LOG(logINFO, ( + "%d) Beb Info:\n" + "\tSerial Add: 0x%x\n" + "\tMAC 1GbE: %s\n" + "\tIP 1GbE: %s\n" + "\tPort 1GbE: %d\n" + "\tMAC 10GbE: %s\n" + "\tIP 10GbE: %s\n" + "\tPort 10GbE: %d\n", + bebInfo->beb_number, + bebInfo->serial_address, + bebInfo->src_mac_1GbE, + bebInfo->src_ip_1GbE, + bebInfo->src_port_1GbE, + bebInfo->src_mac_10GbE, + bebInfo->src_ip_10GbE, + bebInfo->src_port_10GbE)); } -void Beb_Beb(){ - +void Beb_Beb(int id) { + Beb_detid = id; Beb_send_ndata = 0; Beb_send_buffer_size = 1026; Beb_send_data_raw = malloc((Beb_send_buffer_size+1) * sizeof(unsigned int)); @@ -111,76 +110,76 @@ void Beb_Beb(){ Beb_recv_data_raw = malloc((Beb_recv_buffer_size+1) * sizeof(unsigned int)); Beb_recv_data = &Beb_recv_data_raw[1]; - udp_header= (struct udp_header_type){ - {0x00, 0x50, 0xc5, 0xb2, 0xcb, 0x46}, // DST MAC - {0x00, 0x50, 0xc2, 0x46, 0xd9, 0x02}, // SRC MAC - {0x08, 0x00}, - {0x45}, - {0x00}, - {0x00, 0x00}, - {0x00, 0x00}, - {0x40}, - {0x00}, - {0xff}, - {0x11}, - {0x00, 0x00}, - {129, 205, 205, 128}, // Src IP - {129, 205, 205, 122}, // Dst IP - {0x0f, 0xa1}, - {0x13, 0x89}, - {0x00, 0x00}, //{0x00, 0x11}, - {0x00, 0x00} - }; + udp_header= (struct udp_header_type) { + {0x00, 0x50, 0xc5, 0xb2, 0xcb, 0x46}, // DST MAC + {0x00, 0x50, 0xc2, 0x46, 0xd9, 0x02}, // SRC MAC + {0x08, 0x00}, + {0x45}, + {0x00}, + {0x00, 0x00}, + {0x00, 0x00}, + {0x40}, + {0x00}, + {0xff}, + {0x11}, + {0x00, 0x00}, + {129, 205, 205, 128}, // Src IP + {129, 205, 205, 122}, // Dst IP + {0x0f, 0xa1}, + {0x13, 0x89}, + {0x00, 0x00}, //{0x00, 0x11}, + {0x00, 0x00} + }; - if(!Beb_InitBebInfos()) exit(1); + if (!Beb_InitBebInfos()) exit(1); - printf("Printing Beb infos:\n"); - unsigned int i; - for(i=1;i 0) + if (fd > 0) Beb_close(fd,csp0base); return ret; } /* do not work at the moment */ -int Beb_SetSlaveViaSoftware(){ +int Beb_SetSlaveViaSoftware() { - if(!Beb_activated) + if (!Beb_activated) return 0; //mapping new memory @@ -347,66 +343,69 @@ int Beb_SetSlaveViaSoftware(){ //open file pointer int fd = Beb_open(&csp0base,XPAR_PLB_GPIO_SYS_BASEADDR); - if(fd < 0) - cprintf(BG_RED,"Set Slave FAIL\n"); - else{ + if (fd < 0) { + FILE_LOG(logERROR, ("Set Slave FAIL\n")); + } else { value = Beb_Read32(csp0base, MASTERCONFIG_OFFSET); value&=~MASTER_BIT; value|=OVERWRITE_HARDWARE_BIT; int newval = Beb_Write32(csp0base, MASTERCONFIG_OFFSET,value); - if(newval!=value) - cprintf(BG_RED,"Could not set Slave via Software\n"); - else + if (newval!=value) { + FILE_LOG(logERROR, ("Could not set Slave via Software\n")); + } else { ret = 0; + } } //close file pointer - if(fd > 0) + if (fd > 0) Beb_close(fd,csp0base); return ret; } -int Beb_Activate(int enable){ +int Beb_Activate(int enable) { //mapping new memory u_int32_t* csp0base=0; u_int32_t value = 0, ret = -1; //open file pointer int fd = Beb_open(&csp0base,XPAR_PLB_GPIO_SYS_BASEADDR); - if(fd < 0) - cprintf(BG_RED,"Deactivate FAIL\n"); - else{ - if(enable > -1){ + if (fd < 0) { + FILE_LOG(logERROR, ("Deactivate FAIL\n")); + } else { + if (enable > -1) { value = Beb_Read32(csp0base, MASTERCONFIG_OFFSET); - printf("Deactivate register value before:%d\n",value); - if(enable) + FILE_LOG(logINFO, ("Deactivate register value before:%d\n",value)); + if (enable) value&=~DEACTIVATE_BIT; else value|=DEACTIVATE_BIT; int newval = Beb_Write32(csp0base, MASTERCONFIG_OFFSET,value); - if(newval!=value){ - if(enable) - cprintf(BG_RED,"Could not activate via Software\n"); - else - cprintf(BG_RED,"Could not deactivate via Software\n"); + if (newval!=value) { + if (enable) { + FILE_LOG(logERROR, ("Could not activate via Software\n")); + } else { + FILE_LOG(logERROR, ("Could not deactivate via Software\n")); + } } } value = Beb_Read32(csp0base, MASTERCONFIG_OFFSET); - if(value&DEACTIVATE_BIT) ret = 0; + if (value&DEACTIVATE_BIT) ret = 0; else ret = 1; - if(enable == -1){ - if(ret) - cprintf(BLUE,"Detector is active. Register value:%d\n", value); - else - cprintf(BG_RED,"Detector is deactivated! Register value:%d\n", value); + if (enable == -1) { + if (ret) { + FILE_LOG(logINFOBLUE, ("Detector is active. Register value:%d\n", value)); + } else { + FILE_LOG(logERROR, ("Detector is deactivated! Register value:%d\n", value)); + } } } //close file pointer - if(fd > 0) + if (fd > 0) Beb_close(fd,csp0base); Beb_activated = ret; @@ -416,23 +415,23 @@ int Beb_Activate(int enable){ int Beb_Set32bitOverflow(int val) { - if(!Beb_activated) + if (!Beb_activated) return val; //mapping new memory u_int32_t* csp0base=0; u_int32_t valueread = 0; u_int32_t offset = FLOW_REG_OFFSET; - if(val>0) val = 1; + if (val>0) val = 1; //open file pointer int fd = Beb_open(&csp0base,XPAR_PLB_GPIO_SYS_BASEADDR); - if(fd < 0){ - cprintf(BG_RED,"Could not read register to set overflow flag in 32 bit mode. FAIL\n"); + if (fd < 0) { + FILE_LOG(logERROR, ("Could not read register to set overflow flag in 32 bit mode. FAIL\n")); return -1; } - else{ - if(val > -1){ + else { + if (val > -1) { // reset bit valueread = Beb_Read32(csp0base, offset); Beb_Write32(csp0base, offset,valueread & ~FLOW_REG_OVERFLOW_32_BIT_MSK); @@ -446,15 +445,15 @@ int Beb_Set32bitOverflow(int val) { valueread = (Beb_Read32(csp0base, offset) & FLOW_REG_OVERFLOW_32_BIT_MSK) >> FLOW_REG_OVERFLOW_32_BIT_OFST; } //close file pointer - if(fd > 0) + if (fd > 0) Beb_close(fd,csp0base); return valueread; } -int Beb_SetNetworkParameter(enum NETWORKINDEX mode, int val){ +int Beb_SetNetworkParameter(enum NETWORKINDEX mode, int val) { - if(!Beb_activated) + if (!Beb_activated) return val; @@ -464,7 +463,7 @@ int Beb_SetNetworkParameter(enum NETWORKINDEX mode, int val){ u_int32_t offset = TXM_DELAY_LEFT_OFFSET; char modename[100] = ""; - switch(mode){ + switch(mode) { case TXN_LEFT: offset = TXM_DELAY_LEFT_OFFSET; strcpy(modename,"Transmission Delay Left"); @@ -480,18 +479,18 @@ int Beb_SetNetworkParameter(enum NETWORKINDEX mode, int val){ case FLOWCTRL_10G: offset = FLOW_REG_OFFSET; strcpy(modename,"Flow Control for 10G"); - if(val>0) val = 1; + if (val>0) val = 1; break; - default: cprintf(BG_RED,"Unrecognized mode in network parameter: %d\n",mode); return -1; + default: FILE_LOG(logERROR, ("Unrecognized mode in network parameter: %d\n",mode)); return -1; } //open file pointer int fd = Beb_open(&csp0base,XPAR_PLB_GPIO_SYS_BASEADDR); - if(fd < 0){ - cprintf(BG_RED,"Could not read register to set network parameter. FAIL\n"); + if (fd < 0) { + FILE_LOG(logERROR, ("Could not read register to set network parameter. FAIL\n")); return -1; } - else{ - if(val > -1){ + else { + if (val > -1) { if (mode != FLOWCTRL_10G) { valueread = Beb_Read32(csp0base, offset); Beb_Write32(csp0base, offset,val); @@ -517,16 +516,16 @@ int Beb_SetNetworkParameter(enum NETWORKINDEX mode, int val){ } //close file pointer - if(fd > 0) + if (fd > 0) Beb_close(fd,csp0base); return valueread; } -int Beb_ResetToHardwareSettings(){ +int Beb_ResetToHardwareSettings() { - if(!Beb_activated) + if (!Beb_activated) return 1; //mapping new memory @@ -535,18 +534,19 @@ int Beb_ResetToHardwareSettings(){ //open file pointer int fd = Beb_open(&csp0base,XPAR_PLB_GPIO_SYS_BASEADDR); - if(fd < 0) - cprintf(BG_RED,"Reset to Hardware Settings FAIL\n"); - else{ + if (fd < 0) { + FILE_LOG(logERROR, ("Reset to Hardware Settings FAIL\n")); + } else { value = Beb_Write32(csp0base, MASTERCONFIG_OFFSET,0); - if(value) - cprintf(BG_RED,"Could not reset to hardware settings\n"); - else + if (value) { + FILE_LOG(logERROR, ("Could not reset to hardware settings\n")); + } else { ret = 0; + } } //close file pointer - if(fd > 0) + if (fd > 0) Beb_close(fd,csp0base); return ret; @@ -554,95 +554,97 @@ int Beb_ResetToHardwareSettings(){ -u_int32_t Beb_GetFirmwareRevision(){ +u_int32_t Beb_GetFirmwareRevision() { //mapping new memory u_int32_t* csp0base=0; u_int32_t value = 0; //open file pointer int fd = Beb_open(&csp0base,XPAR_VERSION); - if(fd < 0) - cprintf(BG_RED,"Firmware Revision Read FAIL\n"); - else{ + if (fd < 0) { + FILE_LOG(logERROR, ("Firmware Revision Read FAIL\n")); + } else { value = Beb_Read32(csp0base, FIRMWARE_VERSION_OFFSET); - if(!value) - cprintf(BG_RED,"Firmware Revision Number does not exist in this version\n"); + if (!value) { + FILE_LOG(logERROR, ("Firmware Revision Number does not exist in this version\n")); + } } //close file pointer - if(fd > 0) + if (fd > 0) Beb_close(fd,csp0base); return value; } -u_int32_t Beb_GetFirmwareSoftwareAPIVersion(){ +u_int32_t Beb_GetFirmwareSoftwareAPIVersion() { //mapping new memory u_int32_t* csp0base=0; u_int32_t value = 0; //open file pointer int fd = Beb_open(&csp0base,XPAR_VERSION); - if(fd < 0) - cprintf(BG_RED,"Firmware Software API Version Read FAIL\n"); - else{ + if (fd < 0) { + FILE_LOG(logERROR, ("Firmware Software API Version Read FAIL\n")); + } else { value = Beb_Read32(csp0base, FIRMWARESOFTWARE_API_OFFSET); - if(!value) - cprintf(BG_RED,"Firmware Software API Version does not exist in this version\n"); + if (!value) { + FILE_LOG(logERROR, ("Firmware Software API Version does not exist in this version\n")); + } } //close file pointer - if(fd > 0) + if (fd > 0) Beb_close(fd,csp0base); return value; } -void Beb_ResetFrameNumber(){ +void Beb_ResetFrameNumber() { - if(!Beb_activated) + if (!Beb_activated) return; //mapping new memory to read master top module configuration u_int32_t* csp0base=0; //open file pointer int fd = Beb_open(&csp0base,XPAR_PLB_GPIO_SYS_BASEADDR); - if(fd < 0){ - cprintf(BG_RED,"Reset Frame Number FAIL\n"); - }else{ + if (fd < 0) { + FILE_LOG(logERROR, ("Reset Frame Number FAIL\n")); + } else { //write a 1 Beb_Write32(csp0base, FRAME_NUM_RESET_OFFSET, 1); usleep(100000); //100ms //write a 0 Beb_Write32(csp0base, FRAME_NUM_RESET_OFFSET, 0); - printf("Frame Number Reset OK\n"); + FILE_LOG(logINFO, ("Frame Number Reset OK\n")); //close file pointer Beb_close(fd,csp0base); } } -void Beb_ClearBebInfos(){ +void Beb_ClearBebInfos() { //unsigned int i; - //for(i=0;i=bebInfoSize){ - printf("WriteTo index error.\n"); - return 0; - } + if (index>=bebInfoSize) { + FILE_LOG(logERROR, ("WriteTo index error.\n")); + return 0; + } - Beb_send_data_raw[0] = 0x90000000 | BebInfo_GetSerialAddress(&beb_infos[index]); - if(Local_Write(ll_beb,4,Beb_send_data_raw)!=4) return 0; + Beb_send_data_raw[0] = 0x90000000 | BebInfo_GetSerialAddress(&beb_infos[index]); + if (Local_Write(ll_beb,4,Beb_send_data_raw)!=4) return 0; - Beb_send_data_raw[0] = 0xc0000000; - if((Beb_send_ndata+1)*4!=Local_Write(ll_beb,(Beb_send_ndata+1)*4,Beb_send_data_raw)) return 0; + Beb_send_data_raw[0] = 0xc0000000; + if ((Beb_send_ndata+1)*4!=Local_Write(ll_beb,(Beb_send_ndata+1)*4,Beb_send_data_raw)) return 0; - return 1; + return 1; } -void Beb_SwapDataFun(int little_endian, unsigned int n, unsigned int *d){ +void Beb_SwapDataFun(int little_endian, unsigned int n, unsigned int *d) { unsigned int i; - if(little_endian) for(i=0;i>8) | ((d[i]&0xff000000)>>24)); //little_endian - else for(i=0;i>16)); + if (little_endian) for(i=0;i>8) | ((d[i]&0xff000000)>>24)); //little_endian + else for(i=0;i>16)); } -int Beb_SetByteOrder(){ - return 1; +int Beb_SetByteOrder() { + return 1; } -int Beb_SetUpUDPHeader(unsigned int beb_number, int ten_gig, unsigned int header_number, char* dst_mac, char* dst_ip, unsigned int dst_port){ +int Beb_SetUpUDPHeader(unsigned int beb_number, int ten_gig, unsigned int header_number, char* dst_mac, char* dst_ip, unsigned int dst_port) { - if(!Beb_activated) + if (!Beb_activated) return 1; u_int32_t bram_phy_addr; @@ -757,14 +760,14 @@ int Beb_SetUpUDPHeader(unsigned int beb_number, int ten_gig, unsigned int header else bram_phy_addr = 0xC6001000; - if(!Beb_SetHeaderData(beb_number,ten_gig,dst_mac,dst_ip,dst_port)) return 0; + if (!Beb_SetHeaderData(beb_number,ten_gig,dst_mac,dst_ip,dst_port)) return 0; int fd = Beb_open(&csp0base,bram_phy_addr); - if(fd < 0){ - cprintf(BG_RED,"Set up UDP Header FAIL\n"); - }else{ + if (fd < 0) { + FILE_LOG(logERROR, ("Set up UDP Header FAIL\n")); + } else { //read data memcpy(csp0base+header_number*16, &udp_header, sizeof(udp_header)); //close file pointer @@ -774,34 +777,17 @@ int Beb_SetUpUDPHeader(unsigned int beb_number, int ten_gig, unsigned int header } -//int Beb_SetUpUDPHeader(unsigned int beb_number, int ten_gig, unsigned int header_number, char* dst_mac, char* dst_ip, unsigned int dst_port){ -// unsigned int i = 1;/*Beb_GetBebInfoIndex(beb_number);*/ -// -// /***********************************if(!i) return 0; *************************************///i must be greater than 0, zero is the global send -// -// Beb_send_ndata = 14; -// Beb_send_data[0] = ten_gig ? 0x00020000 : 0x00010000; //write to fanout numbers 1 or 2 -// Beb_send_data[1] = ((header_number*8)<<16); -// if(!Beb_SetHeaderData(beb_number,ten_gig,dst_mac,dst_ip,dst_port)) return 0; -// -// Beb_SwapDataFun(1,12,&(Beb_send_data[2])); -// -// if(!Beb_WriteTo(i)) return 0; -// printf("beb dst_port:%d\n",dst_port); -// return 1; -//} - -int Beb_SetHeaderData(unsigned int beb_number, int ten_gig, char* dst_mac, char* dst_ip, unsigned int dst_port){ - unsigned int i = 1;/*Beb_GetBebInfoIndex(beb_number);*/ - /***********************************if(!i) return 0; *************************************///i must be greater than 0, zero is the global send - return Beb_SetHeaderData1(BebInfo_GetSrcMAC(&beb_infos[i],ten_gig),BebInfo_GetSrcIP(&beb_infos[i],ten_gig),BebInfo_GetSrcPort(&beb_infos[i],ten_gig),dst_mac,dst_ip,dst_port); +int Beb_SetHeaderData(unsigned int beb_number, int ten_gig, char* dst_mac, char* dst_ip, unsigned int dst_port) { + unsigned int i = 1;/*Beb_GetBebInfoIndex(beb_number);*/ + /***********************************if (!i) return 0; *************************************///i must be greater than 0, zero is the global send + return Beb_SetHeaderData1(BebInfo_GetSrcMAC(&beb_infos[i],ten_gig),BebInfo_GetSrcIP(&beb_infos[i],ten_gig),BebInfo_GetSrcPort(&beb_infos[i],ten_gig),dst_mac,dst_ip,dst_port); } -int Beb_SetHeaderData1(char* src_mac, char* src_ip, unsigned int src_port, char* dst_mac, char* dst_ip, unsigned int dst_port){ - /* example header*/ - //static unsigned int* word_ptr = new unsigned int [16]; - /*static*/ +int Beb_SetHeaderData1(char* src_mac, char* src_ip, unsigned int src_port, char* dst_mac, char* dst_ip, unsigned int dst_port) { + /* example header*/ + //static unsigned int* word_ptr = new unsigned int [16]; + /*static*/ /* udp_header_type udp_header = { {0x00, 0x50, 0xc5, 0xb2, 0xcb, 0x46}, // DST MAC @@ -823,46 +809,46 @@ int Beb_SetHeaderData1(char* src_mac, char* src_ip, unsigned int src_port, char* {0x00, 0x00}, //{0x00, 0x11}, {0x00, 0x00} }; -*/ + */ - if(!Beb_SetMAC(src_mac,&(udp_header.src_mac[0]))) return 0; - printf("Setting Source MAC to %s\n",src_mac); - if(!Beb_SetIP(src_ip,&(udp_header.src_ip[0]))) return 0; - printf("Setting Source IP to %s\n",src_ip); - if(!Beb_SetPortNumber(src_port,&(udp_header.src_port[0]))) return 0; - printf("Setting Source port to %d\n",src_port); + if (!Beb_SetMAC(src_mac,&(udp_header.src_mac[0]))) return 0; + FILE_LOG(logINFO, ("Setting Source MAC to %s\n",src_mac)); + if (!Beb_SetIP(src_ip,&(udp_header.src_ip[0]))) return 0; + FILE_LOG(logINFO, ("Setting Source IP to %s\n",src_ip)); + if (!Beb_SetPortNumber(src_port,&(udp_header.src_port[0]))) return 0; + FILE_LOG(logINFO, ("Setting Source port to %d\n",src_port)); - if(!Beb_SetMAC(dst_mac,&(udp_header.dst_mac[0]))) return 0; - printf("Setting Destination MAC to %s\n",dst_mac); - if(!Beb_SetIP(dst_ip,&(udp_header.dst_ip[0]))) return 0; - printf("Setting Destination IP to %s\n",dst_ip); - if(!Beb_SetPortNumber(dst_port,&(udp_header.dst_port[0]))) return 0; - printf("Setting Destination port to %d\n",dst_port); + if (!Beb_SetMAC(dst_mac,&(udp_header.dst_mac[0]))) return 0; + FILE_LOG(logINFO, ("Setting Destination MAC to %s\n",dst_mac)); + if (!Beb_SetIP(dst_ip,&(udp_header.dst_ip[0]))) return 0; + FILE_LOG(logINFO, ("Setting Destination IP to %s\n",dst_ip)); + if (!Beb_SetPortNumber(dst_port,&(udp_header.dst_port[0]))) return 0; + FILE_LOG(logINFO, ("Setting Destination port to %d\n",dst_port)); - Beb_AdjustIPChecksum(&udp_header); + Beb_AdjustIPChecksum(&udp_header); - unsigned int* base_ptr = (unsigned int *) &udp_header; - unsigned int num_words = ( sizeof(struct udp_header_type) + 3 ) / 4; - // for(unsigned int i=0; i %s\n",macVal); + while (pch != NULL) { + if (strlen(pch)!=2) { + FILE_LOG(logERROR, ("Error: in mac address -> %s\n",macVal)); return 0; } @@ -875,15 +861,15 @@ int Beb_SetMAC(char* mac, uint8_t* dst_ptr){ return 1; } -int Beb_SetIP(char* ip, uint8_t* dst_ptr){ +int Beb_SetIP(char* ip, uint8_t* dst_ptr) { char ipVal[50];strcpy(ipVal,ip); int i = 0; char *pch = strtok (ipVal,"."); - while (pch != NULL){ - if(((i!=3) && ((strlen(pch)>3) || (strlen(pch)<1))) || ((i==3)&&((strlen(pch)<1) || (strlen(pch) > 3)))){ - printf("Error: in ip address -> %s\n",ipVal); - return 0; - } + while (pch != NULL) { + if (((i!=3) && ((strlen(pch)>3) || (strlen(pch)<1))) || ((i==3)&&((strlen(pch)<1) || (strlen(pch) > 3)))) { + FILE_LOG(logERROR, ("Error: in ip address -> %s\n",ipVal)); + return 0; + } int itemp; sscanf(pch,"%d",&itemp); @@ -894,98 +880,94 @@ int Beb_SetIP(char* ip, uint8_t* dst_ptr){ return 1; } -int Beb_SetPortNumber(unsigned int port_number, uint8_t* dst_ptr){ - dst_ptr[0] = (port_number >> 8) & 0xff ; - dst_ptr[1] = port_number & 0xff; - return 1; +int Beb_SetPortNumber(unsigned int port_number, uint8_t* dst_ptr) { + dst_ptr[0] = (port_number >> 8) & 0xff ; + dst_ptr[1] = port_number & 0xff; + return 1; } -void Beb_AdjustIPChecksum(struct udp_header_type *ip){ - unsigned char *cptr = (unsigned char *) ip->ver_headerlen; +void Beb_AdjustIPChecksum(struct udp_header_type *ip) { + unsigned char *cptr = (unsigned char *) ip->ver_headerlen; - ip->ip_header_checksum[0] = 0; - ip->ip_header_checksum[1] = 0; - ip->total_length[0] = 0; - ip->total_length[1] = 28; // IP + UDP Header Length - - // calc ip checksum - unsigned int ip_checksum = 0; - unsigned int i; - for(i=0; i<10; i++){ - ip_checksum += ( (cptr[2*i] << 8) + (cptr[2*i + 1]) ); - if (ip_checksum & 0x00010000) ip_checksum = (ip_checksum + 1) & 0x0000ffff; - } - - ip->ip_header_checksum[0] = (ip_checksum >> 8) & 0xff ; - ip->ip_header_checksum[1] = ip_checksum & 0xff ; -} + ip->ip_header_checksum[0] = 0; + ip->ip_header_checksum[1] = 0; + ip->total_length[0] = 0; + ip->total_length[1] = 28; // IP + UDP Header Length - - -int Beb_SendMultiReadRequest(unsigned int beb_number, unsigned int left_right, int ten_gig, unsigned int dst_number, unsigned int npackets, unsigned int packet_size, int stop_read_when_fifo_empty){ - -// This is a dead function, will be removed in future -// ================================================== - - unsigned int i = 1;/*Beb_GetBebInfoIndex(beb_number); //zero is the global send*/ - - Beb_send_ndata = 3; - if(left_right == 1) Beb_send_data[0] = 0x00040000; - else if(left_right == 2) Beb_send_data[0] = 0x00080000; - else if(left_right == 3) Beb_send_data[0] = 0x000c0000; - else return 0; - - //packet_size/=2; - if(dst_number>0x3f) return 0; - if(packet_size>0x3ff) return 0; - if(npackets==0||npackets>0x100) return 0; - npackets--; - - - Beb_send_data[1] = 0x62000000 | (!stop_read_when_fifo_empty) << 27 | (ten_gig==1) << 24 | packet_size << 14 | dst_number << 8 | npackets; -#ifdef MARTIN - cprintf(GREEN, "Beb_send_data[1]:%X\n",Beb_send_data[1]); -#endif - Beb_send_data[2] = 0; - - Beb_SwapDataFun(0,2,&(Beb_send_data[1])); -#ifdef MARTIN - cprintf(GREEN, "Beb_send_data[1] Swapped:%X\n",Beb_send_data[1]); -#endif - - if(Beb_activated){ - if(!Beb_WriteTo(i)) return 0; + // calc ip checksum + unsigned int ip_checksum = 0; + unsigned int i; + for(i=0; i<10; i++) { + ip_checksum += ( (cptr[2*i] << 8) + (cptr[2*i + 1]) ); + if (ip_checksum & 0x00010000) ip_checksum = (ip_checksum + 1) & 0x0000ffff; } - return 1; + ip->ip_header_checksum[0] = (ip_checksum >> 8) & 0xff ; + ip->ip_header_checksum[1] = ip_checksum & 0xff ; } -int Beb_SetUpTransferParameters(short the_bit_mode){ - if(the_bit_mode!=4&&the_bit_mode!=8&&the_bit_mode!=16&&the_bit_mode!=32) return 0; - Beb_bit_mode = the_bit_mode; - - //nimages = the_number_of_images; - // on_dst = 0; - return 1; +int Beb_SendMultiReadRequest(unsigned int beb_number, unsigned int left_right, int ten_gig, unsigned int dst_number, unsigned int npackets, unsigned int packet_size, int stop_read_when_fifo_empty) { + + // This is a dead function, will be removed in future + // ================================================== + + unsigned int i = 1;/*Beb_GetBebInfoIndex(beb_number); //zero is the global send*/ + + Beb_send_ndata = 3; + if (left_right == 1) Beb_send_data[0] = 0x00040000; + else if (left_right == 2) Beb_send_data[0] = 0x00080000; + else if (left_right == 3) Beb_send_data[0] = 0x000c0000; + else return 0; + + //packet_size/=2; + if (dst_number>0x3f) return 0; + if (packet_size>0x3ff) return 0; + if (npackets==0||npackets>0x100) return 0; + npackets--; + + + Beb_send_data[1] = 0x62000000 | (!stop_read_when_fifo_empty) << 27 | (ten_gig==1) << 24 | packet_size << 14 | dst_number << 8 | npackets; + FILE_LOG(logDEBUG5, ("Beb_send_data[1]:%X\n",Beb_send_data[1])); + Beb_send_data[2] = 0; + + Beb_SwapDataFun(0,2,&(Beb_send_data[1])); + FILE_LOG(logDEBUG5, ("Beb_send_data[1] Swapped:%X\n",Beb_send_data[1])); + + if (Beb_activated) { + if (!Beb_WriteTo(i)) return 0; + } + + return 1; +} + + +int Beb_SetUpTransferParameters(short the_bit_mode) { + if (the_bit_mode!=4&&the_bit_mode!=8&&the_bit_mode!=16&&the_bit_mode!=32) return 0; + Beb_bit_mode = the_bit_mode; + + //nimages = the_number_of_images; + // on_dst = 0; + + return 1; } int Beb_StopAcquisition() { - if(!Beb_activated) + if (!Beb_activated) return 1; u_int32_t* csp0base=0; volatile u_int32_t valuel,valuer; //open file pointer int fd = Beb_open(&csp0base,XPAR_CMD_GENERATOR); - if(fd < 0){ - cprintf(BG_RED,"Beb Stop Acquisition FAIL\n"); + if (fd < 0) { + FILE_LOG(logERROR, ("Beb Stop Acquisition FAIL\n")); return 0; - }else{ + } else { //find value valuel = Beb_Read32(csp0base, (LEFT_OFFSET+STOP_ACQ_OFFSET)); valuer = Beb_Read32(csp0base, (RIGHT_OFFSET+STOP_ACQ_OFFSET)); @@ -996,19 +978,19 @@ int Beb_StopAcquisition() Beb_Write32(csp0base, (LEFT_OFFSET + STOP_ACQ_OFFSET),(valuel&(~STOP_ACQ_BIT))); Beb_Write32(csp0base, (RIGHT_OFFSET + STOP_ACQ_OFFSET),(valuer&(~STOP_ACQ_BIT))); - printf("Beb Stop Acquisition OK\n"); + FILE_LOG(logINFO, ("Beb Stop Acquisition OK\n")); //close file pointer Beb_close(fd,csp0base); } return 1; } -int Beb_RequestNImages(unsigned int beb_number, int ten_gig, unsigned int dst_number, unsigned int nimages, int test_just_send_out_packets_no_wait){ +int Beb_RequestNImages(unsigned int beb_number, int ten_gig, unsigned int dst_number, unsigned int nimages, int test_just_send_out_packets_no_wait) { - if(!Beb_activated) + if (!Beb_activated) return 1; - if(dst_number>64) return 0; + if (dst_number>64) return 0; unsigned int header_size = 4; //4*64 bits unsigned int packet_size = ten_gig ? 0x200 : 0x80; // 4k or 1k packets @@ -1020,12 +1002,13 @@ int Beb_RequestNImages(unsigned int beb_number, int ten_gig, unsigned int dst_nu u_int32_t send_header_command; u_int32_t send_frame_command; - if(in_two_requests) npackets/=2; + if (in_two_requests) npackets/=2; -#ifdef MARTIN - cprintf(RED, "----Beb_RequestNImages Start----\n"); - cprintf(RED, "beb_number:%X, ten_gig:%X,dst_number:%X,npackets:%X,Beb_bit_mode:%X,header_size:%X,nimages:%d,test_just_send_out_packets_no_wait:%X\n",beb_number,ten_gig,dst_number,npackets,Beb_bit_mode,header_size,nimages,test_just_send_out_packets_no_wait); -#endif + FILE_LOG(logDEBUG5, ("----Beb_RequestNImages Start----\n")); + FILE_LOG(logDEBUG5, ("beb_number:%X, ten_gig:%X,dst_number:%X, npackets:%X, " + "Beb_bit_mode:%X, header_size:%X, nimages:%d, test_just_send_out_packets_no_wait:%X\n", + beb_number, ten_gig, dst_number, npackets, Beb_bit_mode, header_size, + nimages, test_just_send_out_packets_no_wait)); // CMD_GEN core registers // @@ -1061,26 +1044,24 @@ int Beb_RequestNImages(unsigned int beb_number, int ten_gig, unsigned int dst_nu volatile u_int32_t value; //open file pointer int fd = Beb_open(&csp0base,XPAR_CMD_GENERATOR); - if(fd < 0){ - cprintf(BG_RED,"Beb Request N Images FAIL\n"); + if (fd < 0) { + FILE_LOG(logERROR, ("Beb Request N Images FAIL\n")); return 0; - }else{ - -#ifdef MARTIN - int i; - for (i=0; i < 10; i++) - printf("%X\n",Beb_Read32(baseaddr, (LEFT_OFFSET + i*4))); -#endif + } else { + { + int i; + for (i=0; i < 10; i++) + FILE_LOG(logDEBUG5, ("%X\n",Beb_Read32(csp0base, (LEFT_OFFSET + i*4)))); + } // Generating commands send_header_command = 0x62000000 | (!test_just_send_out_packets_no_wait) << 27 | (ten_gig==1) << 24 | header_size << 14 | 0; send_frame_command = 0x62000000 | (!test_just_send_out_packets_no_wait) << 27 | (ten_gig==1) << 24 | packet_size << 14 | (npackets-1); - -#ifdef MARTIN - for (i=0; i < 10; i++) - printf("%X\n",Beb_Read32(baseaddr, (LEFT_OFFSET + i*4))); - printf("%d\n",in_two_requests); -#endif - + { + int i; + for (i=0; i < 10; i++) + FILE_LOG(logDEBUG5, ("%X\n",Beb_Read32(csp0base, (LEFT_OFFSET + i*4)))); + FILE_LOG(logDEBUG5, ("%d\n",in_two_requests)); + } //"0x20 << 8" is dst_number (0x00 for left, 0x20 for right) //Left Beb_Write32(csp0base, (LEFT_OFFSET + FIRST_CMD_PART1_OFFSET),0); @@ -1088,7 +1069,7 @@ int Beb_RequestNImages(unsigned int beb_number, int ten_gig, unsigned int dst_nu Beb_Write32(csp0base, (LEFT_OFFSET + SECOND_CMD_PART1_OFFSET),0); Beb_Write32(csp0base, (LEFT_OFFSET + SECOND_CMD_PART2_OFFSET),send_frame_command); value = Beb_Read32(csp0base,(LEFT_OFFSET + TWO_REQUESTS_OFFSET)); - if(in_two_requests) Beb_Write32(csp0base, (LEFT_OFFSET + TWO_REQUESTS_OFFSET),(value | TWO_REQUESTS_BIT)); + if (in_two_requests) Beb_Write32(csp0base, (LEFT_OFFSET + TWO_REQUESTS_OFFSET),(value | TWO_REQUESTS_BIT)); else Beb_Write32(csp0base, (LEFT_OFFSET + TWO_REQUESTS_OFFSET),(value &~(TWO_REQUESTS_BIT))); // Right @@ -1097,62 +1078,59 @@ int Beb_RequestNImages(unsigned int beb_number, int ten_gig, unsigned int dst_nu Beb_Write32(csp0base, (RIGHT_OFFSET + SECOND_CMD_PART1_OFFSET),0); Beb_Write32(csp0base, (RIGHT_OFFSET + SECOND_CMD_PART2_OFFSET),send_frame_command | right_port_value); value = Beb_Read32(csp0base,(RIGHT_OFFSET + TWO_REQUESTS_OFFSET)); - if(in_two_requests) Beb_Write32(csp0base, (RIGHT_OFFSET + TWO_REQUESTS_OFFSET),(value | TWO_REQUESTS_BIT)); + if (in_two_requests) Beb_Write32(csp0base, (RIGHT_OFFSET + TWO_REQUESTS_OFFSET),(value | TWO_REQUESTS_BIT)); else Beb_Write32(csp0base, (RIGHT_OFFSET + TWO_REQUESTS_OFFSET),(value &~(TWO_REQUESTS_BIT))); // Set number of frames Beb_Write32(csp0base, (LEFT_OFFSET + COMMAND_COUNTER_OFFSET), nimages*(2+in_two_requests)); Beb_Write32(csp0base, (RIGHT_OFFSET + COMMAND_COUNTER_OFFSET), nimages*(2+in_two_requests)); - -#ifdef MARTIN - for (i=0; i < 10; i++) - printf("%X\n",Beb_Read32(baseaddr, (LEFT_OFFSET + i*4))); //*(ptrl+i)); - printf("%d\n",in_two_requests); -#endif - + { + int i; + for (i=0; i < 10; i++) + FILE_LOG(logDEBUG5, ("%X\n",Beb_Read32(csp0base, (LEFT_OFFSET + i*4)))); //*(ptrl+i)); + FILE_LOG(logDEBUG5, ("%d\n",in_two_requests)); + } Beb_close(fd,csp0base); -#ifdef MARTIN - printf("----Beb_RequestNImages----\n"); -#endif + FILE_LOG(logDEBUG5, ("----Beb_RequestNImages----\n")); } return 1; } -int Beb_Test(unsigned int beb_number){ - printf("Testing module number: %d\n",beb_number); - +int Beb_Test(unsigned int beb_number) { + FILE_LOG(logINFO, ("Testing module number: %d\n",beb_number)); - //int SetUpUDPHeader(unsigned int beb_number, int ten_gig, unsigned int header_number, string dst_mac, string dst_ip, unsigned int dst_port){ - //SetUpUDPHeader(26,0,0,"60:fb:42:f4:e3:d2","129.129.205.186",22000); - unsigned int index = Beb_GetBebInfoIndex(beb_number); - if(!index){ - printf("Error beb number (%d)not in list????\n",beb_number); - return 0; - } + //int SetUpUDPHeader(unsigned int beb_number, int ten_gig, unsigned int header_number, string dst_mac, string dst_ip, unsigned int dst_port) { + //SetUpUDPHeader(26,0,0,"60:fb:42:f4:e3:d2","129.129.205.186",22000); - unsigned int i; - for(i=0;i<64;i++){ - if(!Beb_SetUpUDPHeader(beb_number,0,i,"60:fb:42:f4:e3:d2","129.129.205.186",22000+i)){ - printf("Error setting up header table....\n"); - return 0; - } - } + unsigned int index = Beb_GetBebInfoIndex(beb_number); + if (!index) { + FILE_LOG(logERROR, ("Error beb number (%d)not in list????\n",beb_number)); + return 0; + } - // SendMultiReadRequest(unsigned int beb_number, unsigned int left_right, int ten_gig, unsigned int dst_number, unsigned int npackets, unsigned int packet_size, int stop_read_when_fifo_empty=1); - for(i=0;i<64;i++){ - if(!Beb_SendMultiReadRequest(beb_number,i%3+1,0,i,1,0,1)){ - printf("Error requesting data....\n"); - return 0; - } - } - + unsigned int i; + for(i=0;i<64;i++) { + if (!Beb_SetUpUDPHeader(beb_number,0,i,"60:fb:42:f4:e3:d2","129.129.205.186",22000+i)) { + FILE_LOG(logERROR, ("Error setting up header table....\n")); + return 0; + } + } - return 1; + // SendMultiReadRequest(unsigned int beb_number, unsigned int left_right, int ten_gig, unsigned int dst_number, unsigned int npackets, unsigned int packet_size, int stop_read_when_fifo_empty=1); + for(i=0;i<64;i++) { + if (!Beb_SendMultiReadRequest(beb_number,i%3+1,0,i,1,0,1)) { + FILE_LOG(logERROR, ("Error requesting data....\n")); + return 0; + } + } + + + return 1; } // Returns the FPGA temperature from the xps sysmon ip core @@ -1165,9 +1143,9 @@ int Beb_GetBebFPGATemp() int ret; //open file pointer int fd = Beb_open(&csp0base,XPAR_SYSMON_0_BASEADDR); - if(fd < 0){ - cprintf(BG_RED,"Module Configuration FAIL\n"); - }else{ + if (fd < 0) { + FILE_LOG(logERROR, ("Module Configuration FAIL\n")); + } else { //read data ret = Beb_Read32(csp0base, FPGA_TEMP_OFFSET); temperature = ((((float)(ret)/65536.0f)/0.00198421639f ) - 273.15f)*1000; // Static conversation, copied from xps sysmon standalone driver @@ -1180,42 +1158,42 @@ int Beb_GetBebFPGATemp() void Beb_SetDetectorNumber(uint32_t detid) { - if(!Beb_activated) + if (!Beb_activated) return; uint32_t swapid = Beb_swap_uint16(detid); - //cprintf(GREEN, "detector id %d swapped %d\n", detid, swapid); + //FILE_LOG(logINFO, "detector id %d swapped %d\n", detid, swapid)); u_int32_t* csp0base=0; int fd = Beb_open(&csp0base,XPAR_PLB_GPIO_TEST_BASEADDR); - if(fd < 0){ - cprintf(BG_RED,"Set Detector ID FAIL\n"); + if (fd < 0) { + FILE_LOG(logERROR, ("Set Detector ID FAIL\n")); return; - }else{ + } else { uint32_t value = Beb_Read32(csp0base, UDP_HEADER_A_LEFT_OFST); value &= UDP_HEADER_X_MSK; // to keep previous x value Beb_Write32(csp0base, UDP_HEADER_A_LEFT_OFST, value | ((swapid << UDP_HEADER_ID_OFST) & UDP_HEADER_ID_MSK)); value = Beb_Read32(csp0base, UDP_HEADER_A_LEFT_OFST); - if((value & UDP_HEADER_ID_MSK) != ((swapid << UDP_HEADER_ID_OFST) & UDP_HEADER_ID_MSK)) - cprintf(BG_RED,"Set Detector ID FAIL\n"); - + if ((value & UDP_HEADER_ID_MSK) != ((swapid << UDP_HEADER_ID_OFST) & UDP_HEADER_ID_MSK)) { + FILE_LOG(logERROR, ("Set Detector ID FAIL\n")); + } value = Beb_Read32(csp0base, UDP_HEADER_A_RIGHT_OFST); value &= UDP_HEADER_X_MSK; // to keep previous x value Beb_Write32(csp0base, UDP_HEADER_A_RIGHT_OFST, value | ((swapid << UDP_HEADER_ID_OFST) & UDP_HEADER_ID_MSK)); value = Beb_Read32(csp0base, UDP_HEADER_A_RIGHT_OFST); - if((value & UDP_HEADER_ID_MSK) != ((swapid << UDP_HEADER_ID_OFST) & UDP_HEADER_ID_MSK)) - cprintf(BG_RED,"Set Detector ID FAIL\n"); - + if ((value & UDP_HEADER_ID_MSK) != ((swapid << UDP_HEADER_ID_OFST) & UDP_HEADER_ID_MSK)) { + FILE_LOG(logERROR, ("Set Detector ID FAIL\n")); + } Beb_close(fd,csp0base); } - printf("detector id %d has been set in udp header\n", detid); + FILE_LOG(logINFO, ("Detector id %d set in UDP Header\n\n", detid)); } int Beb_SetDetectorPosition(int pos[]) { - if(!Beb_activated) + if (!Beb_activated) return OK; - cprintf(BLUE,"Got Position values %d %d %d...\n", pos[0],pos[1], pos[2]); + FILE_LOG(logINFO, ("Got Position values %d %d %d...\n", pos[0],pos[1], pos[2])); pos[0] = Beb_swap_uint16(pos[0]); //pos[1] = Beb_swap_uint16(pos[1]); @@ -1226,10 +1204,10 @@ int Beb_SetDetectorPosition(int pos[]) { u_int32_t* csp0base=0; //open file pointer int fd = Beb_open(&csp0base,XPAR_PLB_GPIO_TEST_BASEADDR); - if(fd < 0){ - cprintf(BG_RED,"Set Detector Position FAIL\n"); + if (fd < 0) { + FILE_LOG(logERROR, ("Set Detector Position FAIL\n")); return FAIL; - }else{ + } else { uint32_t value = 0; ret = OK; // x left @@ -1237,7 +1215,7 @@ int Beb_SetDetectorPosition(int pos[]) { value &= UDP_HEADER_ID_MSK; // to keep previous id value Beb_Write32(csp0base, UDP_HEADER_A_LEFT_OFST, value | ((pos[0] << UDP_HEADER_X_OFST) & UDP_HEADER_X_MSK)); value = Beb_Read32(csp0base, UDP_HEADER_A_LEFT_OFST); - if((value & UDP_HEADER_X_MSK) != ((pos[0] << UDP_HEADER_X_OFST) & UDP_HEADER_X_MSK)) + if ((value & UDP_HEADER_X_MSK) != ((pos[0] << UDP_HEADER_X_OFST) & UDP_HEADER_X_MSK)) ret = FAIL; // x right @@ -1245,7 +1223,7 @@ int Beb_SetDetectorPosition(int pos[]) { value &= UDP_HEADER_ID_MSK; // to keep previous id value Beb_Write32(csp0base, UDP_HEADER_A_RIGHT_OFST, value | ((pos[0] << UDP_HEADER_X_OFST) & UDP_HEADER_X_MSK)); value = Beb_Read32(csp0base, UDP_HEADER_A_RIGHT_OFST); - if((value & UDP_HEADER_X_MSK) != ((pos[0] << UDP_HEADER_X_OFST) & UDP_HEADER_X_MSK)) + if ((value & UDP_HEADER_X_MSK) != ((pos[0] << UDP_HEADER_X_OFST) & UDP_HEADER_X_MSK)) ret = FAIL; @@ -1255,7 +1233,7 @@ int Beb_SetDetectorPosition(int pos[]) { int posval = Beb_swap_uint16(Beb_top ? pos[1] : (pos[1]+1)); Beb_Write32(csp0base, UDP_HEADER_B_LEFT_OFST, ((posval << UDP_HEADER_Y_OFST) & UDP_HEADER_Y_MSK)); value = Beb_Read32(csp0base, UDP_HEADER_B_LEFT_OFST); - if(value != ((posval << UDP_HEADER_Y_OFST) & UDP_HEADER_Y_MSK)) + if (value != ((posval << UDP_HEADER_Y_OFST) & UDP_HEADER_Y_MSK)) ret = FAIL; // y right @@ -1263,7 +1241,7 @@ int Beb_SetDetectorPosition(int pos[]) { posval = Beb_swap_uint16(Beb_top ? (pos[1]+1) : pos[1]); Beb_Write32(csp0base, UDP_HEADER_B_RIGHT_OFST, ((posval << UDP_HEADER_Y_OFST) & UDP_HEADER_Y_MSK)); value = Beb_Read32(csp0base, UDP_HEADER_B_RIGHT_OFST); - if(value != ((posval << UDP_HEADER_Y_OFST) & UDP_HEADER_Y_MSK)) + if (value != ((posval << UDP_HEADER_Y_OFST) & UDP_HEADER_Y_MSK)) ret = FAIL; @@ -1273,7 +1251,7 @@ int Beb_SetDetectorPosition(int pos[]) { value &= UDP_HEADER_Y_MSK; // to keep previous y value Beb_Write32(csp0base, UDP_HEADER_B_LEFT_OFST, value | ((pos[2] << UDP_HEADER_Z_OFST) & UDP_HEADER_Z_MSK)); value = Beb_Read32(csp0base, UDP_HEADER_B_LEFT_OFST); - if((value & UDP_HEADER_Z_MSK) != ((pos[2] << UDP_HEADER_Z_OFST) & UDP_HEADER_Z_MSK)) + if ((value & UDP_HEADER_Z_MSK) != ((pos[2] << UDP_HEADER_Z_OFST) & UDP_HEADER_Z_MSK)) ret = FAIL; // z right @@ -1281,7 +1259,7 @@ int Beb_SetDetectorPosition(int pos[]) { value &= UDP_HEADER_Y_MSK; // to keep previous y value Beb_Write32(csp0base, UDP_HEADER_B_RIGHT_OFST, value | ((pos[2] << UDP_HEADER_Z_OFST) & UDP_HEADER_Z_MSK)); value = Beb_Read32(csp0base, UDP_HEADER_B_RIGHT_OFST); - if((value & UDP_HEADER_Z_MSK) != ((pos[2] << UDP_HEADER_Z_OFST) & UDP_HEADER_Z_MSK)) + if ((value & UDP_HEADER_Z_MSK) != ((pos[2] << UDP_HEADER_Z_OFST) & UDP_HEADER_Z_MSK)) ret = FAIL; @@ -1289,11 +1267,11 @@ int Beb_SetDetectorPosition(int pos[]) { Beb_close(fd,csp0base); } if (ret == OK) { - cprintf(BLUE, "Position set to...\n" + FILE_LOG(logINFO, ("Position set to...\n" "Left: [%d, %d, %d]\n" "Right:[%d, %d, %d]\n", - Beb_swap_uint16(pos[0]), Beb_top ? pos[1] : (pos[1]+1), Beb_swap_uint16(pos[2]), - Beb_swap_uint16(pos[0]), Beb_top ? (pos[1]+1) : pos[1], Beb_swap_uint16(pos[2])); + Beb_swap_uint16(pos[0]), Beb_top ? pos[1] : (pos[1]+1), Beb_swap_uint16(pos[2]), + Beb_swap_uint16(pos[0]), Beb_top ? (pos[1]+1) : pos[1], Beb_swap_uint16(pos[2]))); } return ret; @@ -1301,46 +1279,42 @@ int Beb_SetDetectorPosition(int pos[]) { uint16_t Beb_swap_uint16( uint16_t val) { - return (val << 8) | (val >> 8 ); + return (val << 8) | (val >> 8 ); } -int Beb_open(u_int32_t** csp0base, u_int32_t offset){ +int Beb_open(u_int32_t** csp0base, u_int32_t offset) { int fd = open("/dev/mem", O_RDWR | O_SYNC, 0); - if (fd == -1) - cprintf(BG_RED,"\nCan't find /dev/mem!\n"); - else{ -#ifdef VERBOSE - printf("/dev/mem opened\n"); -#endif + if (fd == -1) { + FILE_LOG(logERROR, ("\nCan't find /dev/mem!\n")); + } else { + FILE_LOG(logDEBUG5, ("/dev/mem opened\n")); *csp0base = (u_int32_t*)mmap(0, BEB_MMAP_SIZE, PROT_READ|PROT_WRITE, MAP_FILE|MAP_SHARED, fd, offset); if (*csp0base == MAP_FAILED) { - cprintf(BG_RED,"\nCan't map memmory area!!\n"); + FILE_LOG(logERROR, ("\nCan't map memmory area!!\n")); fd = -1; } -#ifdef VERBOSE - else printf("CSP0 mapped %p\n",(void*)*csp0base); -#endif + else FILE_LOG(logDEBUG5, ("CSP0 mapped %p\n",(void*)*csp0base)); } return fd; } -u_int32_t Beb_Read32 (u_int32_t* baseaddr, u_int32_t offset){ +u_int32_t Beb_Read32 (u_int32_t* baseaddr, u_int32_t offset) { volatile u_int32_t value; value=* (u_int32_t*)(baseaddr + offset/(sizeof(u_int32_t))); return value; } -u_int32_t Beb_Write32 (u_int32_t* baseaddr, u_int32_t offset, u_int32_t data){ +u_int32_t Beb_Write32 (u_int32_t* baseaddr, u_int32_t offset, u_int32_t data) { volatile u_int32_t *ptr1; ptr1=(u_int32_t*)(baseaddr + offset/(sizeof(u_int32_t))); *ptr1 = data; return *ptr1; } -void Beb_close(int fd,u_int32_t* csp0base){ - if(fd >= 0) +void Beb_close(int fd,u_int32_t* csp0base) { + if (fd >= 0) close(fd); munmap(csp0base,BEB_MMAP_SIZE); } diff --git a/slsDetectorServers/eigerDetectorServer/Beb.h b/slsDetectorServers/eigerDetectorServer/Beb.h index 73718db03..6ab1338e8 100644 --- a/slsDetectorServers/eigerDetectorServer/Beb.h +++ b/slsDetectorServers/eigerDetectorServer/Beb.h @@ -1,103 +1,84 @@ - -/** - * @author Ian Johnson - * @version 1.0 - */ - - -#ifndef BEB_H -#define BEB_H - +#pragma once #include "LocalLinkInterface.h" #include "slsDetectorServer_defs.h" - + struct BebInfo{ - unsigned int beb_number; - unsigned int serial_address; - char src_mac_1GbE[50]; - char src_mac_10GbE[50]; - char src_ip_1GbE[50]; - char src_ip_10GbE[50]; - unsigned int src_port_1GbE; - unsigned int src_port_10GbE; + unsigned int beb_number; + unsigned int serial_address; + char src_mac_1GbE[50]; + char src_mac_10GbE[50]; + char src_ip_1GbE[50]; + char src_ip_10GbE[50]; + unsigned int src_port_1GbE; + unsigned int src_port_10GbE; }; - void BebInfo_BebInfo(struct BebInfo* bebInfo, unsigned int beb_num); - void BebInfo_BebDstInfo(struct BebInfo* bebInfo, unsigned int beb_num); - int BebInfo_SetSerialAddress(struct BebInfo* bebInfo, unsigned int add); - int BebInfo_SetHeaderInfo(struct BebInfo* bebInfo, int ten_gig, char* src_mac, char* src_ip, unsigned int src_port);//src_port fixed 42000+beb_number or 52000 + beb_number); - unsigned int BebInfo_GetBebNumber(struct BebInfo* bebInfo); - unsigned int BebInfo_GetSerialAddress(struct BebInfo* bebInfo); - char* BebInfo_GetSrcMAC(struct BebInfo* bebInfo, int ten_gig); - char* BebInfo_GetSrcIP(struct BebInfo* bebInfo, int ten_gig); - unsigned int BebInfo_GetSrcPort(struct BebInfo* bebInfo, int ten_gig); - void BebInfo_Print(struct BebInfo* bebInfo); +void BebInfo_BebInfo(struct BebInfo* bebInfo, unsigned int beb_num); +void BebInfo_BebDstInfo(struct BebInfo* bebInfo, unsigned int beb_num); +int BebInfo_SetSerialAddress(struct BebInfo* bebInfo, unsigned int add); +int BebInfo_SetHeaderInfo(struct BebInfo* bebInfo, int ten_gig, char* src_mac, char* src_ip, unsigned int src_port);//src_port fixed 42000+beb_number or 52000 + beb_number); +unsigned int BebInfo_GetBebNumber(struct BebInfo* bebInfo); +unsigned int BebInfo_GetSerialAddress(struct BebInfo* bebInfo); +char* BebInfo_GetSrcMAC(struct BebInfo* bebInfo, int ten_gig); +char* BebInfo_GetSrcIP(struct BebInfo* bebInfo, int ten_gig); +unsigned int BebInfo_GetSrcPort(struct BebInfo* bebInfo, int ten_gig); +void BebInfo_Print(struct BebInfo* bebInfo); +void Beb_ClearBebInfos(); +int Beb_InitBebInfos(); +int Beb_CheckSourceStuffBebInfo(); +unsigned int Beb_GetBebInfoIndex(unsigned int beb_numb); +void Beb_GetModuleConfiguration(int* master, int* top, int* normal); +void Beb_EndofDataSend(int tengiga); - void Beb_ClearBebInfos(); - int Beb_InitBebInfos(); - int Beb_CheckSourceStuffBebInfo(); - unsigned int Beb_GetBebInfoIndex(unsigned int beb_numb); +int Beb_SetMasterViaSoftware(); +int Beb_SetSlaveViaSoftware(); +int Beb_Activate(int enable); +int Beb_Set32bitOverflow(int val); +int Beb_SetNetworkParameter(enum NETWORKINDEX mode, int val); +int Beb_ResetToHardwareSettings(); +u_int32_t Beb_GetFirmwareRevision(); +u_int32_t Beb_GetFirmwareSoftwareAPIVersion(); +void Beb_ResetFrameNumber(); +int Beb_WriteTo(unsigned int index); +int Beb_SetMAC(char* mac, uint8_t* dst_ptr); +int Beb_SetIP(char* ip, uint8_t* dst_ptr); +int Beb_SetPortNumber(unsigned int port_number, uint8_t* dst_ptr); +void Beb_AdjustIPChecksum(struct udp_header_type *ip); + +int Beb_SetHeaderData(unsigned int beb_number, int ten_gig, char* dst_mac, char* dst_ip, unsigned int dst_port); +int Beb_SetHeaderData1(char* src_mac, char* src_ip, unsigned int src_port, char* dst_mac, char* dst_ip, unsigned int dst_port); + +void Beb_SwapDataFun(int little_endian, unsigned int n, unsigned int *d); +int Beb_SetByteOrder(); +void Beb_Beb(); +int Beb_SetBebSrcHeaderInfos(unsigned int beb_number, int ten_gig, char* src_mac, char* src_ip, unsigned int src_port); +int Beb_SetUpUDPHeader(unsigned int beb_number, int ten_gig, unsigned int header_number, char* dst_mac, char* dst_ip, unsigned int dst_port); + +/*int Beb_SendMultiReadRequest(unsigned int beb_number, unsigned int left_right, int ten_gig, unsigned int dst_number, unsigned int npackets, unsigned int packet_size, int stop_read_when_fifo_empty=1);*/ +int Beb_SendMultiReadRequest(unsigned int beb_number, unsigned int left_right, int ten_gig, unsigned int dst_number, unsigned int npackets, unsigned int packet_size, int stop_read_when_fifo_empty); + +int Beb_StopAcquisition(); +int Beb_SetUpTransferParameters(short the_bit_mode); +/*int Beb_RequestNImages(unsigned int beb_number, unsigned int left_right, int ten_gig, unsigned int dst_number, unsigned int nimages, int test_just_send_out_packets_no_wait=0); //all images go to the same destination!*/ +int Beb_RequestNImages(unsigned int beb_number, int ten_gig, unsigned int dst_number, unsigned int nimages, int test_just_send_out_packets_no_wait); + +int Beb_Test(unsigned int beb_number); + +int Beb_GetBebFPGATemp(); + +void Beb_SetDetectorNumber(uint32_t detid); +int Beb_SetDetectorPosition(int pos[]); + +uint16_t Beb_swap_uint16( uint16_t val); +int Beb_open(u_int32_t** csp0base, u_int32_t offset); +u_int32_t Beb_Read32 (u_int32_t* baseaddr, u_int32_t offset); +u_int32_t Beb_Write32 (u_int32_t* baseaddr, u_int32_t offset, u_int32_t data); +void Beb_close(int fd,u_int32_t* csp0base); - void Beb_GetModuleConfiguration(int* master, int* top, int* normal); - void Beb_EndofDataSend(int tengiga); - - int Beb_SetMasterViaSoftware(); - int Beb_SetSlaveViaSoftware(); - int Beb_Activate(int enable); - int Beb_Set32bitOverflow(int val); - int Beb_SetNetworkParameter(enum NETWORKINDEX mode, int val); - int Beb_ResetToHardwareSettings(); - u_int32_t Beb_GetFirmwareRevision(); - u_int32_t Beb_GetFirmwareSoftwareAPIVersion(); - void Beb_ResetFrameNumber(); - - int Beb_WriteTo(unsigned int index); - - int Beb_SetMAC(char* mac, uint8_t* dst_ptr); - int Beb_SetIP(char* ip, uint8_t* dst_ptr); - int Beb_SetPortNumber(unsigned int port_number, uint8_t* dst_ptr); - void Beb_AdjustIPChecksum(struct udp_header_type *ip); - - int Beb_SetHeaderData(unsigned int beb_number, int ten_gig, char* dst_mac, char* dst_ip, unsigned int dst_port); - int Beb_SetHeaderData1(char* src_mac, char* src_ip, unsigned int src_port, char* dst_mac, char* dst_ip, unsigned int dst_port); - - void Beb_SwapDataFun(int little_endian, unsigned int n, unsigned int *d); - int Beb_SetByteOrder(); - - - void Beb_Beb(); - - - int Beb_SetBebSrcHeaderInfos(unsigned int beb_number, int ten_gig, char* src_mac, char* src_ip, unsigned int src_port); - int Beb_SetUpUDPHeader(unsigned int beb_number, int ten_gig, unsigned int header_number, char* dst_mac, char* dst_ip, unsigned int dst_port); - - /*int Beb_SendMultiReadRequest(unsigned int beb_number, unsigned int left_right, int ten_gig, unsigned int dst_number, unsigned int npackets, unsigned int packet_size, int stop_read_when_fifo_empty=1);*/ - int Beb_SendMultiReadRequest(unsigned int beb_number, unsigned int left_right, int ten_gig, unsigned int dst_number, unsigned int npackets, unsigned int packet_size, int stop_read_when_fifo_empty); - - int Beb_StopAcquisition(); - int Beb_SetUpTransferParameters(short the_bit_mode); - /*int Beb_RequestNImages(unsigned int beb_number, unsigned int left_right, int ten_gig, unsigned int dst_number, unsigned int nimages, int test_just_send_out_packets_no_wait=0); //all images go to the same destination!*/ - int Beb_RequestNImages(unsigned int beb_number, int ten_gig, unsigned int dst_number, unsigned int nimages, int test_just_send_out_packets_no_wait); - - int Beb_Test(unsigned int beb_number); - - int Beb_GetBebFPGATemp(); - - void Beb_SetDetectorNumber(uint32_t detid); - int Beb_SetDetectorPosition(int pos[]); - - uint16_t Beb_swap_uint16( uint16_t val); - int Beb_open(u_int32_t** csp0base, u_int32_t offset); - u_int32_t Beb_Read32 (u_int32_t* baseaddr, u_int32_t offset); - u_int32_t Beb_Write32 (u_int32_t* baseaddr, u_int32_t offset, u_int32_t data); - void Beb_close(int fd,u_int32_t* csp0base); - -#endif - diff --git a/slsDetectorServers/eigerDetectorServer/FebControl.c b/slsDetectorServers/eigerDetectorServer/FebControl.c index aa63dbab7..7ee4fb6bc 100644 --- a/slsDetectorServers/eigerDetectorServer/FebControl.c +++ b/slsDetectorServers/eigerDetectorServer/FebControl.c @@ -1,10 +1,8 @@ - -/** - * @author Ian Johnson - * @version 1.0 - */ - - +#include "FebRegisterDefs.h" +#include "FebControl.h" +#include "Beb.h" +#include "slsDetectorServer_defs.h" +#include "logger.h" #include #include @@ -14,18 +12,14 @@ #include #include // POSIX terminal control definitions(CS8, CREAD, CLOCAL..) #include - -#include "FebRegisterDefs.h" -#include "FebControl.h" -#include "Beb.h" -#include "slsDetectorServer_defs.h" +#include +#include - -//GetDAQStatusRegister(512,current_mode_bits_from_fpga)){ +//GetDAQStatusRegister(512,current_mode_bits_from_fpga)) { unsigned int Module_ndacs = 16; -char Module_dac_names[16][10]={"SvP","Vtr","Vrf","Vrs","SvN","Vtgstv","Vcmp_ll","Vcmp_lr","cal","Vcmp_rl","rxb_rb","rxb_lb","Vcmp_rr","Vcp","Vcn","Vis"};; +char Module_dac_names[16][10]={"SvP","Vtr","Vrf","Vrs","SvN","Vtgstv","Vcmp_ll","Vcmp_lr","cal","Vcmp_rl","rxb_rb","rxb_lb","Vcmp_rr","Vcp","Vcn","Vis"}; @@ -68,7 +62,7 @@ int Feb_Control_activated = 1; int Feb_Control_hv_fd = -1; -void Module_Module(struct Module* mod,unsigned int number, unsigned int address_top){ +void Module_Module(struct Module* mod,unsigned int number, unsigned int address_top) { unsigned int i; mod->module_number = number; mod->top_address_valid = 1; @@ -86,7 +80,7 @@ void Module_Module(struct Module* mod,unsigned int number, unsigned int address_ } -void Module_ModuleBottom(struct Module* mod,unsigned int number, unsigned int address_bottom){ +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; @@ -108,7 +102,7 @@ void Module_ModuleBottom(struct Module* mod,unsigned int number, unsigned int ad -void Module_Module1(struct Module* mod,unsigned int number, unsigned int address_top, unsigned int address_bottom){ +void Module_Module1(struct Module* mod,unsigned int number, unsigned int address_top, unsigned int address_bottom) { unsigned int i; mod->module_number = number; mod->top_address_valid = 1; @@ -154,23 +148,23 @@ int Module_GetBottomDACValue(struct Module* mod,unsigned int i) -void Feb_Control_activate(int activate){ +void Feb_Control_activate(int activate) { Feb_Control_activated = activate; } -int Feb_Control_IsBottomModule(){ - if(Module_BottomAddressIsValid(&modules[Feb_Control_current_index])) +int Feb_Control_IsBottomModule() { + if (Module_BottomAddressIsValid(&modules[Feb_Control_current_index])) return 1; return 0; } -int Feb_Control_GetModuleNumber(){ +int Feb_Control_GetModuleNumber() { return Feb_Control_module_number; } -void Feb_Control_FebControl(){ +void Feb_Control_FebControl() { Feb_Control_staticBits=Feb_Control_acquireNReadoutMode=Feb_Control_triggerMode=Feb_Control_externalEnableMode=Feb_Control_subFrameMode=0; Feb_Control_trimbit_size=263680; Feb_Control_last_downloaded_trimbits = malloc(Feb_Control_trimbit_size * sizeof(int)); @@ -180,7 +174,7 @@ void Feb_Control_FebControl(){ -int Feb_Control_Init(int master, int top, int normal, int module_num){ +int Feb_Control_Init(int master, int top, int normal, int module_num) { unsigned int i; Feb_Control_module_number = 0; Feb_Control_current_index = 0; @@ -193,7 +187,7 @@ int Feb_Control_Init(int master, int top, int normal, int module_num){ Feb_Control_module_number = (module_num & 0xFF); int serial = !top; - printf("serial: %d\n",serial); + FILE_LOG(logDEBUG5, ("serial: %d\n",serial)); Feb_Control_current_index = 1; @@ -205,12 +199,12 @@ int Feb_Control_Init(int master, int top, int normal, int module_num){ unsigned int nfebs = 0; unsigned int* feb_list = malloc(moduleSize*4 * sizeof(unsigned int)); - for(i=1;i3){ - cprintf(RED,"Error SetIDelay chip_pos %d doesn't exist.\n",chip_pos);; + if (chip_pos>3) { + FILE_LOG(logERROR, ("SetIDelay chip_pos %d doesn't exist.\n",chip_pos)); return 0; } unsigned int module_index=0; - if(!Feb_Control_GetModuleIndex(module_num,&module_index)){ - cprintf(RED,"Error could not set i delay module number %d invalid.\n",module_num); + if (!Feb_Control_GetModuleIndex(module_num,&module_index)) { + FILE_LOG(logERROR, ("could not set i delay module number %d invalid.\n",module_num)); return 0; } int ok = 1; - if(chip_pos/2==0){ //left fpga - if(Module_TopAddressIsValid(&modules[module_index])){ - if(Feb_Control_SendIDelays(Module_GetTopLeftAddress(&modules[module_index]),chip_pos%2==0,0xffffffff,ndelay_units)){ - if(module_index!=0) Module_SetTopIDelay(&modules[module_index],chip_pos,ndelay_units); - else{ + if (chip_pos/2==0) { //left fpga + if (Module_TopAddressIsValid(&modules[module_index])) { + if (Feb_Control_SendIDelays(Module_GetTopLeftAddress(&modules[module_index]),chip_pos%2==0,0xffffffff,ndelay_units)) { + if (module_index!=0) Module_SetTopIDelay(&modules[module_index],chip_pos,ndelay_units); + else { for(i=0;i0x3ff) ndelay_units=0x3ff; +int Feb_Control_SendIDelays(unsigned int dst_num, int chip_lr, unsigned int channels, unsigned int ndelay_units) { + if (ndelay_units>0x3ff) ndelay_units=0x3ff; // this is global unsigned int delay_data_valid_nclks = 15 - ((ndelay_units&0x3c0)>>6); //data valid delay upto 15 clks ndelay_units &= 0x3f; @@ -520,18 +525,19 @@ int Feb_Control_SendIDelays(unsigned int dst_num, int chip_lr, unsigned int chan unsigned int set_left_delay_channels = chip_lr ? channels:0; unsigned int set_right_delay_channels = chip_lr ? 0:channels; - printf("\tSetting delays of "); - if(set_left_delay_channels!=0) printf("left chips of dst_num %d",dst_num); - else if(set_right_delay_channels!=0) printf("right chips of dst_num %d",dst_num); - printf(", tracks 0x%x to: %d, %d clks and %d units.\n",channels,(((15-delay_data_valid_nclks)<<6)|ndelay_units),delay_data_valid_nclks,ndelay_units); + FILE_LOG(logDEBUG5, ("\tSetting delays of %s chips of dst_num %d, " + "tracks 0x%x to %d, %d clks and %d units.\n", + ((set_left_delay_channels != 0) ? "left" : "right"), + dst_num, channels, (((15-delay_data_valid_nclks)<<6)|ndelay_units), + delay_data_valid_nclks, ndelay_units)); - if(Feb_Control_activated){ - if(!Feb_Interface_WriteRegister(dst_num,CHIP_DATA_OUT_DELAY_REG2, 1<<31 | delay_data_valid_nclks<<16 | ndelay_units,0,0) || //the 1<<31 time enables the setting of the data valid delays + if (Feb_Control_activated) { + if (!Feb_Interface_WriteRegister(dst_num,CHIP_DATA_OUT_DELAY_REG2, 1<<31 | delay_data_valid_nclks<<16 | ndelay_units,0,0) || //the 1<<31 time enables the setting of the data valid delays !Feb_Interface_WriteRegister(dst_num,CHIP_DATA_OUT_DELAY_REG3,set_left_delay_channels,0,0) || !Feb_Interface_WriteRegister(dst_num,CHIP_DATA_OUT_DELAY_REG4,set_right_delay_channels,0,0) || - !Feb_Interface_WriteRegister(dst_num,CHIP_DATA_OUT_DELAY_REG_CTRL,CHIP_DATA_OUT_DELAY_SET,1,1)){ - cprintf(RED,"Warning: could not SetChipDataInputDelays(...).\n"); + !Feb_Interface_WriteRegister(dst_num,CHIP_DATA_OUT_DELAY_REG_CTRL,CHIP_DATA_OUT_DELAY_SET,1,1)) { + FILE_LOG(logERROR, ("could not SetChipDataInputDelays(...).\n")); return 0; } } @@ -540,20 +546,20 @@ int Feb_Control_SendIDelays(unsigned int dst_num, int chip_lr, unsigned int chan } -int Feb_Control_VoltageToDAC(float value, unsigned int* digital,unsigned int nsteps,float vmin,float vmax){ - if(valuevmax) return 0; +int Feb_Control_VoltageToDAC(float value, unsigned int* digital,unsigned int nsteps,float vmin,float vmax) { + if (valuevmax) return 0; *digital = (int)(((value-vmin)/(vmax-vmin))*(nsteps-1) + 0.5); return 1; } -float Feb_Control_DACToVoltage(unsigned int digital,unsigned int nsteps,float vmin,float vmax){ +float Feb_Control_DACToVoltage(unsigned int digital,unsigned int nsteps,float vmin,float vmax) { return vmin+(vmax-vmin)*digital/(nsteps-1); } //only master gets to call this function -int Feb_Control_SetHighVoltage(int value){ - printf(" Setting High Voltage:\t"); +int Feb_Control_SetHighVoltage(int value) { + FILE_LOG(logDEBUG5, (" Setting High Voltage:\t")); /* * maximum voltage of the hv dc/dc converter: * 300 for single module power distribution board @@ -562,7 +568,7 @@ int Feb_Control_SetHighVoltage(int value){ */ const float vmin=0; float vmax=200; - if(Feb_control_normal) + if (Feb_control_normal) vmax=300; const float vlimit=200; const unsigned int ntotalsteps = 256; @@ -570,21 +576,22 @@ int Feb_Control_SetHighVoltage(int value){ unsigned int dacval = 0; //calculate dac value - if(!Feb_Control_VoltageToDAC(value,&dacval,nsteps,vmin,vlimit)){ - cprintf(RED,"\nWarning: SetHighVoltage bad value, %d. The range is 0 to %d V.\n",value, (int)vlimit); + if (!Feb_Control_VoltageToDAC(value,&dacval,nsteps,vmin,vlimit)) { + FILE_LOG(logERROR, ("SetHighVoltage bad value, %d. The range is 0 to %d V.\n",value, (int)vlimit)); return -1; } - printf("(%d dac):\t%dV\n", dacval, value); + FILE_LOG(logINFO, ("High Voltage set to %dV\n", value)); + FILE_LOG(logDEBUG5, ("High Voltage set to (%d dac):\t%dV\n", dacval, value)); return Feb_Control_SendHighVoltage(dacval); } -int Feb_Control_GetHighVoltage(int* value){ - printf(" Getting High Voltage:\t"); +int Feb_Control_GetHighVoltage(int* value) { + FILE_LOG(logDEBUG5, (" Getting High Voltage:\t")); unsigned int dacval = 0; - if(!Feb_Control_ReceiveHighVoltage(&dacval)) + if (!Feb_Control_ReceiveHighVoltage(&dacval)) return 0; //ok, convert dac to v @@ -596,25 +603,25 @@ int Feb_Control_GetHighVoltage(int* value){ */ const float vmin=0; float vmax=200; - if(Feb_control_normal) + if (Feb_control_normal) vmax=300; const float vlimit=200; const unsigned int ntotalsteps = 256; unsigned int nsteps = ntotalsteps*vlimit/vmax; *value = (int)(Feb_Control_DACToVoltage(dacval,nsteps,vmin,vlimit)+0.5); - printf("(%d dac)\t%dV\n", dacval, *value); - + FILE_LOG(logINFO, ("High Voltage read %dV\n", *value)); + FILE_LOG(logDEBUG5, ("High Voltage read (%d dac)\t%dV\n", dacval, *value)); return 1; } -int Feb_Control_SendHighVoltage(int dacvalue){ +int Feb_Control_SendHighVoltage(int dacvalue) { //normal - if(Feb_control_normal){ + if (Feb_control_normal) { //open file FILE* fd=fopen(NORMAL_HIGHVOLTAGE_OUTPUTPORT,"w"); - if(fd==NULL){ - cprintf(RED,"\nWarning: Could not open file for writing to set high voltage\n"); + if (fd==NULL) { + FILE_LOG(logERROR, ("Could not open file for writing to set high voltage\n")); return 0; } //convert to string, add 0 and write to file @@ -623,10 +630,10 @@ int Feb_Control_SendHighVoltage(int dacvalue){ } //9m - else{ + else { /*Feb_Control_OpenSerialCommunication();*/ - if (Feb_Control_hv_fd == -1){ - cprintf(RED,"\nWarning: High voltage serial communication not set up for 9m\n"); + if (Feb_Control_hv_fd == -1) { + FILE_LOG(logERROR, ("High voltage serial communication not set up for 9m\n")); return 0; } @@ -635,34 +642,34 @@ int Feb_Control_SendHighVoltage(int dacvalue){ buffer[SPECIAL9M_HIGHVOLTAGE_BUFFERSIZE-1]='\n'; int n; sprintf(buffer,"p%d",dacvalue); - cprintf(GREEN,"Sending HV: '%s'\n",buffer); + FILE_LOG(logINFO, ("Sending HV: '%s'\n",buffer)); n = write(Feb_Control_hv_fd, buffer, SPECIAL9M_HIGHVOLTAGE_BUFFERSIZE); if (n < 0) { - cprintf(RED,"\nWarning: Error writing to i2c bus\n"); + FILE_LOG(logERROR, ("writing to i2c bus\n")); return 0; } #ifdef VERBOSEI - cprintf(GREEN,"Sent %d Bytes\n", n); + FILE_LOG(logINFO, ("Sent %d Bytes\n", n)); #endif //ok/fail memset(buffer,0,SPECIAL9M_HIGHVOLTAGE_BUFFERSIZE); buffer[SPECIAL9M_HIGHVOLTAGE_BUFFERSIZE-1] = '\n'; n = read(Feb_Control_hv_fd, buffer, SPECIAL9M_HIGHVOLTAGE_BUFFERSIZE); if (n < 0) { - cprintf(RED,"\nWarning: Error reading from i2c bus\n"); + FILE_LOG(logERROR, ("reading from i2c bus\n")); return 0; } #ifdef VERBOSEI - cprintf(GREEN,"Received %d Bytes\n", n); + FILE_LOG(logINFO, ("Received %d Bytes\n", n)); #endif - cprintf(GREEN,"Received HV: '%s'\n",buffer); + FILE_LOG(logINFO, ("Received HV: '%s'\n",buffer)); fflush(stdout); /*Feb_Control_CloseSerialCommunication();*/ - if(buffer[0] != 's'){ - cprintf(RED,"\nError: Failed to set high voltage\n"); + if (buffer[0] != 's') { + FILE_LOG(logERROR, ("\nError: Failed to set high voltage\n")); return 0; } - cprintf(GREEN,"%s\n",buffer); + FILE_LOG(logINFO, ("%s\n",buffer)); } @@ -675,22 +682,22 @@ int Feb_Control_SendHighVoltage(int dacvalue){ -int Feb_Control_ReceiveHighVoltage(unsigned int* value){ +int Feb_Control_ReceiveHighVoltage(unsigned int* value) { //normal - if(Feb_control_normal){ + if (Feb_control_normal) { //open file FILE* fd=fopen(NORMAL_HIGHVOLTAGE_INPUTPORT,"r"); - if(fd==NULL){ - cprintf(RED,"\nWarning: Could not open file for writing to get high voltage\n"); + if (fd==NULL) { + FILE_LOG(logERROR, ("Could not open file for writing to get high voltage\n")); return 0; } //read, assigning line to null and readbytes to 0 then getline allocates initial buffer size_t readbytes=0; char* line=NULL; - if(getline(&line, &readbytes, fd) == -1){ - cprintf(RED,"\nWarning: could not read file to get high voltage\n"); + if (getline(&line, &readbytes, fd) == -1) { + FILE_LOG(logERROR, ("could not read file to get high voltage\n")); return 0; } //read again to read the updated value @@ -698,8 +705,8 @@ int Feb_Control_ReceiveHighVoltage(unsigned int* value){ free(line); readbytes=0; readbytes = getline(&line, &readbytes, fd); - if(readbytes == -1){ - cprintf(RED,"\nWarning: could not read file to get high voltage\n"); + if (readbytes == -1) { + FILE_LOG(logERROR, ("could not read file to get high voltage\n")); return 0; } // Remove the trailing 0 @@ -710,11 +717,11 @@ int Feb_Control_ReceiveHighVoltage(unsigned int* value){ //9m - else{ + else { /*Feb_Control_OpenSerialCommunication();*/ - if (Feb_Control_hv_fd == -1){ - cprintf(RED,"\nWarning: High voltage serial communication not set up for 9m\n"); + if (Feb_Control_hv_fd == -1) { + FILE_LOG(logERROR, ("High voltage serial communication not set up for 9m\n")); return 0; } char buffer[SPECIAL9M_HIGHVOLTAGE_BUFFERSIZE]; @@ -723,14 +730,14 @@ int Feb_Control_ReceiveHighVoltage(unsigned int* value){ //request strcpy(buffer,"g "); - cprintf(GREEN,"\nSending HV: '%s'\n",buffer); + FILE_LOG(logINFO, ("\nSending HV: '%s'\n",buffer)); n = write(Feb_Control_hv_fd, buffer, SPECIAL9M_HIGHVOLTAGE_BUFFERSIZE); if (n < 0) { - cprintf(RED,"\nWarning: Error writing to i2c bus\n"); + FILE_LOG(logERROR, ("writing to i2c bus\n")); return 0; } #ifdef VERBOSEI - cprintf(GREEN,"Sent %d Bytes\n", n); + FILE_LOG(logINFO, ("Sent %d Bytes\n", n)); #endif //ok/fail @@ -738,15 +745,15 @@ int Feb_Control_ReceiveHighVoltage(unsigned int* value){ buffer[SPECIAL9M_HIGHVOLTAGE_BUFFERSIZE-1] = '\n'; n = read(Feb_Control_hv_fd, buffer, SPECIAL9M_HIGHVOLTAGE_BUFFERSIZE); if (n < 0) { - cprintf(RED,"\nWarning: Error reading from i2c bus\n"); + FILE_LOG(logERROR, ("reading from i2c bus\n")); return 0; } #ifdef VERBOSEI - cprintf(GREEN,"Received %d Bytes\n", n); + FILE_LOG(logINFO, ("Received %d Bytes\n", n)); #endif - cprintf(GREEN,"Received HV: '%s'\n",buffer); - if(buffer[0] != 's'){ - cprintf(RED,"\nWarning: failed to read high voltage\n"); + FILE_LOG(logINFO, ("Received HV: '%s'\n",buffer)); + if (buffer[0] != 's') { + FILE_LOG(logERROR, ("failed to read high voltage\n")); return 0; } @@ -754,16 +761,16 @@ int Feb_Control_ReceiveHighVoltage(unsigned int* value){ buffer[SPECIAL9M_HIGHVOLTAGE_BUFFERSIZE-1] = '\n'; n = read(Feb_Control_hv_fd, buffer, SPECIAL9M_HIGHVOLTAGE_BUFFERSIZE); if (n < 0) { - cprintf(RED,"\nWarning: Error reading from i2c bus\n"); + FILE_LOG(logERROR, ("reading from i2c bus\n")); return 0; } #ifdef VERBOSEI - cprintf(GREEN,"Received %d Bytes\n", n); + FILE_LOG(logINFO, ("Received %d Bytes\n", n)); #endif - cprintf(GREEN,"Received HV: '%s'\n",buffer); + FILE_LOG(logINFO, ("Received HV: '%s'\n",buffer)); /*Feb_Control_OpenSerialCommunication();*/ - if (!sscanf(buffer,"%d",value)){ - cprintf(RED,"\nWarning: failed to scan high voltage read\n"); + if (!sscanf(buffer,"%d",value)) { + FILE_LOG(logERROR, ("failed to scan high voltage read\n")); return 0; } } @@ -773,87 +780,87 @@ int Feb_Control_ReceiveHighVoltage(unsigned int* value){ -int Feb_Control_DecodeDACString(char* dac_str, unsigned int* module_index, int* top, int* bottom, unsigned int* dac_ch){ +int Feb_Control_DecodeDACString(char* dac_str, unsigned int* module_index, int* top, int* bottom, unsigned int* dac_ch) { char* local_s = dac_str; *module_index = Feb_Control_current_index; *top = 1;//make them both 1 instead of this *bottom = 1; - if(Module_BottomAddressIsValid(&modules[*module_index])) + if (Module_BottomAddressIsValid(&modules[*module_index])) *top=0; else *bottom=0; *dac_ch = 0; - if(!Feb_Control_GetDACNumber(local_s,dac_ch)){ - cprintf(RED,"Error in dac_name: %s (%s)\n",dac_str,local_s); + if (!Feb_Control_GetDACNumber(local_s,dac_ch)) { + FILE_LOG(logERROR, ("invalid dac_name: %s (%s)\n",dac_str,local_s)); return 0; } return 1; } -int Feb_Control_SetDAC(char* dac_str, int value, int is_a_voltage_mv){ +int Feb_Control_SetDAC(char* dac_str, int value, int is_a_voltage_mv) { unsigned int i; unsigned int module_index, dac_ch; int top, bottom; - if(!Feb_Control_DecodeDACString(dac_str,&module_index,&top,&bottom,&dac_ch)) return 0; + if (!Feb_Control_DecodeDACString(dac_str,&module_index,&top,&bottom,&dac_ch)) return 0; unsigned int v = value; - if(is_a_voltage_mv&&!Feb_Control_VoltageToDAC(value,&v,4096,0,2048)){ - cprintf(RED,"Warning: SetDac bad value, %d. The range is 0 to 2048 mV.\n",value); + if (is_a_voltage_mv&&!Feb_Control_VoltageToDAC(value,&v,4096,0,2048)) { + FILE_LOG(logERROR, ("SetDac bad value, %d. The range is 0 to 2048 mV.\n",value)); return 0; } - if(v<0||v>4095){ - cprintf(RED,"Warning: SetDac bad value, %d. The range is 0 to 4095.\n",v); + if (v<0||v>4095) { + FILE_LOG(logERROR, ("SetDac bad value, %d. The range is 0 to 4095.\n",v)); return 0; } - if(top&&Module_TopAddressIsValid(&modules[module_index])){ + if (top&&Module_TopAddressIsValid(&modules[module_index])) { - if(!Feb_Control_SendDACValue(Module_GetTopRightAddress(&modules[module_index]),dac_ch,&v)) return 0; + if (!Feb_Control_SendDACValue(Module_GetTopRightAddress(&modules[module_index]),dac_ch,&v)) return 0; - if(module_index!=0) Module_SetTopDACValue(&modules[module_index],dac_ch,v); + if (module_index!=0) Module_SetTopDACValue(&modules[module_index],dac_ch,v); else for(i=0;i=Module_ndacs){ - cprintf(RED,"Warning: GetDACName index out of range, %d invalid.\n",dac_num); +int Feb_Control_GetDACName(unsigned int dac_num, char* s) { + if (dac_num>=Module_ndacs) { + FILE_LOG(logERROR, ("GetDACName index out of range, %d invalid.\n",dac_num)); return 0; } strcpy(s,Module_dac_names[dac_num]); return 1; } -int Feb_Control_GetDACNumber(char* s, unsigned int* n){ +int Feb_Control_GetDACNumber(char* s, unsigned int* n) { unsigned int i; - for(i=0;i15){ - cprintf(RED,"Warning invalid ch for SetDAC.\n"); + if (ch<0||ch>15) { + FILE_LOG(logERROR, ("invalid ch for SetDAC.\n")); return 0; } - //if(voltage<0) return PowerDownDAC(socket_num,ch); + //if (voltage<0) return PowerDownDAC(socket_num,ch); *value&=0xfff; unsigned int dac_ic = (ch<8) ? 1:2; @@ -878,73 +885,72 @@ int Feb_Control_SendDACValue(unsigned int dst_num, unsigned int ch, unsigned int unsigned int r = dac_ic<<30 | 3<<16 | dac_ch<<12 | *value; //3 write and power up - if(Feb_Control_activated){ - if(!Feb_Interface_WriteRegister(dst_num,0,r,1,0)){ - cprintf(RED,"Warning: trouble setting dac %d voltage.\n",ch); + if (Feb_Control_activated) { + if (!Feb_Interface_WriteRegister(dst_num,0,r,1,0)) { + FILE_LOG(logERROR, ("trouble setting dac %d voltage.\n",ch)); return 0; } } float voltage=Feb_Control_DACToVoltage(*value,4096,0,2048); - printf("\tDac number %d (%s) of dst %d set to %d (%f mV).\n",ch,Module_dac_names[ch],dst_num,*value,voltage); + FILE_LOG(logINFO, ("%s set to %d (%.2fmV)\n", Module_dac_names[ch],*value,voltage)); + FILE_LOG(logDEBUG5, ("Dac number %d (%s) of dst %d set to %d (%f mV)\n",ch,Module_dac_names[ch],dst_num,*value,voltage)); return 1; } -int Feb_Control_SetTrimbits(unsigned int module_num, unsigned int *trimbits){ - printf("Setting Trimbits\n"); +int Feb_Control_SetTrimbits(unsigned int module_num, unsigned int *trimbits) { + FILE_LOG(logINFO, ("Setting Trimbits\n")); //for (int iy=10000;iy<20020;++iy)//263681 //for (int iy=263670;iy<263680;++iy)//263681 - // printf("%d:%c\t\t",iy,trimbits[iy]); + // FILE_LOG(logINFO, ("%d:%c\t\t",iy,trimbits[iy])); unsigned int trimbits_to_load_l[1024]; unsigned int trimbits_to_load_r[1024]; unsigned int module_index=0; - if(!Feb_Control_GetModuleIndex(module_num,&module_index)){ - cprintf(RED,"Warning could not set trimbits, bad module number.\n"); + if (!Feb_Control_GetModuleIndex(module_num,&module_index)) { + FILE_LOG(logERROR, ("could not set trimbits, bad module number.\n")); return 0; } - if(Feb_Control_Reset() == STATUS_ERROR) cprintf(RED,"Warning could not reset DAQ.\n"); - int l_r; //printf("222\n"); - for(l_r=0;l_r<2;l_r++){ // l_r loop - //printf("\nl_r:%d\t\t",l_r); + if (Feb_Control_Reset() == STATUS_ERROR) { + FILE_LOG(logERROR, ("could not reset DAQ.\n")); + } + int l_r; + for(l_r=0;l_r<2;l_r++) { // l_r loop unsigned int disable_chip_mask = l_r ? DAQ_CS_BAR_LEFT : DAQ_CS_BAR_RIGHT; - if(Feb_Control_activated){ - if(!(Feb_Interface_WriteRegister(0xfff,DAQ_REG_STATIC_BITS,disable_chip_mask|DAQ_STATIC_BIT_PROGRAM|DAQ_STATIC_BIT_M8,0,0) + if (Feb_Control_activated) { + if (!(Feb_Interface_WriteRegister(0xfff,DAQ_REG_STATIC_BITS,disable_chip_mask|DAQ_STATIC_BIT_PROGRAM|DAQ_STATIC_BIT_M8,0,0) &&Feb_Control_SetCommandRegister(DAQ_SET_STATIC_BIT) - &&(Feb_Control_StartDAQOnlyNWaitForFinish(5000) == STATUS_IDLE))){ - printf("Could not select chips\n"); + &&(Feb_Control_StartDAQOnlyNWaitForFinish(5000) == STATUS_IDLE))) { + FILE_LOG(logERROR, ("Could not select chips\n")); return 0; } } int row_set; - for(row_set=0;row_set<16;row_set++){ //16 rows at a time - //printf("row_set:%d\t\t",row_set); - if(row_set==0){ - if(!Feb_Control_SetCommandRegister(DAQ_RESET_COMPLETELY|DAQ_SEND_A_TOKEN_IN|DAQ_LOAD_16ROWS_OF_TRIMBITS)){ - cprintf(RED,"Warning: Could not Feb_Control_SetCommandRegister for loading trim bits.\n"); + for(row_set=0;row_set<16;row_set++) { //16 rows at a time + if (row_set==0) { + if (!Feb_Control_SetCommandRegister(DAQ_RESET_COMPLETELY|DAQ_SEND_A_TOKEN_IN|DAQ_LOAD_16ROWS_OF_TRIMBITS)) { + FILE_LOG(logERROR, ("Could not Feb_Control_SetCommandRegister for loading trim bits.\n")); return 0; } - }else{ - if(!Feb_Control_SetCommandRegister(DAQ_LOAD_16ROWS_OF_TRIMBITS)){ - cprintf(RED,"Warning: Could not Feb_Control_SetCommandRegister for loading trim bits.\n"); + } else { + if (!Feb_Control_SetCommandRegister(DAQ_LOAD_16ROWS_OF_TRIMBITS)) { + FILE_LOG(logERROR, ("Could not Feb_Control_SetCommandRegister for loading trim bits.\n")); return 0; } } int row; - for(row=0;row<16;row++){ //row loop - //printf("row:%d\t\t",row); + for(row=0;row<16;row++) { //row loop int offset = 2*32*row; int sc; - for(sc=0;sc<32;sc++){ //supercolumn loop sc - //printf("sc:%d\t\t",sc); + for(sc=0;sc<32;sc++) { //supercolumn loop sc int super_column_start_position_l = 1030*row + l_r *258 + sc*8; int super_column_start_position_r = 1030*row + 516 + l_r *258 + sc*8; @@ -958,15 +964,14 @@ int Feb_Control_SetTrimbits(unsigned int module_num, unsigned int *trimbits){ trimbits_to_load_l[offset+chip_sc+32] = 0; trimbits_to_load_r[offset+chip_sc+32] = 0; int i; - for(i=0;i<8;i++){ // column loop i - //printf("i:%d\t\t",i); + for(i=0;i<8;i++) { // column loop i - if(Module_TopAddressIsValid(&modules[1])){ + if (Module_TopAddressIsValid(&modules[1])) { 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{ + } 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 @@ -977,25 +982,25 @@ int Feb_Control_SetTrimbits(unsigned int module_num, unsigned int *trimbits){ } //end supercolumn loop sc } //end row loop - if(Module_TopAddressIsValid(&modules[1])){ - if(Feb_Control_activated){ - if(!Feb_Interface_WriteMemoryInLoops(Module_GetTopLeftAddress(&modules[Feb_Control_current_index]),0,0,1024,trimbits_to_load_l)|| + if (Module_TopAddressIsValid(&modules[1])) { + if (Feb_Control_activated) { + if (!Feb_Interface_WriteMemoryInLoops(Module_GetTopLeftAddress(&modules[Feb_Control_current_index]),0,0,1024,trimbits_to_load_l)|| !Feb_Interface_WriteMemoryInLoops(Module_GetTopRightAddress(&modules[Feb_Control_current_index]),0,0,1024,trimbits_to_load_r)|| - //if(!Feb_Interface_WriteMemory(Module_GetTopLeftAddress(&modules[0]),0,0,1023,trimbits_to_load_r)|| + //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) != STATUS_IDLE)){ - printf(" some errror!\n"); + (Feb_Control_StartDAQOnlyNWaitForFinish(5000) != STATUS_IDLE)) { + FILE_LOG(logERROR, (" some errror!\n")); return 0; } } - }else{ - if(Feb_Control_activated){ - if(!Feb_Interface_WriteMemoryInLoops(Module_GetBottomLeftAddress(&modules[Feb_Control_current_index]),0,0,1024,trimbits_to_load_l)|| + } else { + if (Feb_Control_activated) { + if (!Feb_Interface_WriteMemoryInLoops(Module_GetBottomLeftAddress(&modules[Feb_Control_current_index]),0,0,1024,trimbits_to_load_l)|| !Feb_Interface_WriteMemoryInLoops(Module_GetBottomRightAddress(&modules[Feb_Control_current_index]),0,0,1024,trimbits_to_load_r)|| - //if(!Feb_Interface_WriteMemory(Module_GetTopLeftAddress(&modules[0]),0,0,1023,trimbits_to_load_r)|| + //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) != STATUS_IDLE)){ - printf(" some errror!\n"); + (Feb_Control_StartDAQOnlyNWaitForFinish(5000) != STATUS_IDLE)) { + FILE_LOG(logERROR, (" some errror!\n")); return 0; } } @@ -1010,47 +1015,46 @@ int Feb_Control_SetTrimbits(unsigned int module_num, unsigned int *trimbits){ } -unsigned int* Feb_Control_GetTrimbits(){ +unsigned int* Feb_Control_GetTrimbits() { return Feb_Control_last_downloaded_trimbits; } -unsigned int Feb_Control_AddressToAll(){printf("in Feb_Control_AddressToAll()\n"); +unsigned int Feb_Control_AddressToAll() { + FILE_LOG(logINFO, ("in Feb_Control_AddressToAll()\n")); -if(moduleSize==0) return 0; + if (moduleSize==0) return 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 (Module_BottomAddressIsValid(&modules[1])) { + //if (Feb_Control_am_i_master) + return Module_GetBottomLeftAddress(&modules[1])|Module_GetBottomRightAddress(&modules[1]); + // else return 0; + } -return Module_GetTopLeftAddress(&modules[1])|Module_GetTopRightAddress(&modules[1]); -//return Module_GetTopLeftAddress(&modules[0])|Module_GetTopRightAddress(&modules[0]); + return Module_GetTopLeftAddress(&modules[1])|Module_GetTopRightAddress(&modules[1]); + //return Module_GetTopLeftAddress(&modules[0])|Module_GetTopRightAddress(&modules[0]); } -int Feb_Control_SetCommandRegister(unsigned int cmd){ - if(Feb_Control_activated) +int Feb_Control_SetCommandRegister(unsigned int cmd) { + if (Feb_Control_activated) return Feb_Interface_WriteRegister(Feb_Control_AddressToAll(),DAQ_REG_CHIP_CMDS,cmd,0,0); else return 1; } -int Feb_Control_GetDAQStatusRegister(unsigned int dst_address, unsigned int* ret_status){ +int Feb_Control_GetDAQStatusRegister(unsigned int dst_address, unsigned int* ret_status) { //if deactivated, should be handled earlier and should not get into this function - if(Feb_Control_activated){ - if(!Feb_Interface_ReadRegister(dst_address,DAQ_REG_STATUS,ret_status)){ - cprintf(RED,"Error: reading status register.\n"); + if (Feb_Control_activated) { + if (!Feb_Interface_ReadRegister(dst_address,DAQ_REG_STATUS,ret_status)) { + FILE_LOG(logERROR, ("Error: reading status register.\n")); return 0; } } @@ -1060,10 +1064,10 @@ int Feb_Control_GetDAQStatusRegister(unsigned int dst_address, unsigned int* ret } -int Feb_Control_StartDAQOnlyNWaitForFinish(int sleep_time_us){ - if(Feb_Control_activated){ - if(!Feb_Interface_WriteRegister(Feb_Control_AddressToAll(),DAQ_REG_CTRL,0,0,0)||!Feb_Interface_WriteRegister(Feb_Control_AddressToAll(),DAQ_REG_CTRL,DAQ_CTRL_START,0,0)){ - cprintf(RED,"Warning: could not start.\n"); +int Feb_Control_StartDAQOnlyNWaitForFinish(int sleep_time_us) { + if (Feb_Control_activated) { + if (!Feb_Interface_WriteRegister(Feb_Control_AddressToAll(),DAQ_REG_CTRL,0,0,0)||!Feb_Interface_WriteRegister(Feb_Control_AddressToAll(),DAQ_REG_CTRL,DAQ_CTRL_START,0,0)) { + FILE_LOG(logERROR, ("could not start.\n")); return 0; } } @@ -1071,30 +1075,31 @@ int Feb_Control_StartDAQOnlyNWaitForFinish(int sleep_time_us){ } -int Feb_Control_AcquisitionInProgress(){ +int Feb_Control_AcquisitionInProgress() { unsigned int status_reg_r=0,status_reg_l=0; //deactivated should return end of acquisition - if(!Feb_Control_activated) + if (!Feb_Control_activated) return STATUS_IDLE; int ind = Feb_Control_current_index; - if(Module_BottomAddressIsValid(&modules[ind])){ + if (Module_BottomAddressIsValid(&modules[ind])) { - if(!(Feb_Control_GetDAQStatusRegister(Module_GetBottomRightAddress(&modules[ind]),&status_reg_r))) - {cprintf(RED,"Error: Trouble reading Status register. bottom right address\n");return STATUS_ERROR;} - if(!(Feb_Control_GetDAQStatusRegister(Module_GetBottomLeftAddress(&modules[ind]),&status_reg_l))) - {cprintf(RED,"Error: Trouble reading Status register. bottom left address\n");return STATUS_ERROR;} + if (!(Feb_Control_GetDAQStatusRegister(Module_GetBottomRightAddress(&modules[ind]),&status_reg_r))) + {FILE_LOG(logERROR, ("Error: Trouble reading Status register. bottom right address\n"));return STATUS_ERROR;} + if (!(Feb_Control_GetDAQStatusRegister(Module_GetBottomLeftAddress(&modules[ind]),&status_reg_l))) + {FILE_LOG(logERROR, ("Error: Trouble reading Status register. bottom left address\n"));return STATUS_ERROR;} - }else{ - if(!(Feb_Control_GetDAQStatusRegister(Module_GetTopRightAddress(&modules[ind]),&status_reg_r))) - {cprintf(RED,"Error: Trouble reading Status register. top right address\n");return STATUS_ERROR;} - if(!(Feb_Control_GetDAQStatusRegister(Module_GetTopLeftAddress(&modules[ind]),&status_reg_l))) - {cprintf(RED,"Error: Trouble reading Status register. top left address\n");return STATUS_ERROR;} + } else { + if (!(Feb_Control_GetDAQStatusRegister(Module_GetTopRightAddress(&modules[ind]),&status_reg_r))) + {FILE_LOG(logERROR, ("Error: Trouble reading Status register. top right address\n"));return STATUS_ERROR;} + if (!(Feb_Control_GetDAQStatusRegister(Module_GetTopLeftAddress(&modules[ind]),&status_reg_l))) + {FILE_LOG(logERROR, ("Error: Trouble reading Status register. top left address\n"));return STATUS_ERROR;} } //running - if((status_reg_r|status_reg_l)&DAQ_STATUS_DAQ_RUNNING) {/*printf("**runningggg\n");*/ + if ((status_reg_r|status_reg_l)&DAQ_STATUS_DAQ_RUNNING) { + FILE_LOG(logDEBUG5, ("**runningggg\n")); return STATUS_RUNNING; } //idle @@ -1102,30 +1107,30 @@ int Feb_Control_AcquisitionInProgress(){ } -int Feb_Control_AcquisitionStartedBit(){ +int Feb_Control_AcquisitionStartedBit() { unsigned int status_reg_r=0,status_reg_l=0; //deactivated should return acquisition started/ready - if(!Feb_Control_activated) + if (!Feb_Control_activated) return 1; int ind = Feb_Control_current_index; - if(Module_BottomAddressIsValid(&modules[ind])){ + if (Module_BottomAddressIsValid(&modules[ind])) { - if(!(Feb_Control_GetDAQStatusRegister(Module_GetBottomRightAddress(&modules[ind]),&status_reg_r))) - {cprintf(RED,"Error: Trouble reading Status register. bottom right address\n");return -1;} - if(!(Feb_Control_GetDAQStatusRegister(Module_GetBottomLeftAddress(&modules[ind]),&status_reg_l))) - {cprintf(RED,"Error: Trouble reading Status register. bottom left address\n");return -1;} + if (!(Feb_Control_GetDAQStatusRegister(Module_GetBottomRightAddress(&modules[ind]),&status_reg_r))) + {FILE_LOG(logERROR, ("Error: Trouble reading Status register. bottom right address\n"));return -1;} + if (!(Feb_Control_GetDAQStatusRegister(Module_GetBottomLeftAddress(&modules[ind]),&status_reg_l))) + {FILE_LOG(logERROR, ("Error: Trouble reading Status register. bottom left address\n"));return -1;} - }else{ - if(!(Feb_Control_GetDAQStatusRegister(Module_GetTopRightAddress(&modules[ind]),&status_reg_r))) - {cprintf(RED,"Error: Trouble reading Status register. top right address\n"); return -1;} - if(!(Feb_Control_GetDAQStatusRegister(Module_GetTopLeftAddress(&modules[ind]),&status_reg_l))) - {cprintf(RED,"Error: Trouble reading Status register. top left address\n");return -1;} + } else { + if (!(Feb_Control_GetDAQStatusRegister(Module_GetTopRightAddress(&modules[ind]),&status_reg_r))) + {FILE_LOG(logERROR, ("Error: Trouble reading Status register. top right address\n")); return -1;} + if (!(Feb_Control_GetDAQStatusRegister(Module_GetTopLeftAddress(&modules[ind]),&status_reg_l))) + {FILE_LOG(logERROR, ("Error: Trouble reading Status register. top left address\n"));return -1;} } //doesnt mean it started, just the bit - if((status_reg_r|status_reg_l)&DAQ_STATUS_DAQ_RUN_TOGGLE) + if ((status_reg_r|status_reg_l)&DAQ_STATUS_DAQ_RUN_TOGGLE) return 1; return 0; @@ -1133,13 +1138,13 @@ int Feb_Control_AcquisitionStartedBit(){ -int Feb_Control_WaitForFinishedFlag(int sleep_time_us){ +int Feb_Control_WaitForFinishedFlag(int sleep_time_us) { int is_running = Feb_Control_AcquisitionInProgress(); int check_error = 0; // it will break out if it is idle or if check_error is more than 5 times - while(is_running != STATUS_IDLE){ + while(is_running != STATUS_IDLE) { usleep(sleep_time_us); is_running = Feb_Control_AcquisitionInProgress(); @@ -1157,35 +1162,35 @@ int Feb_Control_WaitForFinishedFlag(int sleep_time_us){ } -int Feb_Control_WaitForStartedFlag(int sleep_time_us, int prev_flag){ +int Feb_Control_WaitForStartedFlag(int sleep_time_us, int prev_flag) { //deactivated dont wait (otherwise give a toggle value back) - if(!Feb_Control_activated) + if (!Feb_Control_activated) return 1; //did not start - if(prev_flag == -1) + if (prev_flag == -1) return 0; int value = prev_flag; - while(value == prev_flag){ + while(value == prev_flag) { usleep(sleep_time_us); value = Feb_Control_AcquisitionStartedBit(); } //did not start - if(value == -1) + if (value == -1) return 0; return 1; } -int Feb_Control_Reset(){ - printf("Reset daq\n"); - if(Feb_Control_activated){ - if(!Feb_Interface_WriteRegister(Feb_Control_AddressToAll(),DAQ_REG_CTRL,0,0,0) || !Feb_Interface_WriteRegister(Feb_Control_AddressToAll(),DAQ_REG_CTRL,DAQ_CTRL_RESET,0,0) || !Feb_Interface_WriteRegister(Feb_Control_AddressToAll(),DAQ_REG_CTRL,0,0,0)){ - cprintf(RED,"Warning: Could not reset daq, no response.\n"); +int Feb_Control_Reset() { + FILE_LOG(logINFO, ("Reset daq\n")); + if (Feb_Control_activated) { + if (!Feb_Interface_WriteRegister(Feb_Control_AddressToAll(),DAQ_REG_CTRL,0,0,0) || !Feb_Interface_WriteRegister(Feb_Control_AddressToAll(),DAQ_REG_CTRL,DAQ_CTRL_RESET,0,0) || !Feb_Interface_WriteRegister(Feb_Control_AddressToAll(),DAQ_REG_CTRL,0,0,0)) { + FILE_LOG(logERROR, ("Could not reset daq, no response.\n")); return 0; } } @@ -1196,278 +1201,280 @@ int Feb_Control_Reset(){ -int Feb_Control_SetStaticBits(){ - if(Feb_Control_activated){ +int Feb_Control_SetStaticBits() { + if (Feb_Control_activated) { //program=1,m4=2,m8=4,test=8,rotest=16,cs_bar_left=32,cs_bar_right=64 - if(!Feb_Interface_WriteRegister(Feb_Control_AddressToAll(),DAQ_REG_STATIC_BITS,Feb_Control_staticBits,0,0) || + if (!Feb_Interface_WriteRegister(Feb_Control_AddressToAll(),DAQ_REG_STATIC_BITS,Feb_Control_staticBits,0,0) || !Feb_Control_SetCommandRegister(DAQ_SET_STATIC_BIT) || - (Feb_Control_StartDAQOnlyNWaitForFinish(5000) != STATUS_IDLE)){ - cprintf(RED,"Warning: Could not set static bits\n"); + (Feb_Control_StartDAQOnlyNWaitForFinish(5000) != STATUS_IDLE)) { + FILE_LOG(logERROR, ("Could not set static bits\n")); return 0; } } return 1; } -int Feb_Control_SetStaticBits1(unsigned int the_static_bits){ +int Feb_Control_SetStaticBits1(unsigned int the_static_bits) { Feb_Control_staticBits = the_static_bits; return Feb_Control_SetStaticBits(); } -int Feb_Control_SetInTestModeVariable(int on){ - if(on) Feb_Control_staticBits |= DAQ_STATIC_BIT_CHIP_TEST; //setting test bit to high +int Feb_Control_SetInTestModeVariable(int on) { + if (on) Feb_Control_staticBits |= DAQ_STATIC_BIT_CHIP_TEST; //setting test bit to high else Feb_Control_staticBits &= (~DAQ_STATIC_BIT_CHIP_TEST); //setting test bit to low return 1; } -int Feb_Control_GetTestModeVariable(){ +int Feb_Control_GetTestModeVariable() { return Feb_Control_staticBits&DAQ_STATIC_BIT_CHIP_TEST; } -int Feb_Control_SetDynamicRange(unsigned int four_eight_sixteen_or_thirtytwo){ +int Feb_Control_SetDynamicRange(unsigned int four_eight_sixteen_or_thirtytwo) { static unsigned int everything_but_bit_mode = DAQ_STATIC_BIT_PROGRAM|DAQ_STATIC_BIT_CHIP_TEST|DAQ_STATIC_BIT_ROTEST; - if(four_eight_sixteen_or_thirtytwo==4){ + if (four_eight_sixteen_or_thirtytwo==4) { Feb_Control_staticBits = DAQ_STATIC_BIT_M4 | (Feb_Control_staticBits&everything_but_bit_mode); //leave test bits in currernt state Feb_Control_subFrameMode &= ~DAQ_NEXPOSURERS_ACTIVATE_AUTO_SUBIMAGING; - }else if(four_eight_sixteen_or_thirtytwo==8){ + } else if (four_eight_sixteen_or_thirtytwo==8) { Feb_Control_staticBits = DAQ_STATIC_BIT_M8 | (Feb_Control_staticBits&everything_but_bit_mode); Feb_Control_subFrameMode &= ~DAQ_NEXPOSURERS_ACTIVATE_AUTO_SUBIMAGING; - }else if(four_eight_sixteen_or_thirtytwo==16){ + } else if (four_eight_sixteen_or_thirtytwo==16) { Feb_Control_staticBits = DAQ_STATIC_BIT_M12 | (Feb_Control_staticBits&everything_but_bit_mode); Feb_Control_subFrameMode &= ~DAQ_NEXPOSURERS_ACTIVATE_AUTO_SUBIMAGING; - }else if(four_eight_sixteen_or_thirtytwo==32){ + } else if (four_eight_sixteen_or_thirtytwo==32) { Feb_Control_staticBits = DAQ_STATIC_BIT_M12 | (Feb_Control_staticBits&everything_but_bit_mode); Feb_Control_subFrameMode |= DAQ_NEXPOSURERS_ACTIVATE_AUTO_SUBIMAGING; - }else{ - cprintf(RED,"Warning: dynamic range (%d) not valid, not setting bit mode.\n",four_eight_sixteen_or_thirtytwo); - printf("Set dynamic range int must equal 4,8 16, or 32.\n"); + } else { + FILE_LOG(logERROR, ("dynamic range (%d) not valid, not setting bit mode.\n",four_eight_sixteen_or_thirtytwo)); + FILE_LOG(logINFO, ("Set dynamic range int must equal 4,8 16, or 32.\n")); return 0; } - printf("Dynamic range set to: %d\n",four_eight_sixteen_or_thirtytwo); + FILE_LOG(logINFO, ("Dynamic range set to %d\n",four_eight_sixteen_or_thirtytwo)); return 1; } -unsigned int Feb_Control_GetDynamicRange(){ - if(Feb_Control_subFrameMode&DAQ_NEXPOSURERS_ACTIVATE_AUTO_SUBIMAGING) return 32; - else if(DAQ_STATIC_BIT_M4&Feb_Control_staticBits) return 4; - else if(DAQ_STATIC_BIT_M8&Feb_Control_staticBits) return 8; +unsigned int Feb_Control_GetDynamicRange() { + if (Feb_Control_subFrameMode&DAQ_NEXPOSURERS_ACTIVATE_AUTO_SUBIMAGING) return 32; + else if (DAQ_STATIC_BIT_M4&Feb_Control_staticBits) return 4; + else if (DAQ_STATIC_BIT_M8&Feb_Control_staticBits) return 8; return 16; } -int Feb_Control_SetReadoutSpeed(unsigned int readout_speed){ //0->full,1->half,2->quarter or 3->super_slow +int Feb_Control_SetReadoutSpeed(unsigned int readout_speed) { //0->full,1->half,2->quarter or 3->super_slow Feb_Control_acquireNReadoutMode &= (~DAQ_CHIP_CONTROLLER_SUPER_SLOW_SPEED); - if(readout_speed==1){ + if (readout_speed==1) { Feb_Control_acquireNReadoutMode |= DAQ_CHIP_CONTROLLER_HALF_SPEED; - printf("Everything at half speed, ie. reading with 50 MHz main clk (half speed) ....\n"); - }else if(readout_speed==2){ + FILE_LOG(logINFO, ("Speed set to half speed (50 MHz)\n")); + } else if (readout_speed==2) { Feb_Control_acquireNReadoutMode |= DAQ_CHIP_CONTROLLER_QUARTER_SPEED; - printf("Everything at quarter speed, ie. reading with 25 MHz main clk (quarter speed) ....\n"); - }else if(readout_speed==3){ + FILE_LOG(logINFO, ("Speed set to quarter speed (25 MHz)\n")); + } else if (readout_speed==3) { Feb_Control_acquireNReadoutMode |= DAQ_CHIP_CONTROLLER_SUPER_SLOW_SPEED; - printf("Everything at super slow speed, ie. reading with ~0.200 MHz main clk (super slow speed) ....\n"); - }else{ - if(readout_speed){ - cprintf(RED,"Warning readout speed %d unknown, defaulting to full speed.\n",readout_speed); - printf("Everything at full speed, ie. reading with 100 MHz main clk (full speed) ....\n"); + FILE_LOG(logINFO, ("Speed set to super slow speed (~0.200 MHz)\n")); + } else { + if (readout_speed) { + FILE_LOG(logERROR, ("readout speed %d unknown, defaulting to full speed.\n",readout_speed)); + FILE_LOG(logINFO, ("full speed, (100 MHz)\n")); return 0; } - printf("Everything at full speed, ie. reading with 100 MHz main clk (full speed) ....\n"); + FILE_LOG(logINFO, ("Speed set to full speed (100 MHz)\n")); } return 1; } -int Feb_Control_SetReadoutMode(unsigned int readout_mode){ //0->parallel,1->non-parallel,2-> safe_mode +int Feb_Control_SetReadoutMode(unsigned int readout_mode) { //0->parallel,1->non-parallel,2-> safe_mode Feb_Control_acquireNReadoutMode &= (~DAQ_NEXPOSURERS_PARALLEL_MODE); - if(readout_mode==1){ + if (readout_mode==1) { Feb_Control_acquireNReadoutMode |= DAQ_NEXPOSURERS_NORMAL_NONPARALLEL_MODE; - printf("Readout mode set to normal non-parallel readout mode ... \n");; - }else if(readout_mode==2){ + FILE_LOG(logINFO, ("Readout mode set to Non Parallel\n")); + } else if (readout_mode==2) { Feb_Control_acquireNReadoutMode |= DAQ_NEXPOSURERS_SAFEST_MODE_ROW_CLK_BEFORE_MODE; - printf("Readout mode set to safest mode, row clk before main clk readout sequence .... \n");; - }else{ + FILE_LOG(logINFO, ("Readout mode set to Safe (row clk before main clk readout sequence)\n")); + } else { Feb_Control_acquireNReadoutMode |= DAQ_NEXPOSURERS_PARALLEL_MODE; - if(readout_mode){ - cprintf(RED,"Warning readout mode %d) unknown, defaulting to full speed.\n",readout_mode); - printf("Readout mode set to parrallel acquire/read mode .... \n");; + if (readout_mode) { + FILE_LOG(logERROR, ("readout mode %d) unknown, defaulting to parallel readout.\n",readout_mode)); + FILE_LOG(logINFO, ("Readout mode set to Parallel\n")); return 0; } - printf("Readout mode set to parrallel acquire/read mode .... \n");; + FILE_LOG(logINFO, ("Readout mode set to Parallel\n")); } return 1; } -int Feb_Control_SetTriggerMode(unsigned int trigger_mode,int polarity){ +int Feb_Control_SetTriggerMode(unsigned int trigger_mode,int polarity) { //"00"-> internal exposure time and period, //"01"-> external acquistion start and internal exposure time and period, //"10"-> external start trigger and internal exposure time, //"11"-> external triggered start and stop of exposures Feb_Control_triggerMode = (~DAQ_NEXPOSURERS_EXTERNAL_IMAGE_START_AND_STOP); - if(trigger_mode == 1){ + if (trigger_mode == 1) { Feb_Control_triggerMode = DAQ_NEXPOSURERS_EXTERNAL_ACQUISITION_START; - printf("Trigger mode: external start of acquisition sequence, internal exposure length and period.\n");; - }else if(trigger_mode == 2){ + FILE_LOG(logINFO, ("Trigger mode set to Burst Trigger\n")); + } else if (trigger_mode == 2) { Feb_Control_triggerMode = DAQ_NEXPOSURERS_EXTERNAL_IMAGE_START; - printf("Trigger mode: external image start, internal exposure time.\n");; - }else if(trigger_mode == 3){ + FILE_LOG(logINFO, ("Trigger mode set to Trigger Exposure\n")); + } else if (trigger_mode == 3) { Feb_Control_triggerMode = DAQ_NEXPOSURERS_EXTERNAL_IMAGE_START_AND_STOP; - printf("Trigger mode: externally controlled, external image window (start and stop).\n");; - }else{ + FILE_LOG(logINFO, ("Trigger mode set to Gated\n")); + } else { Feb_Control_triggerMode = DAQ_NEXPOSURERS_INTERNAL_ACQUISITION; - if(trigger_mode) cprintf(RED,"Warning trigger %d) unknown, defaulting to internal triggering.\n",trigger_mode);; + if (trigger_mode) { + FILE_LOG(logERROR, ("trigger %d) unknown, defaulting to Auto\n",trigger_mode)); + } - printf("Trigger mode: acquisition internally controlled exposure length and period.\n");; + FILE_LOG(logINFO, ("Trigger mode set to Auto\n")); return trigger_mode==0; } - if(polarity){ + if (polarity) { Feb_Control_triggerMode |= DAQ_NEXPOSURERS_EXTERNAL_TRIGGER_POLARITY; - printf("External trigger polarity set to positive.\n");; - }else{ + FILE_LOG(logINFO, ("External trigger polarity set to positive\n")); + } else { Feb_Control_triggerMode &= (~DAQ_NEXPOSURERS_EXTERNAL_TRIGGER_POLARITY); - printf("External trigger polarity set to negitive.\n");; + FILE_LOG(logINFO, ("External trigger polarity set to negitive\n")); } return 1; } -int Feb_Control_SetExternalEnableMode(int use_external_enable, int polarity){ - if(use_external_enable){ +int Feb_Control_SetExternalEnableMode(int use_external_enable, int polarity) { + if (use_external_enable) { Feb_Control_externalEnableMode |= DAQ_NEXPOSURERS_EXTERNAL_ENABLING; - printf("External enabling enabled, "); - if(polarity){ + if (polarity) { Feb_Control_externalEnableMode |= DAQ_NEXPOSURERS_EXTERNAL_ENABLING_POLARITY; - printf(", polarity set to positive.\n");; - }else{ + } else { Feb_Control_externalEnableMode &= (~DAQ_NEXPOSURERS_EXTERNAL_ENABLING_POLARITY); - printf(", polarity set to negative.\n");; } - }else{ + FILE_LOG(logINFO, ("External enabling enabled, polarity set to %s\n", + (polarity ? "positive" : "negative"))); + + } else { Feb_Control_externalEnableMode = 0; /* changed by Dhanya according to old code &= (~DAQ_NEXPOSURERS_EXTERNAL_ENABLING);*/ - printf("External enabling disabled.\n");; + FILE_LOG(logINFO, ("External enabling disabled\n")); } return 1; } -int Feb_Control_SetNExposures(unsigned int n_images){ - if(!n_images){ - cprintf(RED,"Warning nimages must be greater than zero.%d\n",n_images); +int Feb_Control_SetNExposures(unsigned int n_images) { + if (!n_images) { + FILE_LOG(logERROR, ("nimages must be greater than zero.%d\n",n_images)); return 0; } Feb_Control_nimages = n_images; - printf("Number of images set to: %d\n",Feb_Control_nimages); + FILE_LOG(logINFO, ("Number of images set to %d\n",Feb_Control_nimages)); return 1; } -unsigned int Feb_Control_GetNExposures(){return Feb_Control_nimages;} +unsigned int Feb_Control_GetNExposures() {return Feb_Control_nimages;} -int Feb_Control_SetExposureTime(double the_exposure_time_in_sec){ +int Feb_Control_SetExposureTime(double the_exposure_time_in_sec) { Feb_Control_exposure_time_in_sec = the_exposure_time_in_sec; - printf("Exposure time set to: %fs\n",Feb_Control_exposure_time_in_sec); + FILE_LOG(logINFO, ("Exposure time set to %fs\n",Feb_Control_exposure_time_in_sec)); return 1; } -double Feb_Control_GetExposureTime(){return Feb_Control_exposure_time_in_sec;} -int64_t Feb_Control_GetExposureTime_in_nsec(){return (int64_t)(Feb_Control_exposure_time_in_sec*(1E9));} +double Feb_Control_GetExposureTime() {return Feb_Control_exposure_time_in_sec;} +int64_t Feb_Control_GetExposureTime_in_nsec() {return (int64_t)(Feb_Control_exposure_time_in_sec*(1E9));} -int Feb_Control_SetSubFrameExposureTime(int64_t the_subframe_exposure_time_in_10nsec){ +int Feb_Control_SetSubFrameExposureTime(int64_t the_subframe_exposure_time_in_10nsec) { Feb_Control_subframe_exposure_time_in_10nsec = the_subframe_exposure_time_in_10nsec; - printf("Sub Frame Exposure time set to: %lld\n",(long long int)Feb_Control_subframe_exposure_time_in_10nsec); + FILE_LOG(logINFO, ("Sub Frame Exposure time set to %lldns\n",(long long int)Feb_Control_subframe_exposure_time_in_10nsec * 10)); return 1; } -int64_t Feb_Control_GetSubFrameExposureTime(){return Feb_Control_subframe_exposure_time_in_10nsec*10;} +int64_t Feb_Control_GetSubFrameExposureTime() {return Feb_Control_subframe_exposure_time_in_10nsec*10;} -int Feb_Control_SetSubFramePeriod(int64_t the_subframe_period_in_10nsec){ +int Feb_Control_SetSubFramePeriod(int64_t the_subframe_period_in_10nsec) { Feb_Control_subframe_period_in_10nsec = the_subframe_period_in_10nsec; - printf("Sub Frame Period set to: %lld\n",(long long int)Feb_Control_subframe_period_in_10nsec); + FILE_LOG(logINFO, ("Sub Frame Period set to %lldns\n",(long long int)Feb_Control_subframe_period_in_10nsec * 10)); return 1; } -int64_t Feb_Control_GetSubFramePeriod(){return Feb_Control_subframe_period_in_10nsec*10;} +int64_t Feb_Control_GetSubFramePeriod() {return Feb_Control_subframe_period_in_10nsec*10;} -int Feb_Control_SetExposurePeriod(double the_exposure_period_in_sec){ +int Feb_Control_SetExposurePeriod(double the_exposure_period_in_sec) { Feb_Control_exposure_period_in_sec = the_exposure_period_in_sec; - printf("Exposure period set to: %f\n",Feb_Control_exposure_period_in_sec); + FILE_LOG(logINFO, ("Exposure period set to %fs\n",Feb_Control_exposure_period_in_sec)); return 1; } -double Feb_Control_GetExposurePeriod(){return Feb_Control_exposure_period_in_sec;} +double Feb_Control_GetExposurePeriod() {return Feb_Control_exposure_period_in_sec;} -unsigned int Feb_Control_ConvertTimeToRegister(float time_in_sec){ +unsigned int Feb_Control_ConvertTimeToRegister(float time_in_sec) { float n_clk_cycles = round(time_in_sec/10e-9); //200 MHz ctb clk or 100 MHz feb clk unsigned int decoded_time; - if(n_clk_cycles>(pow(2,29)-1)*pow(10,7)){ + if (n_clk_cycles>(pow(2,29)-1)*pow(10,7)) { float max_time = 10e-9*(pow(2,28)-1)*pow(10,7); - cprintf(RED,"Warning: time exceeds (%f) maximum exposure time of %f sec.\n",time_in_sec,max_time); - printf("\t Setting to maximum %f us.\n",max_time); + FILE_LOG(logERROR, ("time exceeds (%f) maximum exposure time of %f sec.\n",time_in_sec,max_time)); + FILE_LOG(logINFO, ("\t Setting to maximum %f us.\n",max_time)); decoded_time = 0xffffffff; - }else{ + } else { int power_of_ten = 0; - while(n_clk_cycles>pow(2,29)-1){ power_of_ten++; n_clk_cycles = round(n_clk_cycles/10.0);} + while(n_clk_cycles>pow(2,29)-1) { power_of_ten++; n_clk_cycles = round(n_clk_cycles/10.0);} decoded_time = (int)(n_clk_cycles)<<3 | (int)(power_of_ten); } return decoded_time; } -int Feb_Control_ResetChipCompletely(){ - if(!Feb_Control_SetCommandRegister(DAQ_RESET_COMPLETELY) || (Feb_Control_StartDAQOnlyNWaitForFinish(5000) != STATUS_IDLE)){ - cprintf(RED,"Warning: could not ResetChipCompletely() with 0x%x.\n",DAQ_RESET_COMPLETELY); +int Feb_Control_ResetChipCompletely() { + if (!Feb_Control_SetCommandRegister(DAQ_RESET_COMPLETELY) || (Feb_Control_StartDAQOnlyNWaitForFinish(5000) != STATUS_IDLE)) { + FILE_LOG(logERROR, ("could not ResetChipCompletely() with 0x%x.\n",DAQ_RESET_COMPLETELY)); return 0; } - printf("Chip reset completely\n"); + FILE_LOG(logINFO, ("Chip reset completely\n")); return 1; } -int Feb_Control_ResetChipPartially(){ - if(!Feb_Control_SetCommandRegister(DAQ_RESET_PERIPHERY) || (Feb_Control_StartDAQOnlyNWaitForFinish(5000) != STATUS_IDLE)){ - cprintf(RED,"Warning: could not ResetChipPartially with periphery\n"); +int Feb_Control_ResetChipPartially() { + if (!Feb_Control_SetCommandRegister(DAQ_RESET_PERIPHERY) || (Feb_Control_StartDAQOnlyNWaitForFinish(5000) != STATUS_IDLE)) { + FILE_LOG(logERROR, ("could not ResetChipPartially with periphery\n")); return 0; } - printf("Chip reset periphery 0x%x\n",DAQ_RESET_PERIPHERY); + FILE_LOG(logINFO, ("Chip reset periphery 0x%x\n",DAQ_RESET_PERIPHERY)); - if(!Feb_Control_SetCommandRegister(DAQ_RESET_COLUMN_SELECT) || (Feb_Control_StartDAQOnlyNWaitForFinish(5000) != STATUS_IDLE)){ - cprintf(RED,"Warning: could not ResetChipPartially with column select\n"); + if (!Feb_Control_SetCommandRegister(DAQ_RESET_COLUMN_SELECT) || (Feb_Control_StartDAQOnlyNWaitForFinish(5000) != STATUS_IDLE)) { + FILE_LOG(logERROR, ("could not ResetChipPartially with column select\n")); return 0; } - printf("Chip reset column select 0x%x\n",DAQ_RESET_COLUMN_SELECT); + FILE_LOG(logINFO, ("Chip reset column select 0x%x\n",DAQ_RESET_COLUMN_SELECT)); return 1; } -void Feb_Control_PrintAcquisitionSetup(){ +void Feb_Control_PrintAcquisitionSetup() { time_t rawtime; time(&rawtime); struct tm *timeinfo = localtime(&rawtime); - printf("\nStarting an exposure: %s",asctime(timeinfo)); - printf("\t Dynamic range nbits: %d\n",Feb_Control_GetDynamicRange()); - printf("\t Trigger mode: 0x%x\n",Feb_Control_triggerMode); - printf("\t Number of exposures: %d\n",Feb_Control_GetNExposures()); - printf("\t Exsposure time (if used): %f seconds.\n",Feb_Control_exposure_time_in_sec); - printf("\t Exsposure period (if used): %f seconds.\n\n\n",Feb_Control_exposure_period_in_sec); + FILE_LOG(logINFO, ("\nStarting an exposure: %s",asctime(timeinfo))); + FILE_LOG(logINFO, ("\t Dynamic range nbits: %d\n",Feb_Control_GetDynamicRange())); + FILE_LOG(logINFO, ("\t Trigger mode: 0x%x\n",Feb_Control_triggerMode)); + FILE_LOG(logINFO, ("\t Number of exposures: %d\n",Feb_Control_GetNExposures())); + FILE_LOG(logINFO, ("\t Exsposure time (if used): %f seconds.\n",Feb_Control_exposure_time_in_sec)); + FILE_LOG(logINFO, ("\t Exsposure period (if used): %f seconds.\n\n\n",Feb_Control_exposure_period_in_sec)); } -int Feb_Control_SendBitModeToBebServer(){ +int Feb_Control_SendBitModeToBebServer() { unsigned int just_bit_mode = (DAQ_STATIC_BIT_M4|DAQ_STATIC_BIT_M8) & Feb_Control_staticBits; unsigned int bit_mode = 16; //default - if(just_bit_mode == DAQ_STATIC_BIT_M4) bit_mode = 4; - else if(just_bit_mode == DAQ_STATIC_BIT_M8) bit_mode = 8; - else if(Feb_Control_subFrameMode&DAQ_NEXPOSURERS_ACTIVATE_AUTO_SUBIMAGING) bit_mode = 32; + if (just_bit_mode == DAQ_STATIC_BIT_M4) bit_mode = 4; + else if (just_bit_mode == DAQ_STATIC_BIT_M8) bit_mode = 8; + else if (Feb_Control_subFrameMode&DAQ_NEXPOSURERS_ACTIVATE_AUTO_SUBIMAGING) bit_mode = 32; - if(!Beb_SetUpTransferParameters(bit_mode)){ - cprintf(RED,"Error: sending bit mode ...\n"); + if (!Beb_SetUpTransferParameters(bit_mode)) { + FILE_LOG(logERROR, ("Error: sending bit mode ...\n")); return 0; } @@ -1475,35 +1482,35 @@ int Feb_Control_SendBitModeToBebServer(){ } -int Feb_Control_PrepareForAcquisition(){//return 1; +int Feb_Control_PrepareForAcquisition() {//return 1; static unsigned int reg_nums[20]; static unsigned int reg_vals[20]; Feb_Control_PrintAcquisitionSetup(); - // if(!Reset()||!ResetDataStream()){ - if(Feb_Control_Reset() == STATUS_ERROR){ - printf("Trouble reseting daq or data stream...\n");; + // if (!Reset()||!ResetDataStream()) { + if (Feb_Control_Reset() == STATUS_ERROR) { + FILE_LOG(logERROR, ("Trouble reseting daq or data stream...\n")); return 0; } - if(!Feb_Control_SetStaticBits1(Feb_Control_staticBits&(DAQ_STATIC_BIT_M4|DAQ_STATIC_BIT_M8))){ - printf("Trouble setting static bits ...\n");; + if (!Feb_Control_SetStaticBits1(Feb_Control_staticBits&(DAQ_STATIC_BIT_M4|DAQ_STATIC_BIT_M8))) { + FILE_LOG(logERROR, ("Trouble setting static bits ...\n")); return 0; } - if(!Feb_Control_SendBitModeToBebServer()){ - printf("Trouble sending static bits to server ...\n");; + if (!Feb_Control_SendBitModeToBebServer()) { + FILE_LOG(logERROR, ("Trouble sending static bits to server ...\n")); return 0; } int ret=0; - if(Feb_Control_counter_bit) + if (Feb_Control_counter_bit) ret = Feb_Control_ResetChipCompletely(); else ret = Feb_Control_ResetChipPartially(); - if(!ret){ - printf("Trouble resetting chips ...\n");; + if (!ret) { + FILE_LOG(logERROR, ("Trouble resetting chips ...\n")); return 0; } @@ -1522,10 +1529,10 @@ int Feb_Control_PrepareForAcquisition(){//return 1; reg_vals[5]= Feb_Control_subframe_exposure_time_in_10nsec; //(1 means 10ns, 100 means 1000ns) reg_nums[6]=DAQ_REG_SUBFRAME_PERIOD; reg_vals[6]= Feb_Control_subframe_period_in_10nsec; //(1 means 10ns, 100 means 1000ns) - // if(!Feb_Interface_WriteRegisters((Module_GetTopLeftAddress(&modules[1])|Module_GetTopRightAddress(&modules[1])),20,reg_nums,reg_vals,0,0)){ - if(Feb_Control_activated){ - if(!Feb_Interface_WriteRegisters(Feb_Control_AddressToAll(),7,reg_nums,reg_vals,0,0)){ - printf("Trouble starting acquisition....\n");; + // if (!Feb_Interface_WriteRegisters((Module_GetTopLeftAddress(&modules[1])|Module_GetTopRightAddress(&modules[1])),20,reg_nums,reg_vals,0,0)) { + if (Feb_Control_activated) { + if (!Feb_Interface_WriteRegisters(Feb_Control_AddressToAll(),7,reg_nums,reg_vals,0,0)) { + FILE_LOG(logERROR, ("Trouble starting acquisition....\n")); return 0; } } @@ -1535,24 +1542,24 @@ int Feb_Control_PrepareForAcquisition(){//return 1; -int Feb_Control_StartAcquisition(){ - printf("****** starting acquisition********* \n"); +int Feb_Control_StartAcquisition() { + FILE_LOG(logINFO, ("****** starting acquisition********* \n")); static unsigned int reg_nums[20]; static unsigned int reg_vals[20]; int i; - for(i=0;i<14;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_Control_activated){ - if(!Feb_Interface_WriteRegisters(Feb_Control_AddressToAll(),15,reg_nums,reg_vals,0,0)){ - cprintf(RED,"Trouble starting acquisition....\n");; + if (Feb_Control_activated) { + if (!Feb_Interface_WriteRegisters(Feb_Control_AddressToAll(),15,reg_nums,reg_vals,0,0)) { + FILE_LOG(logERROR, ("Trouble starting acquisition....\n")); return 0; } } @@ -1561,13 +1568,13 @@ int Feb_Control_StartAcquisition(){ return 1; } -int Feb_Control_StopAcquisition(){ +int Feb_Control_StopAcquisition() { return Feb_Control_Reset(); } -int Feb_Control_SaveAllTrimbitsTo(int value){ +int Feb_Control_SaveAllTrimbitsTo(int value) { unsigned int chanregs[Feb_Control_trimbit_size]; int i; for(i=0;i255||y<0||y>255){ - cprintf(RED,"Warning: Pixel out of range.\n"); + if (x<0||x>255||y<0||y>255) { + FILE_LOG(logERROR, ("Pixel out of range.\n")); return 0; } @@ -1609,17 +1616,17 @@ int Feb_Control_Pulse_Pixel(int npulses, int x, int y){ Feb_Control_SetStaticBits(); Feb_Control_SetCommandRegister(DAQ_RESET_PERIPHERY|DAQ_RESET_COLUMN_SELECT); if (Feb_Control_StartDAQOnlyNWaitForFinish(5000) != STATUS_IDLE) { - cprintf(RED,"Warning: could not pulse pixel as status not idle\n"); + FILE_LOG(logERROR, ("could not pulse pixel as status not idle\n")); return 0; } unsigned int serial_in = 8<<(4*(7-x%8)); - if(!Feb_Control_Shift32InSerialIn(serial_in)){ - cprintf(RED,"Warning ChipController::PulsePixel: could shift in the initail 32.\n"); + if (!Feb_Control_Shift32InSerialIn(serial_in)) { + FILE_LOG(logERROR, ("ChipController::PulsePixel: could shift in the initail 32.\n")); return 0; } - if(!pulse_multiple) + if (!pulse_multiple) serial_in=0; for(i=0;i1023){ - cprintf(RED,"Warning: Clock row clock ntimes (%d) exceeds the maximum value of 1023.\n\t Setting ntimes to 1023.\n",ntimes); +int Feb_Control_ClockRowClock(unsigned int ntimes) { + if (ntimes>1023) { + FILE_LOG(logERROR, ("Clock row clock ntimes (%d) exceeds the maximum value of 1023.\n\t Setting ntimes to 1023.\n",ntimes)); ntimes=1023; } - if(Feb_Control_activated){ - if(!Feb_Control_SetCommandRegister(DAQ_CLK_ROW_CLK_NTIMES) || + if (Feb_Control_activated) { + if (!Feb_Control_SetCommandRegister(DAQ_CLK_ROW_CLK_NTIMES) || !Feb_Interface_WriteRegister(Feb_Control_AddressToAll(),DAQ_REG_CLK_ROW_CLK_NTIMES,ntimes,0,0) || - (Feb_Control_StartDAQOnlyNWaitForFinish(5000) != STATUS_IDLE)){ - cprintf(RED,"Warning: could not clock row clock.\n"); + (Feb_Control_StartDAQOnlyNWaitForFinish(5000) != STATUS_IDLE)) { + FILE_LOG(logERROR, ("could not clock row clock.\n")); return 0; } } @@ -1691,16 +1698,16 @@ int Feb_Control_ClockRowClock(unsigned int ntimes){ } -int Feb_Control_PulseChip(int npulses){ +int Feb_Control_PulseChip(int npulses) { int i; int on = 1; - if(npulses == -1){ + if (npulses == -1) { on = 0; - printf("\nResetting to normal mode\n"); - }else{ - printf("\n\nPulsing Chip.\n");//really just toggles the enable - printf("Vcmp should be set to 2.0 and Vtrim should be 2.\n"); + FILE_LOG(logINFO, ("\nResetting to normal mode\n")); + } else { + FILE_LOG(logINFO, ("\n\nPulsing Chip.\n"));//really just toggles the enable + FILE_LOG(logINFO, ("Vcmp should be set to 2.0 and Vtrim should be 2.\n")); } @@ -1708,145 +1715,149 @@ int Feb_Control_PulseChip(int npulses){ Feb_Control_SetStaticBits(); //toggle the enable 2x times Feb_Control_ResetChipCompletely(); - for(i=0;i ratemax) ratemax= Feb_Control_rate_meas[i]; + for(i=0;i ratemax) ratemax= Feb_Control_rate_meas[i]; } /* b : index/address of block ram/rate correction table b0 : base in vhdl m : slope in vhdl - + Firmware: data_in(11..2) -> memory address --> memory data_in( 1..0) -> lsb - + mem_data_out(13.. 0) -> base mem_data_out(17..14) -> slope - + delta = slope*lsb corr = base+delta - */ - + */ + int next_i=0; double beforemax; b0[0] = 0; m[0] = 1; - + Feb_Control_rate_correction_table[0] = (((int)(m[0]+0.5)&0xf)<<14) | ((int)(b0[0]+0.5)&0x3fff); int b=0; - for(b=1;b<1024;b++){ - if(m[b-1]<15){ + for(b=1;b<1024;b++) { + if (m[b-1]<15) { double s=0,sx=0,sy=0,sxx=0,sxy=0; - for(;;next_i++){ - if(next_i>=np){ - for(; b<1024; b++){ - if(beforemax>ratemax) b0[b] = beforemax; - else b0[b] = ratemax; - m[b] = 15; - Feb_Control_rate_correction_table[b] = (((int)(m[b]+0.5)&0xf)<<14) | ((int)(b0[b]+0.5)&0x3fff); - } - b=1024; - break; - } - - double x = Feb_Control_rate_meas[next_i] - b*4; - double y = next_i; - /*printf("Start Loop x: %f,\t y: %f,\t s: %f,\t sx: %f,\t sy: %f,\t sxx: %f,\t sxy: %f,\t " + for(;;next_i++) { + if (next_i>=np) { + for(; b<1024; b++) { + if (beforemax>ratemax) b0[b] = beforemax; + else b0[b] = ratemax; + m[b] = 15; + Feb_Control_rate_correction_table[b] = (((int)(m[b]+0.5)&0xf)<<14) | ((int)(b0[b]+0.5)&0x3fff); + } + b=1024; + break; + } + + double x = Feb_Control_rate_meas[next_i] - b*4; + double y = next_i; + /*FILE_LOG(logDEBUG5, ("Start Loop x: %f,\t y: %f,\t s: %f,\t sx: %f,\t sy: %f,\t sxx: %f,\t sxy: %f,\t " "next_i: %d,\t b: %d,\t Feb_Control_rate_meas[next_i]: %f\n", - x, y, s, sx, sy, sxx, sxy, next_i, b, Feb_Control_rate_meas[next_i]);*/ - - if(x < -0.5) continue; - if(x > 3.5) break; - s += 1; - sx += x; - sy += y; - sxx += x*x; - sxy += x*y; - /*printf("End Loop x: %f,\t y: %f,\t s: %f,\t sx: %f,\t sy: %f,\t sxx: %f,\t sxy: %f,\t " + x, y, s, sx, sy, sxx, sxy, next_i, b, Feb_Control_rate_meas[next_i]));*/ + + if (x < -0.5) continue; + if (x > 3.5) break; + s += 1; + sx += x; + sy += y; + sxx += x*x; + sxy += x*y; + /*FILE_LOG(logDEBUG5, ("End Loop x: %f,\t y: %f,\t s: %f,\t sx: %f,\t sy: %f,\t sxx: %f,\t sxy: %f,\t " "next_i: %d,\t b: %d,\t Feb_Control_rate_meas[next_i]: %f\n", - x, y, s, sx, sy, sxx, sxy, next_i, b, Feb_Control_rate_meas[next_i]);*/ + x, y, s, sx, sy, sxx, sxy, next_i, b, Feb_Control_rate_meas[next_i]));*/ } double delta = s*sxx - sx*sx; b0[b] = (sxx*sy - sx*sxy)/delta; m[b] = (s*sxy - sx*sy) /delta; beforemax= b0[b]; - if(m[b]<0||m[b]>15){ - m[b]=15; - if(beforemax>ratemax) b0[b] = beforemax; - else b0[b] = ratemax; + if (m[b]<0||m[b]>15) { + m[b]=15; + if (beforemax>ratemax) b0[b] = beforemax; + else b0[b] = ratemax; } - /*printf("After Loop s: %f,\t sx: %f,\t sy: %f,\t sxx: %f,\t sxy: %f,\t " + /*FILE_LOG(logDEBUG5, ("After Loop s: %f,\t sx: %f,\t sy: %f,\t sxx: %f,\t sxy: %f,\t " "next_i: %d,\t b: %d,\t Feb_Control_rate_meas[next_i]: %f\n", - s, sx, sy, sxx, sxy, next_i, b, Feb_Control_rate_meas[next_i]);*/ + s, sx, sy, sxx, sxy, next_i, b, Feb_Control_rate_meas[next_i]));*/ // cout<ratemax) b0[b] = beforemax; - else b0[b] = ratemax; - m[b] = 15; + } else { + if (beforemax>ratemax) b0[b] = beforemax; + else b0[b] = ratemax; + m[b] = 15; } Feb_Control_rate_correction_table[b] = (((int)(m[b]+0.5)&0xf)<<14) | ((int)(b0[b]+0.5)&0x3fff); - /*printf("After Loop 4*b: %d\tbase:%d\tslope:%d\n",4*b, (int)(b0[b]+0.5), (int)(m[b]+0.5) );*/ + /*FILE_LOG(logDEBUG5, ("After Loop 4*b: %d\tbase:%d\tslope:%d\n",4*b, (int)(b0[b]+0.5), (int)(m[b]+0.5) ));*/ } - if(Feb_Control_SetRateCorrectionTable(Feb_Control_rate_correction_table)){ + if (Feb_Control_SetRateCorrectionTable(Feb_Control_rate_correction_table)) { Feb_Control_RateTable_Tau_in_nsec = tau_in_Nsec; Feb_Control_RateTable_Period_in_nsec = period_in_sec*1e9; return 1; - }else{ + } else { Feb_Control_RateTable_Tau_in_nsec = -1; Feb_Control_RateTable_Period_in_nsec = -1; return 0; @@ -1858,75 +1869,75 @@ int Feb_Control_SetRateCorrectionTau(int64_t tau_in_Nsec){ -int Feb_Control_SetRateCorrectionTable(unsigned int *table){ - if(!table){ - printf("Error: could not set rate correction table, point is zero.\n"); - Feb_Control_SetRateCorrectionVariable(0); - return 0; - } +int Feb_Control_SetRateCorrectionTable(unsigned int *table) { + if (!table) { + FILE_LOG(logERROR, ("Error: could not set rate correction table, point is zero.\n")); + Feb_Control_SetRateCorrectionVariable(0); + return 0; + } - printf("Setting rate correction table. %d %d %d %d ....\n", - table[0],table[1],table[2],table[3]); + FILE_LOG(logINFO, ("Setting rate correction table. %d %d %d %d ....\n", + table[0],table[1],table[2],table[3])); - //was added otherwise after an acquire, startdaqonlywatiforfinish waits forever - if(!Feb_Control_SetCommandRegister(DAQ_RESET_COMPLETELY)){ - cprintf(RED,"Warning: Could not Feb_Control_SetCommandRegister for loading trim bits.\n"); - return 0; - } - printf("daq reset completely\n"); + //was added otherwise after an acquire, startdaqonlywatiforfinish waits forever + if (!Feb_Control_SetCommandRegister(DAQ_RESET_COMPLETELY)) { + FILE_LOG(logERROR, ("Could not Feb_Control_SetCommandRegister for loading trim bits.\n")); + return 0; + } + FILE_LOG(logINFO, ("daq reset completely\n")); - if(Module_TopAddressIsValid(&modules[1])){ - if(Feb_Control_activated){ - if(!Feb_Interface_WriteMemoryInLoops(Module_GetTopLeftAddress(&modules[Feb_Control_current_index]),1,0,1024,Feb_Control_rate_correction_table)|| - !Feb_Interface_WriteMemoryInLoops(Module_GetTopRightAddress(&modules[Feb_Control_current_index]),1,0,1024,Feb_Control_rate_correction_table)|| - (Feb_Control_StartDAQOnlyNWaitForFinish(5000) != STATUS_IDLE)){ - cprintf(BG_RED,"Error in Top Writing to Memory ::Feb_Control_SetRateCorrectionTable\n"); - return 0; - } - } - }else{ - if(Feb_Control_activated){ - if(!Feb_Interface_WriteMemoryInLoops(Module_GetBottomLeftAddress(&modules[Feb_Control_current_index]),1,0,1024,Feb_Control_rate_correction_table)|| - !Feb_Interface_WriteMemoryInLoops(Module_GetBottomRightAddress(&modules[Feb_Control_current_index]),1,0,1024,Feb_Control_rate_correction_table)|| - (Feb_Control_StartDAQOnlyNWaitForFinish(5000) != STATUS_IDLE)){ - cprintf(BG_RED,"Error in Bottom Writing to Memory ::Feb_Control_SetRateCorrectionTable\n"); - return 0; - } - } - } - return 1; + if (Module_TopAddressIsValid(&modules[1])) { + if (Feb_Control_activated) { + if (!Feb_Interface_WriteMemoryInLoops(Module_GetTopLeftAddress(&modules[Feb_Control_current_index]),1,0,1024,Feb_Control_rate_correction_table)|| + !Feb_Interface_WriteMemoryInLoops(Module_GetTopRightAddress(&modules[Feb_Control_current_index]),1,0,1024,Feb_Control_rate_correction_table)|| + (Feb_Control_StartDAQOnlyNWaitForFinish(5000) != STATUS_IDLE)) { + FILE_LOG(logERROR, ("could not write to memory (top) ::Feb_Control_SetRateCorrectionTable\n")); + return 0; + } + } + } else { + if (Feb_Control_activated) { + if (!Feb_Interface_WriteMemoryInLoops(Module_GetBottomLeftAddress(&modules[Feb_Control_current_index]),1,0,1024,Feb_Control_rate_correction_table)|| + !Feb_Interface_WriteMemoryInLoops(Module_GetBottomRightAddress(&modules[Feb_Control_current_index]),1,0,1024,Feb_Control_rate_correction_table)|| + (Feb_Control_StartDAQOnlyNWaitForFinish(5000) != STATUS_IDLE)) { + FILE_LOG(logERROR, ("could not write to memory (bottom) ::Feb_Control_SetRateCorrectionTable\n")); + return 0; + } + } + } + return 1; } -int Feb_Control_GetRateCorrectionVariable(){ return (Feb_Control_subFrameMode&DAQ_NEXPOSURERS_ACTIVATE_RATE_CORRECTION);} +int Feb_Control_GetRateCorrectionVariable() { return (Feb_Control_subFrameMode&DAQ_NEXPOSURERS_ACTIVATE_RATE_CORRECTION);} -void Feb_Control_SetRateCorrectionVariable(int activate_rate_correction){ - if(activate_rate_correction){ - Feb_Control_subFrameMode |= DAQ_NEXPOSURERS_ACTIVATE_RATE_CORRECTION; - printf("Rate correction activated.\n"); - }else{ - Feb_Control_subFrameMode &= ~DAQ_NEXPOSURERS_ACTIVATE_RATE_CORRECTION; - printf("Rate correction deactivated.\n"); - } +void Feb_Control_SetRateCorrectionVariable(int activate_rate_correction) { + if (activate_rate_correction) { + Feb_Control_subFrameMode |= DAQ_NEXPOSURERS_ACTIVATE_RATE_CORRECTION; + FILE_LOG(logINFO, ("Rate correction activated\n")); + } else { + Feb_Control_subFrameMode &= ~DAQ_NEXPOSURERS_ACTIVATE_RATE_CORRECTION; + FILE_LOG(logINFO, ("Rate correction deactivated\n")); + } } -int Feb_Control_PrintCorrectedValues(){ +int Feb_Control_PrintCorrectedValues() { int i; int delta, slope, base, lsb, corr; - for (i=0; i < 4096; i++){ + for (i=0; i < 4096; i++) { lsb = i&3; base = Feb_Control_rate_correction_table[i>>2] & 0x3fff; slope = ((Feb_Control_rate_correction_table[i>>2] & 0x3c000) >> 14); - + delta = slope*lsb; corr = delta+base; - if(slope==15) corr= 3*slope+base; + if (slope==15) corr= 3*slope+base; - printf("Readout Input: %d,\tBase:%d,\tSlope:%d,\tLSB:%d,\tDelta:%d\tResult:%d\tReal:%lf\n", - i, base, slope, lsb, delta, corr, Feb_Control_rate_meas[i]); + FILE_LOG(logDEBUG5, ("Readout Input: %d,\tBase:%d,\tSlope:%d,\tLSB:%d,\tDelta:%d\tResult:%d\tReal:%lf\n", + i, base, slope, lsb, delta, corr, Feb_Control_rate_meas[i])); } return 1; } @@ -1935,9 +1946,9 @@ int Feb_Control_PrintCorrectedValues(){ //So if software says now 40.00 you neeed to convert to mdegrees 40000(call it A1) and then //A1/65536/0.00198421639-273.15 -int Feb_Control_GetLeftFPGATemp(){ +int Feb_Control_GetLeftFPGATemp() { unsigned int temperature=0; - if(Module_TopAddressIsValid(&modules[1])) + if (Module_TopAddressIsValid(&modules[1])) Feb_Interface_ReadRegister(Module_GetTopLeftAddress (&modules[1]),FEB_REG_STATUS, &temperature); else Feb_Interface_ReadRegister(Module_GetBottomLeftAddress (&modules[1]),FEB_REG_STATUS, &temperature); @@ -1947,9 +1958,9 @@ int Feb_Control_GetLeftFPGATemp(){ return (int)temperature; } -int Feb_Control_GetRightFPGATemp(){ +int Feb_Control_GetRightFPGATemp() { unsigned int temperature=0; - if(Module_TopAddressIsValid(&modules[1])) + if (Module_TopAddressIsValid(&modules[1])) Feb_Interface_ReadRegister(Module_GetTopRightAddress (&modules[1]),FEB_REG_STATUS, &temperature); else Feb_Interface_ReadRegister(Module_GetBottomRightAddress (&modules[1]),FEB_REG_STATUS, &temperature); @@ -1986,24 +1997,20 @@ int Feb_Control_SoftwareTrigger() { unsigned int cmd = orig_value | DAQ_REG_CHIP_CMDS_INT_TRIGGER; - if(Feb_Control_activated) { + if (Feb_Control_activated) { // set trigger bit -#ifdef VERBOSE - cprintf(BLUE,"Setting Trigger, Register:0x%x\n",cmd); -#endif + FILE_LOG(logDEBUG5, ("Setting Trigger, Register:0x%x\n",cmd)); if (!Feb_Interface_WriteRegister(Feb_Control_AddressToAll(),DAQ_REG_CHIP_CMDS,cmd,0,0)) { - cprintf(RED,"Warning: Could not give software trigger\n"); + FILE_LOG(logERROR, ("Could not give software trigger\n")); return 0; } // unset trigger bit -#ifdef VERBOSE - cprintf(BLUE,"Unsetting Trigger, Register:0x%x\n",orig_value); -#endif + FILE_LOG(logDEBUG5, ("Unsetting Trigger, Register:0x%x\n",orig_value)); if (!Feb_Interface_WriteRegister(Feb_Control_AddressToAll(),DAQ_REG_CHIP_CMDS,orig_value,0,0)) { - cprintf(RED,"Warning: Could not give software trigger\n"); + FILE_LOG(logERROR, ("Could not give software trigger\n")); return 0; } - cprintf(BLUE,"Software Internal Trigger Sent!\n"); + FILE_LOG(logINFO, ("Software Internal Trigger Sent!\n")); } return 1; @@ -2012,14 +2019,14 @@ int Feb_Control_SoftwareTrigger() { uint32_t Feb_Control_WriteRegister(uint32_t offset, uint32_t data) { uint32_t value=0; - if(Module_TopAddressIsValid(&modules[1])){ - if(!Feb_Interface_WriteRegister(Module_GetTopRightAddress (&modules[1]),offset, data,0, 0)) { - cprintf(RED,"Could not read value. Value read:%d\n", value); + if (Module_TopAddressIsValid(&modules[1])) { + if (!Feb_Interface_WriteRegister(Module_GetTopRightAddress (&modules[1]),offset, data,0, 0)) { + FILE_LOG(logERROR, ("Could not read value. Value read:%d\n", value)); value = 0; } } else { - if(!Feb_Interface_WriteRegister(Module_GetBottomRightAddress (&modules[1]),offset, data,0, 0)) { - cprintf(RED,"Could not read value. Value read:%d\n", value); + if (!Feb_Interface_WriteRegister(Module_GetBottomRightAddress (&modules[1]),offset, data,0, 0)) { + FILE_LOG(logERROR, ("Could not read value. Value read:%d\n", value)); value = 0; } } @@ -2029,14 +2036,14 @@ uint32_t Feb_Control_WriteRegister(uint32_t offset, uint32_t data) { uint32_t Feb_Control_ReadRegister(uint32_t offset) { uint32_t value=0; - if(Module_TopAddressIsValid(&modules[1])){ - if(!Feb_Interface_ReadRegister(Module_GetTopRightAddress (&modules[1]),offset, &value)) { - cprintf(RED,"Could not read value. Value read:%d\n", value); + if (Module_TopAddressIsValid(&modules[1])) { + if (!Feb_Interface_ReadRegister(Module_GetTopRightAddress (&modules[1]),offset, &value)) { + FILE_LOG(logERROR, ("Could not read value. Value read:%d\n", value)); value = 0; } } else { - if(!Feb_Interface_ReadRegister(Module_GetBottomRightAddress (&modules[1]),offset, &value)) { - cprintf(RED,"Could not read value. Value read:%d\n", value); + if (!Feb_Interface_ReadRegister(Module_GetBottomRightAddress (&modules[1]),offset, &value)) { + FILE_LOG(logERROR, ("Could not read value. Value read:%d\n", value)); value = 0; } } diff --git a/slsDetectorServers/eigerDetectorServer/FebControl.h b/slsDetectorServers/eigerDetectorServer/FebControl.h index b20da4fab..ba3cc4a55 100644 --- a/slsDetectorServers/eigerDetectorServer/FebControl.h +++ b/slsDetectorServers/eigerDetectorServer/FebControl.h @@ -1,36 +1,24 @@ - -/** - * @author Ian Johnson - * @version 1.0 - */ - - -#ifndef FEBCONTROL_H -#define FEBCONTROL_H - -#include -#include -//#include -//#include - - +#pragma once #include "FebInterface.h" +#include +#include + struct Module{ - unsigned int module_number; - int top_address_valid; - unsigned int top_left_address; - unsigned int top_right_address; - int bottom_address_valid; - unsigned int bottom_left_address; - unsigned int bottom_right_address; + unsigned int module_number; + int top_address_valid; + unsigned int top_left_address; + unsigned int top_right_address; + int bottom_address_valid; + unsigned int bottom_left_address; + unsigned int bottom_right_address; - unsigned int idelay_top[4]; //ll,lr,rl,ll - unsigned int idelay_bottom[4]; //ll,lr,rl,ll - float high_voltage; - int* top_dac; - int* bottom_dac; + unsigned int idelay_top[4]; //ll,lr,rl,ll + unsigned int idelay_bottom[4]; //ll,lr,rl,ll + float high_voltage; + int* top_dac; + int* bottom_dac; }; @@ -38,12 +26,12 @@ void Module_Module(struct Module* mod,unsigned int number, unsigned int address_ 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); +int Module_TopAddressIsValid(struct Module* mod); unsigned int Module_GetTopBaseAddress(struct Module* mod); unsigned int Module_GetTopLeftAddress(struct Module* mod) ; unsigned int Module_GetTopRightAddress(struct Module* mod); unsigned int Module_GetBottomBaseAddress(struct Module* mod); -int Module_BottomAddressIsValid(struct Module* mod); +int Module_BottomAddressIsValid(struct Module* mod); unsigned int Module_GetBottomLeftAddress(struct Module* mod); unsigned int Module_GetBottomRightAddress(struct Module* mod); unsigned int Module_SetTopIDelay(struct Module* mod,unsigned int chip,unsigned int value); @@ -51,17 +39,13 @@ unsigned int Module_GetTopIDelay(struct Module* mod,unsigned int chip) ; unsigned int Module_SetBottomIDelay(struct Module* mod,unsigned int chip,unsigned int value); unsigned int Module_GetBottomIDelay(struct Module* mod,unsigned int chip); -float Module_SetHighVoltage(struct Module* mod,float value); -float Module_GetHighVoltage(struct Module* mod); - -int Module_SetTopDACValue(struct Module* mod,unsigned int i, int value); -int Module_GetTopDACValue(struct Module* mod,unsigned int i); -int Module_SetBottomDACValue(struct Module* mod,unsigned int i, int value); -int Module_GetBottomDACValue(struct Module* mod,unsigned int i); - - - +float Module_SetHighVoltage(struct Module* mod,float value); +float Module_GetHighVoltage(struct Module* mod); +int Module_SetTopDACValue(struct Module* mod,unsigned int i, int value); +int Module_GetTopDACValue(struct Module* mod,unsigned int i); +int Module_SetBottomDACValue(struct Module* mod,unsigned int i, int value); +int Module_GetBottomDACValue(struct Module* mod,unsigned int i); void Feb_Control_activate(int activate); @@ -69,142 +53,107 @@ void Feb_Control_activate(int activate); int Feb_Control_IsBottomModule(); int Feb_Control_GetModuleNumber(); +void Feb_Control_PrintModuleList(); +int Feb_Control_GetModuleIndex(unsigned int module_number, unsigned int* module_index); +int Feb_Control_CheckModuleAddresses(struct Module* m); +int Feb_Control_AddModule(unsigned int module_number, unsigned int top_address); +int Feb_Control_AddModule1(unsigned int module_number, int top_enable, unsigned int top_address, unsigned int bottom_address, int half_module); +int Feb_Control_GetDACNumber(char* s, unsigned int* n); +int Feb_Control_SendDACValue(unsigned int dst_num, unsigned int ch, unsigned int* value); +int Feb_Control_VoltageToDAC(float value, unsigned int* digital, unsigned int nsteps, float vmin, float vmax); +float Feb_Control_DACToVoltage(unsigned int digital,unsigned int nsteps,float vmin,float vmax); +int Feb_Control_SendIDelays(unsigned int dst_num, int chip_lr, unsigned int channels, unsigned int ndelay_units); +int Feb_Control_SetStaticBits(); +int Feb_Control_SetStaticBits1(unsigned int the_static_bits); +int Feb_Control_SendBitModeToBebServer(); +unsigned int Feb_Control_ConvertTimeToRegister(float time_in_sec); +unsigned int Feb_Control_AddressToAll(); +int Feb_Control_SetCommandRegister(unsigned int cmd); +int Feb_Control_GetDAQStatusRegister(unsigned int dst_address, unsigned int* ret_status); +int Feb_Control_StartDAQOnlyNWaitForFinish(int sleep_time_us); +int Feb_Control_ResetChipCompletely(); +int Feb_Control_ResetChipPartially(); +void Feb_Control_FebControl(); +int Feb_Control_Init(int master, int top, int normal, int module_num); +int Feb_Control_OpenSerialCommunication(); +void Feb_Control_CloseSerialCommunication(); +int Feb_Control_CheckSetup(); +unsigned int Feb_Control_GetNModules(); +unsigned int Feb_Control_GetNHalfModules(); +int Feb_Control_SetHighVoltage(int value); +int Feb_Control_GetHighVoltage(int* value); +int Feb_Control_SendHighVoltage(int dacvalue); +int Feb_Control_ReceiveHighVoltage(unsigned int* value); - void Feb_Control_PrintModuleList(); - int Feb_Control_GetModuleIndex(unsigned int module_number, unsigned int* module_index); - int Feb_Control_CheckModuleAddresses(struct Module* m); - int Feb_Control_AddModule(unsigned int module_number, unsigned int top_address); - /*int Feb_Control_AddModule(unsigned int module_number, unsigned int top_address, unsigned int bottom_address, int half_module=0);*/ - int Feb_Control_AddModule1(unsigned int module_number, int top_enable, unsigned int top_address, unsigned int bottom_address, int half_module); +int Feb_Control_SetIDelays(unsigned int module_num, unsigned int ndelay_units); +int Feb_Control_SetIDelays1(unsigned int module_num, unsigned int chip_pos, unsigned int ndelay_units); - int Feb_Control_GetDACNumber(char* s, unsigned int* n); - int Feb_Control_SendDACValue(unsigned int dst_num, unsigned int ch, unsigned int* value); - int Feb_Control_VoltageToDAC(float value, unsigned int* digital, unsigned int nsteps, float vmin, float vmax); - float Feb_Control_DACToVoltage(unsigned int digital,unsigned int nsteps,float vmin,float vmax); +int Feb_Control_DecodeDACString(char* dac_str, unsigned int* module_index, int* top, int* bottom, unsigned int* dac_ch); +int Feb_Control_SetDAC(char* s, int value, int is_a_voltage_mv); +int Feb_Control_GetDAC(char* s, int* ret_value, int voltage_mv); +int Feb_Control_GetDACName(unsigned int dac_num,char* s); +int Feb_Control_SetTrimbits(unsigned int module_num, unsigned int* trimbits); +unsigned int* Feb_Control_GetTrimbits(); +int Feb_Control_SaveAllTrimbitsTo(int value); +int Feb_Control_Reset(); +int Feb_Control_PrepareForAcquisition(); - int Feb_Control_SendIDelays(unsigned int dst_num, int chip_lr, unsigned int channels, unsigned int ndelay_units); +int Feb_Control_StartAcquisition(); +int Feb_Control_StopAcquisition(); +int Feb_Control_AcquisitionInProgress(); +int Feb_Control_AcquisitionStartedBit(); +int Feb_Control_WaitForFinishedFlag(int sleep_time_us); +int Feb_Control_WaitForStartedFlag(int sleep_time_us, int prev_flag); +void Feb_Control_PrintAcquisitionSetup(); +int Feb_Control_SetNExposures(unsigned int n_images); +unsigned int Feb_Control_GetNExposures(); +int Feb_Control_SetExposureTime(double the_exposure_time_in_sec); +double Feb_Control_GetExposureTime(); +int64_t Feb_Control_GetExposureTime_in_nsec(); +int Feb_Control_SetSubFrameExposureTime(int64_t the_subframe_exposure_time_in_10nsec); +int64_t Feb_Control_GetSubFrameExposureTime(); +int Feb_Control_SetSubFramePeriod(int64_t the_subframe_period_in_10nsec); +int64_t Feb_Control_GetSubFramePeriod(); +int Feb_Control_SetExposurePeriod(double the_exposure_period_in_sec); +double Feb_Control_GetExposurePeriod(); +int Feb_Control_SetDynamicRange(unsigned int four_eight_sixteen_or_thirtytwo); +unsigned int Feb_Control_GetDynamicRange(); +int Feb_Control_SetReadoutSpeed(unsigned int readout_speed); //0 was default, 0->full,1->half,2->quarter or 3->super_slow +int Feb_Control_SetReadoutMode(unsigned int readout_mode); ///0 was default,0->parallel,1->non-parallel,2-> safe_mode +int Feb_Control_SetTriggerMode(unsigned int trigger_mode, int polarity);//0 and 1 was default, +int Feb_Control_SetExternalEnableMode(int use_external_enable, int polarity);//0 and 1 was default, - int Feb_Control_SetStaticBits(); - int Feb_Control_SetStaticBits1(unsigned int the_static_bits); +int Feb_Control_SetInTestModeVariable(int on); +int Feb_Control_GetTestModeVariable(); - int Feb_Control_SendBitModeToBebServer(); +void Feb_Control_Set_Counter_Bit(int value); +int Feb_Control_Get_Counter_Bit(); +int Feb_Control_Pulse_Pixel(int npulses,int x, int y); +int Feb_Control_PulsePixelNMove(int npulses, int inc_x_pos, int inc_y_pos); +int Feb_Control_Shift32InSerialIn(unsigned int value_to_shift_in); +int Feb_Control_SendTokenIn(); +int Feb_Control_ClockRowClock(unsigned int ntimes); +int Feb_Control_PulseChip(int npulses); - unsigned int Feb_Control_ConvertTimeToRegister(float time_in_sec); +int64_t Feb_Control_Get_RateTable_Tau_in_nsec(); +int64_t Feb_Control_Get_RateTable_Period_in_nsec(); +int Feb_Control_SetRateCorrectionTau(int64_t tau_in_Nsec); +int Feb_Control_SetRateCorrectionTable(unsigned int *table); +int Feb_Control_GetRateCorrectionVariable(); +void Feb_Control_SetRateCorrectionVariable(int activate_rate_correction); +int Feb_Control_PrintCorrectedValues(); - unsigned int Feb_Control_AddressToAll(); - int Feb_Control_SetCommandRegister(unsigned int cmd); - int Feb_Control_GetDAQStatusRegister(unsigned int dst_address, unsigned int* ret_status); - /*int Feb_Control_StartDAQOnlyNWaitForFinish(int sleep_time_us=5000);*/ - int Feb_Control_StartDAQOnlyNWaitForFinish(int sleep_time_us); +int Feb_Control_GetLeftFPGATemp(); +int Feb_Control_GetRightFPGATemp(); - int Feb_Control_ResetChipCompletely(); - int Feb_Control_ResetChipPartially(); +int64_t Feb_Control_GetMeasuredPeriod(); +int64_t Feb_Control_GetSubMeasuredPeriod(); - //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); -*/ +int Feb_Control_SoftwareTrigger(); +uint32_t Feb_Control_WriteRegister(uint32_t offset, uint32_t data); +uint32_t Feb_Control_ReadRegister(uint32_t offset); - void Feb_Control_FebControl(); - int Feb_Control_Init(int master, int top, int normal, int module_num); - int Feb_Control_OpenSerialCommunication(); - void Feb_Control_CloseSerialCommunication(); - int Feb_Control_CheckSetup(); - - unsigned int Feb_Control_GetNModules(); - unsigned int Feb_Control_GetNHalfModules(); - - int Feb_Control_SetHighVoltage(int value); - int Feb_Control_GetHighVoltage(int* value); - - int Feb_Control_SendHighVoltage(int dacvalue); - int Feb_Control_ReceiveHighVoltage(unsigned int* value); - - int Feb_Control_SetIDelays(unsigned int module_num, unsigned int ndelay_units); - int Feb_Control_SetIDelays1(unsigned int module_num, unsigned int chip_pos, unsigned int ndelay_units); - - int Feb_Control_DecodeDACString(char* dac_str, unsigned int* module_index, int* top, int* bottom, unsigned int* dac_ch); - /*int Feb_Control_SetDAC(string s, int value, int is_a_voltage_mv=0);*/ - int Feb_Control_SetDAC(char* s, int value, int is_a_voltage_mv); - /* int Feb_Control_GetDAC(string s, int* ret_value, int voltage_mv=0);*/ - int Feb_Control_GetDAC(char* s, int* ret_value, int voltage_mv); - int Feb_Control_GetDACName(unsigned int dac_num,char* s); - - int Feb_Control_SetTrimbits(unsigned int module_num, unsigned int* trimbits); - unsigned int* Feb_Control_GetTrimbits(); - - - /**Added by Dhanya */ - int Feb_Control_SaveAllTrimbitsTo(int value); - - - - int Feb_Control_Reset(); - int Feb_Control_PrepareForAcquisition(); - - int Feb_Control_StartAcquisition(); - int Feb_Control_StopAcquisition(); - int Feb_Control_AcquisitionInProgress(); - int Feb_Control_AcquisitionStartedBit(); - /*int Feb_Control_WaitForFinishedFlag(int sleep_time_us=5000);*/ - int Feb_Control_WaitForFinishedFlag(int sleep_time_us); - int Feb_Control_WaitForStartedFlag(int sleep_time_us, int prev_flag); - - //functions for setting up exposure - void Feb_Control_PrintAcquisitionSetup(); - int Feb_Control_SetNExposures(unsigned int n_images); - unsigned int Feb_Control_GetNExposures(); - int Feb_Control_SetExposureTime(double the_exposure_time_in_sec); - double Feb_Control_GetExposureTime(); - int64_t Feb_Control_GetExposureTime_in_nsec(); - int Feb_Control_SetSubFrameExposureTime(int64_t the_subframe_exposure_time_in_10nsec); - int64_t Feb_Control_GetSubFrameExposureTime(); - int Feb_Control_SetSubFramePeriod(int64_t the_subframe_period_in_10nsec); - int64_t Feb_Control_GetSubFramePeriod(); - int Feb_Control_SetExposurePeriod(double the_exposure_period_in_sec); - double Feb_Control_GetExposurePeriod(); - int Feb_Control_SetDynamicRange(unsigned int four_eight_sixteen_or_thirtytwo); - unsigned int Feb_Control_GetDynamicRange(); - int Feb_Control_SetReadoutSpeed(unsigned int readout_speed); //0 was default, 0->full,1->half,2->quarter or 3->super_slow - int Feb_Control_SetReadoutMode(unsigned int readout_mode); ///0 was default,0->parallel,1->non-parallel,2-> safe_mode - int Feb_Control_SetTriggerMode(unsigned int trigger_mode, int polarity);//0 and 1 was default, - int Feb_Control_SetExternalEnableMode(int use_external_enable, int polarity);//0 and 1 was default, - - //functions for testing - /*int Feb_Control_SetTestModeVariable(int on=1);*/ - int Feb_Control_SetInTestModeVariable(int on); - int Feb_Control_GetTestModeVariable(); - - void Feb_Control_Set_Counter_Bit(int value); - int Feb_Control_Get_Counter_Bit(); - int Feb_Control_Pulse_Pixel(int npulses,int x, int y); - int Feb_Control_PulsePixelNMove(int npulses, int inc_x_pos, int inc_y_pos); - int Feb_Control_Shift32InSerialIn(unsigned int value_to_shift_in); - int Feb_Control_SendTokenIn(); - int Feb_Control_ClockRowClock(unsigned int ntimes); - int Feb_Control_PulseChip(int npulses); - - int64_t Feb_Control_Get_RateTable_Tau_in_nsec(); - int64_t Feb_Control_Get_RateTable_Period_in_nsec(); - int Feb_Control_SetRateCorrectionTau(int64_t tau_in_Nsec); - int Feb_Control_SetRateCorrectionTable(unsigned int *table); - int Feb_Control_GetRateCorrectionVariable(); - void Feb_Control_SetRateCorrectionVariable(int activate_rate_correction); - int Feb_Control_PrintCorrectedValues(); - - int Feb_Control_GetLeftFPGATemp(); - int Feb_Control_GetRightFPGATemp(); - - int64_t Feb_Control_GetMeasuredPeriod(); - int64_t Feb_Control_GetSubMeasuredPeriod(); - - int Feb_Control_SoftwareTrigger(); - - uint32_t Feb_Control_WriteRegister(uint32_t offset, uint32_t data); - uint32_t Feb_Control_ReadRegister(uint32_t offset); -#endif diff --git a/slsDetectorServers/eigerDetectorServer/FebInterface.c b/slsDetectorServers/eigerDetectorServer/FebInterface.c index a094bda44..5ca087d42 100644 --- a/slsDetectorServers/eigerDetectorServer/FebInterface.c +++ b/slsDetectorServers/eigerDetectorServer/FebInterface.c @@ -1,45 +1,31 @@ - -/** - * @author Ian Johnson - * @version 1.0 - */ - - - -//#include -//#include -//#include -//#include -//#include -//#include +#include "FebInterface.h" +#include "LocalLinkInterface.h" +#include "xparameters.h" +#include "logger.h" #include #include #include -#include "xparameters.h" - -#include "FebInterface.h" +struct LocalLinkInterface ll_local,* ll; - struct LocalLinkInterface ll_local,* ll; +unsigned int Feb_Interface_nfebs; +unsigned int* Feb_Interface_feb_numb; - unsigned int Feb_Interface_nfebs; - unsigned int* Feb_Interface_feb_numb; +int Feb_Interface_send_ndata; +unsigned int Feb_Interface_send_buffer_size; +unsigned int* Feb_Interface_send_data_raw; +unsigned int* Feb_Interface_send_data; - int Feb_Interface_send_ndata; - unsigned int Feb_Interface_send_buffer_size; - unsigned int* Feb_Interface_send_data_raw; - unsigned int* Feb_Interface_send_data; - - int Feb_Interface_recv_ndata; - unsigned int Feb_Interface_recv_buffer_size; - unsigned int* Feb_Interface_recv_data_raw; - unsigned int* Feb_Interface_recv_data; +int Feb_Interface_recv_ndata; +unsigned int Feb_Interface_recv_buffer_size; +unsigned int* Feb_Interface_recv_data_raw; +unsigned int* Feb_Interface_recv_data; -void Feb_Interface_FebInterface(){ +void Feb_Interface_FebInterface() { ll = &ll_local; Feb_Interface_nfebs = 0; Feb_Interface_feb_numb = 0; @@ -54,131 +40,129 @@ void Feb_Interface_FebInterface(){ Feb_Interface_recv_data_raw = malloc((Feb_Interface_recv_buffer_size+1) * sizeof(unsigned int)); Feb_Interface_recv_data = &Feb_Interface_recv_data_raw[1]; - Local_LocalLinkInterface1(ll,XPAR_PLB_LL_FIFO_AURORA_DUAL_CTRL_FEB_RIGHT_BASEADDR); + Local_LocalLinkInterface1(ll,XPAR_PLB_LL_FIFO_AURORA_DUAL_CTRL_FEB_RIGHT_BASEADDR); } -void Feb_Interface_SendCompleteList(unsigned int n,unsigned int* list){ +void Feb_Interface_SendCompleteList(unsigned int n,unsigned int* list) { unsigned int i; - if(Feb_Interface_feb_numb) free(Feb_Interface_feb_numb); - Feb_Interface_nfebs = n; - Feb_Interface_feb_numb = malloc(n * sizeof(unsigned int)); - for(i=0;i0xfff) return 0; +int Feb_Interface_WriteTo(unsigned int ch) { + if (ch>0xfff) return 0; -#ifdef MARTIN - cprintf(YELLOW, "FIW ch %d\n", ch); -#endif + FILE_LOG(logDEBUG5, ("FIW ch %d\n", ch)); - Feb_Interface_send_data_raw[0] = 0x8fff0000; - if(Local_Write(ll,4,Feb_Interface_send_data_raw)!=4) return 0; +Feb_Interface_send_data_raw[0] = 0x8fff0000; +if (Local_Write(ll,4,Feb_Interface_send_data_raw)!=4) return 0; - Feb_Interface_send_data_raw[0] = 0x90000000 | (ch<<16); - if(Local_Write(ll,4,Feb_Interface_send_data_raw)!=4) return 0; +Feb_Interface_send_data_raw[0] = 0x90000000 | (ch<<16); +if (Local_Write(ll,4,Feb_Interface_send_data_raw)!=4) return 0; - Feb_Interface_send_data_raw[0] = 0xc0000000; - return ((Feb_Interface_send_ndata+1)*4==Local_Write(ll,(Feb_Interface_send_ndata+1)*4,Feb_Interface_send_data_raw)); +Feb_Interface_send_data_raw[0] = 0xc0000000; +return ((Feb_Interface_send_ndata+1)*4==Local_Write(ll,(Feb_Interface_send_ndata+1)*4,Feb_Interface_send_data_raw)); } -int Feb_Interface_ReadFrom(unsigned int ch, unsigned int ntrys){ +int Feb_Interface_ReadFrom(unsigned int ch, unsigned int ntrys) { unsigned int t; - if(ch>=0xfff) return 0; + if (ch>=0xfff) return 0; - Feb_Interface_recv_data_raw[0] = 0xa0000000 | (ch<<16); - Local_Write(ll,4,Feb_Interface_recv_data_raw); - usleep(20); - - Feb_Interface_recv_ndata=-1; - for(t=0;t0){ - Feb_Interface_recv_ndata--; - break; - } - usleep(1000); - } + Feb_Interface_recv_data_raw[0] = 0xa0000000 | (ch<<16); + Local_Write(ll,4,Feb_Interface_recv_data_raw); + usleep(20); - return (Feb_Interface_recv_ndata>=0); + Feb_Interface_recv_ndata=-1; + for(t=0;t0) { + Feb_Interface_recv_ndata--; + break; + } + usleep(1000); + } + + return (Feb_Interface_recv_ndata>=0); } -int Feb_Interface_SetByteOrder(){ +int Feb_Interface_SetByteOrder() { Feb_Interface_send_data_raw[0] = 0x8fff0000; - if(Local_Write(ll,4,Feb_Interface_send_data_raw)!=4) return 0; - Feb_Interface_send_ndata = 2; - Feb_Interface_send_data[0] = 0; - Feb_Interface_send_data[1] = 0; - unsigned int i; - unsigned int dst = 0xff; - for(i=0;iFeb_Interface_send_buffer_size-2) return 0; + unsigned int dst = 0xff; + for(i=0;iFeb_Interface_send_buffer_size-2) return 0; + nreads &= 0x3ff; + if (!nreads||nreads>Feb_Interface_send_buffer_size-2) return 0; - //cout<<"Write register : "<Feb_Interface_send_buffer_size-2) return 0; + + //cout<<"Write register : "<0){ + while(ndata_countdown>0) { n_to_send = ndata_countdownFeb_Interface_send_buffer_size-2) {printf("error herer: nwrites:%d\n",nwrites);return 0;}//*d-1026 + mem_num &= 0x3f; + start_address &= 0x3fff; + nwrites &= 0x3ff; + if (!nwrites||nwrites>Feb_Interface_send_buffer_size-2) { + FILE_LOG(logERROR, ("invalid nwrites:%d\n",nwrites)); + return 0; + }//*d-1026 - Feb_Interface_send_ndata = nwrites+2;//*d-1026 - Feb_Interface_send_data[0] = 0xc0000000 | mem_num << 24 | nwrites << 14 | start_address; //cmd -> write to memory, nwrites, mem number, start address - Feb_Interface_send_data[nwrites+1] = 0; - for(i=0;i write to memory, nwrites, mem number, start address + Feb_Interface_send_data[nwrites+1] = 0; + for(i=0;i -//#include -//#include -//#include -//#include - #include "HardwareIO.h" xfs_u8 HWIO_xfs_in8(xfs_u32 InAddress) diff --git a/slsDetectorServers/eigerDetectorServer/LocalLinkInterface.c b/slsDetectorServers/eigerDetectorServer/LocalLinkInterface.c index 8d1b9db1f..7679ad432 100644 --- a/slsDetectorServers/eigerDetectorServer/LocalLinkInterface.c +++ b/slsDetectorServers/eigerDetectorServer/LocalLinkInterface.c @@ -1,44 +1,36 @@ - -//Class initially from Gerd and was called mmap_test.c -//return reversed 1 means good, 0 means failed - +#include "LocalLinkInterface.h" +#include "HardwareMMappingDefs.h" +#include "logger.h" +#include "ansi.h" #include #include -//#include +#include +#include -#include "HardwareMMappingDefs.h" - -#include "LocalLinkInterface.h" - - - -void Local_LocalLinkInterface1(struct LocalLinkInterface* ll,unsigned int ll_fifo_badr){ - // printf("\n v 1 \n"); - printf("Initialize PLB LL FIFOs\n"); +void Local_LocalLinkInterface1(struct LocalLinkInterface* ll,unsigned int ll_fifo_badr) { + FILE_LOG(logDEBUG5, ("Initialize PLB LL FIFOs\n")); ll->ll_fifo_base=0; ll->ll_fifo_ctrl_reg=0; - if(Local_Init(ll,ll_fifo_badr)){ + if (Local_Init(ll,ll_fifo_badr)) { Local_Reset(ll); - printf("\tFIFO Status : 0x%08x\n",Local_StatusVector(ll)); - }else printf("\tError LocalLink Mappping : 0x%08x\n",ll_fifo_badr); - printf("\n\n"); + FILE_LOG(logDEBUG5, ("\tFIFO Status : 0x%08x\n\n\n", Local_StatusVector(ll))); + } else FILE_LOG(logERROR, ("\tCould not map LocalLink : 0x%08x\n\n\n", ll_fifo_badr)); } -/*~LocalLinkInterface(){};*/ -void Local_LocalLinkInterface(struct LocalLinkInterface* ll){ - printf("Initializing new memory\n"); +void Local_LocalLinkInterface(struct LocalLinkInterface* ll) { + FILE_LOG(logDEBUG5, ("Initializing new memory\n")); } -int Local_Init(struct LocalLinkInterface* ll,unsigned int ll_fifo_badr){ +int Local_Init(struct LocalLinkInterface* ll,unsigned int ll_fifo_badr) { int fd; void *plb_ll_fifo_ptr; - if ((fd=open("/dev/mem", O_RDWR)) < 0){ + if ((fd=open("/dev/mem", O_RDWR)) < 0) { fprintf(stderr, "Could not open /dev/mem\n"); return 0; } @@ -46,7 +38,7 @@ int Local_Init(struct LocalLinkInterface* ll,unsigned int ll_fifo_badr){ plb_ll_fifo_ptr = mmap(0, getpagesize(), PROT_READ | PROT_WRITE, MAP_FILE | MAP_SHARED, fd, ll_fifo_badr); close(fd); - if (plb_ll_fifo_ptr == MAP_FAILED){ + if (plb_ll_fifo_ptr == MAP_FAILED) { perror ("mmap"); return 0; } @@ -59,13 +51,13 @@ int Local_Init(struct LocalLinkInterface* ll,unsigned int ll_fifo_badr){ -int Local_Reset(struct LocalLinkInterface* ll){ +int Local_Reset(struct LocalLinkInterface* ll) { return Local_Reset1(ll,PLB_LL_FIFO_CTRL_RESET_STD); } -int Local_Reset1(struct LocalLinkInterface* ll,unsigned int rst_mask){ +int Local_Reset1(struct LocalLinkInterface* ll,unsigned int rst_mask) { ll->ll_fifo_ctrl_reg |= rst_mask; - printf("\tCTRL Register bits: 0x%08x\n",ll->ll_fifo_ctrl_reg); + FILE_LOG(logDEBUG5, ("\tCTRL Register bits: 0x%08x\n",ll->ll_fifo_ctrl_reg)); HWIO_xfs_out32(ll->ll_fifo_base+4*PLB_LL_FIFO_REG_CTRL,ll->ll_fifo_ctrl_reg); HWIO_xfs_out32(ll->ll_fifo_base+4*PLB_LL_FIFO_REG_CTRL,ll->ll_fifo_ctrl_reg); @@ -75,17 +67,16 @@ int Local_Reset1(struct LocalLinkInterface* ll,unsigned int rst_mask){ ll->ll_fifo_ctrl_reg &= (~rst_mask); HWIO_xfs_out32(ll->ll_fifo_base+4*PLB_LL_FIFO_REG_CTRL,ll->ll_fifo_ctrl_reg); - // printf("FIFO CTRL Address: 0x%08x\n FIFO CTRL Register: 0x%08x\n",PLB_LL_FIFO_REG_CTRL,plb_ll_fifo[PLB_LL_FIFO_REG_CTRL]); return 1; } -unsigned int Local_StatusVector(struct LocalLinkInterface* ll){ +unsigned int Local_StatusVector(struct LocalLinkInterface* ll) { return HWIO_xfs_in32(ll->ll_fifo_base+4*PLB_LL_FIFO_REG_STATUS); } -int Local_Write(struct LocalLinkInterface* ll,unsigned int buffer_len, void *buffer){ +int Local_Write(struct LocalLinkInterface* ll,unsigned int buffer_len, void *buffer) { // note: buffer must be word (4 byte) aligned // frame_len in byte int vacancy=0; @@ -101,22 +92,19 @@ int Local_Write(struct LocalLinkInterface* ll,unsigned int buffer_len, void *buf last_word = (buffer_len-1)/4; word_ptr = (unsigned int *)buffer; -#ifdef MARTIN - cprintf(BLUE, "LL Write - Len: %2d - If: %X - Data: ",buffer_len, ll->ll_fifo_base); + FILE_LOG(logDEBUG5, ("LL Write - Len: %2d - If: %X - Data: ",buffer_len, ll->ll_fifo_base)); for (i=0; i < buffer_len/4; i++) - cprintf(BLUE, "%.8X ",*(((unsigned *) buffer)+i)); - printf("\n"); -#endif + FILE_LOG(logDEBUG5, ("%.8X ",*(((unsigned *) buffer)+i))); while (words_send <= last_word) { while (!vacancy)//wait for Fifo to be empty again { status = HWIO_xfs_in32(ll->ll_fifo_base+4*PLB_LL_FIFO_REG_STATUS); - if((status & PLB_LL_FIFO_STATUS_ALMOSTFULL) == 0) vacancy = 1; -#ifdef MARTIN - if (vacancy == 0) cprintf(RED, "Fifo full!\n"); -#endif + if ((status & PLB_LL_FIFO_STATUS_ALMOSTFULL) == 0) vacancy = 1; + if (vacancy == 0) { + FILE_LOG(logERROR, ("Fifo full!\n")); + } } //Just to know: #define PLB_LL_FIFO_ALMOST_FULL_THRESHOLD_WORDS 100 @@ -140,7 +128,7 @@ int Local_Write(struct LocalLinkInterface* ll,unsigned int buffer_len, void *buf } -int Local_Read(struct LocalLinkInterface* ll,unsigned int buffer_len, void *buffer){ +int Local_Read(struct LocalLinkInterface* ll,unsigned int buffer_len, void *buffer) { static unsigned int buffer_ptr = 0; // note: buffer must be word (4 byte) aligned // frame_len in byte @@ -150,9 +138,7 @@ int Local_Read(struct LocalLinkInterface* ll,unsigned int buffer_len, void *buff volatile unsigned int fifo_val; int sof = 0; -#ifdef MARTIN - cprintf(CYAN, "LL Read - If: %X - Data: ",ll->ll_fifo_base); -#endif + FILE_LOG(logDEBUG5, ("LL Read - If: %X - Data: ",ll->ll_fifo_base)); word_ptr = (unsigned int *)buffer; do @@ -168,7 +154,6 @@ int Local_Read(struct LocalLinkInterface* ll,unsigned int buffer_len, void *buff buffer_ptr = 0; return -1; // buffer overflow } - // printf(">>>> SOF\n\r"); buffer_ptr = 0; sof = 1; } @@ -179,9 +164,7 @@ int Local_Read(struct LocalLinkInterface* ll,unsigned int buffer_len, void *buff { if ( (buffer_len >> 2) > buffer_ptr) { -#ifdef MARTIN - cprintf(CYAN, "%.8X ", fifo_val); -#endif + FILE_LOG(logDEBUG5, ("%.8X ", fifo_val)); word_ptr[buffer_ptr++] = fifo_val; //write to buffer } else @@ -193,10 +176,7 @@ int Local_Read(struct LocalLinkInterface* ll,unsigned int buffer_len, void *buff if (status & PLB_LL_FIFO_STATUS_LL_EOF) { len = (buffer_ptr << 2) -3 + ( (status & PLB_LL_FIFO_STATUS_LL_REM)>>PLB_LL_FIFO_STATUS_LL_REM_SHIFT ); -#ifdef MARTIN - cprintf(CYAN, "Len: %d\n",len); -#endif - // printf(">>>>status=0x%08x EOF len = %d \n\r\n\r",status, len); + FILE_LOG(logDEBUG5, ("Len: %d\n",len)); buffer_ptr = 0; return len; } @@ -209,19 +189,15 @@ int Local_Read(struct LocalLinkInterface* ll,unsigned int buffer_len, void *buff return 0; } -int Local_ctrl_reg_write_mask(struct LocalLinkInterface* ll,unsigned int mask, unsigned int val){ - // printf("Fifo CTRL Reg(1): 0x%08x\n",plb_ll_fifo_ctrl_reg); +int Local_ctrl_reg_write_mask(struct LocalLinkInterface* ll,unsigned int mask, unsigned int val) { ll->ll_fifo_ctrl_reg &= (~mask); - //printf("Fifo CTRL Reg(2): 0x%08x\n",plb_ll_fifo_ctrl_reg); ll->ll_fifo_ctrl_reg |= ( mask & val); - // printf("Fifo CTRL Reg: 0x%08x\n",plb_ll_fifo_ctrl_reg); HWIO_xfs_out32(ll->ll_fifo_base+4*PLB_LL_FIFO_REG_CTRL,ll->ll_fifo_ctrl_reg); - // printf("Fifo STAT Reg: 0x%08x\n", plb_ll_fifo[PLB_LL_FIFO_REG_STATUS]); return 1; } -int Local_Test(struct LocalLinkInterface* ll,unsigned int buffer_len, void *buffer){ +int Local_Test(struct LocalLinkInterface* ll,unsigned int buffer_len, void *buffer) { int len; unsigned int rec_buff_len = 4096; @@ -233,28 +209,14 @@ int Local_Test(struct LocalLinkInterface* ll,unsigned int buffer_len, void *buff do{ len = Local_Read(ll,rec_buff_len,rec_buffer); - printf("receive length: %i\n",len); + FILE_LOG(logDEBUG5, ("receive length: %i\n",len)); - if (len > 0){ + if (len > 0) { rec_buffer[len]=0; - printf((char*) rec_buffer); - printf("\n"); + FILE_LOG(logINFO, ("%s\n", (char*) rec_buffer)); } } while(len > 0); - printf("\n\n\n\n"); return 1; } -void Local_llfifo_print_frame(struct LocalLinkInterface* ll,unsigned char* fbuff, int len){ - int i; - printf("\n\r----Frame of len : %d Byte\n\r",len); - for(i=0;i - -#include "ansi.h" -#include -#include - -/*class LocalLinkInterface: public HardwareIO{ //*/ struct LocalLinkInterface{ - xfs_u32 ll_fifo_base; - unsigned int ll_fifo_ctrl_reg; + xfs_u32 ll_fifo_base; + unsigned int ll_fifo_ctrl_reg; }; +int Local_Init(struct LocalLinkInterface* ll,unsigned int ll_fifo_badr); +int Local_Reset1(struct LocalLinkInterface* ll,unsigned int rst_mask); +int Local_ctrl_reg_write_mask(struct LocalLinkInterface* ll,unsigned int mask, unsigned int val); +void Local_LocalLinkInterface1(struct LocalLinkInterface* ll,unsigned int ll_fifo_badr); +unsigned int Local_StatusVector(struct LocalLinkInterface* ll); +int Local_Reset(struct LocalLinkInterface* ll); +int Local_Write(struct LocalLinkInterface* ll,unsigned int buffer_len, void *buffer); +int Local_Read(struct LocalLinkInterface* ll,unsigned int buffer_len, void *buffer); +int Local_Test(struct LocalLinkInterface* ll,unsigned int buffer_len, void *buffer); +void Local_LocalLinkInterface(struct LocalLinkInterface* ll); - - int Local_Init(struct LocalLinkInterface* ll,unsigned int ll_fifo_badr); - int Local_Reset1(struct LocalLinkInterface* ll,unsigned int rst_mask); - - int Local_ctrl_reg_write_mask(struct LocalLinkInterface* ll,unsigned int mask, unsigned int val); - void Local_llfifo_print_frame(struct LocalLinkInterface* ll,unsigned char* fbuff, int len); - - - void Local_LocalLinkInterface1(struct LocalLinkInterface* ll,unsigned int ll_fifo_badr); - /* virtual ~LocalLinkInterface();*/ - - unsigned int Local_StatusVector(struct LocalLinkInterface* ll); - int Local_Reset(struct LocalLinkInterface* ll); - int Local_Write(struct LocalLinkInterface* ll,unsigned int buffer_len, void *buffer); - int Local_Read(struct LocalLinkInterface* ll,unsigned int buffer_len, void *buffer); - - int Local_Test(struct LocalLinkInterface* ll,unsigned int buffer_len, void *buffer); - - void Local_LocalLinkInterface(struct LocalLinkInterface* ll); - - /* - int FiFoReset(unsigned int numb); - int FifoSend(unsigned int numb, unsigned int frame_len, void *buffer); - int FifoReceive(unsigned int numb, unsigned int frame_len, void *buffer); - int FifoTest(unsigned int numb,unsigned int send_len, char *send_str); - */ - - - - -#endif diff --git a/slsDetectorServers/eigerDetectorServer/gitInfo.txt b/slsDetectorServers/eigerDetectorServer/gitInfo.txt index 8aa8ce29d..136474476 100644 --- a/slsDetectorServers/eigerDetectorServer/gitInfo.txt +++ b/slsDetectorServers/eigerDetectorServer/gitInfo.txt @@ -1,9 +1,9 @@ Path: slsDetectorPackage/slsDetectorServers/eigerDetectorServer URL: origin git@github.com:slsdetectorgroup/slsDetectorPackage.git Repository Root: origin git@github.com:slsdetectorgroup/slsDetectorPackage.git -Repsitory UUID: 178b83222380f7b7294cde66e66719c5d1c1363c -Revision: 2 +Repsitory UUID: dfad145e1492e961c95063aa5b2f54e5e1b418a0 +Revision: 3 Branch: refactor Last Changed Author: Dhanya_Thattil -Last Changed Rev: 4125 -Last Changed Date: 2018-10-16 09:02:45.000000002 +0200 ./Makefile +Last Changed Rev: 4127 +Last Changed Date: 2018-10-23 12:30:26.000000002 +0200 ./Beb.c diff --git a/slsDetectorServers/eigerDetectorServer/gitInfoEiger.h b/slsDetectorServers/eigerDetectorServer/gitInfoEiger.h index 6ae33d32f..2254b38c9 100644 --- a/slsDetectorServers/eigerDetectorServer/gitInfoEiger.h +++ b/slsDetectorServers/eigerDetectorServer/gitInfoEiger.h @@ -1,6 +1,6 @@ #define GITURL "git@github.com:slsdetectorgroup/slsDetectorPackage.git" -#define GITREPUUID "178b83222380f7b7294cde66e66719c5d1c1363c" +#define GITREPUUID "dfad145e1492e961c95063aa5b2f54e5e1b418a0" #define GITAUTH "Dhanya_Thattil" -#define GITREV 0x4125 -#define GITDATE 0x20181016 +#define GITREV 0x4127 +#define GITDATE 0x20181023 #define GITBRANCH "refactor" diff --git a/slsDetectorServers/eigerDetectorServer/slsDetectorFunctionList.c b/slsDetectorServers/eigerDetectorServer/slsDetectorFunctionList.c index 2231ae283..0de061582 100644 --- a/slsDetectorServers/eigerDetectorServer/slsDetectorFunctionList.c +++ b/slsDetectorServers/eigerDetectorServer/slsDetectorFunctionList.c @@ -1,3 +1,12 @@ +#include "slsDetectorFunctionList.h" +#ifndef VIRTUAL +#include "gitInfoEiger.h" +#include "FebControl.h" +#include "Beb.h" +#include "versionAPI.h" +#endif +#include "logger.h" + #include #include //to gethostname @@ -7,32 +16,39 @@ #include #endif -#include "slsDetectorFunctionList.h" -#ifndef VIRTUAL -#include "gitInfoEiger.h" -#include "FebControl.h" -#include "Beb.h" -#include "versionAPI.h" -#endif - // Global variable from slsDetectorServer extern int debugflag; +extern int isControlServer; -int default_tau_from_file= -1; - -#define BEB_NUM 34 - -enum detectorSettings thisSettings; const char* dac_names[16] = {"SvP","Vtr","Vrf","Vrs","SvN","Vtgstv","Vcmp_ll","Vcmp_lr","cal","Vcmp_rl","rxb_rb","rxb_lb","Vcmp_rr","Vcp","Vcn","Vis"}; - -enum{E_PARALLEL, E_NON_PARALLEL, E_SAFE}; - +int default_tau_from_file= -1; +enum detectorSettings thisSettings; sls_detector_module *detectorModules=NULL; int *detectorChips=NULL; int *detectorChans=NULL; int *detectorDacs=NULL; int *detectorAdcs=NULL; +int send_to_ten_gig = 0; +int ndsts_in_use=32; +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}; + +enum masterFlags masterMode=IS_SLAVE; +int top = 0; +int master = 0; +int normal = 0; +#ifndef VIRTUAL +uint32_t detid = 0; +#endif + + +int firmware_compatibility = OK; +int firmware_check_done = 0; +char firmware_message[MAX_STR_LENGTH]; + + int eiger_highvoltage = 0; int eiger_theo_highvoltage = 0; int eiger_iodelay = 0; @@ -72,30 +88,6 @@ int eiger_virtual_stop = 0; #endif -int send_to_ten_gig = 0; -int ndsts_in_use=32; -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_gain_values[3] = {517000,517000,517000}; -int default_offset_values[3] = {3851000,3851000,3851000}; - - -enum masterFlags masterMode=IS_SLAVE; -int top = 0; -int master = 0; -int normal = 0; -#ifndef VIRTUAL -uint32_t detid = 0; -#endif - -/* basic tests */ - -int firmware_compatibility = OK; -int firmware_check_done = 0; -char firmware_message[MAX_STR_LENGTH]; int isFirmwareCheckDone() { @@ -107,15 +99,12 @@ int getFirmwareCheckResult(char** mess) { return firmware_compatibility; } -void checkFirmwareCompatibility(){ +void checkFirmwareCompatibility() { firmware_compatibility = OK; firmware_check_done = 0; memset(firmware_message, 0, MAX_STR_LENGTH); #ifdef VIRTUAL - cprintf(BLUE,"\n\n" - "********************************************************\n" - "***************** EIGER Virtual Server *****************\n" - "********************************************************\n"); + FILE_LOG(logINFOBLUE, ("************ EIGER Virtual Server *****************\n\n")); firmware_check_done = 1; return; #endif @@ -126,11 +115,7 @@ void checkFirmwareCompatibility(){ int64_t sw_fw_apiversion = getDetectorId(SOFTWARE_FIRMWARE_API_VERSION); int64_t client_sw_apiversion = getDetectorId(CLIENT_SOFTWARE_API_VERSION); - cprintf(BLUE,"\n\n" - "********************************************************\n" - "**********************EIGER Server**********************\n" - "********************************************************\n"); - cprintf(BLUE,"\n" + FILE_LOG(logINFOBLUE, ("**************** EIGER Server *********************\n\n" "Detector IP Addr:\t\t 0x%x\n" "Detector MAC Addr:\t\t 0x%llx\n" @@ -147,50 +132,47 @@ void checkFirmwareCompatibility(){ (long long int)swversion, (long long int)sw_fw_apiversion, REQUIRED_FIRMWARE_VERSION, - (long long int)client_sw_apiversion); + (long long int)client_sw_apiversion)); // return if debugflag is not zero, debug mode if (debugflag) { firmware_check_done = 1; - return; + return; } //cant read versions - if(!fwversion || !sw_fw_apiversion){ - strcpy(firmware_message, - "FATAL ERROR: Cant read versions from FPGA. Please update firmware.\n"); - cprintf(RED,"%s\n\n", firmware_message); + if (!fwversion || !sw_fw_apiversion) { + strcpy(firmware_message, "Cant read versions from FPGA. Please update firmware.\n"); + FILE_LOG(logERROR, (firmware_message)); firmware_compatibility = FAIL; firmware_check_done = 1; return; } //check for API compatibility - old server - if(sw_fw_apiversion > REQUIRED_FIRMWARE_VERSION){ - sprintf(firmware_message, - "FATAL ERROR: This detector software software version (%lld) is incompatible.\n" + if (sw_fw_apiversion > REQUIRED_FIRMWARE_VERSION) { + sprintf(firmware_message, "This detector software software version (%lld) is incompatible.\n" "Please update detector software (min. %lld) to be compatible with this firmware.\n", (long long int)sw_fw_apiversion, (long long int)REQUIRED_FIRMWARE_VERSION); - cprintf(RED,"%s\n\n", firmware_message); + FILE_LOG(logERROR, (firmware_message)); firmware_compatibility = FAIL; firmware_check_done = 1; return; } //check for firmware compatibility - old firmware - if( REQUIRED_FIRMWARE_VERSION > fwversion){ - sprintf(firmware_message, - "FATAL ERROR: This firmware version (%lld) is incompatible.\n" + if ( REQUIRED_FIRMWARE_VERSION > fwversion) { + sprintf(firmware_message, "This firmware version (%lld) is incompatible.\n" "Please update firmware (min. %lld) to be compatible with this server.\n", (long long int)fwversion, (long long int)REQUIRED_FIRMWARE_VERSION); - cprintf(RED,"%s\n\n", firmware_message); + FILE_LOG(logERROR, (firmware_message)); firmware_compatibility = FAIL; firmware_check_done = 1; return; } - printf("Compatibility - success\n"); + FILE_LOG(logINFO, ("Compatibility - success\n")); firmware_check_done = 1; } @@ -200,13 +182,13 @@ void checkFirmwareCompatibility(){ /* Ids */ -int64_t getDetectorId(enum idMode arg){ +int64_t getDetectorId(enum idMode arg) { #ifdef VIRTUAL return 0; #else int64_t retval = -1; - switch(arg){ + switch(arg) { case DETECTOR_SERIAL_NUMBER: retval = getDetectorNumber();/** to be implemented with mac? */ break; @@ -215,7 +197,7 @@ int64_t getDetectorId(enum idMode arg){ case SOFTWARE_FIRMWARE_API_VERSION: return (int64_t)Beb_GetFirmwareSoftwareAPIVersion(); case DETECTOR_SOFTWARE_VERSION: - return (GITDATE & 0xFFFFFF); + return (GITDATE & 0xFFFFFF); case CLIENT_SOFTWARE_API_VERSION: return APIEIGER; default: @@ -236,7 +218,7 @@ u_int64_t getFirmwareVersion() { -u_int32_t getDetectorNumber(){ +u_int32_t getDetectorNumber() { #ifdef VIRTUAL return 0; #else @@ -262,22 +244,22 @@ u_int64_t getDetectorMAC() { //getting rid of ":" char * pch; pch = strtok (output,":"); - while (pch != NULL){ + while (pch != NULL) { strcat(mac,pch); pch = strtok (NULL, ":"); } sscanf(mac,"%llx",&res); //increment by 1 for 10g - if(send_to_ten_gig) + if (send_to_ten_gig) res++; - //printf("mac:%llx\n",res); + //FILE_LOG(logINFO, ("mac:%llx\n",res)); return res; #endif } -u_int32_t getDetectorIP(){ +u_int32_t getDetectorIP() { #ifdef VIRTUAL return 0; #endif @@ -298,7 +280,7 @@ u_int32_t getDetectorIP(){ } strcpy(output,temp); sscanf(output, "%x", &res); - //printf("ip:%x\n",res); + //FILE_LOG(logINFO, ("ip:%x\n",res)); return res; } @@ -309,11 +291,10 @@ u_int32_t getDetectorIP(){ /* initialization */ -void initControlServer(){ +void initControlServer() { #ifdef VIRTUAL getModuleConfiguration(); setupDetector(); - printf("\n"); return; #else //Feb and Beb Initializations @@ -322,38 +303,35 @@ void initControlServer(){ Feb_Control_FebControl(); Feb_Control_Init(master,top,normal, getDetectorNumber()); //master of 9M, check high voltage serial communication to blackfin - if(master && !normal){ - if(Feb_Control_OpenSerialCommunication()) - ;// Feb_Control_CloseSerialCommunication(); + if (master && !normal) { + if (Feb_Control_OpenSerialCommunication()) + ;// Feb_Control_CloseSerialCommunication(); } - printf("FEB Initialization done\n"); - Beb_Beb(); + FILE_LOG(logDEBUG5, ("Control server: FEB Initialization done\n")); + Beb_Beb(detid); Beb_SetDetectorNumber(getDetectorNumber()); - printf("BEB Initialization done\n"); + FILE_LOG(logDEBUG5, ("Control server: BEB Initialization done\n")); setupDetector(); #endif - printf("\n"); } -void initStopServer(){ +void initStopServer() { #ifdef VIRTUAL getModuleConfiguration(); - printf("\n"); return; #else getModuleConfiguration(); Feb_Interface_FebInterface(); Feb_Control_FebControl(); Feb_Control_Init(master,top,normal,getDetectorNumber()); - printf("FEB Initialization done\n"); + FILE_LOG(logDEBUG5, ("Stop server: FEB Initialization done\n")); #endif - printf("\n"); } -void getModuleConfiguration(){ +void getModuleConfiguration() { #ifdef VIRTUAL #ifdef VIRTUAL_MASTER master = 1; @@ -367,24 +345,22 @@ void getModuleConfiguration(){ #else normal = 1; #endif - if(top) printf("*************** TOP ***************\n"); - else printf("*************** BOTTOM ***************\n"); - if(master) printf("*************** MASTER ***************\n"); - else printf("*************** SLAVE ***************\n"); - if(normal) printf("*************** NORMAL ***************\n"); - else printf("*************** SPECIAL ***************\n"); + FILE_LOG(logINFOBLUE, ("Module: %s %s %s\n", + (top ? "TOP" : "BOTTOM"), + (master ? "MASTER" : "SLAVE"), + (normal ? "NORMAL" : "SPECIAL"))); return; #else int *m=&master; int *t=⊤ int *n=&normal; Beb_GetModuleConfiguration(m,t,n); - if(top) printf("*************** TOP ***************\n"); - else printf("*************** BOTTOM ***************\n"); - if(master) printf("*************** MASTER ***************\n"); - else printf("*************** SLAVE ***************\n"); - if(normal) printf("*************** NORMAL ***************\n"); - else printf("*************** SPECIAL ***************\n"); + if (isControlServer) { + FILE_LOG(logINFOBLUE, ("Module: %s %s %s\n", + (top ? "TOP" : "BOTTOM"), + (master ? "MASTER" : "SLAVE"), + (normal ? "NORMAL" : "SPECIAL"))); + } // read detector id char output[255]; @@ -392,7 +368,9 @@ void getModuleConfiguration(){ fgets(output, sizeof(output), sysFile); pclose(sysFile); sscanf(output,"%u",&detid); - printf("detector id: %u\n",detid); + if (isControlServer) { + FILE_LOG(logINFOBLUE, ("Detector ID: %u\n\n", detid)); + } #endif } @@ -400,8 +378,8 @@ void getModuleConfiguration(){ /* set up detector */ -void allocateDetectorStructureMemory(){ - printf("This Server is for 1 Eiger half module (250k)\n"); +void allocateDetectorStructureMemory() { + FILE_LOG(logINFO, ("This Server is for 1 Eiger half module (250k)\n\n")); //Allocation of memory detectorModules=malloc(sizeof(sls_detector_module)); @@ -409,13 +387,11 @@ void allocateDetectorStructureMemory(){ detectorChans=malloc(NCHIP*NCHAN*sizeof(int)); detectorDacs=malloc(NDAC*sizeof(int)); detectorAdcs=malloc(NADC*sizeof(int)); -#ifdef VERBOSE - printf("modules from 0x%x to 0x%x\n",detectorModules, detectorModules+n); - printf("chips from 0x%x to 0x%x\n",detectorChips, detectorChips+n*NCHIP); - printf("chans from 0x%x to 0x%x\n",detectorChans, detectorChans+n*NCHIP*NCHAN); - printf("dacs from 0x%x to 0x%x\n",detectorDacs, detectorDacs+n*NDAC); - printf("adcs from 0x%x to 0x%x\n",detectorAdcs, detectorAdcs+n*NADC); -#endif + FILE_LOG(logDEBUG5, ("modules from 0x%x to 0x%x\n",detectorModules, detectorModules)); + FILE_LOG(logDEBUG5, ("chips from 0x%x to 0x%x\n",detectorChips, detectorChips)); + FILE_LOG(logDEBUG5, ("chans from 0x%x to 0x%x\n",detectorChans, detectorChans)); + FILE_LOG(logDEBUG5, ("dacs from 0x%x to 0x%x\n",detectorDacs, detectorDacs)); + FILE_LOG(logDEBUG5, ("adcs from 0x%x to 0x%x\n",detectorAdcs, detectorAdcs)); (detectorModules)->dacs=detectorDacs; (detectorModules)->adcs=detectorAdcs; (detectorModules)->chipregs=detectorChips; @@ -442,18 +418,20 @@ void setupDetector() { allocateDetectorStructureMemory(); //set dacs - printf("Setting Default Dac values\n"); + FILE_LOG(logINFOBLUE, ("Setting Default Dac values\n")); { int i = 0; int retval[2]={-1,-1}; const int defaultvals[NDAC] = DEFAULT_DAC_VALS; for(i = 0; i < NDAC; ++i) { setDAC((enum DACINDEX)i,defaultvals[i],0,retval); - if (retval[0] != defaultvals[i]) - cprintf(RED, "Warning: Setting dac %d failed, wrote %d, read %d\n",i ,defaultvals[i], retval[0]); + if (retval[0] != defaultvals[i]) { + FILE_LOG(logERROR, ("Setting dac %d failed, wrote %d, read %d\n",i ,defaultvals[i], retval[0])); + } } } + FILE_LOG(logINFOBLUE, ("Setting Default Parameters\n")); //setting default measurement parameters setTimer(FRAME_NUMBER, DEFAULT_NUM_FRAMES); setTimer(ACQUISITION_TIME, DEFAULT_EXPTIME); @@ -466,7 +444,7 @@ void setupDetector() { setReadOutFlags(DEFAULT_READOUT_MODE); setReadOutFlags(DEFAULT_READOUT_STOREINRAM_MODE); setReadOutFlags(DEFAULT_READOUT_OVERFLOW32_MODE); - setSpeed(CLOCK_DIVIDER, DEFAULT_CLK_SPEED);//clk_devider,half speed + setSpeed(DEFAULT_CLK_SPEED);//clk_devider,half speed setIODelay(DEFAULT_IO_DELAY); setTiming(DEFAULT_TIMING_MODE); //SetPhotonEnergyCalibrationParameters(-5.8381e-5,1.838515,5.09948e-7,-4.32390e-11,1.32527e-15); @@ -480,6 +458,7 @@ void setupDetector() { #ifndef VIRTUAL Feb_Control_CheckSetup(); #endif + FILE_LOG(logDEBUG5, ("Setup detector done\n\n")); } @@ -506,25 +485,25 @@ uint32_t readRegister(uint32_t offset) { /* set parameters - dr, roi */ -int setDynamicRange(int dr){ +int setDynamicRange(int dr) { #ifdef VIRTUAL - if(dr > 0){ - printf(" Setting dynamic range: %d\n",dr); + if (dr > 0) { + FILE_LOG(logINFO, ("Setting dynamic range: %d\n", dr)); eiger_dynamicrange = dr; } return eiger_dynamicrange; #else - if(dr > 0){ - printf(" Setting dynamic range: %d\n",dr); - if(Feb_Control_SetDynamicRange(dr)){ + if (dr > 0) { + FILE_LOG(logDEBUG5, ("Setting dynamic range: %d\n", dr)); + if (Feb_Control_SetDynamicRange(dr)) { //EigerSetBitMode(dr); on_dst = 0; int i; for(i=0;i<32;i++) dst_requested[i] = 0; //clear dst requested - if(Beb_SetUpTransferParameters(dr)) + if (Beb_SetUpTransferParameters(dr)) eiger_dynamicrange = dr; - else printf("ERROR:Could not set bit mode in the back end\n"); + else FILE_LOG(logERROR, ("Could not set bit mode in the back end\n")); } } //make sure back end and front end have the same bit mode @@ -539,15 +518,12 @@ int setDynamicRange(int dr){ /* parameters - readout */ -int setSpeed(enum speedVariable arg, int val){ +enum speedVariable setSpeed(int val) { - if (arg != CLOCK_DIVIDER) - return -1; - - if(val != -1){ - printf(" Setting Read out Speed: %d\n",val); + if (val != -1) { + FILE_LOG(logDEBUG5, ("Setting Read out Speed: %d\n", val)); #ifndef VIRTUAL - if(Feb_Control_SetReadoutSpeed(val)) + if (Feb_Control_SetReadoutSpeed(val)) #endif eiger_readoutspeed = val; } @@ -555,25 +531,33 @@ int setSpeed(enum speedVariable arg, int val){ } -enum readOutFlags setReadOutFlags(enum readOutFlags val){ +enum readOutFlags setReadOutFlags(enum readOutFlags val) { enum readOutFlags retval = GET_READOUT_FLAGS; - if(val!=GET_READOUT_FLAGS){ + if (val!=GET_READOUT_FLAGS) { - if(val&0xF0000){ - switch(val){ - case PARALLEL: val=E_PARALLEL; printf(" Setting Read out Flag: Parallel\n"); break; - case NONPARALLEL: val=E_NON_PARALLEL; printf(" Setting Read out Flag: Non Parallel\n"); break; - case SAFE: val=E_SAFE; printf(" Setting Read out Flag: Safe\n"); break; + if (val&0xF0000) { + switch(val) { + case PARALLEL: + val=E_PARALLEL; + FILE_LOG(logDEBUG5, ("Setting Read out Flag: Parallel\n")); + break; + case NONPARALLEL: + val=E_NON_PARALLEL; + FILE_LOG(logDEBUG5, ("Setting Read out Flag: Non Parallel\n")); + break; + case SAFE: + val=E_SAFE; + FILE_LOG(logDEBUG5, ("Setting Read out Flag: Safe\n")); + break; default: - cprintf(RED,"Cannot set unknown readout flag. 0x%x\n", val); + FILE_LOG(logERROR, ("Cannot set unknown readout flag. 0x%x\n", val)); return -1; } - printf(" Setting Read out Flag: %d\n",val); #ifndef VIRTUAL - if(Feb_Control_SetReadoutMode(val)) + if (Feb_Control_SetReadoutMode(val)) #endif eiger_readoutmode = val; #ifndef VIRTUAL @@ -583,16 +567,21 @@ enum readOutFlags setReadOutFlags(enum readOutFlags val){ } else if (val&0xF00000) { - switch(val){ - case SHOW_OVERFLOW: val=1; printf(" Setting Read out Flag: Overflow in 32 bit mode\n"); break; - case NOOVERFLOW: val=0; printf(" Setting Read out Flag: No overflow in 32 bit mode\n"); break; + switch(val) { + case SHOW_OVERFLOW: + val=1; + FILE_LOG(logDEBUG5, ("Setting Read out Flag: Overflow in 32 bit mode\n")); + break; + case NOOVERFLOW: + val=0; + FILE_LOG(logDEBUG5, ("Setting Read out Flag: No overflow in 32 bit mode\n")); + break; default: - cprintf(RED,"Cannot set unknown readout flag. 0x%x\n", val); + FILE_LOG(logERROR, ("Cannot set unknown readout flag. 0x%x\n", val)); return -1; } - printf(" Setting Read out Flag: %d\n",val); #ifndef VIRTUAL - if(Beb_Set32bitOverflow(val) != -1) + if (Beb_Set32bitOverflow(val) != -1) #endif eiger_overflow32 = val; #ifndef VIRTUAL @@ -601,41 +590,58 @@ enum readOutFlags setReadOutFlags(enum readOutFlags val){ } - else{ - switch(val){ - case STORE_IN_RAM: val=1; printf(" Setting Read out Flag: Store in Ram\n"); break; - case CONTINOUS_RO: val=0; printf(" Setting Read out Flag: Continuous Readout\n"); break; + else { + switch(val) { + case STORE_IN_RAM: + val=1; + FILE_LOG(logDEBUG5, ("Setting Read out Flag: Store in Ram\n")); + break; + case CONTINOUS_RO: + val=0; + FILE_LOG(logDEBUG5, ("Setting Read out Flag: Continuous Readout\n")); + break; default: - cprintf(RED,"Cannot set unknown readout flag. 0x%x\n", val); + FILE_LOG(logERROR, ("Cannot set unknown readout flag. 0x%x\n", val)); return -1; } - printf(" Setting store in ram variable: %d\n",val); eiger_storeinmem = val; } } - switch(eiger_readoutmode){ - case E_PARALLEL: retval=PARALLEL; break; - case E_NON_PARALLEL: retval=NONPARALLEL; break; - case E_SAFE: retval=SAFE; break; + switch(eiger_readoutmode) { + case E_PARALLEL: + retval=PARALLEL; + break; + case E_NON_PARALLEL: + retval=NONPARALLEL; + break; + case E_SAFE: + retval=SAFE; + break; } - switch(eiger_overflow32){ - case 1: retval|=SHOW_OVERFLOW; break; - case 0: retval|=NOOVERFLOW; break; + switch(eiger_overflow32) { + case 1: + retval|=SHOW_OVERFLOW; + break; + case 0: + retval|=NOOVERFLOW; + break; } - switch(eiger_storeinmem){ - case 0: retval|=CONTINOUS_RO; break; - case 1: retval|=STORE_IN_RAM; break; + switch(eiger_storeinmem) { + case 0: + retval|=CONTINOUS_RO; + break; + case 1: + retval|=STORE_IN_RAM; + break; } - - - printf("Read out Flag: 0x%x\n",retval); + FILE_LOG(logDEBUG5, ("Read out Flag: 0x%x\n", retval)); return retval; } @@ -648,17 +654,17 @@ enum readOutFlags setReadOutFlags(enum readOutFlags val){ /* parameters - timer */ -int64_t setTimer(enum timerIndex ind, int64_t val){ +int64_t setTimer(enum timerIndex ind, int64_t val) { #ifndef VIRTUAL int64_t subdeadtime = 0; #endif int64_t subexptime = 0; - switch(ind){ + switch(ind) { case FRAME_NUMBER: - if(val >= 0){ - printf(" Setting number of frames: %d * %d\n",(unsigned int)val,eiger_ncycles); + if (val >= 0) { + FILE_LOG(logDEBUG5, ("Setting number of frames: %d * %d\n", (unsigned int)val, eiger_ncycles)); #ifndef VIRTUAL - if(Feb_Control_SetNExposures((unsigned int)val*eiger_ncycles)){ + if (Feb_Control_SetNExposures((unsigned int)val*eiger_ncycles)) { eiger_nexposures = val; //SetDestinationParameters(EigerGetNumberOfExposures()*EigerGetNumberOfCycles()); on_dst = 0; @@ -674,8 +680,8 @@ int64_t setTimer(enum timerIndex ind, int64_t val){ }return eiger_nexposures; case ACQUISITION_TIME: - if(val >= 0){ - printf(" Setting exp time: %fs\n",val/(1E9)); + if (val >= 0) { + FILE_LOG(logDEBUG5, ("Setting exp time: %fs\n", val/(1E9))); #ifndef VIRTUAL Feb_Control_SetExposureTime(val/(1E9)); #else @@ -689,8 +695,8 @@ int64_t setTimer(enum timerIndex ind, int64_t val){ #endif case SUBFRAME_ACQUISITION_TIME: - if(val >= 0){ - printf(" Setting sub exp time: %lldns\n",(long long int)val); + if (val >= 0) { + FILE_LOG(logDEBUG5, ("Setting sub exp time: %lldns\n", (long long int)val)); #ifndef VIRTUAL // calculate subdeadtime before settings subexptime subdeadtime = Feb_Control_GetSubFramePeriod() - @@ -714,16 +720,16 @@ int64_t setTimer(enum timerIndex ind, int64_t val){ case SUBFRAME_DEADTIME: #ifndef VIRTUAL - // get subexptime - subexptime = Feb_Control_GetSubFrameExposureTime(); + // get subexptime + subexptime = Feb_Control_GetSubFrameExposureTime(); #else - subexptime = eiger_virtual_subexptime*10; + subexptime = eiger_virtual_subexptime*10; #endif - if(val >= 0){ - printf(" Setting sub period: %lldns = subexptime(%lld) + subdeadtime(%lld)\n", - (long long int)(val + subexptime), + if (val >= 0) { + FILE_LOG(logINFO, ("Setting sub period (subdeadtime(%lld)): %lldns\n", (long long int)subexptime, - (long long int)val); + (long long int)val), + (long long int)(val + subexptime)); //calculate subperiod val += subexptime; #ifndef VIRTUAL @@ -739,8 +745,8 @@ int64_t setTimer(enum timerIndex ind, int64_t val){ #endif case FRAME_PERIOD: - if(val >= 0){ - printf(" Setting acq period: %fs\n",val/(1E9)); + if (val >= 0) { + FILE_LOG(logDEBUG5, ("Setting acq period: %fs\n", val/(1E9))); #ifndef VIRTUAL Feb_Control_SetExposurePeriod(val/(1E9)); #else @@ -754,10 +760,11 @@ int64_t setTimer(enum timerIndex ind, int64_t val){ #endif case CYCLES_NUMBER: - if(val >= 0){ - printf(" Setting number of triggers: %d * %d\n",(unsigned int)val,eiger_nexposures); + if (val >= 0) { + FILE_LOG(logDEBUG5, ("Setting number of triggers: %d * %d\n", + (unsigned int)val,eiger_nexposures)); #ifndef VIRTUAL - if(Feb_Control_SetNExposures((unsigned int)val*eiger_nexposures)){ + if (Feb_Control_SetNExposures((unsigned int)val*eiger_nexposures)) { eiger_ncycles = val; //SetDestinationParameters(EigerGetNumberOfExposures()*EigerGetNumberOfCycles()); on_dst = 0; @@ -772,7 +779,7 @@ int64_t setTimer(enum timerIndex ind, int64_t val){ } return eiger_ncycles; default: - cprintf(RED,"Warning: Timer Index not implemented for this detector: %d\n", ind); + FILE_LOG(logERROR, ("Timer Index not implemented for this detector: %d\n", ind)); break; } @@ -784,12 +791,12 @@ int64_t getTimeLeft(enum timerIndex ind) { #ifdef VIRTUAL return 0; #else - switch(ind){ + switch(ind) { case MEASURED_PERIOD: return Feb_Control_GetMeasuredPeriod(); case MEASURED_SUBPERIOD: return Feb_Control_GetSubMeasuredPeriod(); return 0; default: - cprintf(RED,"This timer left index (%d) not defined for Eiger\n",ind); + FILE_LOG(logERROR, ("This timer left index (%d) not defined for Eiger\n", ind)); return -1; } #endif @@ -801,13 +808,11 @@ int64_t getTimeLeft(enum timerIndex ind) { /* parameters - channel, chip, module, settings */ -int setModule(sls_detector_module myMod, int delay){ +int setModule(sls_detector_module myMod, int delay) { int retval[2]; int i; - //#ifdef VERBOSE - printf("Setting module with settings %d\n",myMod.reg); - //#endif + FILE_LOG(logINFO, ("Setting module with settings %d\n",myMod.reg)); //copy module locally (module number, serial number, gain offset, //dacs (pointless), trimbit values(if needed) @@ -819,8 +824,8 @@ int setModule(sls_detector_module myMod, int delay){ setSettings( (enum detectorSettings)myMod.reg); // iodelay - if(setIODelay(delay)!= delay){ - cprintf(RED,"could not set iodelay %d\n",delay); + if (setIODelay(delay)!= delay) { + FILE_LOG(logERROR, ("Could not set iodelay %d\n", delay)); return FAIL; } @@ -830,10 +835,10 @@ int setModule(sls_detector_module myMod, int delay){ // trimbits #ifndef VIRTUAL - if(myMod.nchan==0 && myMod.nchip == 0) - cprintf(BLUE,"Setting module without trimbits\n"); - else{ - printf("Setting module with trimbits\n"); + if (myMod.nchan==0 && myMod.nchip == 0) { + FILE_LOG(logINFO, ("Setting module without trimbits\n")); + } else { + FILE_LOG(logINFO, ("Setting module with trimbits\n")); //includ gap pixels unsigned int tt[263680]; int iy,ichip,ix,ip=0,ich=0; @@ -850,8 +855,8 @@ int setModule(sls_detector_module myMod, int delay){ } //set trimbits - if(!Feb_Control_SetTrimbits(Feb_Control_GetModuleNumber(),tt)){ - cprintf(BG_RED,"Could not set trimbits\n"); + if (!Feb_Control_SetTrimbits(Feb_Control_GetModuleNumber(),tt)) { + FILE_LOG(logERROR, ("Could not set trimbits\n")); return FAIL; } } @@ -860,7 +865,7 @@ int setModule(sls_detector_module myMod, int delay){ } -int getModule(sls_detector_module *myMod){ +int getModule(sls_detector_module *myMod) { #ifndef VIRTUAL int i; @@ -869,7 +874,7 @@ int getModule(sls_detector_module *myMod){ //dacs for(i=0;idacs)+i)); + //FILE_LOG(logINFO,"dac%d:%d\n",i, *((detectorModules->dacs)+i)); } //trimbits @@ -895,7 +900,7 @@ int getModule(sls_detector_module *myMod){ if (detectorModules) { if (copyModule(myMod, detectorModules) == FAIL) return FAIL; - } + } else return FAIL; return OK; @@ -903,16 +908,16 @@ int getModule(sls_detector_module *myMod){ -enum detectorSettings setSettings(enum detectorSettings sett){ - if(sett == UNINITIALIZED){ +enum detectorSettings setSettings(enum detectorSettings sett) { + if (sett == UNINITIALIZED) { return thisSettings; - }if(sett != GET_SETTINGS) + }if (sett != GET_SETTINGS) thisSettings = sett; - printf(" Settings: %d\n", thisSettings); + FILE_LOG(logINFO, ("Settings: %d\n", thisSettings)); return thisSettings; } -enum detectorSettings getSettings(){ +enum detectorSettings getSettings() { return thisSettings; } @@ -923,15 +928,15 @@ enum detectorSettings getSettings(){ /* parameters - threshold */ -int getThresholdEnergy(){ - printf(" Getting Threshold energy\n"); +int getThresholdEnergy() { + FILE_LOG(logINFO, ("Getting Threshold energy\n")); return eiger_photonenergy; } -int setThresholdEnergy(int ev){ - printf(" Setting threshold energy:%d\n",ev); - if(ev >= 0) +int setThresholdEnergy(int ev) { + FILE_LOG(logINFO, ("Setting threshold energy:%d\n",ev)); + if (ev >= 0) eiger_photonenergy = ev; return getThresholdEnergy(); } @@ -942,61 +947,55 @@ int setThresholdEnergy(int ev){ /* parameters - dac, adc, hv */ -void setDAC(enum DACINDEX ind, int val, int mV, int retval[]){ - printf("Going to set dac %d to %d with mv mode %d \n", (int)ind, val, mV); - if(ind == VTHRESHOLD){ +void setDAC(enum DACINDEX ind, int val, int mV, int retval[]) { + FILE_LOG(logDEBUG5, ("Going to set dac %d to %d with mv mode %d \n", (int)ind, val, mV)); + if (ind == VTHRESHOLD) { int ret[5]; setDAC(VCMP_LL,val,mV,retval); - ret[0] = retval[mV]; + ret[0] = retval[mV]; setDAC(VCMP_LR,val,mV,retval); - ret[1] = retval[mV]; + ret[1] = retval[mV]; setDAC(VCMP_RL,val,mV,retval); - ret[2] = retval[mV]; + ret[2] = retval[mV]; setDAC(VCMP_RR,val,mV,retval); - ret[3] = retval[mV]; + ret[3] = retval[mV]; setDAC(VCP,val,mV,retval); - ret[4] = retval[mV]; + ret[4] = retval[mV]; - if((ret[0]== ret[1])&& + if ((ret[0]== ret[1])&& (ret[1]==ret[2])&& (ret[2]==ret[3]) && - (ret[3]==ret[4])) - cprintf(GREEN,"vthreshold match\n"); - else{ - retval[0] = -1;retval[1] = -1; - cprintf(RED,"vthreshold mismatch 0:%d 1:%d 2:%d 3:%d\n", - ret[0],ret[1],ret[2],ret[3]); + (ret[3]==ret[4])) { + FILE_LOG(logINFO, ("vthreshold match\n")); + } else { + retval[0] = -1;retval[1] = -1; + FILE_LOG(logERROR, ("vthreshold mismatch 0:%d 1:%d 2:%d 3:%d\n", + ret[0],ret[1],ret[2],ret[3])); } return; } char iname[10]; - if(((int)ind>=0)&&((int)ind=0)&&((int)ind= 0) - printf("Setting dac %d: %s to %d ",ind, iname,val); - else - printf("Getting dac %d: %s ",ind, iname); - if(mV) - printf("in mV\n"); - else - printf("in dac units\n"); -#endif + FILE_LOG(logDEBUG5, ("%s dac %d: %s to %d %s\n", + (val >= 0) ? "Setting" : "Getting", + ind, iname, val, + mV ? "mV" : "dac units")); #ifdef VIRTUAL - if (mV){ + if (mV) { retval[0] = (int)(((val-0)/(2048-0))*(4096-1) + 0.5); retval[1] = val; - }else + } else retval[0] = val; #else - if(val >= 0) + if (val >= 0) Feb_Control_SetDAC(iname,val,mV); int k; Feb_Control_GetDAC(iname, &k,0); @@ -1010,7 +1009,7 @@ void setDAC(enum DACINDEX ind, int val, int mV, int retval[]){ -int getADC(enum ADCINDEX ind){ +int getADC(enum ADCINDEX ind) { #ifdef VIRTUAL return 0; #else @@ -1018,43 +1017,43 @@ int getADC(enum ADCINDEX ind){ char tempnames[6][20]={"FPGA EXT", "10GE","DCDC", "SODL", "SODR", "FPGA"}; char cstore[255]; - switch(ind){ - case TEMP_FPGA: - retval=getBebFPGATemp(); - break; - case TEMP_FPGAFEBL: - retval=Feb_Control_GetLeftFPGATemp(); - break; - case TEMP_FPGAFEBR: - retval=Feb_Control_GetRightFPGATemp(); - break; - case TEMP_FPGAEXT: - case TEMP_10GE: - case TEMP_DCDC: - case TEMP_SODL: - case TEMP_SODR: - sprintf(cstore,"more /sys/class/hwmon/hwmon%d/device/temp1_input",ind); - FILE* sysFile = popen(cstore, "r"); - fgets(cstore, sizeof(cstore), sysFile); - pclose(sysFile); - sscanf(cstore,"%d",&retval); - break; - default: - return -1; + switch(ind) { + case TEMP_FPGA: + retval=getBebFPGATemp(); + break; + case TEMP_FPGAFEBL: + retval=Feb_Control_GetLeftFPGATemp(); + break; + case TEMP_FPGAFEBR: + retval=Feb_Control_GetRightFPGATemp(); + break; + case TEMP_FPGAEXT: + case TEMP_10GE: + case TEMP_DCDC: + case TEMP_SODL: + case TEMP_SODR: + sprintf(cstore,"more /sys/class/hwmon/hwmon%d/device/temp1_input",ind); + FILE* sysFile = popen(cstore, "r"); + fgets(cstore, sizeof(cstore), sysFile); + pclose(sysFile); + sscanf(cstore,"%d",&retval); + break; + default: + return -1; } - printf("Temperature %s: %f°C\n",tempnames[ind],(double)retval/1000.00); + FILE_LOG(logINFO, ("Temperature %s: %f°C\n", tempnames[ind], (double)retval/1000.00)); return retval; #endif } -int setHighVoltage(int val){ +int setHighVoltage(int val) { #ifdef VIRTUAL if (master) { // set - if(val!=-1){ + if (val!=-1) { eiger_theo_highvoltage = val; } return eiger_theo_highvoltage; @@ -1066,10 +1065,10 @@ int setHighVoltage(int val){ if (master) { // set - if(val!=-1){ + if (val!=-1) { eiger_theo_highvoltage = val; int ret = Feb_Control_SetHighVoltage(val); - if(!ret) //could not set + if (!ret) //could not set return -2; else if (ret == -1) //outside range return -1; @@ -1077,13 +1076,13 @@ int setHighVoltage(int val){ // get if (!Feb_Control_GetHighVoltage(&eiger_highvoltage)) { - cprintf(RED,"Warning: Could not read high voltage\n"); + FILE_LOG(logERROR, ("Could not read high voltage\n")); return -3; } // tolerance of 5 if (abs(eiger_theo_highvoltage-eiger_highvoltage) > HIGH_VOLTAGE_TOLERANCE) { - cprintf(BLUE, "High voltage still ramping: %d\n", eiger_highvoltage); + FILE_LOG(logINFO, ("High voltage still ramping: %d\n", eiger_highvoltage)); return eiger_highvoltage; } return eiger_theo_highvoltage; @@ -1101,18 +1100,18 @@ int setHighVoltage(int val){ /* parameters - timing, extsig */ -void setTiming( enum externalCommunicationMode arg){ +void setTiming( enum externalCommunicationMode arg) { enum externalCommunicationMode ret=GET_EXTERNAL_COMMUNICATION_MODE; - if(arg != GET_EXTERNAL_COMMUNICATION_MODE){ - switch((int)arg){ + if (arg != GET_EXTERNAL_COMMUNICATION_MODE) { + switch((int)arg) { case AUTO_TIMING: ret = 0; break; case TRIGGER_EXPOSURE: ret = 2; break; case BURST_TRIGGER: ret = 1; break; case GATE_FIX_NUMBER: ret = 3; break; } - printf(" Setting Triggering Mode: %d\n",(int)ret); + FILE_LOG(logDEBUG5, ("Setting Triggering Mode: %d\n", (int)ret)); #ifndef VIRTUAL - if(Feb_Control_SetTriggerMode(ret,1)) + if (Feb_Control_SetTriggerMode(ret,1)) #endif eiger_triggermode = ret; } @@ -1122,13 +1121,13 @@ void setTiming( enum externalCommunicationMode arg){ enum externalCommunicationMode getTiming() { enum externalCommunicationMode ret = GET_EXTERNAL_COMMUNICATION_MODE; ret = eiger_triggermode; - switch((int)ret){ + switch((int)ret) { case 0: ret = AUTO_TIMING; break; case 2: ret = TRIGGER_EXPOSURE; break; case 1: ret = BURST_TRIGGER; break; case 3: ret = GATE_FIX_NUMBER; break; default: - printf("Unknown trigger mode found %d\n",ret); + FILE_LOG(logERROR, ("Unknown trigger mode found %d\n", ret)); ret = 0; } return ret; @@ -1138,7 +1137,7 @@ enum externalCommunicationMode getTiming() { /* configure mac */ -int configureMAC(uint32_t destip, uint64_t destmac, uint64_t sourcemac, uint32_t sourceip, uint32_t udpport, uint32_t udpport2, int ival) { +int configureMAC(uint32_t destip, uint64_t destmac, uint64_t sourcemac, uint32_t sourceip, uint32_t udpport, uint32_t udpport2) { #ifndef VIRTUAL char src_mac[50], src_ip[50],dst_mac[50], dst_ip[50]; int src_port = 0xE185; @@ -1157,40 +1156,47 @@ int configureMAC(uint32_t destip, uint64_t destmac, uint64_t sourcemac, uint32_t (unsigned int)((destmac>>8)&0xFF), (unsigned int)((destmac>>0)&0xFF)); - printf("src_port:%d\n",src_port); - printf("src_ip:%s\n",src_ip); - printf("dst_ip:%s\n",dst_ip); - printf("src_mac:%s\n",src_mac); - printf("dst_mac:%s\n",dst_mac); - int beb_num = BEB_NUM;//Feb_Control_GetModuleNumber(); + FILE_LOG(logINFO, ("src_port:%d\n" + "src_ip:%s\n" + "dst_ip:%s\n" + "src_mac:%s\n" + "dst_mac:%s\n", + src_port, src_ip, dst_ip, src_mac, dst_mac)); + + + int beb_num = detid; int header_number = 0; int dst_port = udpport; - if(!top) + if (!top) dst_port = udpport2; - printf("dst_port:%d\n\n",dst_port); + FILE_LOG(logINFO, ("dst_port:%d\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; + /* 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)) { + FILE_LOG(logINFO, ("set up left ok\n")); + } else { + return -1; + } /*}*/ header_number = 32; dst_port = udpport2; - if(!top) + if (!top) dst_port = udpport; - printf("dst_port:%d\n\n",dst_port); + FILE_LOG(logINFO, ("dst_port:%d\n",dst_port)); - /*for(i=0;i<32;i++){*//** modified for Aldo*/ - if(Beb_SetBebSrcHeaderInfos(beb_num,send_to_ten_gig,src_mac,src_ip,src_port) && - Beb_SetUpUDPHeader(beb_num,send_to_ten_gig,header_number+i,dst_mac,dst_ip, dst_port)) - printf("set up right ok\n\n"); - else return -1; + /*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)) { + FILE_LOG(logINFO, ("set up right ok\n")); + } else { + return -1; + } /*}*/ on_dst = 0; @@ -1217,11 +1223,11 @@ int setDetectorPosition(int pos[]) { /* eiger specific - iodelay, 10g, pulse, rate, temp, activate, delay nw parameter */ -int setIODelay(int val){ - if(val!=-1){ - printf(" Setting IO Delay: %d\n",val); +int setIODelay(int val) { + if (val!=-1) { + FILE_LOG(logDEBUG5, ("Setting IO Delay: %d\n",val)); #ifndef VIRTUAL - if(Feb_Control_SetIDelays(Feb_Control_GetModuleNumber(),val)) + if (Feb_Control_SetIDelays(Feb_Control_GetModuleNumber(),val)) #endif eiger_iodelay = val; } @@ -1229,30 +1235,26 @@ int setIODelay(int val){ } -int enableTenGigabitEthernet(int val){ - if(val!=-1){ - if(val>0) +int enableTenGigabitEthernet(int val) { + if (val!=-1) { + FILE_LOG(logINFO, ("Setting 10Gbe: %d\n", (val > 0) ? 1 : 0)); + if (val>0) send_to_ten_gig = 1; else send_to_ten_gig = 0; //configuremac called from client } -#ifdef VERBOSE - printf("10Gbe:%d\n",send_to_ten_gig); -#endif return send_to_ten_gig; } -int setCounterBit(int val){ - if(val!=-1){ +int setCounterBit(int val) { + if (val!=-1) { + FILE_LOG(logINFO, ("Setting Counter Bit: %d\n",val)); #ifdef VIRTUAL eiger_virtual_counter_bit = val; #else Feb_Control_Set_Counter_Bit(val); -#endif -#ifdef VERBOSE - printf("Counter Bit:%d\n",val); #endif } #ifdef VIRTUAL @@ -1263,45 +1265,45 @@ int setCounterBit(int val){ } -int pulsePixel(int n, int x, int y){ +int pulsePixel(int n, int x, int y) { #ifndef VIRTUAL - if(!Feb_Control_Pulse_Pixel(n,x,y)) + if (!Feb_Control_Pulse_Pixel(n,x,y)) return FAIL; #endif return OK; } -int pulsePixelNMove(int n, int x, int y){ +int pulsePixelNMove(int n, int x, int y) { #ifndef VIRTUAL - if(!Feb_Control_PulsePixelNMove(n,x,y)) + if (!Feb_Control_PulsePixelNMove(n,x,y)) return FAIL; #endif return OK; } -int pulseChip(int n){ +int pulseChip(int n) { #ifndef VIRTUAL - if(!Feb_Control_PulseChip(n)) + if (!Feb_Control_PulseChip(n)) return FAIL; #endif return OK; } -int64_t setRateCorrection(int64_t custom_tau_in_nsec){//in nanosec (will never be -1) +int64_t setRateCorrection(int64_t custom_tau_in_nsec) {//in nanosec (will never be -1) #ifdef VIRTUAL //deactivating rate correction - if(custom_tau_in_nsec==0){ + if (custom_tau_in_nsec==0) { eiger_virtual_ratecorrection_variable = 0; return 0; } //when dynamic range changes, use old tau - else if(custom_tau_in_nsec == -1) + else if (custom_tau_in_nsec == -1) custom_tau_in_nsec = eiger_virtual_ratetable_tau_in_ns; //get period = subexptime if 32bit , else period = exptime if 16 bit int64_t actual_period = eiger_virtual_subexptime*10; //already in nsec - if(eiger_dynamicrange == 16) + if (eiger_dynamicrange == 16) actual_period = eiger_virtual_exptime; int64_t ratetable_period_in_nsec = eiger_virtual_ratetable_period_in_ns; @@ -1310,44 +1312,44 @@ int64_t setRateCorrection(int64_t custom_tau_in_nsec){//in nanosec (will never b //same setting - if((tau_in_nsec == custom_tau_in_nsec) && (ratetable_period_in_nsec == actual_period)){ - if(eiger_dynamicrange == 32) - printf("Rate Table already created before: Same Tau %lldns, Same subexptime %lldns\n", - (long long int)tau_in_nsec,(long long int)ratetable_period_in_nsec); + if ((tau_in_nsec == custom_tau_in_nsec) && (ratetable_period_in_nsec == actual_period)) { + if (eiger_dynamicrange == 32) + FILE_LOG(logINFO, ("Rate Table already created before: Same Tau %lldns, Same subexptime %lldns\n", + (long long int)tau_in_nsec,(long long int)ratetable_period_in_nsec)); else - printf("Rate Table already created before: Same Tau %lldns, Same exptime %lldns\n", - (long long int)tau_in_nsec,(long long int)ratetable_period_in_nsec); + FILE_LOG(logINFO, ("Rate Table already created before: Same Tau %lldns, Same exptime %lldns\n", + (long long int)tau_in_nsec,(long long int)ratetable_period_in_nsec)); } //different setting, calculate table - else{ + else { eiger_virtual_ratetable_tau_in_ns = custom_tau_in_nsec; double period_in_sec = (double)(eiger_virtual_subexptime*10)/(double)1e9; - if(eiger_dynamicrange == 16) + if (eiger_dynamicrange == 16) period_in_sec = eiger_virtual_exptime; eiger_virtual_ratetable_period_in_ns = period_in_sec*1e9; } //activating rate correction eiger_virtual_ratecorrection_variable = 1; - printf("Rate Correction Value set to %lld ns\n",(long long int)eiger_virtual_ratetable_tau_in_ns); + FILE_LOG(logINFO, ("Rate Correction Value set to %lld ns\n",(long long int)eiger_virtual_ratetable_tau_in_ns)); return eiger_virtual_ratetable_tau_in_ns; #else //deactivating rate correction - if(custom_tau_in_nsec==0){ + if (custom_tau_in_nsec==0) { Feb_Control_SetRateCorrectionVariable(0); return 0; } //when dynamic range changes, use old tau - else if(custom_tau_in_nsec == -1) + else if (custom_tau_in_nsec == -1) custom_tau_in_nsec = Feb_Control_Get_RateTable_Tau_in_nsec(); int dr = Feb_Control_GetDynamicRange(); //get period = subexptime if 32bit , else period = exptime if 16 bit int64_t actual_period = Feb_Control_GetSubFrameExposureTime(); //already in nsec - if(dr == 16) + if (dr == 16) actual_period = Feb_Control_GetExposureTime_in_nsec(); int64_t ratetable_period_in_nsec = Feb_Control_Get_RateTable_Period_in_nsec(); @@ -1355,35 +1357,34 @@ int64_t setRateCorrection(int64_t custom_tau_in_nsec){//in nanosec (will never b //same setting - if((tau_in_nsec == custom_tau_in_nsec) && (ratetable_period_in_nsec == actual_period)){ - if(dr == 32) - printf("Rate Table already created before: Same Tau %lldns, Same subexptime %lldns\n", - tau_in_nsec,ratetable_period_in_nsec); - else - printf("Rate Table already created before: Same Tau %lldns, Same exptime %lldns\n", - tau_in_nsec,ratetable_period_in_nsec); + if ((tau_in_nsec == custom_tau_in_nsec) && (ratetable_period_in_nsec == actual_period)) { + if (dr == 32) { + FILE_LOG(logINFO, ("Rate Table already created before: Same Tau %lldns, Same subexptime %lldns\n", + tau_in_nsec,ratetable_period_in_nsec)); + } else { + FILE_LOG(logINFO, ("Rate Table already created before: Same Tau %lldns, Same exptime %lldns\n", + tau_in_nsec,ratetable_period_in_nsec)); + } } //different setting, calculate table - else{ + else { int ret = Feb_Control_SetRateCorrectionTau(custom_tau_in_nsec); - if(ret<=0){ - cprintf(RED,"Rate correction failed. Deactivating rate correction\n"); + if (ret<=0) { + FILE_LOG(logERROR, ("Rate correction failed. Deactivating rate correction\n")); Feb_Control_SetRateCorrectionVariable(0); return ret; } } //activating rate correction Feb_Control_SetRateCorrectionVariable(1); - printf("Rate Correction Value set to %lld ns\n",(long long int)Feb_Control_Get_RateTable_Tau_in_nsec()); -#ifdef VERBOSE + FILE_LOG(logINFO, ("Rate Correction Value set to %lld ns\n", (long long int)Feb_Control_Get_RateTable_Tau_in_nsec())); Feb_Control_PrintCorrectedValues(); -#endif return Feb_Control_Get_RateTable_Tau_in_nsec(); #endif } -int getRateCorrectionEnable(){ +int getRateCorrectionEnable() { #ifdef VIRTUAL return eiger_virtual_ratecorrection_variable; #else @@ -1391,28 +1392,28 @@ int getRateCorrectionEnable(){ #endif } -int getDefaultSettingsTau_in_nsec(){ +int getDefaultSettingsTau_in_nsec() { return default_tau_from_file; } -void setDefaultSettingsTau_in_nsec(int t){ +void setDefaultSettingsTau_in_nsec(int t) { default_tau_from_file = t; - printf("Default tau set to %d\n",default_tau_from_file); + FILE_LOG(logINFO, ("Default tau set to %d\n", default_tau_from_file)); } -int64_t getCurrentTau(){ - if(!getRateCorrectionEnable()) +int64_t getCurrentTau() { + if (!getRateCorrectionEnable()) return 0; else #ifndef VIRTUAL return Feb_Control_Get_RateTable_Tau_in_nsec(); #else - return eiger_virtual_ratetable_tau_in_ns; + return eiger_virtual_ratetable_tau_in_ns; #endif } -void setExternalGating(int enable[]){ - if(enable>=0){ +void setExternalGating(int enable[]) { + if (enable>=0) { #ifndef VIRTUAL Feb_Control_SetExternalEnableMode(enable[0], enable[1]);//enable = 0 or 1, polarity = 0 or 1 , where 1 is positive #endif @@ -1423,44 +1424,41 @@ void setExternalGating(int enable[]){ enable[1] = eiger_extgatingpolarity; } -int setAllTrimbits(int val){ +int setAllTrimbits(int val) { #ifndef VIRTUAL - if(!Feb_Control_SaveAllTrimbitsTo(val)){ - cprintf(RED,"error in setting all trimbits to value\n"); + if (!Feb_Control_SaveAllTrimbitsTo(val)) { + FILE_LOG(logERROR, ("Could not set all trimbits\n")); return FAIL; } #endif -#ifdef VERBOSE - printf("Copying register %x value %d\n",destMod->reg,val); -#endif - if (detectorModules){ + if (detectorModules) { int ichan; for (ichan=0; ichan<(detectorModules->nchan); ichan++) { *((detectorModules->chanregs)+ichan)=val; } } - cprintf(GREEN, "All trimbits have been set to %d\n", val); + FILE_LOG(logINFO, ("All trimbits have been set to %d\n", val)); return OK; } -int getAllTrimbits(){ +int getAllTrimbits() { int ichan=0; int value = *((detectorModules->chanregs)); - if (detectorModules){ + if (detectorModules) { for (ichan=0; ichan<(detectorModules->nchan); ichan++) { - if(*((detectorModules->chanregs)+ichan) != value) { + if (*((detectorModules->chanregs)+ichan) != value) { value= -1; break; } } } - printf("Value of all Trimbits: %d\n", value); + FILE_LOG(logINFO, ("Value of all Trimbits: %d\n", value)); return value; } -int getBebFPGATemp(){ +int getBebFPGATemp() { #ifdef VIRTUAL return 0; #else @@ -1468,7 +1466,7 @@ int getBebFPGATemp(){ #endif } -int activate(int enable){ +int activate(int enable) { #ifdef VIRTUAL if (enable >=0) eiger_virtual_activate = enable; @@ -1480,12 +1478,12 @@ int activate(int enable){ #endif } -int setNetworkParameter(enum NETWORKINDEX mode, int value){ +int setNetworkParameter(enum NETWORKINDEX mode, int value) { #ifndef VIRTUAL return Beb_SetNetworkParameter(mode, value); #else if (value>-1) { - switch(mode){ + switch(mode) { case TXN_LEFT: eiger_virtual_transmission_delay_left = value; break; @@ -1497,13 +1495,13 @@ int setNetworkParameter(enum NETWORKINDEX mode, int value){ break; case FLOWCTRL_10G: eiger_virtual_transmission_flowcontrol_10g = value; - if(value>0) value = 1; + if (value>0) value = 1; break; - default: cprintf(BG_RED,"Unrecognized mode in network parameter: %d\n",mode); - return -1; + default: FILE_LOG(logERROR, ("Unrecognized mode in network parameter: %d\n",mode)); + return -1; } } - switch(mode){ + switch(mode) { case TXN_LEFT: return eiger_virtual_transmission_delay_left; case TXN_RIGHT: @@ -1512,8 +1510,8 @@ int setNetworkParameter(enum NETWORKINDEX mode, int value){ return eiger_virtual_transmission_delay_frame; case FLOWCTRL_10G: return eiger_virtual_transmission_flowcontrol_10g; - default: cprintf(BG_RED,"Unrecognized mode in network parameter: %d\n",mode); - return -1; + default: FILE_LOG(logERROR, ("Unrecognized mode in network parameter: %d\n",mode)); + return -1; } #endif } @@ -1527,11 +1525,11 @@ int setNetworkParameter(enum NETWORKINDEX mode, int value){ /* aquisition */ -int prepareAcquisition(){ +int prepareAcquisition() { #ifndef VIRTUAL - printf("Going to prepare for acquisition with counter_bit:%d\n",Feb_Control_Get_Counter_Bit()); + FILE_LOG(logINFO, ("Going to prepare for acquisition with counter_bit:%d\n",Feb_Control_Get_Counter_Bit())); Feb_Control_PrepareForAcquisition(); - printf("Going to reset Frame Number\n"); + FILE_LOG(logINFO, ("Going to reset Frame Number\n")); Beb_ResetFrameNumber(); #endif return OK; @@ -1539,16 +1537,16 @@ int prepareAcquisition(){ } -int startStateMachine(){ +int startStateMachine() { #ifdef VIRTUAL eiger_virtual_status = 1; eiger_virtual_stop = 0; - if(pthread_create(&eiger_virtual_tid, NULL, &start_timer, NULL)) { - cprintf(RED,"Could not start Virtual acquisition thread\n"); + if (pthread_create(&eiger_virtual_tid, NULL, &start_timer, NULL)) { + FILE_LOG(logERROR, ("Could not start Virtual acquisition thread\n")); eiger_virtual_status = 0; return FAIL; } - cprintf(GREEN,"***Virtual Acquisition started\n"); + FILE_LOG(logINFO ,"***Virtual Acquisition started\n"); return OK; #else @@ -1556,24 +1554,24 @@ int startStateMachine(){ //get the DAQ toggle bit prev_flag = Feb_Control_AcquisitionStartedBit(); - printf("Going to start acquisition\n"); + FILE_LOG(logINFO, ("Going to start acquisition\n")); Feb_Control_StartAcquisition(); - if(!eiger_storeinmem){ - printf("requesting images right after start\n"); + if (!eiger_storeinmem) { + FILE_LOG(logINFO, ("requesting images right after start\n")); ret = startReadOut(); } //wait for acquisition start - if(ret == OK){ - if(!Feb_Control_WaitForStartedFlag(5000, prev_flag)){ - cprintf(RED,"Error: Acquisition did not start or trouble reading register\n"); + if (ret == OK) { + if (!Feb_Control_WaitForStartedFlag(5000, prev_flag)) { + FILE_LOG(logERROR, ("Acquisition did not FILE_LOG(logERROR ouble reading register\n")); return FAIL; } - cprintf(GREEN,"***Acquisition started\n"); + FILE_LOG(logINFO, ("***Acquisition started\n")); } - /*while(getRunStatus() == IDLE){printf("waiting for being not idle anymore\n");}*/ + /*while(getRunStatus() == IDLE) {FILE_LOG(logINFO, ("waiting for being not idle anymore\n"));}*/ return ret; #endif @@ -1583,12 +1581,12 @@ int startStateMachine(){ void* start_timer(void* arg) { eiger_virtual_status = 1; int wait_in_s = nimages_per_request * eiger_virtual_period; - cprintf(GREEN,"going to wait for %d s\n", wait_in_s); + FILE_LOG(logINFO, ("going to wait for %d s\n", wait_in_s)); while(!eiger_virtual_stop && (wait_in_s >= 0)) { usleep(1000 * 1000); wait_in_s--; } - cprintf(GREEN,"Virtual Timer Done***\n"); + FILE_LOG(logINFO, ("Virtual Timer Done***\n")); eiger_virtual_status = 0; return NULL; @@ -1597,16 +1595,16 @@ void* start_timer(void* arg) { -int stopStateMachine(){ - cprintf(BG_RED,"Going to stop acquisition\n"); +int stopStateMachine() { + FILE_LOG(logERROR, ("Going to stop acquisition\n")); #ifdef VIRTUAL eiger_virtual_stop = 0; return OK; #else - if((Feb_Control_StopAcquisition() == STATUS_IDLE) & Beb_StopAcquisition()) + if ((Feb_Control_StopAcquisition() == STATUS_IDLE) & Beb_StopAcquisition()) return OK; - cprintf(BG_RED,"failed to stop acquisition\n"); + FILE_LOG(logERROR, ("failed to stop acquisition\n")); return FAIL; #endif } @@ -1622,29 +1620,29 @@ int softwareTrigger() { } -int startReadOut(){ +int startReadOut() { - printf("Requesting images...\n"); + FILE_LOG(logINFO, ("Requesting images...\n")); #ifdef VIRTUAL return OK; #else //RequestImages(); int ret_val = 0; dst_requested[0] = 1; - while(dst_requested[on_dst]){ + while(dst_requested[on_dst]) { //waits on data - int beb_num = BEB_NUM;//Feb_Control_GetModuleNumber(); + int beb_num = detid; if ((ret_val = (!Beb_RequestNImages(beb_num,send_to_ten_gig,on_dst,nimages_per_request,0)))) break; -// for(i=0;iserialnumber>=0){ + if (srcMod->serialnumber>=0) { destMod->serialnumber=srcMod->serialnumber; } //no trimbit feature if (destMod->nchip && ((srcMod->nchip)>(destMod->nchip))) { - printf("Number of chip of source is larger than number of chips of destination\n"); + FILE_LOG(logINFO, ("Number of chip of source is larger than number of chips of destination\n")); return FAIL; } //no trimbit feature if (destMod->nchan && ((srcMod->nchan)>(destMod->nchan))) { - printf("Number of channels of source is larger than number of channels of destination\n"); + FILE_LOG(logINFO, ("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"); + FILE_LOG(logINFO, ("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"); + FILE_LOG(logINFO, ("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 + FILE_LOG(logDEBUG5, ("DACs: src %d, dest %d\n",srcMod->ndac,destMod->ndac)); + FILE_LOG(logDEBUG5, ("ADCs: src %d, dest %d\n",srcMod->nadc,destMod->nadc)); + FILE_LOG(logDEBUG5, ("Chips: src %d, dest %d\n",srcMod->nchip,destMod->nchip)); + FILE_LOG(logDEBUG5, ("Chans: src %d, dest %d\n",srcMod->nchan,destMod->nchan)); 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 + FILE_LOG(logDEBUG5, ("Copying register %x (%x)\n",destMod->reg,srcMod->reg )); if (srcMod->gain>=0) destMod->gain=srcMod->gain; if (srcMod->offset>=0) destMod->offset=srcMod->offset; - if((destMod->nchip!=0) || (destMod->nchan!=0)) { + if ((destMod->nchip!=0) || (destMod->nchan!=0)) { for (ichip=0; ichip<(srcMod->nchip); ichip++) { if (*((srcMod->chipregs)+ichip)>=0) *((destMod->chipregs)+ichip)=*((srcMod->chipregs)+ichip); @@ -1792,9 +1786,7 @@ int copyModule(sls_detector_module *destMod, sls_detector_module *srcMod){ *((destMod->chanregs)+ichan)=*((srcMod->chanregs)+ichan); } } -#ifdef VERBOSE - else printf("Not Copying trimbits\n"); -#endif + else FILE_LOG(logINFO, ("Not Copying trimbits\n")); for (idac=0; idac<(srcMod->ndac); idac++) { if (*((srcMod->dacs)+idac)>=0) { *((destMod->dacs)+idac)=*((srcMod->dacs)+idac); @@ -1808,8 +1800,8 @@ int copyModule(sls_detector_module *destMod, sls_detector_module *srcMod){ } -int calculateDataBytes(){ - if(send_to_ten_gig) +int calculateDataBytes() { + if (send_to_ten_gig) return setDynamicRange(-1) * ONE_GIGA_CONSTANT * TEN_GIGA_BUFFER_SIZE; else return setDynamicRange(-1) * TEN_GIGA_CONSTANT * ONE_GIGA_BUFFER_SIZE; @@ -1818,13 +1810,13 @@ int calculateDataBytes(){ -int getTotalNumberOfChannels(){return ((int)getNumberOfChannelsPerChip() * (int)getNumberOfChips());} -int getNumberOfChips(){return NCHIP;} -int getNumberOfDACs(){return NDAC;} -int getNumberOfADCs(){return NADC;} -int getNumberOfChannelsPerChip(){return NCHAN;} -int getNumberOfGains(){return NGAIN;} -int getNumberOfOffsets(){return NOFFSET;} +int getTotalNumberOfChannels() {return ((int)getNumberOfChannelsPerChip() * (int)getNumberOfChips());} +int getNumberOfChips() {return NCHIP;} +int getNumberOfDACs() {return NDAC;} +int getNumberOfADCs() {return NADC;} +int getNumberOfChannelsPerChip() {return NCHAN;} +int getNumberOfGains() {return NGAIN;} +int getNumberOfOffsets() {return NOFFSET;} diff --git a/slsDetectorServers/eigerDetectorServer/slsDetectorServer_defs.h b/slsDetectorServers/eigerDetectorServer/slsDetectorServer_defs.h index fec509799..dfc4d745b 100644 --- a/slsDetectorServers/eigerDetectorServer/slsDetectorServer_defs.h +++ b/slsDetectorServers/eigerDetectorServer/slsDetectorServer_defs.h @@ -42,7 +42,7 @@ enum DACINDEX {SVP,VTR,VRF,VRS,SVN,VTGSTV,VCMP_LL,VCMP_LR,CAL,VCMP_RL,RX }; enum ADCINDEX {TEMP_FPGAEXT, TEMP_10GE, TEMP_DCDC, TEMP_SODL, TEMP_SODR, TEMP_FPGA, TEMP_FPGAFEBL, TEMP_FPGAFEBR}; enum NETWORKINDEX {TXN_LEFT, TXN_RIGHT, TXN_FRAME,FLOWCTRL_10G}; - +enum {E_PARALLEL, E_NON_PARALLEL, E_SAFE}; /* Hardware Definitions */ #define NCHAN (256 * 256) diff --git a/slsDetectorServers/jungfrauDetectorServer/slsDetectorFunctionList.c b/slsDetectorServers/jungfrauDetectorServer/slsDetectorFunctionList.c index c922d0ddc..81a7e4912 100644 --- a/slsDetectorServers/jungfrauDetectorServer/slsDetectorFunctionList.c +++ b/slsDetectorServers/jungfrauDetectorServer/slsDetectorFunctionList.c @@ -448,7 +448,7 @@ void setupDetector() { bus_w(DAQ_REG, 0x0); /* Only once at server startup */ - setSpeed(CLOCK_DIVIDER, HALF_SPEED); + setSpeed(HALF_SPEED); cleanFifos(); resetCore(); @@ -465,7 +465,7 @@ void setupDetector() { setTimer(DELAY_AFTER_TRIGGER, DEFAULT_DELAY); setTimer(STORAGE_CELL_NUMBER, DEFAULT_NUM_STRG_CLLS); selectStoragecellStart(DEFAULT_STRG_CLL_STRT); - /*setSpeed(CLOCK_DIVIDER, HALF_SPEED); depends if all the previous stuff works*/ + /*setSpeed(HALF_SPEED); depends if all the previous stuff works*/ setTiming(DEFAULT_TIMING_MODE); setHighVoltage(DEFAULT_HIGH_VOLTAGE); @@ -611,10 +611,7 @@ int setDynamicRange(int dr){ /* parameters - readout */ -int setSpeed(enum speedVariable arg, int val) { - - if (arg != CLOCK_DIVIDER) - return -1; +enum speedVariable setSpeed(int val) { // setting if(val >= 0) { @@ -1620,7 +1617,7 @@ void readFrame(int *ret, char *mess){ } else { *ret = (int)FINISHED; sprintf(mess,"acquisition successfully finished\n"); - printf("%s",mess); + cprintf(GREEN, "%s",mess); } } diff --git a/slsDetectorServers/mythen3DetectorServer/AD9257.h b/slsDetectorServers/mythen3DetectorServer/AD9257.h deleted file mode 120000 index 87b70e097..000000000 --- a/slsDetectorServers/mythen3DetectorServer/AD9257.h +++ /dev/null @@ -1 +0,0 @@ -../slsDetectorServer/AD9257.h \ No newline at end of file diff --git a/slsDetectorServers/mythen3DetectorServer/Makefile b/slsDetectorServers/mythen3DetectorServer/Makefile deleted file mode 100644 index ba8ffe5f1..000000000 --- a/slsDetectorServers/mythen3DetectorServer/Makefile +++ /dev/null @@ -1,33 +0,0 @@ -CROSS = bfin-uclinux- -CC = $(CROSS)gcc -#CC = gcc -CLAGS += -Wall -DMYTHEN3D -DSLS_DETECTOR_FUNCTION_LIST -DDACS_INT -DSTOP_SERVER #-DVERBOSEI #-DVERBOSE -LDLIBS += -lm -lstdc++ - - -PROGS = mythen3DetectorServer -DESTDIR ?= bin -INSTMODE = 0777 - -SRC_CLNT = communication_funcs.c slsDetectorServer.c slsDetectorServer_funcs.c slsDetectorFunctionList.c -OBJS = $(SRC_CLNT:.c=.o) - - - -all: clean versioning $(PROGS) - -boot: $(OBJS) - -versioning: - @echo `tput setaf 6; ./updateGitVersion.sh; tput sgr0;` - -$(PROGS): $(OBJS) -# echo $(OBJS) - mkdir -p $(DESTDIR) - $(CC) -o $@ $^ $(CFLAGS) $(LDLIBS) - mv $(PROGS) $(DESTDIR) - rm *.gdb - -clean: - rm -rf $(DESTDIR)/$(PROGS) *.o - diff --git a/slsDetectorServers/mythen3DetectorServer/Makefile.virtual b/slsDetectorServers/mythen3DetectorServer/Makefile.virtual deleted file mode 100644 index de7284bcc..000000000 --- a/slsDetectorServers/mythen3DetectorServer/Makefile.virtual +++ /dev/null @@ -1,25 +0,0 @@ -CC = gcc -CFLAGS += -Wall -DVIRTUAL -DMYTHEN3D -DSLS_DETECTOR_FUNCTION_LIST -DDACS_INT -DSTOP_SERVER #-DVERBOSEI #-DVERBOSE -LDLIBS += -lm -lstdc++ - -PROGS = virtualMythen3DetectorServer -DESTDIR ?= bin -INSTMODE = 0777 - -SRC_CLNT = communication_funcs.c slsDetectorServer.c slsDetectorServer_funcs.c slsDetectorFunctionList.c -OBJS = $(SRC_CLNT:.c=.o) - -all: clean $(PROGS) - -boot: $(OBJS) - -$(PROGS): $(OBJS) - echo $(OBJS) - mkdir -p $(DESTDIR) - $(CC) -o $@ $^ $(CFLAGS) $(LDLIBS) - mv $(PROGS) $(DESTDIR) - rm *.gdb - -clean: - rm -rf $(DESTDIR)/$(PROGS) *.o - diff --git a/slsDetectorServers/mythen3DetectorServer/RegisterDefs.h b/slsDetectorServers/mythen3DetectorServer/RegisterDefs.h deleted file mode 100644 index 1fa922d3b..000000000 --- a/slsDetectorServers/mythen3DetectorServer/RegisterDefs.h +++ /dev/null @@ -1,101 +0,0 @@ -#ifndef REGISTERS_G_H -#define REGISTERS_G_H - -/* Definitions for FPGA*/ - -/* FPGA Version register */ -#define FPGA_VERSION_REG (0x00 << 11) - -#define BOARD_REVISION_OFST (0) -#define BOARD_REVISION_MSK (0x00FFFFFF << BOARD_REVISION_OFST) -#define DETECTOR_TYPE_OFST (24) -#define DETECTOR_TYPE_MSK (0x000000FF << DETECTOR_TYPE_OFST) - -/* Fix pattern register */ -#define FIX_PATT_REG (0x01 << 11) - - -/* Timer 64 bit Regiser */ -#define SET_DELAY_LSB_REG (0x60 << 11) //96<<11 //0x68<<11 -#define SET_DELAY_MSB_REG (0x61 << 11) //97<<11 //0x69<<11 -#define SET_CYCLES_LSB_REG (0x62 << 11) //98<<11//0x6c<<11 -#define SET_CYCLES_MSB_REG (0x63 << 11) //99<<11//0x6d<<11 -#define SET_FRAMES_LSB_REG (0x64 << 11) //(100<<11)/** to hex */ -#define SET_FRAMES_MSB_REG (0x65 << 11) //101<<11//0x71<<11 -#define SET_PERIOD_LSB_REG (0x66 << 11) //102<<11//0x74<<11 -#define SET_PERIOD_MSB_REG (0x67 << 11) //103<<11//0x75<<11 -#define SET_GATES_LSB_REG (0x6A << 11) /*check in firmware*///106<<11//0x7c<<11 -#define SET_GATES_MSB_REG (0x6B << 11) //107<<11//0x7d<<11 -#define SET_EXPTIME_LSB_REG (0x72 << 11) /** check in firmware *///114<<11//0x78<<11 -#define SET_EXPTIME_MSB_REG (0x73 << 11) //115<<11//0x79<<11 - -#define GET_ACTUAL_TIME_LSB_REG (0x10 << 11) //16<<11 -#define GET_ACTUAL_TIME_MSB_REG (0x11 << 11) //17<<11 -#define GET_DELAY_LSB_REG (0x12 << 11) //18<<11//0x6a<<11 -#define GET_DELAY_MSB_REG (0x13 << 11) //19<<11//0x6b<<11 -#define GET_CYCLES_LSB_REG (0x14 << 11) //20<<11//0x6e<<11 -#define GET_CYCLES_MSB_REG (0x15 << 11) //21<<11//0x6f<<11 -#define GET_FRAMES_LSB_REG (0x16 << 11) //22<<11//0x72<<11 -#define GET_FRAMES_MSB_REG (0x17 << 11) //23<<11//0x73<<11 -#define GET_PERIOD_LSB_REG (0x18 << 11) //24<<11//0x76<<11 -#define GET_PERIOD_MSB_REG (0x19 << 11) //25<<11//0x77<<11 -#define GET_EXPTIME_LSB_REG (0x1A << 11) //26<<11//0x7a<<11 -#define GET_EXPTIME_MSB_REG (0x1B << 11) //27<<11//0x7b<<11 -#define GET_GATES_LSB_REG (0x1C << 11) //28<<11//0x7e<<11 -#define GET_GATES_MSB_REG (0x1D << 11) //29<<11//0x7f<<11 - -#define FRAMES_FROM_START_LSB_REG (0x22 << 11) //34<<11 -#define FRAMES_FROM_START_MSB_REG (0x23 << 11) //35<<11 -#define FRAMES_FROM_START_PG_LSB_REG (0x24 << 11) //36<<11 -#define FRAMES_FROM_START_PG_MSB_REG (0x25 << 11) //37<<11 -#define GET_MEASUREMENT_TIME_LSB_REG (0x26 << 11) //38<<11 -#define GET_MEASUREMENT_TIME_MSB_REG (0x27 << 11) //39<<11 - - -/* SPI (Serial Peripheral Interface) Register */ -#define SPI_REG (0x40 << 11) - -#define DAC_SERIAL_DIGITAL_OUT_OFST (0) -#define DAC_SERIAL_DIGITAL_OUT_MSK (0x00000001 << DAC_SERIAL_DIGITAL_OUT_OFST) -#define DAC_SERIAL_CLK_OUT_OFST (1) -#define DAC_SERIAL_CLK_OUT_MSK (0x00000001 << DAC_SERIAL_CLK_OUT_OFST) -#define DAC_SERIAL_CS_OUT_OFST (2) -#define DAC_SERIAL_CS_OUT_MSK (0x00000001 << DAC_SERIAL_CS_OUT_OFST) -#define HV_SERIAL_DIGITAL_OUT_OFST (8) -#define HV_SERIAL_DIGITAL_OUT_MSK (0x00000001 << HV_SERIAL_DIGITAL_OUT_OFST) -#define HV_SERIAL_CLK_OUT_OFST (9) -#define HV_SERIAL_CLK_OUT_MSK (0x00000001 << HV_SERIAL_CLK_OUT_OFST) -#define HV_SERIAL_CS_OUT_OFST (10) -#define HV_SERIAL_CS_OUT_MSK (0x00000001 << HV_SERIAL_CS_OUT_OFST) - -/* Control Register */ -#define CONTROL_REG (0x4F << 11) //(79 << 11) /** to hex */ - - -/* Reconfiguratble PLL Control Regiser */ -#define PLL_CONTROL_REG (0x51 << 11) //(81 << 11)/** to hex */ - -//#define PLL_CTRL_RECONFIG_RST_OFST (0) //parameter reset -//#define PLL_CTRL_RECONFIG_RST_MSK (0x00000001 << PLL_CTRL_RECONFIG_RST_OFST) //parameter reset -//#define PLL_CTRL_WR_PARAMETER_OFST (2) -//#define PLL_CTRL_WR_PARAMETER_MSK (0x00000001 << PLL_CTRL_WR_PARAMETER_OFST) -#define PLL_CTRL_RST_OFST (3) -#define PLL_CTRL_RST_MSK (0x00000001 << PLL_CTRL_RST_OFST) -//#define PLL_CTRL_ADDR_OFST (16) -//#define PLL_CTRL_ADDR_MSK (0x0000003F << PLL_CTRL_ADDR_OFST) - -/* Samples Register */ -#define NSAMPLES_REG (0x5D << 11) //93<<11 - -/* Power On Register */ -#define POWER_ON_REG (0x5e<<11) - -#define POWER_ENABLE_OFST (16) - -/* Dac Registers */ -#define DAC_VAL_REG (0x79 << 11) //121<<11 -#define DAC_NUM_REG (0x80 << 11) //122<<11 -#define DAC_VAL_OUT_REG (0x2A << 11) //42<<11 - -#endif - diff --git a/slsDetectorServers/mythen3DetectorServer/ansi.h b/slsDetectorServers/mythen3DetectorServer/ansi.h deleted file mode 120000 index a122db0ad..000000000 --- a/slsDetectorServers/mythen3DetectorServer/ansi.h +++ /dev/null @@ -1 +0,0 @@ -../../slsReceiverSoftware/include/ansi.h \ No newline at end of file diff --git a/slsDetectorServers/mythen3DetectorServer/blackfin.h b/slsDetectorServers/mythen3DetectorServer/blackfin.h deleted file mode 120000 index 24f9c08f7..000000000 --- a/slsDetectorServers/mythen3DetectorServer/blackfin.h +++ /dev/null @@ -1 +0,0 @@ -/afs/psi.ch/project/mythen/marie_a/MythenServer/slsDetectorPackage/slsDetectorSoftware/slsDetectorServer/blackfin.h \ No newline at end of file diff --git a/slsDetectorServers/mythen3DetectorServer/commonServerFunctions.h b/slsDetectorServers/mythen3DetectorServer/commonServerFunctions.h deleted file mode 120000 index 33bdd8d53..000000000 --- a/slsDetectorServers/mythen3DetectorServer/commonServerFunctions.h +++ /dev/null @@ -1 +0,0 @@ -../slsDetectorServer/commonServerFunctions.h \ No newline at end of file diff --git a/slsDetectorServers/mythen3DetectorServer/communication_funcs.c b/slsDetectorServers/mythen3DetectorServer/communication_funcs.c deleted file mode 120000 index 87a4f95d1..000000000 --- a/slsDetectorServers/mythen3DetectorServer/communication_funcs.c +++ /dev/null @@ -1 +0,0 @@ -../commonFiles/communication_funcs.c \ No newline at end of file diff --git a/slsDetectorServers/mythen3DetectorServer/communication_funcs.h b/slsDetectorServers/mythen3DetectorServer/communication_funcs.h deleted file mode 120000 index f220903b2..000000000 --- a/slsDetectorServers/mythen3DetectorServer/communication_funcs.h +++ /dev/null @@ -1 +0,0 @@ -../commonFiles/communication_funcs.h \ No newline at end of file diff --git a/slsDetectorServers/mythen3DetectorServer/gitInfo.txt b/slsDetectorServers/mythen3DetectorServer/gitInfo.txt deleted file mode 100644 index 4df512cd8..000000000 --- a/slsDetectorServers/mythen3DetectorServer/gitInfo.txt +++ /dev/null @@ -1,9 +0,0 @@ -Path: slsDetectorsPackage/slsDetectorSoftware/jungfrauDetectorServer -URL: origin git@git.psi.ch:sls_detectors_software/slsDetectorPackage.git -Repository Root: origin git@git.psi.ch:sls_detectors_software/slsDetectorPackage.git -Repsitory UUID: 2f3dc8d109de8607f3217cf429619073dc9cc60e -Revision: 103 -Branch: developer -Last Changed Author: Dhanya_Maliakal -Last Changed Rev: 3397 -Last Changed Date: 2017-12-04 18:23:05.000000002 +0100 ./RegisterDefs.h diff --git a/slsDetectorServers/mythen3DetectorServer/gitInfoMythen3.h b/slsDetectorServers/mythen3DetectorServer/gitInfoMythen3.h deleted file mode 100644 index 1acd1f071..000000000 --- a/slsDetectorServers/mythen3DetectorServer/gitInfoMythen3.h +++ /dev/null @@ -1,6 +0,0 @@ -#define GITURL "git@git.psi.ch:sls_detectors_software/slsDetectorPackage.git" -#define GITREPUUID "2f3dc8d109de8607f3217cf429619073dc9cc60e" -#define GITAUTH "Dhanya_Maliakal" -#define GITREV 0x3397 -#define GITDATE 0x20171204 -#define GITBRANCH "developer" diff --git a/slsDetectorServers/mythen3DetectorServer/gitInfoMythen3Tmp.h b/slsDetectorServers/mythen3DetectorServer/gitInfoMythen3Tmp.h deleted file mode 100644 index dfd9bb246..000000000 --- a/slsDetectorServers/mythen3DetectorServer/gitInfoMythen3Tmp.h +++ /dev/null @@ -1,6 +0,0 @@ -#define GITURL "" -#define GITREPUUID "" -#define GITAUTH "" -#define GITREV "" -#define GITDATE "" -#define GITBRANCH "" diff --git a/slsDetectorServers/mythen3DetectorServer/mythen3Server b/slsDetectorServers/mythen3DetectorServer/mythen3Server deleted file mode 100755 index 2f0fcf0df..000000000 Binary files a/slsDetectorServers/mythen3DetectorServer/mythen3Server and /dev/null differ diff --git a/slsDetectorServers/mythen3DetectorServer/mythen3Server.gdb b/slsDetectorServers/mythen3DetectorServer/mythen3Server.gdb deleted file mode 100755 index 4d4b23a68..000000000 Binary files a/slsDetectorServers/mythen3DetectorServer/mythen3Server.gdb and /dev/null differ diff --git a/slsDetectorServers/mythen3DetectorServer/programfpga.h b/slsDetectorServers/mythen3DetectorServer/programfpga.h deleted file mode 120000 index 72c54d21d..000000000 --- a/slsDetectorServers/mythen3DetectorServer/programfpga.h +++ /dev/null @@ -1 +0,0 @@ -../slsDetectorServer/programfpga.h \ No newline at end of file diff --git a/slsDetectorServers/mythen3DetectorServer/slsDetectorFunctionList.c b/slsDetectorServers/mythen3DetectorServer/slsDetectorFunctionList.c deleted file mode 100644 index b31416c6a..000000000 --- a/slsDetectorServers/mythen3DetectorServer/slsDetectorFunctionList.c +++ /dev/null @@ -1,1304 +0,0 @@ -//#ifdef SLS_DETECTOR_FUNCTION_LIST - - -#include "slsDetectorFunctionList.h" -#include "gitInfoMythen3.h" - - -#include "AD9257.h" // include "commonServerFunctions.h", which in turn includes "blackfin.h" -#include "programfpga.h" -#include "RegisterDefs.h" - -/* global variables */ -sls_detector_module *detectorModules=NULL; -int *detectorChips=NULL; -int *detectorChans=NULL; -dacs_t *detectorDacs=NULL; -dacs_t *detectorAdcs=NULL; - -enum detectorSettings thisSettings; -enum masterFlags masterMode = NO_MASTER; -int32_t clkPhase[2] = {0, 0}; -int vlimit = -1; - - - -/* basic tests */ - -void checkFirmwareCompatibility(int flag) { - - defineGPIOpins(); - resetFPGA(); - if (mapCSP0() == FAIL) { - cprintf(BG_RED, "Dangerous to continue. Goodbye!\n"); - exit(EXIT_FAILURE); - } - - // does check only if flag is 0 (by default), set by command line - if ((!flag) && ((checkType() == FAIL) || (testFpga() == FAIL) || (testBus() == FAIL))) { - cprintf(BG_RED, "Dangerous to continue. Goodbye!\n"); - exit(EXIT_FAILURE); - } - - uint32_t ipadd = getDetectorIP(); - uint64_t macadd = getDetectorMAC(); - int64_t fwversion = getDetectorId(DETECTOR_FIRMWARE_VERSION); - int64_t swversion = getDetectorId(DETECTOR_SOFTWARE_VERSION); - //int64_t sw_fw_apiversion = getDetectorId(SOFTWARE_FIRMWARE_API_VERSION); - cprintf(BLUE,"\n\n" - "********************************************************\n" - "****************** Mythen3 Server *********************\n" - "********************************************************\n\n" - - "Detector IP Addr:\t\t 0x%x\n" - "Detector MAC Addr:\t\t 0x%llx\n" - - "Firmware Version:\t\t 0x%llx\n" - "Software Version:\t\t 0x%llx\n" - //"F/w-S/w API Version:\t\t 0x%llx\n" - //"Required Firmware Version:\t 0x%x\n" - "\n" - "********************************************************\n", - hversion, hsnumber, - ipadd, macadd, - fwversion, swversion - //, sw_fw_apiversion, REQUIRED_FIRMWARE_VERSION - ); - - -/* - * printf("Testing firmware capability... "); - //cant read versions - if(!fwversion || !sw_fw_apiversion){ - cprintf(RED,"FATAL ERROR: Cant read versions from FPGA. Please update firmware\n"); - cprintf(RED,"Exiting Server. Goodbye!\n\n"); - exit(-1); - } - - //check for API compatibility - old server - if(sw_fw_apiversion > REQUIRED_FIRMWARE_VERSION){ - cprintf(RED,"FATAL ERROR: This software version is incompatible.\n" - "Please update it to be compatible with this firmware\n\n"); - cprintf(RED,"Exiting Server. Goodbye!\n\n"); - exit(-1); - } - - //check for firmware compatibility - old firmware - if( REQUIRED_FIRMWARE_VERSION > fwversion){ - cprintf(RED,"FATAL ERROR: This firmware version is incompatible.\n" - "Please update it to v%d to be compatible with this server\n\n", REQUIRED_FIRMWARE_VERSION); - cprintf(RED,"Exiting Server. Goodbye!\n\n"); - exit(-1); - } -*/ -} - - -int checkType() { - volatile u_int32_t type = ((bus_r(FPGA_VERSION_REG) & DETECTOR_TYPE_MSK) >> DETECTOR_TYPE_OFST); - if (type != JUNGFRAUCTB){ - cprintf(BG_RED,"This is not a Mythen 3 Server (read %d, expected %d)\n",type, JUNGFRAUCTB); - return FAIL; - } - - return OK; -} - - - -u_int32_t testFpga(void) { - printf("\nTesting FPGA...\n"); - - //fixed pattern - int ret = OK; - volatile u_int32_t val = bus_r(FIX_PATT_REG); - if (val == FIX_PATT_VAL) { - printf("Fixed pattern: successful match 0x%08x\n",val); - } else { - cprintf(RED,"Fixed pattern does not match! Read 0x%08x, expected 0x%08x\n", val, FIX_PATT_VAL); - ret = FAIL; - } - return ret; -} - - -int testBus() { - printf("\nTesting Bus...\n"); - - int ret = OK; - u_int32_t addr = SET_DELAY_LSB_REG; - int times = 1000 * 1000; - int i = 0; - - for (i = 0; i < times; ++i) { - bus_w(addr, i * 100); - if (i * 100 != bus_r(SET_DELAY_LSB_REG)) { - cprintf(RED,"ERROR: Mismatch! Wrote 0x%x, read 0x%x\n", i * 100, bus_r(SET_DELAY_LSB_REG)); - ret = FAIL; - } - } - - if (ret == OK) - printf("Successfully tested bus %d times\n", times); - return ret; -} - - - - -int detectorTest( enum digitalTestMode arg){ - switch(arg){ - case DETECTOR_FIRMWARE_TEST: return testFpga(); - case DETECTOR_BUS_TEST: return testBus(); - default: - cprintf(RED,"Warning: Test not implemented for this detector %d\n", (int)arg); - break; - } - return OK; -} - - - - - -/* Ids */ - -int64_t getDetectorId(enum idMode arg){ - int64_t retval = -1; - - switch(arg){ - case DETECTOR_SERIAL_NUMBER: - retval = getDetectorMAC(); - break; - case DETECTOR_FIRMWARE_VERSION: - retval = getFirmwareVersion(); - break; - //case SOFTWARE_FIRMWARE_API_VERSION: - //return GetFirmwareSoftwareAPIVersion(); - case DETECTOR_SOFTWARE_VERSION: - retval= GITREV; - retval= (retval <<32) | GITDATE; - break; - default: - break; - } - - return retval; -} - -u_int64_t getFirmwareVersion() { - return ((bus_r(FPGA_VERSION_REG) & BOARD_REVISION_MSK) >> BOARD_REVISION_OFST); -} - - - -u_int64_t getDetectorMAC() { - char output[255],mac[255]=""; - u_int64_t res=0; - FILE* sysFile = popen("ifconfig eth0 | grep HWaddr | cut -d \" \" -f 11", "r"); - fgets(output, sizeof(output), sysFile); - pclose(sysFile); - //getting rid of ":" - char * pch; - pch = strtok (output,":"); - while (pch != NULL){ - strcat(mac,pch); - pch = strtok (NULL, ":"); - } - sscanf(mac,"%llx",&res); - return res; -} - -u_int32_t getDetectorIP(){ - char temp[50]=""; - u_int32_t res=0; - //execute and get address - char output[255]; - FILE* sysFile = popen("ifconfig | grep 'inet addr:'| grep -v '127.0.0.1' | cut -d: -f2", "r"); - fgets(output, sizeof(output), sysFile); - pclose(sysFile); - - //converting IPaddress to hex. - char* pcword = strtok (output,"."); - while (pcword != NULL) { - sprintf(output,"%02x",atoi(pcword)); - strcat(temp,output); - pcword = strtok (NULL, "."); - } - strcpy(output,temp); - sscanf(output, "%x", &res); - //printf("ip:%x\n",res); - - return res; -} - - - - - - - - -/* initialization */ - -void initControlServer(){ - clkPhase[0] = 0; clkPhase[1] = 0; - setupDetector(); - printf("\n"); -} - - - -void initStopServer() { - - usleep(CTRL_SRVR_INIT_TIME_US); - if (mapCSP0() == FAIL) { - cprintf(BG_RED, "Stop Server: Map Fail. Dangerous to continue. Goodbye!\n"); - exit(EXIT_FAILURE); - } -} - - - - - - -/* set up detector */ - -void allocateDetectorStructureMemory(){ - printf("This Server is for 1 Jungfrau module (500k)\n"); - - //Allocation of memory - if (detectorModules!=NULL) free(detectorModules); - if (detectorChans!=NULL) free(detectorChans); - if (detectorChips!=NULL) free(detectorChips); - if (detectorDacs!=NULL) free(detectorDacs); - if (detectorAdcs!=NULL) free(detectorAdcs); - detectorModules=malloc(sizeof(sls_detector_module)); - detectorChips=malloc(NCHIP*sizeof(int)); - detectorChans=malloc(NCHIP*NCHAN*sizeof(int)); - detectorDacs=malloc(NDAC*sizeof(dacs_t)); - detectorAdcs=malloc(NADC*sizeof(dacs_t)); -#ifdef VERBOSE - printf("modules from 0x%x to 0x%x\n",detectorModules, detectorModules+n); - printf("dacs from 0x%x to 0x%x\n",detectorDacs, detectorDacs+n*NDAC); - printf("adcs from 0x%x to 0x%x\n",detectorAdcs, detectorAdcs+n*NADC); -#endif - (detectorModules)->dacs=detectorDacs; - (detectorModules)->adcs=detectorAdcs; - (detectorModules)->ndac=NDAC; - (detectorModules)->nadc=NADC; - (detectorModules)->nchip=NCHIP; - (detectorModules)->nchan=NCHIP*NCHAN; - (detectorModules)->module=0; - (detectorModules)->gain=0; - (detectorModules)->offset=0; - (detectorModules)->reg=0; - thisSettings = UNINITIALIZED; - - // if trimval requested, should return -1 to acknowledge unknown - int ichan=0; - for (ichan=0; ichan<(detectorModules->nchan); ichan++) { - *((detectorModules->chanregs)+ichan) = -1; - } -} - - - -void setupDetector() { - - allocateDetectorStructureMemory(); - - resetPLL(); - resetCore(); - resetPeripheral(); - cleanFifos(); - - //initialize dac series - initDac(0); - initDac(8); - initDac(16); - - //set dacs - printf("Setting Default Dac values\n"); - { - int i = 0; - int retval[2]={-1,-1}; - const int defaultvals[NDAC] = DEFAULT_DAC_VALS; - for(i = 0; i < NDAC; ++i) { - setDAC((enum DACINDEX)i,defaultvals[i],0,0,retval); - if (retval[0] != defaultvals[i]) - cprintf(RED, "Warning: Setting dac %d failed, wrote %d, read %d\n",i ,defaultvals[i], retval[0]); - } - } - - /*setSamples(1); - bus_w(DAC_REG,0xffff); - setSpeed - cleanFifos(); /* todo might work without - resetCore(); /* todo might work without */ - - //Initialization of acquistion parameters - setTimer(FRAME_NUMBER, DEFAULT_NUM_FRAMES); - setTimer(CYCLES_NUMBER, DEFAULT_NUM_CYCLES); - setTimer(ACQUISITION_TIME, DEFAULT_EXPTIME); - setTimer(FRAME_PERIOD, DEFAULT_PERIOD); - setTimer(DELAY_AFTER_TRIGGER, DEFAULT_DELAY); -} - - - - - - - -/* firmware functions (resets) */ - -int powerChip (int on){ - - /* set all the required voltages */ - return 0; -} - - -void cleanFifos() { printf("\nClearing Acquisition Fifos - Not doing anything\n"); - /* printf("\nClearing Acquisition Fifos\n"); - bus_w(CONTROL_REG, bus_r(CONTROL_REG) | CONTROL_ACQ_FIFO_CLR_MSK); - bus_w(CONTROL_REG, bus_r(CONTROL_REG) & ~CONTROL_ACQ_FIFO_CLR_MSK);*/ -} - -void resetCore() {printf("\nResetting Core - Not doing anything\n"); - /*printf("\nResetting Core\n"); - bus_w(CONTROL_REG, bus_r(CONTROL_REG) | CONTROL_CORE_RST_MSK); - bus_w(CONTROL_REG, bus_r(CONTROL_REG) & ~CONTROL_CORE_RST_MSK);*/ -} - -void resetPeripheral() {printf("\nResetting Peripheral - Not doing anything\n"); - /* printf("\nResetting Peripheral\n"); - bus_w(CONTROL_REG, bus_r(CONTROL_REG) | CONTROL_PERIPHERAL_RST_MSK); - bus_w(CONTROL_REG, bus_r(CONTROL_REG) & ~CONTROL_PERIPHERAL_RST_MSK);*/ -} - -int getPhase(int i) { - if (i>=0 && i<4) - return clkPhase[i]; - else - return -1; -} - - -int configurePhase(int val, int i) { /** compare with old jungfrau software and add in */ - - u_int32_t l=0x0c; - u_int32_t h=0x0d; - u_int32_t vv; - int32_t phase=0, inv=0; - - u_int32_t tot; - u_int32_t odd=1;//0; - - if (i<0 || i>3) - return -1; - - if (val>65535 || val<-65535) - return clkPhase[i]; - - resetPLL(); - - setPllReconfigReg(PLL_MODE_REG, 1, 0); - printf("phase in %d\n",clkPhase[1]); - - if (val>0) { - inv=0; - phase=val&0xffff; - } else { - inv=0; - val=-1*val; - phase=(~val)&0xffff; - } - - - vv=phase | (i<<16);// | (inv<<21); - - setPllReconfigReg(PLL_PHASE_SHIFT_REG,vv,0); - - clkPhase[i]=val; - return clkPhase[i]; -} - - - -int configureFrequency(int val, enum CLKINDEX i) { /** compare with old jungfrau software and add in */ - - - u_int32_t l=0x0c; - u_int32_t h=0x0d; - u_int32_t vv; - int32_t phase=0, inv=0; - - u_int32_t tot; - u_int32_t odd=1;//0; - printf("Want to configure frequency of counter %d to %d\n",i,val); - // printf("PLL reconfig reset\N"); bus_w(PLL_CNTRL_REG,(1<3) { - printf("wrong counter number %d\n",i); - return -1; - } - - if (val<=0) { - - printf("get value %d %d \n",i,clkDivider[i]); - return clkDivider[i]; - } - if (i==adc_clk_c){ - if (val>40) - { - printf("Too high frequency %d MHz for these ADCs!\n", val); - return clkDivider[i]; - } - } - - tot= PLL_VCO_FREQ_MHZ/val; - l=tot/2; - h=l; - if (tot>2*l) { - h=l+1; - odd=1; - } - else - { - odd=0; - } - - printf("Counter %d: Low is %d, High is %d\n",i, l,h); - - - vv= (i<<18)| (odd<<17) | l | (h<<8); - - printf("Counter %d, val: %08x\n", i, vv); - setPllReconfigReg(PLL_C_COUNTER_REG, vv,0); - - - usleep(10000); - - resetPLL(); - - clkDivider[i]=PLL_VCO_FREQ_MHZ/(l+h); - - printf("Frequency of clock %d is %d\n", i, clkDivider[i]); - - return clkDivider[i]; -} - - - - - - - - -/* set parameters - nmod, dr, roi */ - -int setNMod(int nm, enum dimension dim){ - return NMOD; -} - - -int getNModBoard(enum dimension arg){ - return NMAXMOD; -} - - -int setDynamicRange(int dr){ - /* edit functionality */ - return 16; -} - - - - -/* parameters - readout */ - -int setSpeed(enum speedVariable arg, int val) { - int retval = -1; - - switch (arg) { - case DBIT_PHASE: - if (val==-1) - retval=getPhase(DBIT_CLK_C); - else - retval=configurePhase(val,DBIT_CLK_C); - break; - case DBIT_CLOCK: - retval=configureFrequency(val,DBIT_CLK_C); - if (configureFrequency(-1,SYNC_CLK_C)>retval){ - configureFrequency(retval,SYNC_CLK_C); - printf("--Configuring sync clk to %d MHz\n",val); - } else if (configureFrequency(-1,ADC_CLK_C)>retval && configureFrequency(-1,RUN_CLK_C)>retval) { - printf("++Configuring sync clk to %d MHz\n",val); - configureFrequency(retval,SYNC_CLK_C); - } - break; - default: - sprintf(mess,"Unknown speed parameter %d",arg); - break; - } - return retval; -} - - - - - - -/* parameters - timer */ - -int64_t setTimer(enum timerIndex ind, int64_t val) { - - int64_t retval = -1; - switch(ind){ - - case FRAME_NUMBER: - if(val >= 0) - printf("\nSetting #frames: %lld\n",(long long int)val); - retval = set64BitReg(val, SET_FRAMES_LSB_REG, SET_FRAMES_MSB_REG); - printf("Getting #frames: %lld\n",(long long int)retval); - break; - - case ACQUISITION_TIME: - if(val >= 0){ - printf("\nSetting exptime: %lldns\n", (long long int)val); - val *= (1E-3 * CLK_RUN); /* ?? */ - } - retval = set64BitReg(val, SET_EXPTIME_LSB_REG, SET_EXPTIME_MSB_REG) / (1E-3 * CLK_RUN); - printf("Getting exptime: %lldns\n", (long long int)retval); - break; - - case FRAME_PERIOD: - if(val >= 0){ - printf("\nSetting period to %lldns\n",(long long int)val); - val *= (1E-3 * CLK_SYNC); /* ?? */ - } - retval = set64BitReg(val, SET_PERIOD_LSB_REG, SET_PERIOD_MSB_REG )/ (1E-3 * CLK_SYNC); - printf("Getting period: %lldns\n", (long long int)retval); - break; - - case DELAY_AFTER_TRIGGER: - if(val >= 0){ - printf("\nSetting delay to %lldns\n", (long long int)val); - val *= (1E-3 * CLK_SYNC); /* ?? */ - } - retval = set64BitReg(val, SET_DELAY_LSB_REG, SET_DELAY_MSB_REG) / (1E-3 * CLK_SYNC); - printf("Getting delay: %lldns\n", (long long int)retval); - break; - - case CYCLES_NUMBER: - if(val >= 0) - printf("\nSetting #cycles to %lld\n", (long long int)val); - retval = set64BitReg(val, SET_CYCLES_LSB_REG, SET_CYCLES_MSB_REG); - printf("Getting #cycles: %lld\n", (long long int)retval); - break; - - case GATES_NUMBER: - if(val >= 0) - printf("\nSetting #gates to %lld\n", (long long int)val); - retval = set64BitReg(val, SET_GATES_LSB_REG, SET_GATES_MSB_REG); - printf("Getting #gates: %lld\n", (long long int)retval); - break; - - case PROBES_NUMBER: /* does not exist in firmware_funcs.c*/ - /*if(val >= 0) - printf("\nSetting #probes to %lld\n", (long long int)val); - retval = set64BitReg(val, SET_PROBES_LSB_REG, SET_PROBES_MSB_REG); - printf("Getting #probes: %lld\n", (long long int)retval); - */ - break; - - case SAMPLES_JCTB: - if(val >= 0) - printf("\nSetting #samples to %lld\n", (long long int)val); - retval = bus_w(NSAMPLES_REG, val); - printf("Getting #samples: %lld\n", (long long int)retval); - - break; - - default: - cprintf(RED,"Warning: Timer Index not implemented for this detector: %d\n", ind); - break; - } - - return retval; - -} - - - -int64_t getTimeLeft(enum timerIndex ind){ - int64_t retval = -1; - switch(ind){ - - case FRAME_NUMBER: - retval = get64BitReg(GET_FRAMES_LSB_REG, GET_FRAMES_MSB_REG); - printf("Getting number of frames left: %lld\n",(long long int)retval); - break; - - case FRAME_PERIOD: - retval = get64BitReg(GET_PERIOD_LSB_REG, GET_PERIOD_MSB_REG) / (1E-3 * CLK_SYNC); - printf("Getting period left: %lldns\n", (long long int)retval); - break; - - case DELAY_AFTER_TRIGGER: - retval = get64BitReg(GET_DELAY_LSB_REG, GET_DELAY_MSB_REG) / (1E-3 * CLK_SYNC); - printf("Getting delay left: %lldns\n", (long long int)retval); - break; - - /** acquisition time and period gives in time left in func.c, pls check with anna */ - - case CYCLES_NUMBER: - retval = get64BitReg(GET_CYCLES_LSB_REG, GET_CYCLES_MSB_REG); - printf("Getting number of cycles left: %lld\n", (long long int)retval); - break; - - case ACTUAL_TIME: - retval = get64BitReg(GET_ACTUAL_TIME_LSB_REG, GET_ACTUAL_TIME_MSB_REG) / (1E-9 * CLK_SYNC); - printf("Getting actual time (time from start): %lld\n", (long long int)retval); - break; - - case MEASUREMENT_TIME: - retval = get64BitReg(GET_MEASUREMENT_TIME_LSB_REG, GET_MEASUREMENT_TIME_MSB_REG) / (1E-9 * CLK_SYNC); - printf("Getting measurement time (timestamp/ start frame time): %lld\n", (long long int)retval); - break; - - case FRAMES_FROM_START: - retval = get64BitReg(FRAMES_FROM_START_LSB_REG, FRAMES_FROM_START_MSB_REG); - printf("Getting frames from start run control %lld\n", (long long int)retval); - break; - - case FRAMES_FROM_START_PG: /** ask anna, seems to be calling previous function (frames_from_start) */ - retval = get64BitReg(FRAMES_FROM_START_PG_LSB_REG, FRAMES_FROM_START_PG_MSB_REG); - printf("Getting frames from start run control %lld\n", (long long int)retval); - break; - - default: - cprintf(RED, "Warning: Remaining Timer index not implemented for this detector: %d\n", ind); - break; - } - - return retval; -} - - - - - - -/* parameters - channel, chip, module, settings */ - - -int setModule(sls_detector_module myMod){ - return thisSettings; -} - - -int getModule(sls_detector_module *myMod){ - return OK; -} - - - -enum detectorSettings setSettings(enum detectorSettings sett, int imod){ - return getSettings(); - -} - - -enum detectorSettings getSettings(){ - return thisSettings; -} - - - - - -/* parameters - dac, adc, hv */ - - - - - - -void initDac(int dacnum) { - printf("\nInitializing dac for %d to \n",dacnum); - - u_int32_t codata; - int csdx = dacnum / NDAC_PER_SET + DAC_SERIAL_CS_OUT_OFST; //,so can be DAC_SERIAL_CS_OUT_OFST or +1 - int dacchannel = 0xf; // all channels - int dacvalue = 0x6; // can be any random value (just writing to power up) - printf(" Write to Input Register\n" - " Chip select bit:%d\n" - " Dac Channel:0x%x\n" - " Dac Value:0x%x\n", - csdx, dacchannel, dacvalue); - - codata = LTC2620_DAC_CMD_WRITE + // command to write to input register - ((dacchannel << LTC2620_DAC_ADDR_OFST) & LTC2620_DAC_ADDR_MSK) + // all channels - ((dacvalue << LTC2620_DAC_DATA_OFST) & LTC2620_DAC_DATA_MSK); // any random value - serializeToSPI(SPI_REG, codata, (0x1 << csdx), LTC2620_DAC_NUMBITS, - DAC_SERIAL_CLK_OUT_MSK, DAC_SERIAL_DIGITAL_OUT_MSK, DAC_SERIAL_DIGITAL_OUT_OFST); -} - - - - - - - - - -int voltageToDac(int value){ - int vmin = 0; - int vmax = MAX_DACVOLTVAL; - int nsteps = MAX_DACVAL; - if ((value < vmin) || (value > vmax)) { - cprintf(RED,"Voltage value (to convert to dac value) is outside bounds: %d\n", value); - return -1; - } - return (int)(((value - vmin) / (vmax - vmin)) * (nsteps - 1) + 0.5); -} - -int dacToVoltage(unsigned int digital){ - int vmin = 0; - int vmax = MAX_DACVOLTVAL; - int nsteps = MAX_DACVAL; - int v = vmin + (vmax - vmin) * digital / (nsteps - 1); - if((v < 0) || (v > nsteps - 1)) { - cprintf(RED,"Voltage value (converted from dac value) is outside bounds: %d\n", v); - return -1; - } - return v; -} - -int powerToDac(int value, int chip) { - int nsteps = MAX_DACVAL; - int vchip = MAX_VCHIPVAL - (getDacRegister(V_CHIP)*1000)/(nsteps -1); - printf("Current V_Chip: %d mV\n",vchip); - - int vmax = vchip - MIN_VCHIP_OFSTVAL; - int vmin = MIN_VCHIP_VAL; - - // recalculating only for v_chip - if (chip) { - printf("vchip\n"); - vmax = MAX_VCHIPVAL; - vmin = MAX_VCHIPVAL - 1000; - } - else - printf("vpower\n"); - - int v = (int)(((vmax - value) * (nsteps - 1) / (vmax - vmin)) ); /***+0.5 removed is this correct? seems different from voltageToDac maybe get rid of 0.5*/ - - - if (v < 0) v = 0; - if (v > nsteps - 1) v = nsteps - 1; - if (value == -100) v = -100; - - return v; -} - -int dacToPower(int value, int chip) { - int retval1 = -1; - int nsteps = MAX_DACVAL; - int vchip = MAX_VCHIPVAL - (getDacRegister(V_CHIP)*1000)/(nsteps -1); - printf("Vchip id %d mV\n",vmax); - int vmax = vchip - MIN_VCHIP_OFSTVAL; - int vmin = MIN_VCHIP_VAL; - - // recalculating only for v_chip - if (chip) { - printf("vchip\n"); - vmax = MAX_VCHIPVAL; - vmin = MAX_VCHIPVAL - 1000; - } - else - printf("vpower\n"); - - retval1 = vmax - (value * (vmax - vmin)) / (nsteps - 1); - if (retval1 > vmax) retval1 = vmax; - if (retval1 < vmin) retval1 = vmin; - if (value < 0) retval1 = value; - return retval1; -} - - - -void setDAC(enum DACINDEX ind, int val, int imod, int mV, int retval[]){ - - int dacval = val; - - // dacs: if set and mv, convert to dac - if (ind < val > 0 && mV) { - val = voltageToDac(val); //gives -1 on error - } - - - if ( (val >= 0) || (val == -100)) { - - - u_int32_t ichip = 2 - ind / NDAC_PER_SET; - u_int32_t valw = 0; - int i; - - // start and chip select bar down ----------------- - SPIChipSelect (&valw, SPI_REG, (0x1 << csdx)); - - - // next dac -------------------------------------- - for (i = 0; i < ichip; ++i) { - printf("%d next DAC\n", i); - sendDataToSPI (&valw, SPI_REG, LTC2620_DAC_CMD_MSK, LTC2620_DAC_NUMBITS, - DAC_SERIAL_CLK_OUT_MSK, DAC_SERIAL_DIGITAL_OUT_MSK, DAC_SERIAL_DIGITAL_OUT_OFST); - } - - - // this dac ---------------------------------------- - u_int32_t codata; - int csdx = DAC_SERIAL_CS_OUT_OFST; - int dacchannel = ind % NDAC_PER_SET; - - printf("\nSetting of DAC %d : %d dac units (%d mV)\n",ind, dacval, val); - // command - if (val >= 0) { - printf(" Write to Input Register and Update\n"); - codata = LTC2620_DAC_CMD_SET; - - } else if (val == -100) { - printf(" POWER DOWN\n"); - codata = LTC2620_DAC_CMD_POWER_DOWN; - } - // address - printf(" Chip select bit:%d\n" - " Dac Channel:0x%x\n" - " Dac Value:0x%x\n", - csdx, dacchannel, val); - codata += ((dacchannel << LTC2620_DAC_ADDR_OFST) & LTC2620_DAC_ADDR_MSK) + - ((val << LTC2620_DAC_DATA_OFST) & LTC2620_DAC_DATA_MSK); - // to spi - serializeToSPI(SPI_REG, codata, (0x1 << csdx), LTC2620_DAC_NUMBITS, - DAC_SERIAL_CLK_OUT_MSK, DAC_SERIAL_DIGITAL_OUT_MSK, DAC_SERIAL_DIGITAL_OUT_OFST); - - - printf("--------done setting dac set %d \n",i); - - // next dac ----------------------------------------------------------- - for (i = ichip+1; i < (N_DAC / NDAC_PER_SET); ++i) { - printf("%d next DAC\n", i); - sendDataToSPI (&valw, SPI_REG, LTC2620_DAC_CMD_MSK, LTC2620_DAC_NUMBITS, - DAC_SERIAL_CLK_OUT_MSK, DAC_SERIAL_DIGITAL_OUT_MSK, DAC_SERIAL_DIGITAL_OUT_OFST); - } - - - //chip select bar up, clk down and stop -------------------------------- - SPIChipDeselect (&valw, SPI_REG, (0x1 << csdx), DAC_SERIAL_CLK_OUT_MSK); - - // writes to register - setDacRegister(ind, dacval); - } - - // reading dac value from register - printf("Getting DAC %d : ",ind); - retval[0] = getDacRegister(ind); printf("%d dac units ", retval[0]); - retval[1] = dacToVoltage(retval[0]);printf("(%d mV)\n", retval[1]); -} - - -int setPower(enum DACINDEX ind, int val) { - - // not implemented yet - if ((ind == V_D) || (ind == V_C)) - return -1; - - // vlimit software limit - else if (ind == V_LIMIT) { - if (val >= 0) - vlimit = val; - return vlimit; - } - - int pwrindex = -1; - int dacval = val; - int retval=-1, retval1=-1; - u_int32_t preg = 0; - int temp[2] = {-1,-1}; - - // get - if (val == -1) - dacval = -1; - - // vchip - else if (ind == V_CHIP) - dacval = powerToDac(val, 1); - - // power a, b, c , d, io - else { - dacval = powerToDac(val, 0); - - switch (ind) { - case V_IO: pwrindex = 0;break; - case V_A: pwrindex = 1; break; - case V_B: pwrindex = 2; break; - default:break; - } - - // shut down - preg = bus_r(POWER_ON_REG); - printf("power reg is %08x\n",bus_r(POWER_ON_REG)); - printf("Switching off power %d\n", ind); - bus_w(POWER_ON_REG,preg &(~(1 << (POWER_ENABLE_OFST + pwrindex)))); - setDac(ind,-100, 0, 1, temp); - printf("power reg is %08x\n",bus_r(POWER_ON_REG)); - retval=0; - } - - // actual setting - if (val != -100) { - printf("Setting power %d to %d mV (%d dac val)\n",ind, val, dacval); - retval = setDac(ind, dacval); - // setting power a, b, c, d, io - if (pwrindex >= 0 && dacval >= 0 ) { - preg = bus_r(POWER_ON_REG); - printf("power reg is %08x\n", bus_r(POWER_ON_REG)); - printf("Switching on power %d\n", pwrindex); - bus_w(POWER_ON_REG, preg | ((1 << (POWER_ENABLE_OFST + pwrindex)))); - printf("power reg is %08x\n",bus_r(POWER_ON_REG)); - } - } - - if (pwrindex >= 0) { - if (bus_r(POWER_ON_REG) & (1 << (POWER_ENABLE_OFST + pwrindex))) { - retval1 = dacToPower(retval, 0); - printf("Vdac id %d mV\n",retval1); - } else - retval1 = 0; - } else { - if (retval >= 0) { - retval1 = dacToPower(retval, 1); - /*printf("Vchip is %d mV\n",vmax); makes no sense.. should be printing retval1??? */ - } else - retval1=-1; - } - - return retval1; -} - -int getVLimit() { - return vlimit; -} - -void setDacRegister(int dacnum,int dacvalue) { - bus_w(DAC_NUM_REG, dacnum); - bus_w(DAC_VAL_REG, dacvalue); - bus_w(DAC_NUM_REG, dacnum | (1<<16));/** super strange writing dac num in weird ways */ - bus_w(DAC_NUM_REG, dacnum); - printf("Wrote dac register value %d address %d\n",bus_r(DAC_VAL_REG),bus_r(DAC_NUM_REG)) ; -} - -int getDacRegister(int dacnum) {/** super strange, reading out in some other register than written */ - bus_w(DAC_NUM_REG, dacnum); - printf("READ dac register value %d address %d\n",(int16_t)bus_r(DAC_VAL_OUT_REG),bus_r(DAC_NUM_REG)) ; - return (int16_t)bus_r(DAC_VAL_OUT_REG); -} - - - - - -/* parameters - timing, extsig */ - - -enum externalCommunicationMode setTiming( enum externalCommunicationMode arg){ - return AUTO_TIMING; -} - - - - -/* jungfrau specific - pll, flashing fpga */ - - - -void resetPLL() { - // reset PLL Reconfiguration and PLL - bus_w(PLL_CONTROL_REG, bus_r(PLL_CONTROL_REG) | PLL_CTRL_RECONFIG_RST_MSK | PLL_CTRL_RST_MSK); - usleep(100); - bus_w(PLL_CONTROL_REG, bus_r(PLL_CONTROL_REG) & ~PLL_CTRL_RECONFIG_RST_MSK & ~PLL_CTRL_RST_MSK); -} - - -u_int32_t setPllReconfigReg(u_int32_t reg, u_int32_t val) { - - // set parameter - bus_w(PLL_PARAM_REG, val); - - // set address - bus_w(PLL_CONTROL_REG, (reg << PLL_CTRL_ADDR_OFST) & PLL_CTRL_ADDR_MSK); - usleep(10*1000); - - //write parameter - bus_w(PLL_CONTROL_REG, bus_r(PLL_CONTROL_REG) | PLL_CTRL_WR_PARAMETER_MSK); - bus_w(PLL_CONTROL_REG, bus_r(PLL_CONTROL_REG) & ~PLL_CTRL_WR_PARAMETER_MSK); - usleep(10*1000); - - return val; -} - - - - -void configurePll() { - u_int32_t val; - int32_t phase=0, inv=0; - - printf(" phase in %d\n", clkPhase[1]); - if (clkPhase[1]>0) { - inv=0; - phase=clkPhase[1]; - } else { - inv=1; - phase=-1*clkPhase[1]; - } - printf(" phase out %d (0x%08x)\n", phase, phase); - - if (inv) { - val = ((phase << PLL_SHIFT_NUM_SHIFTS_OFST) & PLL_SHIFT_NUM_SHIFTS_MSK) + PLL_SHIFT_CNT_SLCT_C1_VAL + PLL_SHIFT_UP_DOWN_NEG_VAL; - printf(" phase word 0x%08x\n", val); - setPllReconfigReg(PLL_PHASE_SHIFT_REG, val); - } else { - val = ((phase << PLL_SHIFT_NUM_SHIFTS_OFST) & PLL_SHIFT_NUM_SHIFTS_MSK) + PLL_SHIFT_CNT_SLCT_C0_VAL + PLL_SHIFT_UP_DOWN_NEG_VAL; - printf(" phase word 0x%08x\n", val); - setPllReconfigReg(PLL_PHASE_SHIFT_REG, val); - - printf(" phase word 0x%08x\n", val); - val = ((phase << PLL_SHIFT_NUM_SHIFTS_OFST) & PLL_SHIFT_NUM_SHIFTS_MSK) + PLL_SHIFT_CNT_SLCT_C2_VAL; - setPllReconfigReg(PLL_PHASE_SHIFT_REG, val); - } - usleep(10000); -} - - - - -/* aquisition */ - -int startStateMachine(){ - printf("*******Starting State Machine*******\n"); - - cleanFifos(); - - //start state machine - bus_w(CONTROL_REG, bus_r(CONTROL_REG) | CONTROL_START_ACQ_MSK); - bus_w(CONTROL_REG, bus_r(CONTROL_REG) & ~CONTROL_START_ACQ_MSK); - - printf("Status Register: %08x\n",bus_r(STATUS_REG)); - return OK; -} - - -int stopStateMachine(){ - cprintf(BG_RED,"*******Stopping State Machine*******\n"); - - //stop state machine - bus_w(CONTROL_REG, bus_r(CONTROL_REG) | CONTROL_STOP_ACQ_MSK); - usleep(100); - bus_w(CONTROL_REG, bus_r(CONTROL_REG) & ~CONTROL_STOP_ACQ_MSK); - - printf("Status Register: %08x\n",bus_r(STATUS_REG)); - return OK; -} - - - - - -enum runStatus getRunStatus(){ -#ifdef VERBOSE - printf("Getting status\n"); -#endif - - enum runStatus s; - u_int32_t retval = bus_r(STATUS_REG); - printf("Status Register: %08x\n",retval); - - //running - if(((retval & RUN_BUSY_MSK) >> RUN_BUSY_OFST)) { - if ((retval & WAITING_FOR_TRIGGER_MSK) >> WAITING_FOR_TRIGGER_OFST) { - printf("-----------------------------------WAITING-----------------------------------\n"); - s=WAITING; - } - else{ - printf("-----------------------------------RUNNING-----------------------------------\n"); - s=RUNNING; - } - } - - //not running - else { - if ((retval & STOPPED_MSK) >> STOPPED_OFST) { - printf("-----------------------------------STOPPED--------------------------\n"); - s=STOPPED; - } else if ((retval & RUNMACHINE_BUSY_MSK) >> RUNMACHINE_BUSY_OFST) { - printf("-----------------------------------READ MACHINE BUSY--------------------------\n"); - s=TRANSMITTING; - } else if (!retval) { - printf("-----------------------------------IDLE--------------------------------------\n"); - s=IDLE; - } else { - printf("-----------------------------------Unknown status %08x--------------------------------------\n", retval); - s=ERROR; - } - } - - return s; -} - - - -void readFrame(int *ret, char *mess){ - - // wait for status to be done - while(runBusy()){ - usleep(500); - } - - // frames left to give status - int64_t retval = getTimeLeft(FRAME_NUMBER) + 1; - if ( retval > 0) { - *ret = (int)FAIL; - sprintf(mess,"no data and run stopped: %lld frames left\n",retval); - cprintf(RED,"%s\n",mess); - } else { - *ret = (int)FINISHED; - sprintf(mess,"acquisition successfully finished\n"); - printf("%s",mess); - } -} - - - -u_int32_t runBusy(void) { - u_int32_t s = ((bus_r(STATUS_REG) & RUN_BUSY_MSK) >> RUN_BUSY_OFST); -#ifdef VERBOSE - printf("Status Register: %08x\n", s); -#endif - return s; -} - - - - - - - - -/* common */ - -//jungfrau doesnt require chips and chans (save memory) -int copyModule(sls_detector_module *destMod, sls_detector_module *srcMod){ - - int idac, iadc; - int ret=OK; - -#ifdef VERBOSE - printf("Copying module %x to module %x\n",srcMod,destMod); -#endif - - if (srcMod->module>=0) { -#ifdef VERBOSE - printf("Copying module number %d to module number %d\n",srcMod->module,destMod->module); -#endif - destMod->module=srcMod->module; - } - if (srcMod->serialnumber>=0){ - - destMod->serialnumber=srcMod->serialnumber; - } - if ((srcMod->nchip)>(destMod->nchip)) { - printf("Number of chip of source is larger than number of chips of destination\n"); - return FAIL; - } - if ((srcMod->nchan)>(destMod->nchan)) { - printf("Number of channels of source is larger than number of channels of destination\n"); - return FAIL; - } - if ((srcMod->ndac)>(destMod->ndac)) { - printf("Number of dacs of source is larger than number of dacs of destination\n"); - return FAIL; - } - if ((srcMod->nadc)>(destMod->nadc)) { - printf("Number of dacs of source is larger than number of dacs of destination\n"); - return FAIL; - } - -#ifdef VERBOSE - printf("DACs: src %d, dest %d\n",srcMod->ndac,destMod->ndac); - printf("ADCs: src %d, dest %d\n",srcMod->nadc,destMod->nadc); - printf("Chips: src %d, dest %d\n",srcMod->nchip,destMod->nchip); - printf("Chans: src %d, dest %d\n",srcMod->nchan,destMod->nchan); - -#endif - destMod->ndac=srcMod->ndac; - destMod->nadc=srcMod->nadc; - destMod->nchip=srcMod->nchip; - destMod->nchan=srcMod->nchan; - if (srcMod->reg>=0) - destMod->reg=srcMod->reg; -#ifdef VERBOSE - printf("Copying register %x (%x)\n",destMod->reg,srcMod->reg ); -#endif - if (srcMod->gain>=0) - destMod->gain=srcMod->gain; - if (srcMod->offset>=0) - destMod->offset=srcMod->offset; - - for (idac=0; idac<(srcMod->ndac); idac++) { - if (*((srcMod->dacs)+idac)>=0) - *((destMod->dacs)+idac)=*((srcMod->dacs)+idac); - } - for (iadc=0; iadc<(srcMod->nadc); iadc++) { - if (*((srcMod->adcs)+iadc)>=0) - *((destMod->adcs)+iadc)=*((srcMod->adcs)+iadc); - } - return ret; -} - - -int calculateDataBytes(){ - return DATA_BYTES; -} - -int getTotalNumberOfChannels(){return ((int)getNumberOfChannelsPerModule() * (int)getTotalNumberOfModules());} -int getTotalNumberOfChips(){return ((int)getNumberOfChipsPerModule() * (int)getTotalNumberOfModules());} -int getTotalNumberOfModules(){return NMOD;} -int getNumberOfChannelsPerModule(){return ((int)getNumberOfChannelsPerChip() * (int)getTotalNumberOfChips());} -int getNumberOfChipsPerModule(){return NCHIP;} -int getNumberOfDACsPerModule(){return NDAC;} -int getNumberOfADCsPerModule(){return NADC;} -int getNumberOfChannelsPerChip(){return NCHAN;} - - - -/* sync */ - -enum masterFlags setMaster(enum masterFlags arg){ - return NO_MASTER; -} - -enum synchronizationMode setSynchronization(enum synchronizationMode arg){ - return NO_SYNCHRONIZATION; -} - - - - - - -//#endif diff --git a/slsDetectorServers/mythen3DetectorServer/slsDetectorFunctionList.h b/slsDetectorServers/mythen3DetectorServer/slsDetectorFunctionList.h deleted file mode 120000 index 345b8c029..000000000 --- a/slsDetectorServers/mythen3DetectorServer/slsDetectorFunctionList.h +++ /dev/null @@ -1 +0,0 @@ -../slsDetectorServer/slsDetectorFunctionList.h \ No newline at end of file diff --git a/slsDetectorServers/mythen3DetectorServer/slsDetectorServer.c b/slsDetectorServers/mythen3DetectorServer/slsDetectorServer.c deleted file mode 120000 index a7eb59acb..000000000 --- a/slsDetectorServers/mythen3DetectorServer/slsDetectorServer.c +++ /dev/null @@ -1 +0,0 @@ -../slsDetectorServer/slsDetectorServer.c \ No newline at end of file diff --git a/slsDetectorServers/mythen3DetectorServer/slsDetectorServer_defs.h b/slsDetectorServers/mythen3DetectorServer/slsDetectorServer_defs.h deleted file mode 100644 index e638f840e..000000000 --- a/slsDetectorServers/mythen3DetectorServer/slsDetectorServer_defs.h +++ /dev/null @@ -1,167 +0,0 @@ -/* - * mythen3Server_defs.h - * - * Created on: Jan 24, 2013 - * Author: l_maliakal_d, changed my Marie A. - */ - -#ifndef SLSDETECTORSERVER_DEFS_H_ -#define SLSDETECTORSERVER_DEFS_H_ - -#include "sls_detector_defs.h" -#include - -/** This is only an example file!!! */ - - - -#define GOODBYE (-200) -enum DACINDEX {vIpre, vIbias, Vrf, VrfSh, vIinSh, VdcSh, Vth2, VPL, Vth1, Vth3, Vtrim, casSh, cas, vIbiasSh, vIcin, VPH, NC, vIpreOut, V_D, V_CHIP, V_C, V_B, V_A, V_IO, V_LIM}; // Mythen 3.01 -enum PWRINDEX {PWR_IO, PWR_A, PWR_B, PWR_C, PWR_D, PWR_CHIP=-1, PWR_LIMIT=-1}; -enum CLKINDEX {RUN_CLK_C, ADC_CLK_C, SYNC_CLK_C, DBIT_CLK_C}; - -#define DEFAULT_DAC_VALS { 2150, /* vIpre */ \ - 1200, /* vIbias */ \ - 900, /* Vrf */ \ - 1050, /* VrfSh */ \ - 1400, /* vIinSh */ \ - 655, /* VdcSh */ \ - 850, /* Vth2 */ \ - 1400, /* VPL */ \ - 850, /* Vth1 */ \ - 850, /* Vth3 */ \ - 2294, /* Vtrim */ \ - 983, /* casSh */ \ - 1474, /* cas */ \ - 1200, /* vIbiasSh */ \ - 1600, /* vIcin */ \ - 1520, /* VPH */ \ - 0, /* NC */ \ - 1000 /* vIpreOut */ \ - 0 /* V_D */ \ - 0 /* V_CHIP */ \ - 0 /* V_C */ \ - 1335 /* V_B */ \ - 1335 /* V_A */ \ - 1350 /* V_IO */ \ - }; - -#define DEFAULT_DAC_NAMES { "vIpre", \ - "vIbias", \ - "Vrf", \ - "VrfSh", \ - "vIinSh", \ - "VdcSh", \ - "Vth2", \ - "VPL", \ - "Vth1", \ - "Vth3", \ - "Vtrim", \ - "casSh", \ - "cas", \ - "vIbiasSh", \ - "vIcin", \ - "VPH", \ - "NC", \ - "vIpreOut" \ - "v_d" \ - "v_chip" \ - "v_c" \ - "v_b" \ - "v_a" \ - "v_io" \ - }; - -/*Hardware Definitions */ -#define NMAXMOD (1) -#define NMOD (1) -#define NCHAN (32) -#define NCHIP (1) -#define NADC (0) -#define NDAC (24) -#define NDAC_PER_SET (8) - - -#define NPWR (5) -#define MAX_DACVOLTVAL (2500) //mV -#define MAX_DACVAL (4096) // dac val -#define MAX_VCHIPVAL (2700) //mV /** name ???? */ -#define MIN_VCHIP_OFSTVAL (200) //mV /** name ???? */ -#define MIN_VCHIP_VAL (600) //mV /** name ???? */ - - -/** Default Parameters */ -#define DEFAULT_NUM_FRAMES (1) -#define DEFAULT_NUM_CYCLES (1) -#define DEFAULT_EXPTIME (200*1000) //ns -#define DEFAULT_PERIOD (1*1000*1000) //ns -#define DEFAULT_DELAY (0) -#define DEFAULT_HIGH_VOLTAGE (0) -#define DEFAULT_TIMING_MODE (AUTO_TIMING) - - -/* Defines in the Firmware */ -#define FIX_PATT_VAL (0xACDC1980) - -/* LTC2620 DAC DEFINES */ -#define LTC2620_DAC_CMD_OFST (20) -#define LTC2620_DAC_CMD_MSK (0x0000000F << LTC2620_DAC_CMD_OFST) -#define LTC2620_DAC_ADDR_OFST (16) -#define LTC2620_DAC_ADDR_MSK (0x0000000F << LTC2620_DAC_ADDR_OFST) -#define LTC2620_DAC_DATA_OFST (4) -#define LTC2620_DAC_DATA_MSK (0x00000FFF << LTC2620_DAC_DATA_OFST) - -#define LTC2620_DAC_CMD_WRITE (0x00000000 << LTC2620_DAC_CMD_OFST) -#define LTC2620_DAC_CMD_SET (0x00000003 << LTC2620_DAC_CMD_OFST) -#define LTC2620_DAC_CMD_POWER_DOWN (0x00000004 << LTC2620_DAC_CMD_OFST) -#define LTC2620_DAC_NUMBITS (24) - -/** PLL Reconfiguration Registers */ -//https://www.altera.com/documentation/mcn1424769382940.html -#define PLL_MODE_REG (0x00) -#define PLL_STATUS_REG (0x01) -#define PLL_START_REG (0x02) -#define PLL_N_COUNTER_REG (0x03) -#define PLL_M_COUNTER_REG (0x04) -#define PLL_C_COUNTER_REG (0x05) -#define PLL_PHASE_SHIFT_REG (0x06) - -#define PLL_SHIFT_NUM_SHIFTS_OFST (0) -#define PLL_SHIFT_NUM_SHIFTS_MSK (0x0000FFFF << PLL_SHIFT_NUM_SHIFTS_OFST) - -#define PLL_SHIFT_CNT_SELECT_OFST (16) -#define PLL_SHIFT_CNT_SELECT_MSK (0x0000001F << PLL_SHIFT_CNT_SELECT_OFST) -#define PLL_SHIFT_CNT_SLCT_C0_VAL ((0x0 << PLL_SHIFT_CNT_SELECT_OFST) & PLL_SHIFT_CNT_SELECT_MSK) -#define PLL_SHIFT_CNT_SLCT_C1_VAL ((0x1 << PLL_SHIFT_CNT_SELECT_OFST) & PLL_SHIFT_CNT_SELECT_MSK) -#define PLL_SHIFT_CNT_SLCT_C2_VAL ((0x2 << PLL_SHIFT_CNT_SELECT_OFST) & PLL_SHIFT_CNT_SELECT_MSK) -#define PLL_SHIFT_CNT_SLCT_C3_VAL ((0x3 << PLL_SHIFT_CNT_SELECT_OFST) & PLL_SHIFT_CNT_SELECT_MSK) -#define PLL_SHIFT_CNT_SLCT_C4_VAL ((0x4 << PLL_SHIFT_CNT_SELECT_OFST) & PLL_SHIFT_CNT_SELECT_MSK) -#define PLL_SHIFT_CNT_SLCT_C5_VAL ((0x5 << PLL_SHIFT_CNT_SELECT_OFST) & PLL_SHIFT_CNT_SELECT_MSK) -#define PLL_SHIFT_CNT_SLCT_C6_VAL ((0x6 << PLL_SHIFT_CNT_SELECT_OFST) & PLL_SHIFT_CNT_SELECT_MSK) -#define PLL_SHIFT_CNT_SLCT_C7_VAL ((0x7 << PLL_SHIFT_CNT_SELECT_OFST) & PLL_SHIFT_CNT_SELECT_MSK) -#define PLL_SHIFT_CNT_SLCT_C8_VAL ((0x8 << PLL_SHIFT_CNT_SELECT_OFST) & PLL_SHIFT_CNT_SELECT_MSK) -#define PLL_SHIFT_CNT_SLCT_C9_VAL ((0x9 << PLL_SHIFT_CNT_SELECT_OFST) & PLL_SHIFT_CNT_SELECT_MSK) -#define PLL_SHIFT_CNT_SLCT_C10_VAL ((0x10 << PLL_SHIFT_CNT_SELECT_OFST) & PLL_SHIFT_CNT_SELECT_MSK) -#define PLL_SHIFT_CNT_SLCT_C11_VAL ((0x11 << PLL_SHIFT_CNT_SELECT_OFST) & PLL_SHIFT_CNT_SELECT_MSK) -#define PLL_SHIFT_CNT_SLCT_C12_VAL ((0x12 << PLL_SHIFT_CNT_SELECT_OFST) & PLL_SHIFT_CNT_SELECT_MSK) -#define PLL_SHIFT_CNT_SLCT_C13_VAL ((0x13 << PLL_SHIFT_CNT_SELECT_OFST) & PLL_SHIFT_CNT_SELECT_MSK) -#define PLL_SHIFT_CNT_SLCT_C14_VAL ((0x14 << PLL_SHIFT_CNT_SELECT_OFST) & PLL_SHIFT_CNT_SELECT_MSK) -#define PLL_SHIFT_CNT_SLCT_C15_VAL ((0x15 << PLL_SHIFT_CNT_SELECT_OFST) & PLL_SHIFT_CNT_SELECT_MSK) -#define PLL_SHIFT_CNT_SLCT_C16_VAL ((0x16 << PLL_SHIFT_CNT_SELECT_OFST) & PLL_SHIFT_CNT_SELECT_MSK) -#define PLL_SHIFT_CNT_SLCT_C17_VAL ((0x17 << PLL_SHIFT_CNT_SELECT_OFST) & PLL_SHIFT_CNT_SELECT_MSK) - -#define PLL_SHIFT_UP_DOWN_OFST (21) -#define PLL_SHIFT_UP_DOWN_MSK (0x00000001 << PLL_SHIFT_UP_DOWN_OFST) -#define PLL_SHIFT_UP_DOWN_NEG_VAL ((0x0 << PLL_SHIFT_UP_DOWN_OFST) & PLL_SHIFT_UP_DOWN_MSK) -#define PLL_SHIFT_UP_DOWN_POS_VAL ((0x1 << PLL_SHIFT_UP_DOWN_OFST) & PLL_SHIFT_UP_DOWN_MSK) - -#define PLL_K_COUNTER_REG (0x07) -#define PLL_BANDWIDTH_REG (0x08) -#define PLL_CHARGEPUMP_REG (0x09) -#define PLL_VCO_DIV_REG (0x1c) -#define PLL_MIF_REG (0x1f) - -#define PLL_VCO_FREQ_MHZ 400 - - -#endif /* SLSDETECTORSERVER_DEFS_H_ */ diff --git a/slsDetectorServers/mythen3DetectorServer/slsDetectorServer_funcs.c b/slsDetectorServers/mythen3DetectorServer/slsDetectorServer_funcs.c deleted file mode 120000 index a7532ccd4..000000000 --- a/slsDetectorServers/mythen3DetectorServer/slsDetectorServer_funcs.c +++ /dev/null @@ -1 +0,0 @@ -../slsDetectorServer/slsDetectorServer_funcs.c \ No newline at end of file diff --git a/slsDetectorServers/mythen3DetectorServer/slsDetectorServer_funcs.h b/slsDetectorServers/mythen3DetectorServer/slsDetectorServer_funcs.h deleted file mode 120000 index 7569daf47..000000000 --- a/slsDetectorServers/mythen3DetectorServer/slsDetectorServer_funcs.h +++ /dev/null @@ -1 +0,0 @@ -../slsDetectorServer/slsDetectorServer_funcs.h \ No newline at end of file diff --git a/slsDetectorServers/mythen3DetectorServer/sls_detector_defs.h b/slsDetectorServers/mythen3DetectorServer/sls_detector_defs.h deleted file mode 120000 index c5062e03f..000000000 --- a/slsDetectorServers/mythen3DetectorServer/sls_detector_defs.h +++ /dev/null @@ -1 +0,0 @@ -../commonFiles/sls_detector_defs.h \ No newline at end of file diff --git a/slsDetectorServers/mythen3DetectorServer/sls_detector_funcs.h b/slsDetectorServers/mythen3DetectorServer/sls_detector_funcs.h deleted file mode 120000 index 844b67129..000000000 --- a/slsDetectorServers/mythen3DetectorServer/sls_detector_funcs.h +++ /dev/null @@ -1 +0,0 @@ -../commonFiles/sls_detector_funcs.h \ No newline at end of file diff --git a/slsDetectorServers/mythen3DetectorServer/sls_receiver_defs.h b/slsDetectorServers/mythen3DetectorServer/sls_receiver_defs.h deleted file mode 120000 index 1de31caf5..000000000 --- a/slsDetectorServers/mythen3DetectorServer/sls_receiver_defs.h +++ /dev/null @@ -1 +0,0 @@ -../../slsReceiverSoftware/include/sls_receiver_defs.h \ No newline at end of file diff --git a/slsDetectorServers/mythen3DetectorServer/sls_receiver_funcs.h b/slsDetectorServers/mythen3DetectorServer/sls_receiver_funcs.h deleted file mode 120000 index c2ea4ded9..000000000 --- a/slsDetectorServers/mythen3DetectorServer/sls_receiver_funcs.h +++ /dev/null @@ -1 +0,0 @@ -../../slsReceiverSoftware/include/sls_receiver_funcs.h \ No newline at end of file diff --git a/slsDetectorServers/mythen3DetectorServer/updateGitVersion.sh b/slsDetectorServers/mythen3DetectorServer/updateGitVersion.sh deleted file mode 100755 index 0c25e7f1e..000000000 --- a/slsDetectorServers/mythen3DetectorServer/updateGitVersion.sh +++ /dev/null @@ -1,31 +0,0 @@ -SERVER=jungfrauDetectorServer -MAINDIR=slsDetectorsPackage -SPECDIR=slsDetectorSoftware/$SERVER -TMPFILE=gitInfoJungfrauTmp.h -INCLFILE=gitInfoJungfrau.h - - -#evaluate the variables -EVALFILE=../../evalVersionVariables.sh -source $EVALFILE - - -#get modified date -#RDATE1='git log --pretty=format:"%ci" -1' -RDATE1="find ../slsDetectorServer . -type f -exec stat --format '%Y :%y %n' '{}' \; | sort -nr | cut -d: -f2- | egrep -v 'gitInfo|bin|.git|updateGitVersion|.o' | head -n 1" -RDATE=`eval $RDATE1` -NEWDATE=$(sed "s/-//g" <<< $RDATE | awk '{print $1;}') -NEWDATE=${NEWDATE/#/0x} - - -#get old date from INCLFILE -OLDDATE=$(more $INCLFILE | grep '#define GITDATE' | awk '{print $3}') - - -#update INCLFILE if changes -if [ "$OLDDATE" != "$NEWDATE" ]; then - echo Path: ${MAINDIR}/${SPECDIR} $'\n'URL: ${GITREPO} $'\n'Repository Root: ${GITREPO} $'\n'Repsitory UUID: ${REPUID} $'\n'Revision: ${FOLDERREV} $'\n'Branch: ${BRANCH} $'\n'Last Changed Author: ${AUTH1}_${AUTH2} $'\n'Last Changed Rev: ${REV} $'\n'Last Changed Date: ${RDATE} > gitInfo.txt - cd ../../ - ./genVersionHeader.sh $SPECDIR/gitInfo.txt $SPECDIR/$TMPFILE $SPECDIR/$INCLFILE - cd $WD -fi \ No newline at end of file diff --git a/slsDetectorServers/slsDetectorServer/communication_funcs.c b/slsDetectorServers/slsDetectorServer/communication_funcs.c index a6ece1276..a82f9bd82 100755 --- a/slsDetectorServers/slsDetectorServer/communication_funcs.c +++ b/slsDetectorServers/slsDetectorServer/communication_funcs.c @@ -95,7 +95,7 @@ int bindSocket(unsigned short int port_number) { // success myport = port_number; ret = OK; - FILE_LOG(logINFO, (" %s socket bound: isock=%d port=%d fd=%d\n", + FILE_LOG(logDEBUG5, ("%s socket bound: isock=%d, port=%d, fd=%d\n", (isControlServer ? "Control":"Stop"), isock, port_number, socketDescriptor)); } @@ -356,25 +356,34 @@ int sendModule(int file_des, sls_detector_module *myMod) { int sendModuleGeneral(int file_des, sls_detector_module *myMod, int sendAll) { - int ts = 0; + int ts = 0, n = 0; int nChips = myMod->nchip; int nChans = myMod->nchan; int nAdcs = myMod->nadc; int nDacs = myMod->ndac; // send module structure - ts += sendData(file_des,&(myMod->serialnumber),sizeof(myMod->serialnumber),INT32); - ts += sendData(file_des,&(myMod->nchan),sizeof(myMod->nchan),INT32); - ts += sendData(file_des,&(myMod->nchip),sizeof(myMod->nchip),INT32); - ts += sendData(file_des,&(myMod->ndac),sizeof(myMod->ndac),INT32); - ts += sendData(file_des,&(myMod->nadc),sizeof(myMod->nadc),INT32); - ts += sendData(file_des,&(myMod->reg),sizeof(myMod->reg),INT32); - ts += sendData(file_des,&(myMod->gain), sizeof(myMod->gain),OTHER); - ts += sendData(file_des,&(myMod->offset), sizeof(myMod->offset),OTHER); + n = sendData(file_des,&(myMod->serialnumber),sizeof(myMod->serialnumber),INT32); + if (!n) return -1; ts += n; + n = sendData(file_des,&(myMod->nchan),sizeof(myMod->nchan),INT32); + if (!n) return -1; ts += n; + n = sendData(file_des,&(myMod->nchip),sizeof(myMod->nchip),INT32); + if (!n) return -1; ts += n; + n = sendData(file_des,&(myMod->ndac),sizeof(myMod->ndac),INT32); + if (!n) return -1; ts += n; + n = sendData(file_des,&(myMod->nadc),sizeof(myMod->nadc),INT32); + if (!n) return -1; ts += n; + n = sendData(file_des,&(myMod->reg),sizeof(myMod->reg),INT32); + if (!n) return -1; ts += n; + n = sendData(file_des,&(myMod->gain), sizeof(myMod->gain),OTHER); + if (!n) return -1; ts += n; + n = sendData(file_des,&(myMod->offset), sizeof(myMod->offset),OTHER); + if (!n) return -1; ts += n; FILE_LOG(logDEBUG5, ("module of size %d sent\n",ts)); // send dac - ts += sendData(file_des,myMod->dacs,sizeof(int)*nDacs,INT32); + n = sendData(file_des,myMod->dacs,sizeof(int)*nDacs,INT32); + if (!n) return -1; ts += n; FILE_LOG(logDEBUG5, ("dacs of size %d sent\n",ts)); { int idac; @@ -383,18 +392,21 @@ int sendModuleGeneral(int file_des, sls_detector_module *myMod, int sendAll) { } // send adc - ts += sendData(file_des,myMod->adcs,sizeof(int)*nAdcs,INT32); + n = sendData(file_des,myMod->adcs,sizeof(int)*nAdcs,INT32); + if (!n) return -1; ts += n; FILE_LOG(logDEBUG5, ("adcs of size %d sent\n", ts)); // some detectors dont require sending all trimbits etc. if(sendAll) { // chips - ts += sendData(file_des,myMod->chipregs,sizeof(int)*nChips,INT32); + n = sendData(file_des,myMod->chipregs,sizeof(int)*nChips,INT32); + if (!n) return -1; ts += n; FILE_LOG(logDEBUG5, ("chips of size %d sent\n", ts)); // channels - ts += sendData(file_des,myMod->chanregs,sizeof(int)*nChans,INT32); + n = sendData(file_des,myMod->chanregs,sizeof(int)*nChans,INT32); FILE_LOG(logDEBUG5, ("chans of size %d sent - %d\n", ts, myMod->nchan)); + if (!n) return -1; ts += n; } FILE_LOG(logDEBUG5, ("module of size %d sent register %x\n", ts, myMod->reg)); @@ -408,7 +420,7 @@ int receiveModule(int file_des, sls_detector_module* myMod) { } int receiveModuleGeneral(int file_des, sls_detector_module* myMod, int receiveAll) { - int ts = 0; + int ts = 0, n = 0; int *dacptr = myMod->dacs; int *adcptr = myMod->adcs; int *chipptr = myMod->chipregs, *chanptr = myMod->chanregs; @@ -416,14 +428,22 @@ int receiveModuleGeneral(int file_des, sls_detector_module* myMod, int receiveA int nChans, nchanold = myMod->nchan, nchandiff; int nDacs, ndold = myMod->ndac, ndacdiff; int nAdcs, naold = myMod->nadc, nadcdiff; - ts += receiveData(file_des,&(myMod->serialnumber),sizeof(myMod->serialnumber),INT32); - ts += receiveData(file_des,&(myMod->nchan),sizeof(myMod->nchan),INT32); - ts += receiveData(file_des,&(myMod->nchip),sizeof(myMod->nchip),INT32); - ts += receiveData(file_des,&(myMod->ndac),sizeof(myMod->ndac),INT32); - ts += receiveData(file_des,&(myMod->nadc),sizeof(myMod->nadc),INT32); - ts += receiveData(file_des,&(myMod->reg),sizeof(myMod->reg),INT32); - ts += receiveData(file_des,&(myMod->gain), sizeof(myMod->gain),OTHER); - ts += receiveData(file_des,&(myMod->offset), sizeof(myMod->offset),OTHER); + n = receiveData(file_des,&(myMod->serialnumber),sizeof(myMod->serialnumber),INT32); + if (!n) return -1; ts += n; + n = receiveData(file_des,&(myMod->nchan),sizeof(myMod->nchan),INT32); + if (!n) return -1; ts += n; + n = receiveData(file_des,&(myMod->nchip),sizeof(myMod->nchip),INT32); + if (!n) return -1; ts += n; + n = receiveData(file_des,&(myMod->ndac),sizeof(myMod->ndac),INT32); + if (!n) return -1; ts += n; + n = receiveData(file_des,&(myMod->nadc),sizeof(myMod->nadc),INT32); + if (!n) return -1; ts += n; + n = receiveData(file_des,&(myMod->reg),sizeof(myMod->reg),INT32); + if (!n) return -1; ts += n; + n = receiveData(file_des,&(myMod->gain), sizeof(myMod->gain),OTHER); + if (!n) return -1; ts += n; + n = receiveData(file_des,&(myMod->offset), sizeof(myMod->offset),OTHER); + if (!n) return -1; ts += n; myMod->dacs = dacptr; myMod->adcs = adcptr; @@ -473,7 +493,8 @@ int receiveModuleGeneral(int file_des, sls_detector_module* myMod, int receiveA else FILE_LOG(logDEBUG5, ("received %d adcs\n",nAdcs)); if (ndacdiff <= 0) { - ts += receiveData(file_des,myMod->dacs, sizeof(int)*nDacs,INT32); + n = receiveData(file_des,myMod->dacs, sizeof(int)*nDacs,INT32); + if (!n) return -1; ts += n; FILE_LOG(logDEBUG5, ("dacs received\n")); int id; for (id = 0; idndac = ndold; - ts += receiveData(file_des,myMod->dacs, sizeof(int)*ndold,INT32); - ts += receiveData(file_des,dacptr, sizeof(int)*ndacdiff,INT32); + n = receiveData(file_des,myMod->dacs, sizeof(int)*ndold,INT32); + if (!n) return -1; ts += n; + n = receiveData(file_des,dacptr, sizeof(int)*ndacdiff,INT32); + if (!n) return -1; ts += n; free(dacptr); return FAIL; } if (nadcdiff <= 0) { - ts += receiveData(file_des,myMod->adcs, sizeof(int)*nAdcs,INT32); + n = receiveData(file_des,myMod->adcs, sizeof(int)*nAdcs,INT32); + if (!n) return -1; ts += n; FILE_LOG(logDEBUG5, ("adcs received\n")); } else { adcptr = (int*)malloc(nadcdiff*sizeof(int)); myMod->nadc = naold; - ts += receiveData(file_des,myMod->adcs, sizeof(int)*naold,INT32); - ts += receiveData(file_des,adcptr, sizeof(int)*nadcdiff,INT32); + n = receiveData(file_des,myMod->adcs, sizeof(int)*naold,INT32); + if (!n) return -1; ts += n; + n = receiveData(file_des,adcptr, sizeof(int)*nadcdiff,INT32); + if (!n) return -1; ts += n; free(adcptr); return FAIL; } @@ -504,25 +530,31 @@ int receiveModuleGeneral(int file_des, sls_detector_module* myMod, int receiveA if(receiveAll){ if (nchipdiff <= 0) { - ts += receiveData(file_des,myMod->chipregs, sizeof(int)*nChips,INT32); + n = receiveData(file_des,myMod->chipregs, sizeof(int)*nChips,INT32); + if (!n) return -1; ts += n; FILE_LOG(logDEBUG5, ("chips received\n")); } else { chipptr = (int*)malloc(nchipdiff*sizeof(int)); myMod->nchip = nchipold; - ts += receiveData(file_des,myMod->chipregs, sizeof(int)*nchipold,INT32); - ts += receiveData(file_des,chipptr, sizeof(int)*nchipdiff,INT32); + n = receiveData(file_des,myMod->chipregs, sizeof(int)*nchipold,INT32); + if (!n) return -1; ts += n; + n = receiveData(file_des,chipptr, sizeof(int)*nchipdiff,INT32); + if (!n) return -1; ts += n; free(chipptr); return FAIL; } if (nchandiff <= 0) { - ts += receiveData(file_des,myMod->chanregs, sizeof(int)*nChans,INT32); + n = receiveData(file_des,myMod->chanregs, sizeof(int)*nChans,INT32); + if (!n) return -1; ts += n; FILE_LOG(logDEBUG5, ("chans received\n")); } else { chanptr = (int*)malloc(nchandiff*sizeof(int)); myMod->nchan = nchanold; - ts += receiveData(file_des,myMod->chanregs, sizeof(int)*nchanold,INT32); - ts += receiveData(file_des,chanptr, sizeof(int)*nchandiff,INT32); + n = receiveData(file_des,myMod->chanregs, sizeof(int)*nchanold,INT32); + if (!n) return -1; ts += n; + n = receiveData(file_des,chanptr, sizeof(int)*nchandiff,INT32); + if (!n) return -1; ts += n; free(chanptr); return FAIL; } @@ -546,7 +578,7 @@ int Server_VerifyLock() { } -void Server_SendResult(int fileDes, intType itype, int update, void* retval, int retvalSize) { +int Server_SendResult(int fileDes, intType itype, int update, void* retval, int retvalSize) { // update if different clients (ret can be ok or acquisition finished), not fail to not overwrite e message if (update && ret != FAIL && differentClients) @@ -554,7 +586,7 @@ void Server_SendResult(int fileDes, intType itype, int update, void* retval, int // send success of operation int ret1 = ret; - sendData(fileDes, &ret1,sizeof(ret1), INT32);/* if < 0, return , socket crash*/ + sendData(fileDes, &ret1,sizeof(ret1), INT32); if(ret == FAIL) { // send error message if (strlen(mess)) @@ -567,4 +599,6 @@ void Server_SendResult(int fileDes, intType itype, int update, void* retval, int } // send return value sendData(fileDes, retval, retvalSize, itype); + + return ret; } diff --git a/slsDetectorServers/slsDetectorServer/communication_funcs.h b/slsDetectorServers/slsDetectorServer/communication_funcs.h index 6b2068e20..0089fc16e 100755 --- a/slsDetectorServers/slsDetectorServer/communication_funcs.h +++ b/slsDetectorServers/slsDetectorServer/communication_funcs.h @@ -64,7 +64,8 @@ int Server_VerifyLock(); * @param update 1 if one must update if different clients, else 0 * @param retval pointer to result * @param retvalSize size of result + * @returns result of operation */ -void Server_SendResult(int fileDes, intType itype, int update, void* retval, int retvalSize); +int Server_SendResult(int fileDes, intType itype, int update, void* retval, int retvalSize); #endif diff --git a/slsDetectorServers/slsDetectorServer/logger.h b/slsDetectorServers/slsDetectorServer/logger.h index c89aafd30..85d0661e4 100644 --- a/slsDetectorServers/slsDetectorServer/logger.h +++ b/slsDetectorServers/slsDetectorServer/logger.h @@ -20,7 +20,7 @@ #endif typedef enum { -logERROR, logWARNING, logINFO, logINFOBLUE, +logERROR, logWARNING, logINFO, logINFOBLUE, logGREEN, logDEBUG, logDEBUG1, logDEBUG2, logDEBUG3, logDEBUG4, logDEBUG5 }TLogLevel; @@ -35,6 +35,7 @@ static inline void FILELOG_PrintLog(TLogLevel level, char* m) { case logERROR: cprintf(RED BOLD, "ERROR: %s", m); break; case logWARNING: cprintf(YELLOW BOLD, "WARNING: %s", m); break; case logINFOBLUE: cprintf(BLUE, "INFO: %s", m); break; + case logGREEN: cprintf(GREEN, "INFO: %s", m); break; case logINFO: cprintf(RESET, "INFO: %s", m); break; case logDEBUG: cprintf(MAGENTA, "DEBUG: %s", m); break; case logDEBUG1: cprintf(MAGENTA, "DEBUG1: %s", m); break; diff --git a/slsDetectorServers/slsDetectorServer/slsDetectorFunctionList.h b/slsDetectorServers/slsDetectorServer/slsDetectorFunctionList.h index d100b85f8..05861f3e0 100644 --- a/slsDetectorServers/slsDetectorServer/slsDetectorFunctionList.h +++ b/slsDetectorServers/slsDetectorServer/slsDetectorFunctionList.h @@ -19,15 +19,12 @@ int getFirmwareCheckResult(char** mess); #endif void checkFirmwareCompatibility(); -#if defined(MYTHEN3D) || defined(JUNGFRAUD) +#ifdef JUNGFRAUD int checkType(); u_int32_t testFpga(void); int testBus(void); #endif -#ifdef MYTHEN3D -int moduleTest( enum digitalTestMode arg); -#endif #ifdef JUNGFRAUD int detectorTest( enum digitalTestMode arg); #endif @@ -40,7 +37,7 @@ u_int64_t getFirmwareAPIVersion(); u_int16_t getHardwareVersionNumber(); u_int16_t getHardwareSerialNumber(); #endif -#if !defined(MYTHEN3D) || !defined(EIGERD) +#ifdef EIGERD u_int32_t getDetectorNumber(); #endif u_int64_t getDetectorMAC(); @@ -73,17 +70,11 @@ uint32_t readRegister(uint32_t offset); // firmware functions (resets) -#if defined(MYTHEN3D) || defined(JUNGFRAUD) +#ifdef JUNGFRAUD int powerChip (int on); void cleanFifos(); void resetCore(); void resetPeripheral(); -#endif -#ifdef MYTHEN3D -int getPhase(int i); -int configurePhase(int val, enum CLKINDEX i); -int configureFrequency(int val, int i); -#elif JUNGFRAUD int autoCompDisable(int on); int adcPhase(int st); int getPhase(); @@ -97,7 +88,7 @@ int setROI(int n, ROI arg[], int *retvalsize, int *ret); #endif // parameters - readout -int setSpeed(enum speedVariable arg, int val); +enum speedVariable setSpeed(int val); #ifdef EIGERD enum readOutFlags setReadOutFlags(enum readOutFlags val); #endif @@ -129,35 +120,21 @@ int setThresholdEnergy(int ev); #endif // parameters - dac, adc, hv -#if defined(MYTHEN3D) || defined(JUNGFRAUD) +#ifdef JUNGFRAUD void serializeToSPI(u_int32_t addr, u_int32_t val, u_int32_t csmask, int numbitstosend, u_int32_t clkmask, u_int32_t digoutmask, int digofset); void initDac(int dacnum); int voltageToDac(int value); int dacToVoltage(unsigned int digital); #endif -#ifdef MYTHEN3D -int setPower(enum DACINDEX ind, int val); -int powerToDac(int value, int chip); -int dacToPower(int value, int chip); -#endif #ifdef JUNGFRAUD extern void setAdc(int addr, int val); // AD9257.h #endif void setDAC(enum DACINDEX ind, int val, int mV, int retval[]); -#ifdef MYTHEN3D -int getVLimit(); -void setDacRegister(int dacnum,int dacvalue); -int getDacRegister(int dacnum); -#endif -#ifndef MYTHEN3D int getADC(enum ADCINDEX ind); -#endif -#ifndef MYTHEN3D int setHighVoltage(int val); -#endif @@ -169,8 +146,10 @@ enum externalCommunicationMode getTiming(); #ifdef JUNGFRAUD long int calcChecksum(int sourceip, int destip); #endif -#ifndef MYTHEN3D +#ifdef GOTTHARDD int configureMAC(uint32_t destip, uint64_t destmac, uint64_t sourcemac, uint32_t sourceip, uint32_t udpport, uint32_t udpport2, int ival); +#else +int configureMAC(uint32_t destip, uint64_t destmac, uint64_t sourcemac, uint32_t sourceip, uint32_t udpport, uint32_t udpport2); #endif #if defined(JUNGFRAUD) || defined(EIGERD) int setDetectorPosition(int pos[]); @@ -187,7 +166,7 @@ int resetCounterBlock(int startACQ); int calibratePedestal(int frames); // jungfrau specific - pll, flashing firmware -#elif defined(JUNGFRAUD) || defined(MYTHEN3D) +#elif JUNGFRAUD void resetPLL(); u_int32_t setPllReconfigReg(u_int32_t reg, u_int32_t val); void configurePll(); diff --git a/slsDetectorServers/slsDetectorServer/slsDetectorServer.c b/slsDetectorServers/slsDetectorServer/slsDetectorServer.c index 9a4c56df3..ef85d11b5 100755 --- a/slsDetectorServers/slsDetectorServer/slsDetectorServer.c +++ b/slsDetectorServers/slsDetectorServer/slsDetectorServer.c @@ -33,6 +33,7 @@ int main(int argc, char *argv[]){ // subsequent read/write to socket gives error - must handle locally signal(SIGPIPE, SIG_IGN); + // circumvent the basic tests { int i; @@ -64,28 +65,20 @@ int main(int argc, char *argv[]){ #endif if (isControlServer) { portno = DEFAULT_PORTNO; - FILE_LOG(logINFOBLUE, - ("***************************************************\n" - "********* opening control server on port %d **********\n" - "********************************************************\n\n" - , portno)); + FILE_LOG(logINFO, ("Opening control server on port %d \n", portno)); #ifdef STOP_SERVER { int i; for (i = 0; i < argc; ++i) sprintf(cmd, "%s %s", cmd, argv[i]); sprintf(cmd,"%s -stopserver&", cmd); - FILE_LOG(logINFO, ("Command to start stop server:%s\n", cmd)); + FILE_LOG(logDEBUG5, ("Command to start stop server:%s\n", cmd)); system(cmd); } #endif } else { portno = DEFAULT_PORTNO + 1; - FILE_LOG(logINFOBLUE, - ("***************************************************\n" - "*********** opening stop server on port %d ***********\n" - "********************************************************\n\n" - , portno)); + FILE_LOG(logINFO,("Opening stop server on port %d \n", portno)); } init_detector(); @@ -100,7 +93,7 @@ int main(int argc, char *argv[]){ function_table(); if (isControlServer) { - FILE_LOG(logINFO, ("Control Server Ready...\n\n")); + FILE_LOG(logINFOBLUE, ("Control Server Ready...\n\n")); } else { FILE_LOG(logINFO, ("Stop Server Ready...\n\n")); } diff --git a/slsDetectorServers/slsDetectorServer/slsDetectorServer_funcs.c b/slsDetectorServers/slsDetectorServer/slsDetectorServer_funcs.c index 6e020da88..c202dceac 100755 --- a/slsDetectorServers/slsDetectorServer/slsDetectorServer_funcs.c +++ b/slsDetectorServers/slsDetectorServer/slsDetectorServer_funcs.c @@ -14,8 +14,6 @@ const enum detectorType myDetectorType=GOTTHARD; const enum detectorType myDetectorType=EIGER; #elif JUNGFRAUD const enum detectorType myDetectorType=JUNGFRAU; -#elif MYTHEN3D -const enum detectorType myDetectorType=MYTHEN3; #else const enum detectorType myDetectorType=GENERIC; #endif @@ -40,7 +38,7 @@ int dataBytes = 10; #ifdef EIGERD uint32_t dhcpipad = 0; #endif -#ifdef GOTTHARD +#ifdef GOTTHARDD int digitalTestBit = 0; #endif @@ -110,7 +108,7 @@ int decode_function(int file_des) { } else { FILE_LOG(logDEBUG5, (" calling function fnum=%d, (%s)\n", fnum, getFunctionName((enum detFuncs)fnum))); - ret=(*flist[fnum])(file_des); + ret = (*flist[fnum])(file_des); if (ret == FAIL) { FILE_LOG(logDEBUG5, ("Error executing the function = %d (%s)\n", @@ -271,24 +269,37 @@ void functionNotImplemented() { void modeNotImplemented(char* modename, int mode) { ret = FAIL; sprintf(mess, "%s (%d) is not implemented for this detector\n", modename, mode); - FILE_LOG(logWARNING,(mess)); + FILE_LOG(logERROR,(mess)); } void validate(int arg, int retval, char* modename, int hex) { if (ret == OK && arg != -1 && retval != arg) { ret = FAIL; if (hex) - sprintf(mess, "Could not set %s. Set 0x%x, but got 0x%x\n", + sprintf(mess, "Could not %s. Set 0x%x, but read 0x%x\n", modename, arg, retval); else - sprintf(mess, "Could not set %s. Set %d, but got %d\n", + sprintf(mess, "Could not %s. Set %d, but read %d\n", + modename, arg, retval); + FILE_LOG(logERROR,(mess)); + } +} + +void validate64(int64_t arg, int64_t retval, char* modename, int hex) { + if (ret == OK && arg != -1 && retval != arg) { + ret = FAIL; + if (hex) + sprintf(mess, "Could not %s. Set 0x%llx, but read 0x%llx\n", + modename, arg, retval); + else + sprintf(mess, "Could not %s. Set %lld, but read %lld\n", modename, arg, retval); FILE_LOG(logERROR,(mess)); } } -int M_nofunc(int file_des){ +int M_nofunc(int file_des) { ret = FAIL; memset(mess, 0, sizeof(mess)); @@ -299,14 +310,12 @@ int M_nofunc(int file_des){ strcpy(mess,"Unrecognized Function. Please do not proceed.\n"); FILE_LOG(logERROR, (mess)); - - Server_SendResult(file_des, OTHER, 0, NULL, 0); - return ret; + return Server_SendResult(file_des, OTHER, 0, NULL, 0); } // Jungfrau program mode -int M_nofuncMode(int file_des){ +int M_nofuncMode(int file_des) { ret = FAIL; memset(mess, 0, sizeof(mess)); @@ -320,9 +329,7 @@ int M_nofuncMode(int file_des){ "Restart detector server in normal mode (without any arguments) to continue.\n", getFunctionName((enum detFuncs)fnum)); FILE_LOG(logERROR, (mess)); - - Server_SendResult(file_des, OTHER, 0, NULL, 0); - return ret; + return Server_SendResult(file_des, OTHER, 0, NULL, 0); } @@ -336,7 +343,6 @@ int exec_command(int file_des) { if (receiveData(file_des, cmd, MAX_STR_LENGTH, OTHER) < 0) return printSocketReadError(); - FILE_LOG(logINFO, ("Executing command (%s)\n", cmd)); // set @@ -359,10 +365,7 @@ int exec_command(int file_des) { pclose(sysFile); FILE_LOG(logINFO, ("Result of cmd (%s):\n%s\n", cmd, retval)); } - - Server_SendResult(file_des, OTHER, 0, retval, sizeof(retval)); - - return ret; + return Server_SendResult(file_des, OTHER, 0, retval, sizeof(retval)); } @@ -372,10 +375,7 @@ int get_detector_type(int file_des) { ret = OK; enum detectorType retval = myDetectorType; FILE_LOG(logDEBUG5,("Returning detector type %d\n", retval)); - - Server_SendResult(file_des, INT32, 1, &retval, sizeof(retval)); - - return ret; + return Server_SendResult(file_des, INT32, 1, &retval, sizeof(retval)); } @@ -391,27 +391,24 @@ int set_external_signal_flag(int file_des) { if (receiveData(file_des, args, sizeof(args), INT32) < 0) return printSocketReadError(); + int signalindex = args[0]; + enum externalSignalFlag flag = args[1]; + FILE_LOG(logDEBUG5, ("Setting external signal %d to flag %d\n", signalindex, flag)); + #ifndef GOTTHARDD functionNotImplemented(); #else - int signalindex = args[0]; - enum externalSignalFlag flag = args[1]; - - FILE_LOG(logDEBUG5, ("Setting external signal %d to flag %d\n", signalindex, flag)); // set if ((flag != GET_EXTERNAL_SIGNAL_FLAG) && (Server_VerifyLock() != FAIL)) { setExtSignal(signalindex, flag); } // get retval = getExtSignal(signalindex); - validate((int)flag, (int)retval, "external signal flag", 1); + validate((int)flag, (int)retval, "set external signal flag", 1); FILE_LOG(logDEBUG5, ("External Signal Flag: %d\n", retval)); } #endif - - Server_SendResult(file_des, INT32, 1, &retval, sizeof(retval)); - - return ret; + return Server_SendResult(file_des, INT32, 1, &retval, sizeof(retval)); } @@ -425,7 +422,6 @@ int set_external_communication_mode(int file_des) { if (receiveData(file_des, &arg, sizeof(arg), INT32) < 0) return printSocketReadError(); - FILE_LOG(logDEBUG5, ("Setting external communication mode to %d\n", arg)); // set @@ -446,12 +442,9 @@ int set_external_communication_mode(int file_des) { } // get retval = getTiming(); - validate((int)arg, (int)retval, "timing mode", 0); + validate((int)arg, (int)retval, "set timing mode", 0); FILE_LOG(logDEBUG5, ("Timing Mode: %d\n",retval)); - - Server_SendResult(file_des, INT32, 1, &retval, sizeof(retval)); - - return ret; + return Server_SendResult(file_des, INT32, 1, &retval, sizeof(retval)); } @@ -465,7 +458,6 @@ int get_id(int file_des) { if (receiveData(file_des, &arg, sizeof(arg), INT32) < 0) return printSocketReadError(); - FILE_LOG(logDEBUG5, ("Getting Id %d\n", arg)); // get @@ -483,10 +475,7 @@ int get_id(int file_des) { modeNotImplemented("ID Index", (int)arg); break; } - - Server_SendResult(file_des, INT64, 1, &retval, sizeof(retval)); - - return ret; + return Server_SendResult(file_des, INT64, 1, &retval, sizeof(retval)); } @@ -501,19 +490,21 @@ int digital_test(int file_des) { if (receiveData(file_des, args, sizeof(args), INT32) < 0) return printSocketReadError(); + enum digitalTestMode mode = args[0]; +#ifdef GOTTHARDD + int ival = args[1]; + FILE_LOG(logDEBUG5, ("Digital test, mode = %d, ival:%d\n", mode, ival)); +#else + FILE_LOG(logDEBUG5, ("Digital test, mode = %d\n", mode)); +#endif #ifdef EIGERD functionNotImplemented(); #else - enum digitalTestMode mode = args[0]; - int ival = args[1]; - - FILE_LOG(logDEBUG5, ("Digital test, mode = %d\n", mode)); - - // set + // only set if (Server_VerifyLock() != FAIL) { switch (mode) { -#ifdef GOTTHARD: +#ifdef GOTTHARDD case DIGITAL_BIT_TEST: FILE_LOG(logDEBUG5, ("Setting digital test bit: %d\n", ival)); if (ival >= 0) @@ -532,10 +523,7 @@ int digital_test(int file_des) { } } #endif - - Server_SendResult(file_des, INT32, 1, &retval, sizeof(retval)); - - return ret; + return Server_SendResult(file_des, INT32, 1, &retval, sizeof(retval)); } @@ -551,7 +539,6 @@ int set_dac(int file_des) { if (receiveData(file_des, args, sizeof(args), INT32) < 0) return printSocketReadError(); - enum dacIndex ind = args[0]; int mV = args[1]; int val = args[2]; @@ -561,7 +548,7 @@ int set_dac(int file_des) { #ifdef JUNGFRAUD if ((ind != HV_NEW) && (ind >= NDAC_OLDBOARD)) { //for compatibility with old board modeNotImplemented("Dac Index", (int)ind); - }else + } else serverDacIndex = ind; #else switch (ind) { @@ -634,73 +621,6 @@ int set_dac(int file_des) { case HV_NEW: case IO_DELAY: break; -#elif MYTHEN3D - case M_vIpre: - serverDacIndex = vIpre; - break; - case M_vIbias: - serverDacIndex = vIbias; - break; - case PREAMP: - serverDacIndex = Vrf; - break; - case SHAPER1: - serverDacIndex = VrfSh; - break; - case M_vIinSh: - serverDacIndex = vIinSh; - break; - case M_VdcSh: - serverDacIndex = VdcSh; - break; - case M_Vth2: - serverDacIndex = Vth2; - break; - case M_VPL: - serverDacIndex = VPL; - break; - case THRESHOLD: - serverDacIndex = Vth1; - break; - case M_Vth3: - serverDacIndex = Vth3; - break; - case TRIMBIT_SIZE: - serverDacIndex = Vtrim; - break; - case M_casSh: - serverDacIndex = casSh; - break; - case M_cas: - serverDacIndex = cas; - break; - case M_vIbiasSh: - serverDacIndex = vIbiasSh; - break; - case M_vIcin: - serverDacIndex = vIcin; - break; - case CALIBRATION_PULSE: // !!! pulse height + 1400 DACu - serverDacIndex = VPH; - break; - case M_vIpreOut: - serverDacIndex = vIpreOut; - break; - case V_POWER_A: - serverDacIndex = V_A; - break; - case V_POWER_B: - serverDacIndex = V_B; - break; - case V_POWER_IO: - serverDacIndex = V_IO; - break; - case V_POWER_CHIP: - serverDacIndex = V_CHIP; - break; - case V_LIMIT: - serverDacIndex = V_LIM; - break; #endif default: modeNotImplemented("Dac Index", (int)ind); @@ -734,92 +654,27 @@ int set_dac(int file_des) { #ifdef EIGERD if ((retval[0] != SLAVE_HIGH_VOLTAGE_READ_VAL) && (retval[0] < 0)) { ret = FAIL; - if(retval[0] == -1) + if (retval[0] == -1) sprintf(mess, "Setting high voltage failed. Bad value %d. " "The range is from 0 to 200 V.\n",val); - else if(retval[0] == -2) + else if (retval[0] == -2) strcpy(mess, "Setting high voltage failed. " "Serial/i2c communication failed.\n"); - else if(retval[0] == -3) + else if (retval[0] == -3) strcpy(mess, "Getting high voltage failed. " "Serial/i2c communication failed.\n"); - FILE_LOG(logWARNING,(mess)); + FILE_LOG(logERROR,(mess)); } #endif break; - // power -#ifdef MYTHEN3D - case V_POWER_A: - case V_POWER_B: - case V_POWER_C: - case V_POWER_D: - case V_POWER_IO: - case V_POWER_CHIP: - case V_LIMIT: - FILE_LOG(logDEBUG5, ("Setting a power %d to %d\n",ind, val); - if (!mV) { - ret = FAIL; - strcpy(mess, "Power of index %d should be set in mV instead of DACu", - serverDacIndex); - FILE_LOG(logWARNING,(mess)); - val = -1; - } - - int lim = getVLimit(); - if (ind != V_LIMIT && lim != -1 && val > lim) { - ret = FAIL; - strcpy(mess, "Power of index %d is %d, should be less than %dmV\n", - serverDacIndex, val, lim); - FILE_LOG(logWARNING,(mess)); - val = -1; - } - - retval[1] = retval[0] = setPower(serverDacIndex,val); - validate(val, retval[1], "power", 0); - FILE_LOG(logDEBUG5, ("Power (%d): %d\n", serverDacIndex, retval[1])); - break; -#endif - // dacs default: -#ifdef MYTHEN3D - if( mV && val > MAX_DACVOLTVAL) { - ret = FAIL; - strcpy(mess, "Dac of index %d should be less than %dmV\n", - serverDacIndex, val, MAX_DACVOLTVAL); - FILE_LOG(logWARNING,(mess)); - val = -1; - } - else if( !mV && val >= MAX_DACVAL) { - ret = FAIL; - strcpy(mess, "Dac of index %d should be less than %d (dac value)\n", - serverDacIndex, val, MAX_DACVAL); - FILE_LOG(logWARNING,(mess)); - val = -1; - } - if (val >= 0) { - // conver to mV - int v = val; - if (!mV) - v = dacToVoltage(val); - - //checkvlimit compliant - int lim = getVLimit(); - if (lim!= -1 && v > lim) { - ret = FAIL; - strcpy(mess, "Dac of index %d should be less than %dmV (%d dac value)\n", - serverDacIndex, lim, voltageToDac(lim)); - FILE_LOG(logWARNING,(mess)); - val = -1; - } - } -#endif setDAC(serverDacIndex, val, mV, retval); #ifdef EIGERD - if(val != -1) { + if (val != -1) { //changing dac changes settings to undefined - switch(serverDacIndex){ + switch(serverDacIndex) { case VCMP_LL: case VCMP_LR: case VCMP_RL: @@ -827,7 +682,7 @@ int set_dac(int file_des) { case VRF: case VCP: setSettings(UNDEFINED); - FILE_LOG(logWARNING, ("Settings has been changed " + FILE_LOG(logERROR, ("Settings has been changed " "to undefined (changed specific dacs)\n")); break; default: @@ -838,7 +693,7 @@ int set_dac(int file_des) { //check if (ret == OK) { int temp = 0; - if(mV) + if (mV) temp = retval[1]; else temp = retval[0]; @@ -847,7 +702,7 @@ int set_dac(int file_des) { } else { ret = FAIL; sprintf(mess,"Setting dac %d : wrote %d but read %d\n", serverDacIndex, val, temp); - FILE_LOG(logWARNING,(mess)); + FILE_LOG(logERROR,(mess)); } } FILE_LOG(logDEBUG5, ("Dac (%d): %d dac units and %d mV\n", serverDacIndex, retval[0], retval[1])); @@ -855,10 +710,7 @@ int set_dac(int file_des) { } } } - - Server_SendResult(file_des, INT32, 1, retval, sizeof(retval)); - - return ret; + return Server_SendResult(file_des, INT32, 1, retval, sizeof(retval)); } @@ -874,14 +726,11 @@ int get_adc(int file_des) { if (receiveData(file_des, &ind, sizeof(ind), INT32) < 0) return printSocketReadError(); - -#ifdef MYTHEN3D - functionNotImplemented(); -#else enum ADCINDEX serverAdcIndex = 0; + // get switch (ind) { -#if defined(GOTTHARD) || defined(JUNGFRAUD) +#if defined(GOTTHARDD) || defined(JUNGFRAUD) case TEMPERATURE_FPGA: serverAdcIndex = TEMP_FPGA; break; @@ -925,11 +774,7 @@ int get_adc(int file_des) { retval = getADC(serverAdcIndex); FILE_LOG(logDEBUG5, ("ADC(%d): %d\n", retval)); } -#endif - - Server_SendResult(file_des, INT32, 1, &retval, sizeof(retval)); - - return ret; + return Server_SendResult(file_des, INT32, 1, &retval, sizeof(retval)); } @@ -937,42 +782,29 @@ int get_adc(int file_des) { int write_register(int file_des) { - int ret=OK,ret1=OK; - int n=0; - uint32_t retval=-1; - sprintf(mess,"write to register failed\n"); + ret = OK; + memset(mess, 0, sizeof(mess)); + int args[2] = {-1, -1}; + uint32_t retval = -1; - // receive arguments - int arg[2]={-1,-1}; - n = receiveData(file_des,arg,sizeof(arg),INT32); - if (n < 0) return printSocketReadError(); - int addr=arg[0]; - uint32_t val=arg[1]; + if (receiveData(file_des, args, sizeof(args), INT32) < 0) + return printSocketReadError(); + uint32_t addr = args[0]; + uint32_t val = args[1]; + FILE_LOG(logDEBUG5, ("Writing to register 0x%x, data 0x%x\n", addr, val)); - // execute action - if (differentClients && lockStatus) { - ret = FAIL; - sprintf(mess,"Detector locked by %s\n",lastClientIP); - cprintf(RED, "Warning: %s", mess); - } - else { -#ifdef VERBOSE - printf("writing to register 0x%x data 0x%x\n", addr, val); -#endif - retval=writeRegister(addr,val); - if (retval!=val) { + // only set + if (Server_VerifyLock() != FAIL) { + retval = writeRegister(addr, val); + // validate + if (retval != val) { ret = FAIL; - sprintf(mess,"Writing to register 0x%x failed: wrote 0x%x but read 0x%x\n", addr, val, retval); - cprintf(RED, "Warning: %s", mess); + sprintf(mess,"Could not write to register 0x%x. Wrote 0x%x but read 0x%x\n", addr, val, retval); + FILE_LOG(logERROR,(mess)); } + FILE_LOG(logDEBUG5, ("Write register (0x%x): 0x%x\n", retval)); } -#ifdef VERBOSE - printf("Data set to 0x%x\n", retval); -#endif - - Server_SendResult(file_des, INT32, 1, &retval, sizeof(retval)); - - return ret; + return Server_SendResult(file_des, INT32, 1, &retval, sizeof(retval)); } @@ -980,148 +812,139 @@ int write_register(int file_des) { int read_register(int file_des) { - int ret=OK,ret1=OK; - int n=0; - uint32_t retval=-1; - sprintf(mess,"read register failed\n"); + ret = OK; + memset(mess, 0, sizeof(mess)); + uint32_t addr = -1; + uint32_t retval = -1; - // receive arguments - int arg=0; - n = receiveData(file_des,&arg,sizeof(arg),INT32); - if (n < 0) return printSocketReadError(); - int addr=arg; + if (receiveData(file_des, &addr, sizeof(addr), INT32) < 0) + return printSocketReadError(); - // execute action -#ifdef VERBOSE - printf("reading register 0x%x\n", addr); -#endif - retval=readRegister(addr); -#ifdef VERBOSE - printf("Returned value 0x%x\n", retval); -#endif + FILE_LOG(logDEBUG5, ("Reading from register 0x%x\n", addr)); - Server_SendResult(file_des, INT32, 1, &retval, sizeof(retval)); + // get + retval = readRegister(addr); + FILE_LOG(logDEBUG5, ("Read register (0x%x): 0x%x\n", retval)); - return ret; + return Server_SendResult(file_des, INT32, 1, &retval, sizeof(retval)); } int set_module(int file_des) { - int ret=OK,ret1=OK; - int n=0; - sls_detector_module myModule; - int retval=-1; -#ifdef EIGERD - int myIODelay=-1; - int myTau=-1; - int myEV=-1; -#endif - sprintf(mess,"set module failed\n"); + ret = OK; + memset(mess, 0, sizeof(mess)); + int retval = -1; - -#ifdef MYTHEN3D - //to receive any arguments - while (n > 0) - n = receiveData(file_des,mess,MAX_STR_LENGTH,OTHER); - ret = FAIL; - sprintf(mess,"Function (Set Module) is not implemented for this detector\n"); - cprintf(RED, "Warning: %s", mess); -#else - - - int *myDac=NULL; - int *myAdc=NULL; + sls_detector_module module; + int *myDac = NULL; + int *myAdc = NULL; int *myChip = NULL; int *myChan = NULL; +#ifdef EIGERD + int ioDelay = -1; + int tau = -1; + int eV = -1; +#endif - myDac=(int*)malloc(getNumberOfDACs()*sizeof(int)); - if (getNumberOfDACs() > 0 && myDac == NULL) { - ret = FAIL; - sprintf(mess,"could not allocate dacs\n"); - cprintf(RED, "Warning: %s", mess); - } - else { - myModule.dacs=myDac; - myAdc=(int*)malloc(getNumberOfADCs()*sizeof(int)); + // allocate to receive arguments + // infinite loop to break out when FAIL or a final OK + while(1) { + // allocate dacs + myDac = (int*)malloc(getNumberOfDACs() * sizeof(int)); + // error + if (getNumberOfDACs() > 0 && myDac == NULL) { + ret = FAIL; + sprintf(mess, "Could not allocate dacs\n"); + FILE_LOG(logERROR,(mess)); + break; + } + module.dacs = myDac; + + // allocate adcs + myAdc = (int*)malloc(getNumberOfADCs() * sizeof(int)); + // error if (getNumberOfADCs() > 0 && myAdc == NULL) { ret = FAIL; - sprintf(mess,"could not allocate adcs\n"); - cprintf(RED, "Warning: %s", mess); + sprintf(mess,"Could not allocate adcs\n"); + FILE_LOG(logERROR,(mess)); + break; } - else { - myModule.adcs=myAdc; - //no chips and chans allocated for jungfrau, too much memory -#ifdef JUNGFRAUD - myModule.chipregs=NULL; - myModule.chanregs=NULL; -#else - myChip=(int*)malloc(getNumberOfChips()*sizeof(int)); - if (getNumberOfChips() > 0 && myChip == NULL) { - ret = FAIL; - sprintf(mess,"could not allocate chips\n"); - cprintf(RED, "Warning: %s", mess); - } - else { - myModule.chipregs=myChip; - myChan=(int*)malloc(getTotalNumberOfChannels()*sizeof(int)); - if (getTotalNumberOfChannels() > 0 && myChan == NULL) { - ret = FAIL; - sprintf(mess,"could not allocate chans\n"); - cprintf(RED, "Warning: %s", mess); - } - else { - myModule.chanregs=myChan; -#endif - myModule.nchip=getNumberOfChips(); - myModule.nchan=getTotalNumberOfChannels(); - myModule.ndac=getNumberOfDACs(); - myModule.nadc=getNumberOfADCs(); + module.adcs=myAdc; - - // receive arguments -#ifdef VERBOSE - printf("Setting module\n"); -#endif - n=receiveModuleGeneral(file_des, &myModule, + // no need to allocate chips and chans for jungfrau, too much memory #ifdef JUNGFRAUD - 0 //0 is to receive partially (without trimbits etc.) + module.chipregs = NULL; + module.chanregs = NULL; #else - 1 -#endif - ); - if (n<0) return FAIL; -#ifdef VERBOSE - printf("module number register is %d, nchan %d, nchip %d, ndac %d, nadc %d, gain %f, offset %f\n", - myModule.reg, myModule.nchan, myModule.nchip, myModule.ndac, myModule.nadc, myModule.gain,myModule.offset); + // allocate chips + myChip = (int*)malloc(getNumberOfChips() * sizeof(int)); + if (getNumberOfChips() > 0 && myChip == NULL) { + ret = FAIL; + sprintf(mess,"Could not allocate chips\n"); + FILE_LOG(logERROR,(mess)); + break; + } + module.chipregs = myChip; + + // allocate chans + myChan = (int*)malloc(getTotalNumberOfChannels() * sizeof(int)); + if (getTotalNumberOfChannels() > 0 && myChan == NULL) { + ret = FAIL; + sprintf(mess,"Could not allocate chans\n"); + FILE_LOG(logERROR,(mess)); + break; + } + module.chanregs=myChan; #endif + module.nchip = getNumberOfChips(); + module.nchan = getTotalNumberOfChannels(); + module.ndac = getNumberOfDACs(); + module.nadc = getNumberOfADCs(); + + // receive arguments (0 to partially receive module without trimbits + if (receiveModuleGeneral(file_des, &module, (myDetectorType == JUNGFRAU) ? 0 : 1) < 0) { + if (myChip != NULL) free(myChip); + if (myChan != NULL) free(myChan); + if (myDac != NULL) free(myDac); + if (myAdc != NULL) free(myAdc); + return printSocketReadError(); + } + FILE_LOG(logDEBUG5, ("module register is %d, nchan %d, nchip %d, " + "ndac %d, nadc %d, gain %f, offset %f\n", + module.reg, module.nchan, module.nchip, + module.ndac, module.nadc, module.gain,module.offset)); + #ifdef EIGERD - n = receiveData(file_des,&myIODelay,sizeof(myIODelay),INT32); - if (n<0) return FAIL; - n = receiveData(file_des,&myTau,sizeof(myTau),INT32); - if (n<0) return FAIL; - n = receiveData(file_des,&myEV,sizeof(myEV),INT32); - if (n<0) return FAIL; -#ifdef VERBOSE - printf("IO Delay:%d\n",myIODelay); - printf("Tau:%d\n",myTau); - printf("eV:%d\n",myEV); -#endif -#endif -#ifndef JUNGFRAUD - } + int args[3] = {-1, -1}; + if (receiveData(file_des, args, sizeof(args), INT32) < 0) { + if (myChip != NULL) free(myChip); + if (myChan != NULL) free(myChan); + if (myDac != NULL) free(myDac); + if (myAdc != NULL) free(myAdc); + return printSocketReadError(); } + ioDelay = args[0]; + tau = args[1]; + eV = args[2]; + FILE_LOG(logDEBUG5, ("ioDelay: %d, tau: d, ev:%d\n", ioDelay, tau, eV)); #endif - } } - //check settings index - if (ret==OK) { -#if defined(JUNGFRAUD) || defined(EIGERD) - switch(myModule.reg){ - case GET_SETTINGS: - case UNINITIALIZED: + + // receive all arguments + if (ret == FAIL) { + int n = 0; + while (n > 0) + n = receiveData(file_des, mess, MAX_STR_LENGTH, OTHER); + } + + + // only set + else if (Server_VerifyLock() != FAIL) { + // check index + switch (module.reg) { #ifdef EIGERD case STANDARD: case HIGHGAIN: @@ -1135,73 +958,68 @@ int set_module(int file_des) { case FIXGAIN2: case FORCESWITCHG1: case FORCESWITCHG2: +#elif GOTTHARDD + case DYNAMICGAIN: + case HIGHGAIN: + case LOWGAIN: + case MEDIUMGAIN: + case VERYHIGHGAIN: #endif break; default: - ret = FAIL; - sprintf(mess,"Setting (%d) is not implemented for this detector\n", myModule.reg); - cprintf(RED, "Warning: %s", mess); + modeNotImplemented("Settings", (int)module.reg); break; } - } -#endif - - // execute action - if (ret==OK) { - if (differentClients && lockStatus) { - ret = FAIL; - sprintf(mess,"Detector locked by %s\n",lastClientIP); - cprintf(RED, "Warning: %s", mess); - } -#ifdef EIGERD - //set dacs, trimbits and iodelay - ret=setModule(myModule, myIODelay); - //set threshhold - if (myEV >= 0) - setThresholdEnergy(myEV); - else { - //changes settings to undefined (loading a random trim file) - setSettings(UNDEFINED); - cprintf(RED,"Settings has been changed to undefined (random trim file)\n"); - } - //rate correction - //switch off rate correction: no value read from load calib/load settings) - if(myTau == -1){ - if(getRateCorrectionEnable()){ - setRateCorrection(0); - ret = FAIL; - strcat(mess,"Cannot set Rate correction. No default tau provided. Deactivating Rate Correction\n"); - cprintf(RED, "Warning: %s", mess); - } - } - //normal tau value (only if enabled) - else{ - setDefaultSettingsTau_in_nsec(myTau); - if (getRateCorrectionEnable()){ - int64_t retvalTau = setRateCorrection(myTau); - if(myTau != retvalTau){ - cprintf(RED,"%s",mess); - ret=FAIL; - } - } - } - retval = getSettings(); + // set +#ifndef EIGERD + retval = setModule(module); + validate(module.reg, retval, "set module (settings)", 0); + // eiger #else - retval=setModule(myModule); - if (retval != myModule.reg) + //set dacs, trimbits and iodelay + ret = setModule(module, ioDelay); + //set threshhold + if (eV >= 0) + setThresholdEnergy(eV); + else { + //changes settings to undefined (loading a random trim file) + setSettings(UNDEFINED); + FILE_LOG(logERROR, ("Settings has been changed to undefined " + "(random trim file)\n")); + } + //rate correction + //switch off rate correction: no value read from load calib/load settings) + if (tau == -1) { + if (getRateCorrectionEnable()) { + setRateCorrection(0); ret = FAIL; + sprintf(mess,"Cannot set module. Cannot set Rate correction. " + "No default tau provided. Deactivating Rate Correction\n"); + FILE_LOG(logERROR, (mess)); + } + } + //normal tau value (only if enabled) + else { + setDefaultSettingsTau_in_nsec(tau); + if (getRateCorrectionEnable()) { + int64_t retvalTau = setRateCorrection(tau); + if (tau != retvalTau) { + ret = FAIL; + sprintf(mess, "Cannot set module. Could not set rate correction\n"); + FILE_LOG(logERROR, (mess)); + } + } + } + retval = getSettings(); #endif - if(myChip != NULL) free(myChip); - if(myChan != NULL) free(myChan); - if(myDac != NULL) free(myDac); - if(myAdc != NULL) free(myAdc); + FILE_LOG(logDEBUG5, ("Settings: %d\n", retval)); } -#endif - - Server_SendResult(file_des, INT32, 1, &retval, sizeof(retval)); - - return ret; + if (myChip != NULL) free(myChip); + if (myChan != NULL) free(myChan); + if (myDac != NULL) free(myDac); + if (myAdc != NULL) free(myAdc); + return Server_SendResult(file_des, INT32, 1, &retval, sizeof(retval)); } @@ -1212,91 +1030,86 @@ int set_module(int file_des) { int get_module(int file_des) { - int ret=OK,ret1=OK; - int n=0; - sls_detector_module myModule; - sprintf(mess,"get module failed\n"); - -#ifdef MYTHEN3D - //to receive any arguments - while (n > 0) - n = receiveData(file_des,mess,MAX_STR_LENGTH,OTHER); - ret = FAIL; - sprintf(mess,"Function (Get Module) is not implemented for this detector\n"); - cprintf(RED, "Warning: %s", mess); -#else - - // execute action - int *myDac=NULL; - int *myAdc=NULL; + ret = OK; + memset(mess, 0, sizeof(mess)); + sls_detector_module module; + int *myDac = NULL; + int *myAdc = NULL; int *myChip = NULL; int *myChan = NULL; - myDac=(int*)malloc(getNumberOfDACs()*sizeof(int)); - if (getNumberOfDACs() > 0 && myDac == NULL) { - ret = FAIL; - sprintf(mess,"could not allocate dacs\n"); - cprintf(RED, "Warning: %s", mess); - } - else { - myModule.dacs=myDac; - myAdc=(int*)malloc(getNumberOfADCs()*sizeof(int)); + // allocate to send arguments + // infinite loop to break out when FAIL or a final OK + while(1) { + + // allocate dacs + myDac = (int*)malloc(getNumberOfDACs() * sizeof(int)); + // error + if (getNumberOfDACs() > 0 && myDac == NULL) { + ret = FAIL; + sprintf(mess, "Could not allocate dacs\n"); + FILE_LOG(logERROR,(mess)); + break; + } + module.dacs = myDac; + + // allocate adcs + myAdc = (int*)malloc(getNumberOfADCs() * sizeof(int)); + // error if (getNumberOfADCs() > 0 && myAdc == NULL) { ret = FAIL; - sprintf(mess,"could not allocate adcs\n"); - cprintf(RED, "Warning: %s", mess); + sprintf(mess,"Could not allocate adcs\n"); + FILE_LOG(logERROR,(mess)); + break; } - else { - myModule.adcs=myAdc; - //no chips and chans allocated for jungfrau, too much memory + module.adcs=myAdc; + + // no need to allocate chips and chans for jungfrau, too much memory #ifdef JUNGFRAUD - myModule.chipregs=NULL; - myModule.chanregs=NULL; + module.chipregs = NULL; + module.chanregs = NULL; #else - myChip=(int*)malloc(getNumberOfChips()*sizeof(int)); - if (getNumberOfChips() > 0 && myChip == NULL) { - ret = FAIL; - sprintf(mess,"could not allocate chips\n"); - cprintf(RED, "Warning: %s", mess); - } - else { - myModule.chipregs=myChip; - myChan=(int*)malloc(getTotalNumberOfChannels()*sizeof(int)); - if (getTotalNumberOfChannels() > 0 && myChan == NULL) { - ret = FAIL; - sprintf(mess,"could not allocate chans\n"); - cprintf(RED, "Warning: %s", mess); - } - else { - myModule.chanregs=myChan; -#endif - myModule.nchip=getNumberOfChips(); - myModule.nchan=getTotalNumberOfChannels(); - myModule.ndac=getNumberOfDACs(); - myModule.nadc=getNumberOfADCs(); - getModule(&myModule); -#ifdef VERBOSE - printf("Returning module of register %x\n", myModule.reg); -#endif -#ifndef JUNGFRAUD - } - } -#endif + // allocate chips + myChip = (int*)malloc(getNumberOfChips() * sizeof(int)); + if (getNumberOfChips() > 0 && myChip == NULL) { + ret = FAIL; + sprintf(mess,"Could not allocate chips\n"); + FILE_LOG(logERROR,(mess)); + break; } - } + module.chipregs = myChip; + + // allocate chans + myChan = (int*)malloc(getTotalNumberOfChannels() * sizeof(int)); + if (getTotalNumberOfChannels() > 0 && myChan == NULL) { + ret = FAIL; + sprintf(mess,"Could not allocate chans\n"); + FILE_LOG(logERROR,(mess)); + break; + } + module.chanregs=myChan; #endif + module.nchip = getNumberOfChips(); + module.nchan = getTotalNumberOfChannels(); + module.ndac = getNumberOfDACs(); + module.nadc = getNumberOfADCs(); + + // only get + FILE_LOG(logDEBUG5, ("Getting module\n")); + getModule(&module); + FILE_LOG(logDEBUG5, ("Getting module. Settings:%d\n", module.reg)); + } Server_SendResult(file_des, INT32, 1, NULL, 0); // send module, 0 is to receive partially (without trimbits etc) if (ret != FAIL) { - ret = sendModuleGeneral(file_des, &myModule, (myDetectorType == JUNGFRAU) ? 0 : 1); + ret = sendModuleGeneral(file_des, &module, (myDetectorType == JUNGFRAU) ? 0 : 1); } - if(myChip != NULL) free(myChip); - if(myChan != NULL) free(myChan); - if(myDac != NULL) free(myDac); - if(myAdc != NULL) free(myAdc); - + if (myChip != NULL) free(myChip); + if (myChan != NULL) free(myChan); + if (myDac != NULL) free(myDac); + if (myAdc != NULL) free(myAdc); return ret; } @@ -1306,100 +1119,63 @@ int get_module(int file_des) { int set_settings(int file_des) { - int ret=OK,ret1=OK; - int n=0; - int arg=-1; - int retval=-1; - enum detectorSettings isett=-1; - sprintf(mess,"set settings failed\n"); + ret = OK; + memset(mess, 0, sizeof(mess)); + enum detectorSettings isett = GET_SETTINGS; + enum detectorSettings retval = GET_SETTINGS; -#ifdef MYTHEN3D - //to receive any arguments - while (n > 0) - n = receiveData(file_des,mess,MAX_STR_LENGTH,OTHER); - ret = FAIL; - sprintf(mess,"Function (Set Settings) is not implemented for this detector\n"); - cprintf(RED, "Warning: %s", mess); -#else + if (receiveData(file_des, &isett, sizeof(isett), INT32) < 0) + return printSocketReadError(); + FILE_LOG(logDEBUG5, ("Setting settings %d\n", isett)); - // receive arguments - n = receiveData(file_des,&arg,sizeof(arg),INT32); - if (n < 0) return printSocketReadError(); - isett=arg; + //set & get + if ((isett == GET_SETTINGS) || ((isett != GET_SETTINGS) && (Server_VerifyLock() != FAIL))) { - // execute action - if (differentClients && lockStatus && isett!=GET_SETTINGS) { - ret = FAIL; - sprintf(mess,"Detector locked by %s\n",lastClientIP); - cprintf(RED, "Warning: %s", mess); - } - - switch(isett) { - case GET_SETTINGS: - case UNINITIALIZED: + // check index + switch(isett) { + case GET_SETTINGS: #ifdef JUNGFRAUD - case DYNAMICGAIN: - case DYNAMICHG0: - case FIXGAIN1: - case FIXGAIN2: - case FORCESWITCHG1: - case FORCESWITCHG2: - break; - default: - ret = FAIL; - sprintf(mess,"Setting (%d) is not implemented for this detector.\n" - "Options are dynamicgain, dynamichg0, fixgain1, fixgain2, " - "forceswitchg1 and forceswitchg2.\n", isett); - cprintf(RED, "Warning: %s", mess); - break; -// other detectors -// #elif GOTTHARDD, MOENCHD, PROPIXD -#else - break; - default: - ret = FAIL; -#ifdef EIGERD - sprintf(mess,"Cannot set settings via SET_SETTINGS, use SET_MODULE\n"); -#else - sprintf(mess,"Setting (%d) is not implemented for this detector\n", isett); + case DYNAMICGAIN: + case DYNAMICHG0: + case FIXGAIN1: + case FIXGAIN2: + case FORCESWITCHG1: + case FORCESWITCHG2: +#elif GOTTHARDD + case DYNAMICGAIN: + case HIGHGAIN: + case LOWGAIN: + case MEDIUMGAIN: + case VERYHIGHGAIN: #endif - cprintf(RED, "Warning: %s", mess); - break; -#endif - } - - if (ret != FAIL) { -#ifdef VERBOSE - printf("Changing settings to %d\n", isett); -#endif - retval=setSettings(isett); -#ifdef VERBOSE - printf("Settings changed to %d\n", isett); -#endif - if (retval == isett || isett < 0) { - ret=OK; - } else { - ret = FAIL; - sprintf(mess,"Changing settings : wrote %d but read %d\n", isett, retval); - cprintf(RED, "Warning: %s", mess); + break; + default: + if (myDetectorType == EIGER) { + ret = FAIL; + sprintf(mess, "Cannot set settings via SET_SETTINGS, use SET_MODULE\n"); + FILE_LOG(logERROR,(mess)); + } else + modeNotImplemented("Settings Index", (int)isett); + break; } - } - // set to default dacs, -//# also for #elif GOTTHARDD, MOENCHD, PROPIXD -#ifdef JUNGFRAUD - if (ret == OK && isett >= 0) { - ret = setDefaultDacs(); - if (ret == FAIL) { - strcpy(mess,"Could change settings, but could not set to default dacs\n"); - cprintf(RED, "Warning: %s", mess); + + // if index is okay, set & get + if (ret == OK) { + retval = setSettings(isett); + FILE_LOG(logDEBUG5, ("Settings: %d\n", retval)); + validate((int)isett, (int)retval, "set settings", 0); +#if defined(JUNGFRAUD) || defined (GOTTHARDD) + if (ret == OK && isett >= 0) { + ret = setDefaultDacs(); + if (ret == FAIL) { + strcpy(mess,"Could change settings, but could not set to default dacs\n"); + FILE_LOG(logERROR,(mess)); + } } +#endif } -#endif -#endif - - Server_SendResult(file_des, INT32, 1, &retval, sizeof(retval)); - - return ret; + } + return Server_SendResult(file_des, INT32, 1, &retval, sizeof(retval)); } @@ -1407,33 +1183,19 @@ int set_settings(int file_des) { int get_threshold_energy(int file_des) { - int ret=OK,ret1=OK; - int n=0; - int retval=-1; - sprintf(mess,"get threshold energy failed\n"); + ret = OK; + memset(mess, 0, sizeof(mess)); + int retval = -1; + FILE_LOG(logDEBUG5, ("Getting Threshold energy\n")); #ifndef EIGERD - //to receive any arguments - while (n > 0) - n = receiveData(file_des,mess,MAX_STR_LENGTH,OTHER); - ret = FAIL; - sprintf(mess,"Function (Get Threshold Energy) is not implemented for this detector\n"); - cprintf(RED, "Warning: %s", mess); + functionNotImplemented(); #else - - // execute action -#ifdef VERBOSE - printf("Getting threshold energy \n"); + // only get + retval = getThresholdEnergy(); + FILE_LOG(logDEBUG5, ("Threshold energy: %d eV\n", retval)); #endif - retval=getThresholdEnergy(); -#ifdef VERBOSE - printf("Threshold is %d eV\n", retval); -#endif -#endif - - Server_SendResult(file_des, INT32, 1, &retval, sizeof(retval)); - - return ret; + return Server_SendResult(file_des, INT32, 1, &retval, sizeof(retval)); } @@ -1442,51 +1204,39 @@ int get_threshold_energy(int file_des) { int start_acquisition(int file_des) { - int ret=OK,ret1=OK; - int n=0; - sprintf(mess,"start acquisition failed\n"); + ret = OK; + memset(mess, 0, sizeof(mess)); - // execute action - if (differentClients && lockStatus) { - ret = FAIL; - sprintf(mess,"Detector locked by %s\n",lastClientIP); - cprintf(RED, "Warning: %s", mess); + FILE_LOG(logDEBUG5, ("Starting Acquisition\n")); + // only set + if (Server_VerifyLock() != FAIL) { + ret = startStateMachine(); + if (ret == FAIL) { + sprintf(mess, "Could not start acquisition\n"); + FILE_LOG(logERROR,(mess)); + } + FILE_LOG(logDEBUG5, ("Starting Acquisition ret: %d\n", ret)); } - else { - printf("Starting acquisition\n"); - ret=startStateMachine(); - if (ret==FAIL) - cprintf(RED, "Warning: %s", mess); - } - - Server_SendResult(file_des, INT32, 1, NULL, 0); - - return ret; + return Server_SendResult(file_des, INT32, 1, NULL, 0); } int stop_acquisition(int file_des) { - int ret=OK,ret1=OK; - int n=0; - sprintf(mess,"stop acquisition failed\n"); + ret = OK; + memset(mess, 0, sizeof(mess)); - // execute action - if (differentClients && lockStatus) { - ret = FAIL; - sprintf(mess,"Detector locked by %s\n",lastClientIP); - cprintf(RED, "Warning: %s", mess); + FILE_LOG(logDEBUG5, ("Stopping Acquisition\n")); + // only set + if (Server_VerifyLock() != FAIL) { + ret = stopStateMachine(); + if (ret == FAIL) { + sprintf(mess, "Could not stop acquisition\n"); + FILE_LOG(logERROR,(mess)); + } + FILE_LOG(logDEBUG5, ("Stopping Acquisition ret: %d\n", ret)); } - else { - printf("Stopping acquisition\n"); - ret=stopStateMachine(); - if (ret==FAIL) - cprintf(RED, "Warning: %s", mess); - } - - Server_SendResult(file_des, INT32, 1, NULL, 0); - - return ret; + return Server_SendResult(file_des, INT32, 1, NULL, 0); } @@ -1494,36 +1244,24 @@ int stop_acquisition(int file_des) { int start_readout(int file_des) { - int ret=OK,ret1=OK; - int n=0; - sprintf(mess,"start readout failed\n"); + ret = OK; + memset(mess, 0, sizeof(mess)); + FILE_LOG(logDEBUG5, ("Starting readout\n")); #ifdef JUNGFRAUD - //to receive any arguments - while (n > 0) - n = receiveData(file_des,mess,MAX_STR_LENGTH,OTHER); - ret = FAIL; - sprintf(mess,"Function (Start Readout) is not implemented for this detector\n"); - cprintf(RED, "%s", mess); + functionNotImplemented(); #else - - // execute action - if (differentClients && lockStatus) { - ret = FAIL; - sprintf(mess,"Detector locked by %s\n",lastClientIP); - cprintf(RED, "Warning: %s", mess); - } - else { - printf("Starting readout\n"); - ret=startReadOut(); - if (ret==FAIL) - cprintf(RED, "Warning: %s", mess); + // only set + if (Server_VerifyLock() != FAIL) { + ret = startReadOut(); + if (ret == FAIL) { + sprintf(mess, "Could not start readout\n"); + FILE_LOG(logERROR,(mess)); + } + FILE_LOG(logDEBUG5, ("Starting readout ret: %d\n", ret)); } #endif - - Server_SendResult(file_des, INT32, 1, NULL, 0); - - return ret; + return Server_SendResult(file_des, INT32, 1, NULL, 0); } @@ -1532,18 +1270,15 @@ int start_readout(int file_des) { int get_run_status(int file_des) { - int ret=OK,ret1=OK; - enum runStatus retval=ERROR; + ret = OK; + memset(mess, 0, sizeof(mess)); + enum runStatus retval = ERROR; - // execute action -#ifdef VERBOSE - printf("Getting status\n"); -#endif + FILE_LOG(logDEBUG5, ("Getting status\n")); + // only get retval = getRunStatus(); - - Server_SendResult(file_des, INT32, 1, &retval, sizeof(retval)); - - return ret; + FILE_LOG(logDEBUG5, ("Status: %d\n", retval)); + return Server_SendResult(file_des, INT32, 1, &retval, sizeof(retval)); } @@ -1551,55 +1286,44 @@ int get_run_status(int file_des) { int start_and_read_all(int file_des) { - ret = FAIL; -#ifdef VERBOSE - printf("Starting and reading all frames\n"); -#endif + ret = OK; + memset(mess, 0, sizeof(mess)); - // execute action - if (differentClients && lockStatus) { - ret = FAIL; - sprintf(mess,"Detector locked by %s\n",lastClientIP); - cprintf(RED, "Warning: %s", mess); + FILE_LOG(logDEBUG5, ("Starting Acquisition and read all frames\n")); + // start state machine + FILE_LOG(logDEBUG5, ("Stopping Acquisition\n")); + // only set + if (Server_VerifyLock() != FAIL) { + ret = startStateMachine(); + if (ret == FAIL) { + sprintf(mess, "Could not start acquisition\n"); + FILE_LOG(logERROR,(mess)); + } + FILE_LOG(logDEBUG5, ("Starting Acquisition ret: %d\n", ret)); - - Server_SendResult(file_des, INT32, 1 , NULL, 0); - - return ret; } - startStateMachine(); - read_all(file_des); - return ret; + + // lock or acquisition start error + if (ret == FAIL) + return Server_SendResult(file_des, INT32, 1 , NULL, 0); + + // read all (again validate lock, but should pass and not fail) + return read_all(file_des); } int read_all(int file_des) { - ret = FAIL; - int n=0; - sprintf(mess, "read all frame failed\n"); + ret = OK; + memset(mess, 0, sizeof(mess)); - // execute action - if (differentClients && lockStatus) { - ret = FAIL; - sprintf(mess,"Detector locked by %s\n",lastClientIP); - cprintf(RED, "Warning: %s", mess); - - Server_SendResult(file_des, INT32, 1 , NULL, 0); - - return ret; + FILE_LOG(logDEBUG5, ("Reading all frames\n")); + // only set + if (Server_VerifyLock() != FAIL) { + readFrame(&ret, mess); } - - readFrame(&ret, mess); - if(ret == FAIL) - cprintf(RED,"%s\n",mess); - else - cprintf(GREEN,"%s",mess); - - Server_SendResult(file_des, INT32, 1 , NULL, 0); - - return ret; + return Server_SendResult(file_des, INT32, 1 , NULL, 0); } @@ -1608,92 +1332,81 @@ int read_all(int file_des) { int set_timer(int file_des) { - int ret=OK,ret1=OK; - int n=0; - enum timerIndex ind=0; - int64_t tns=-1; - int64_t retval=-1; - sprintf(mess,"set timer failed\n"); + ret = OK; + memset(mess, 0, sizeof(mess)); + int64_t args[2] = {-1,-1}; + int64_t retval = -1; - // receive arguments - n = receiveData(file_des,&ind,sizeof(ind),INT32); - if (n < 0) return printSocketReadError(); - - n = receiveData(file_des,&tns,sizeof(tns),INT64); - if (n < 0) return printSocketReadError(); - - // execute action - if (differentClients && lockStatus && tns!=-1) { - ret = FAIL; - sprintf(mess,"Detector locked by %s\n",lastClientIP); - cprintf(RED, "Warning: %s", mess); - } - else { -#ifdef VERBOSE - printf("setting timer %d to %lld ns\n",ind,tns); -#endif + if (receiveData(file_des, args, sizeof(args), INT64) < 0) + return printSocketReadError(); + enum timerIndex ind = (int)args[0]; + int64_t tns = args[1]; #ifdef EIGERD - int64_t subexptime = 0; + int64_t subexptime = 0; #endif - switch(ind) { + FILE_LOG(logDEBUG5, ("Setting timer index %d to %lld ns\n", ind, tns)); + + // set & get + if ((tns == -1) || ((tns != -1) && (Server_VerifyLock() != FAIL))) { + + // check index + switch (ind) { + case FRAME_NUMBER: + case ACQUISITION_TIME: + case FRAME_PERIOD: + case CYCLES_NUMBER: +#ifdef JUNGFRAUD + case DELAY_AFTER_TRIGGER: +#endif + retval = setTimer(ind, tns); + break; #ifdef JUNGFRAUD case STORAGE_CELL_NUMBER: if (tns > MAX_STORAGE_CELL_VAL) { - ret=FAIL; + ret = FAIL; strcpy(mess,"Max Storage cell number should not exceed 15\n"); - cprintf(RED, "Warning: %s", mess); + FILE_LOG(logERROR,(mess)); break; } + retval = setTimer(ind,tns); + break; #endif #ifdef EIGERD case SUBFRAME_ACQUISITION_TIME: - if (tns > ((int64_t)MAX_SUBFRAME_EXPOSURE_VAL_IN_10NS*10) ){ - ret=FAIL; + if (tns > ((int64_t)MAX_SUBFRAME_EXPOSURE_VAL_IN_10NS*10) ) { + ret = FAIL; strcpy(mess,"Sub Frame exposure time should not exceed 5.368 seconds\n"); - cprintf(RED, "Warning: %s", mess); + FILE_LOG(logERROR,(mess)); break; } retval = setTimer(ind,tns); break; case SUBFRAME_DEADTIME: subexptime = setTimer(SUBFRAME_ACQUISITION_TIME, -1); - if ((tns + subexptime) > ((int64_t)MAX_SUBFRAME_EXPOSURE_VAL_IN_10NS*10) ){ - ret=FAIL; + if ((tns + subexptime) > ((int64_t)MAX_SUBFRAME_EXPOSURE_VAL_IN_10NS*10) ) { + ret = FAIL; sprintf(mess,"Sub Frame Period should not exceed 5.368 seconds. " - "So sub frame dead time should not exceed %lfu seconds (subexptime = %lf seconds)\n", - ((((int64_t)MAX_SUBFRAME_EXPOSURE_VAL_IN_10NS*10) - subexptime)/1E9), (subexptime/1E9)); - cprintf(RED, "Warning: %s", mess); + "So sub frame dead time should not exceed %lfu seconds " + "(subexptime = %lf seconds)\n", + ((((int64_t)MAX_SUBFRAME_EXPOSURE_VAL_IN_10NS*10) - subexptime)/1E9), + (subexptime/1E9)); + FILE_LOG(logERROR,(mess)); break; } retval = setTimer(ind,tns); break; #endif -#ifdef JUNGFRAUD - case DELAY_AFTER_TRIGGER: -#elif MYTHEN3D - case DELAY_AFTER_TRIGGER: - case GATES_NUMBER: - case PROBES_NUMBER: - case SAMPLES_JCTB: -#endif - case FRAME_NUMBER: - case ACQUISITION_TIME: - case FRAME_PERIOD: - case CYCLES_NUMBER: - retval = setTimer(ind,tns); - break; default: - ret = FAIL; - sprintf(mess,"Timer Index (%d) is not implemented for this detector\n", (int) ind); - cprintf(RED, "%s", mess); + modeNotImplemented("Timer index", (int)ind); break; } - + // validate + validate64(tns, retval, "set timer", 0); } - - Server_SendResult(file_des, INT64, 1, &retval, sizeof(retval)); - - return ret; + if (ret != FAIL) { + FILE_LOG(logDEBUG5, ("Timer index %d: %lld\n", ind, retval)); + } + return Server_SendResult(file_des, INT64, 1, &retval, sizeof(retval)); } @@ -1702,48 +1415,29 @@ int set_timer(int file_des) { - - int get_time_left(int file_des) { - int ret=OK,ret1=OK; - int n=0; - int64_t retval=-1; - sprintf(mess,"get timer left failed\n"); + ret = OK; + memset(mess, 0, sizeof(mess)); + enum timerIndex ind = -1; + int64_t retval = -1; + if (receiveData(file_des, &ind, sizeof(ind), INT32) < 0) + return printSocketReadError(); + FILE_LOG(logDEBUG5, ("Getting timer left index %d\n", ind)); - // receive arguments - enum timerIndex ind=0; - n = receiveData(file_des,&ind,sizeof(ind),INT32); - if (n < 0) return printSocketReadError(); - -#ifdef VERBOSE - printf("getting time left on timer %d \n",ind); -#endif - -#ifdef JUNGFRAUD - if (ind == DELAY_AFTER_TRIGGER) { - ret = FAIL; - sprintf(mess,"Timer Left Index (%d) is not implemented for this release.\n", (int)ind); - cprintf(RED, "%s", mess); - } else { -#endif - - switch(ind) { + // only get + // check index + switch(ind) { #ifdef EIGERD case MEASURED_PERIOD: case MEASURED_SUBPERIOD: #elif JUNGFRAUD case FRAMES_FROM_START: case FRAMES_FROM_START_PG: -#elif MYTHEN3D - case GATES_NUMBER: - case PROBES_NUMBER: - case SAMPLES_JCTB: -#endif -#ifndef EIGERD -#ifndef JUNGFRAUD +#elif GOTTHARDD case GATES_NUMBER: #endif +#if defined(GOTTHARDD) || defined(JUNGFRAUD) case FRAME_NUMBER: case ACQUISITION_TIME: case FRAME_PERIOD: @@ -1753,25 +1447,22 @@ int get_time_left(int file_des) { case ACTUAL_TIME: case MEASUREMENT_TIME: #endif - retval=getTimeLeft(ind); + retval = getTimeLeft(ind); + FILE_LOG(logDEBUG5, ("Timer left index %d: %lld\n", ind, retval)); break; - default: - ret = FAIL; - sprintf(mess,"Timer Left Index (%d) is not implemented for this detector\n", (int)ind); - cprintf(RED, "%s", mess); - break; - } -#ifdef VERBOSE - printf("Time left on timer %d is %lld\n",ind, retval); -#endif - #ifdef JUNGFRAUD - } // end of if (ind == DELAY_AFTER_TRIGGER) + case DELAY_AFTER_TRIGGER: + ret = FAIL; + sprintf(mess,"Timer Left Index (%d) is not implemented for this release.\n", (int)ind); + FILE_LOG(logERROR,(mess)); + break; #endif - Server_SendResult(file_des, INT64, 1, &retval, sizeof(retval)); - - return ret; + default: + modeNotImplemented("Timer left index", (int)ind); + break; + } + return Server_SendResult(file_des, INT64, 1, &retval, sizeof(retval)); } @@ -1780,76 +1471,63 @@ int get_time_left(int file_des) { int set_dynamic_range(int file_des) { - int retval[2]; - int ret=OK,ret1=OK; - int rateret=OK,rateret1=OK; - int n=0; - int dr=-1; - int retval=-1; - sprintf(mess,"set dynamic range failed\n"); + ret = OK; + memset(mess, 0, sizeof(mess)); + int dr = -1; + int retval = -1; - // receive arguments - n = receiveData(file_des,&dr,sizeof(dr),INT32); - if (n < 0) return printSocketReadError(); + if (receiveData(file_des, &dr, sizeof(dr), INT32) < 0) + return printSocketReadError(); + FILE_LOG(logDEBUG5, ("Setting dr to %d\n", dr)); - // execute action - if (differentClients && lockStatus && dr>=0) { - ret = FAIL; - sprintf(mess,"Detector locked by %s\n",lastClientIP); - cprintf(RED, "Warning: %s", mess); - } - else { - switch(dr){ + // set & get + if ((dr == -1) || ((dr != -1) && (Server_VerifyLock() != FAIL))) { + +#ifdef EIGERD + int old_dr = setDynamicRange(-1); +#endif + // check dr + switch(dr) { case -1: case 16: #ifdef EIGERD case 4: case 8: case 32: #endif - break; + retval = setDynamicRange(dr); + FILE_LOG(logDEBUG5, ("Dynamic range: %d\n", retval)); + validate(dr, retval, "set dynamic range", 0); + if (dr >= 0) + dataBytes=calculateDataBytes(); + break; default: - ret = FAIL; - sprintf(mess,"Dynamic Range (%d) is not implemented for this detector\n", dr); - cprintf(RED, "Warning: %s", mess); + modeNotImplemented("Dynamic range", dr); + break; } - } - if(ret == OK){ + #ifdef EIGERD - int old_dr = setDynamicRange(-1); - retval=setDynamicRange(dr); - if (dr>=0 && retval!=dr) - ret=FAIL; - //look at rate correction only if dr change worked - if((ret==OK) && (dr!=32) && (dr!=16) && (dr!=-1) && (getRateCorrectionEnable())){ - setRateCorrection(0); - rateret = FAIL; - strcpy(mess,"Switching off Rate Correction. Must be in 32 or 16 bit mode\n"); - cprintf(RED,"%s",mess); - }else{ - //setting it if dr changed from 16 to 32 or vice versa with tau value as in rate table - if((dr!=-1) && (old_dr != dr) && getRateCorrectionEnable() && (dr == 16 || dr == 32)){ + if (dr != -1 && getRateCorrectionEnable()) { + // 4 or 8 bit, switch off rate corr (only if dr worked) + if ((dr != 32) && (dr != 16) && (ret == OK)) { + setRateCorrection(0); + ret = FAIL; + strcpy(mess,"Switching off Rate Correction. Must be in 32 or 16 bit mode\n"); + FILE_LOG(logERROR,(mess)); + } + + // 16, 32 (diff from old value), set new tau in rate table(-1), if it didnt work, give error + else if ((dr == 16 || dr == 32) && (old_dr != dr)) { setRateCorrection(-1); //tau_ns will not be -1 here - if(!getRateCorrectionEnable()){ + // it didnt work + if (!getRateCorrectionEnable()) { ret = FAIL; strcpy(mess,"Deactivating Rate Correction. Could not set it.\n"); - cprintf(RED,"%s",mess); + FILE_LOG(logERROR,(mess)); } } } - -#else - retval = setDynamicRange(dr); #endif - if (dr>=0) dataBytes=calculateDataBytes(); } - if ((ret == OK) && dr>=0 && retval!=dr) { - ret = FAIL; - cprintf(RED,"%s",mess); - } - - - Server_SendResult(file_des, INT32, 1, retval, sizeof(retval)); - - return ret; + return Server_SendResult(file_des, INT32, 1, &retval, sizeof(retval)); } @@ -1858,38 +1536,22 @@ int set_dynamic_range(int file_des) { int set_readout_flags(int file_des) { - int ret=OK,ret1=OK; - int n=0; - enum readOutFlags retval=-1; - sprintf(mess,"set readout flags failed\n"); + ret = OK; + memset(mess, 0, sizeof(mess)); + enum readOutFlags arg = GET_READOUT_FLAGS; + enum readOutFlags retval = GET_READOUT_FLAGS; + + if (receiveData(file_des, &arg, sizeof(arg), INT32) < 0) + return printSocketReadError(); + FILE_LOG(logDEBUG5, ("Setting readout flags to %d\n", arg)); #ifndef EIGERD - //to receive any arguments - while (n > 0) - n = receiveData(file_des,mess,MAX_STR_LENGTH,OTHER); - ret=FAIL; - sprintf(mess,"Function (Set Read Out Flags) is not implemented for this detector\n"); - cprintf(RED, "%s",mess); + functionNotImplemented(); #else + // set & get + if ((arg == GET_READOUT_FLAGS) || ((arg != GET_READOUT_FLAGS) && (Server_VerifyLock() != FAIL))) { - // receive arguments - enum readOutFlags arg=-1; - n = receiveData(file_des,&arg,sizeof(arg),INT32); - if (n < 0) return printSocketReadError(); - - // execute action - if (differentClients && lockStatus && arg!=GET_READOUT_FLAGS) { - ret = FAIL; - sprintf(mess,"Detector locked by %s\n",lastClientIP); - cprintf(RED, "Warning: %s", mess); - } - else { -#ifdef VERBOSE - printf("setting readout flags to %d\n",arg); -#endif switch(arg) { - case GET_READOUT_FLAGS: -#ifdef EIGERD case STORE_IN_RAM: case CONTINOUS_RO: case PARALLEL: @@ -1897,26 +1559,17 @@ int set_readout_flags(int file_des) { case SAFE: case SHOW_OVERFLOW: case NOOVERFLOW: -#endif - retval=setReadOutFlags(arg); + retval = setReadOutFlags(arg); + FILE_LOG(logDEBUG5, ("Read out flags: %d\n", retval)); + validate((int)arg, (int)retval, "set readout flag", 0); break; default: - ret = FAIL; - sprintf(mess,"Readout Flag Index (%d) is not implemented for this detector\n", (int)arg); - cprintf(RED, "Warning: %s", mess); + modeNotImplemented("Read out flag index", (int)arg); break; } - if (ret==OK && ((retval == -1) || ((arg!=-1) && ((retval&arg)!=arg)))){ - ret = FAIL; - sprintf(mess,"Could not change readout flag: should be 0x%x but is 0x%x\n", arg, retval); - cprintf(RED, "Warning: %s", mess); - } } #endif - - Server_SendResult(file_des, INT32, 1, &retval, sizeof(retval)); - - return ret; + return Server_SendResult(file_des, INT32, 1, &retval, sizeof(retval)); } @@ -1925,87 +1578,68 @@ int set_readout_flags(int file_des) { int set_roi(int file_des) { - int ret=OK,ret1=OK; - int n=0; - strcpy(mess,"set nroi failed\n"); + ret = OK; + memset(mess, 0, sizeof(mess)); + int narg = -1; + ROI arg[MAX_ROIS]; + int nretval = -1; + ROI* retval = NULL; + + // receive number of ROIs + if (receiveData(file_des, &narg, sizeof(narg), INT32) < 0) + return printSocketReadError(); + // receive ROIs + { + int iloop = 0; + for (iloop = 0; iloop < narg; ++iloop) { + if (receiveData(file_des, &arg[iloop].xmin, sizeof(int), INT32) < 0) + return printSocketReadError(); + if (receiveData(file_des, &arg[iloop].xmax, sizeof(int), INT32) < 0) + return printSocketReadError(); + if (receiveData(file_des, &arg[iloop].ymin, sizeof(int), INT32) < 0) + return printSocketReadError(); + if (receiveData(file_des, &arg[iloop].ymax, sizeof(int), INT32) < 0) + return printSocketReadError(); + } + } + FILE_LOG(logDEBUG5, ("Set ROI (nroi:%d)\n", narg)); + { + int iloop = 0; + for (iloop = 0; iloop < narg; ++iloop) { + FILE_LOG(logDEBUG5, ("%d: %d\t%d\t%d\t%d\n", + arg[iloop].xmin, arg[iloop].xmax, arg[iloop].ymin, arg[iloop].ymax)); + } + } #ifndef GOTTHARDD - //to receive any arguments - while (n > 0) - n = receiveData(file_des,mess,MAX_STR_LENGTH,OTHER); - ret=FAIL; - sprintf(mess,"Function (Set ROI) is not implemented for this detector\n"); - cprintf(RED, "%s",mess); + functionNotImplemented(); #else - - ROI* retval=0; - int retvalsize=0; - - // receive arguments - int nroi=-1; - ROI arg[MAX_ROIS]; - n = receiveData(file_des,&nroi,sizeof(nroi),INT32); - if (n < 0) return printSocketReadError(); - - { - int i; - if(nroi!=-1){ - for(i=0;i=0) { - ret = FAIL; - sprintf(mess,"Detector locked by %s\n",lastClientIP); - cprintf(RED, "Warning: %s", mess); - } - else { -#ifdef VERBOSE - printf("setting speed variable %d to %d\n",arg,val); -#endif - switch (arg) { + // set & get + if ((val == -1) || ((val != -1) && (Server_VerifyLock() != FAIL))) { + // check index + switch(ind) { #ifdef JUNGFRAUD case ADC_PHASE: retval = adcPhase(val); - if ((val != 100000) && (retval!=val) && (val>=0)) { - ret=FAIL; - sprintf(mess,"could not change set adc phase: should be %d but is %d \n", val, retval); - cprintf(RED, "Warning: %s", mess); - } - break; -#endif -#ifdef EIGERD - case CLOCK_DIVIDER: -#elif JUNGFRAUD - case CLOCK_DIVIDER: -#elif MYTHEN3D - case DBIT_CLOCK: - case DBIT_PHASE: -#endif - retval=setSpeed(arg, val); - if ((retval!=val) && (val>=0)) { - ret=FAIL; - sprintf(mess,"could not change speed variable %d: should be %d but is %d \n",arg, val, retval); - cprintf(RED, "Warning: %s", mess); + FILE_LOG(logDEBUG5, ("ADc Phase: %d\n", retval)); + if (val != 100000) { + validate(val, retval, "set adc phase ", 0); } break; +#endif + case CLOCK_DIVIDER: + retval = setSpeed(val); + FILE_LOG(logDEBUG5, ("Clock: %d\n", retval)); + validate(val, retval, "set clock ", 0); + break; default: - ret = FAIL; - sprintf(mess,"Speed Index (%d) is not implemented for this detector\n",(int) arg); - cprintf(RED, "Warning: %s", mess); + modeNotImplemented("Speed index", (int)ind); break; } } - - Server_SendResult(file_des, INT32, 1, &retval, sizeof(retval)); - - return ret; + return Server_SendResult(file_des, INT32, 1, &retval, sizeof(retval)); } @@ -2083,9 +1691,9 @@ int set_speed(int file_des) { int exit_server(int file_des) { - ret = OK; cprintf(BG_RED,"Closing Server\n"); - Server_SendResult(file_des, INT32, 1, NULL, 0); + ret = OK; + Server_SendResult(file_des, INT32, 0, NULL, 0); return GOODBYE; } @@ -2093,41 +1701,34 @@ int exit_server(int file_des) { int lock_server(int file_des) { - int ret=OK,ret1=OK; - int n=0; - int lock=0; - sprintf(mess,"lock server failed\n"); + ret = OK; + memset(mess, 0, sizeof(mess)); + int lock = 0; - // receive arguments - n = receiveData(file_des,&lock,sizeof(lock),INT32); - if (n < 0) return printSocketReadError(); + if (receiveData(file_des, &lock, sizeof(lock), INT32) < 0) + return printSocketReadError(); + FILE_LOG(logDEBUG5, ("Locking Server to %d\n", lock)); - // execute action - if (lock>=0) { - if (lockStatus==0 || strcmp(lastClientIP,thisClientIP)==0 || strcmp(lastClientIP,"none")==0) { - lockStatus=lock; - strcpy(lastClientIP,thisClientIP); + // set + if (lock >= 0) { + if (!lockStatus || // if it was unlocked, anyone can lock + (!strcmp(lastClientIP, thisClientIP)) || // if it was locked, need same ip + (!strcmp(lastClientIP,"none"))) { // if it was locked, must be by "none" + lockStatus = lock; + strcpy(lastClientIP, thisClientIP); } else { - ret = FAIL; - sprintf(mess,"Server already locked by %s\n", lastClientIP); - cprintf(RED, "Warning: %s", mess); + Server_LockedError(); } } - Server_SendResult(file_des, INT32, 1, &lockStatus, sizeof(lockStatus)); - - return ret; + return Server_SendResult(file_des, INT32, 1, &lockStatus, sizeof(lockStatus)); } - int get_last_client_ip(int file_des) { - int ret=OK,ret1=OK; - - Server_SendResult(file_des, INT32, 1, lastClientIP, sizeof(lastClientIP)); - - return ret; + ret = OK; + return Server_SendResult(file_des, INT32, 1, lastClientIP, sizeof(lastClientIP)); } @@ -2136,42 +1737,34 @@ int get_last_client_ip(int file_des) { int set_port(int file_des) { ret = OK; memset(mess, 0, sizeof(mess)); - int n=0; - int p_number=-1; - sprintf(mess,"set port failed\n"); + int p_number = -1; - // receive argumets - n = receiveData(file_des,&p_number,sizeof(p_number),INT32); - if (n < 0) return printSocketReadError(); + if (receiveData(file_des, &p_number, sizeof(p_number), INT32) < 0) + return printSocketReadError(); - // execute action - int sd=-1; - if (differentClients && lockStatus) { - ret = FAIL; - sprintf(mess,"Detector locked by %s\n",lastClientIP); - cprintf(RED, "Warning: %s", mess); - } - else { + // set only + int sd = -1; + if ((Server_VerifyLock() != FAIL)) { + // port number too low if (p_number < 1024) { ret = FAIL; sprintf(mess,"%s port Number (%d) too low\n", (isControlServer ? "control":"stop"), p_number); - FILE_LOG(logWARNING, (mess)); + FILE_LOG(logERROR,(mess)); } else { FILE_LOG(logINFO, ("Setting %s port to %d\n", (isControlServer ? "control":"stop"), p_number)); - sd=bindSocket(p_number); + sd = bindSocket(p_number); } } Server_SendResult(file_des, INT32, 1, &p_number, sizeof(p_number)); - - if (ret!=FAIL) { + // delete old socket + if (ret != FAIL) { closeConnection(file_des); exitServer(sockfd); - sockfd=sd; + sockfd = sd; } - return ret; } @@ -2180,6 +1773,7 @@ int set_port(int file_des) { int update_client(int file_des) { ret = OK; + memset(mess, 0, sizeof(mess)); Server_SendResult(file_des, INT32, 0, NULL, 0); return send_update(file_des); } @@ -2188,72 +1782,71 @@ int update_client(int file_des) { int send_update(int file_des) { - int n=0; // if (n<0) should fail to stop talking to a closed client socket - int nm=0; + int n = 0; // if (n<0) should fail to stop talking to a closed client socket + int nm = 0; int64_t retval = 0; - enum detectorSettings t; n = sendData(file_des,lastClientIP,sizeof(lastClientIP),OTHER); if (n < 0) return printSocketReadError(); - nm=setDynamicRange(GET_FLAG); + nm = setDynamicRange(GET_FLAG); n = sendData(file_des,&nm,sizeof(nm),INT32); if (n < 0) return printSocketReadError(); - dataBytes=calculateDataBytes(); + dataBytes = calculateDataBytes(); n = sendData(file_des,&dataBytes,sizeof(dataBytes),INT32); if (n < 0) return printSocketReadError(); - t=setSettings(GET_SETTINGS); - n = sendData(file_des,&t,sizeof(t),INT32); + nm = (int)setSettings(GET_SETTINGS); + n = sendData(file_des,&nm,sizeof(nm),INT32); if (n < 0) return printSocketReadError(); #ifdef EIGERD - nm=getThresholdEnergy(GET_FLAG); + nm = getThresholdEnergy(GET_FLAG); n = sendData(file_des,&nm,sizeof(nm),INT32); if (n < 0) return printSocketReadError(); #endif - retval=setTimer(FRAME_NUMBER,GET_FLAG); + retval = setTimer(FRAME_NUMBER,GET_FLAG); n = sendData(file_des,&retval,sizeof(int64_t),INT64); if (n < 0) return printSocketReadError(); - retval=setTimer(ACQUISITION_TIME,GET_FLAG); + retval = setTimer(ACQUISITION_TIME,GET_FLAG); n = sendData(file_des,&retval,sizeof(int64_t),INT64); if (n < 0) return printSocketReadError(); #ifdef EIGERD - retval=setTimer(SUBFRAME_ACQUISITION_TIME,GET_FLAG); + retval = setTimer(SUBFRAME_ACQUISITION_TIME,GET_FLAG); n = sendData(file_des,&retval,sizeof(int64_t),INT64); if (n < 0) return printSocketReadError(); - retval=setTimer(SUBFRAME_DEADTIME,GET_FLAG); + retval = setTimer(SUBFRAME_DEADTIME,GET_FLAG); n = sendData(file_des,&retval,sizeof(int64_t),INT64); if (n < 0) return printSocketReadError(); #endif - retval=setTimer(FRAME_PERIOD,GET_FLAG); + retval = setTimer(FRAME_PERIOD,GET_FLAG); n = sendData(file_des,&retval,sizeof(int64_t),INT64); if (n < 0) return printSocketReadError(); #ifndef EIGERD - retval=setTimer(DELAY_AFTER_TRIGGER,GET_FLAG); + retval = setTimer(DELAY_AFTER_TRIGGER,GET_FLAG); n = sendData(file_des,&retval,sizeof(int64_t),INT64); if (n < 0) return printSocketReadError(); #endif #if !defined(EIGERD) && !defined(JUNGFRAUD) - retval=setTimer(GATES_NUMBER,GET_FLAG); + retval = setTimer(GATES_NUMBER,GET_FLAG); n = sendData(file_des,&retval,sizeof(int64_t),INT64); if (n < 0) return printSocketReadError(); #endif - retval=setTimer(CYCLES_NUMBER,GET_FLAG); + retval = setTimer(CYCLES_NUMBER,GET_FLAG); n = sendData(file_des,&retval,sizeof(int64_t),INT64); if (n < 0) return printSocketReadError(); - if (lockStatus==0) { + if (lockStatus == 0) { strcpy(lastClientIP,thisClientIP); } @@ -2266,141 +1859,145 @@ int send_update(int file_des) { int configure_mac(int file_des) { - int ret=OK,ret1=OK; - int n=0; - int retval=-100; - sprintf(mess,"configure mac failed\n"); + ret = OK; + memset(mess, 0, sizeof(mess)); + char args[9][50]; + memset(args, 0, sizeof(args)); + char retvals[3][50]; + memset(retvals, 0, sizeof(retvals)); + int iretval = -1; - // receive arguments - char arg[6][50]; - memset(arg, 0, sizeof(arg)); - n = receiveData(file_des,arg,sizeof(arg),OTHER); -#if defined(JUNGFRAUD) || defined(EIGERD) - int pos[3]={0,0,0}; - n = receiveData(file_des,pos,sizeof(pos),INT32); + if (receiveData(file_des, args, sizeof(args), OTHER) < 0) + return printSocketReadError(); + FILE_LOG(logDEBUG5, ("\n Configuring UDP Destination\n")); +#ifdef GOTTHARDD + FILE_LOG(logDEBUG5, ("Digital Test Bit %d\t", digitalTestBit); #endif - if (n < 0) return printSocketReadError(); - - uint32_t ipad; - uint64_t imacadd; - uint64_t idetectormacadd; - uint32_t udpport; - uint32_t udpport2; - uint32_t detipad; - sscanf(arg[0], "%x", &ipad); + uint32_t dstIp = 0; + sscanf(args[0], "%x", &dstIp); + FILE_LOG(logDEBUG5, ("Dst Ip Addr: %d.%d.%d.%d = 0x%x \n", + (dstIp >> 24) & 0xff, (dstIp >> 16) & 0xff, (dstIp >> 8) & 0xff, (dstIp) & 0xff, + dstIp)); + uint64_t dstMac = 0; #ifdef VIRTUAL - sscanf(arg[1], "%lx", &imacadd); + sscanf(args[1], "%lx", &dstMac); #else - sscanf(arg[1], "%llx", &imacadd); + sscanf(args[1], "%llx", &dstMac); #endif - sscanf(arg[2], "%x", &udpport); -#ifdef VIRTUAL - sscanf(arg[3], "%lx", &idetectormacadd); -#else - sscanf(arg[3], "%llx", &idetectormacadd); -#endif - sscanf(arg[4], "%x", &detipad); - sscanf(arg[5], "%x", &udpport2); - - if (differentClients && lockStatus) { - ret = FAIL; - sprintf(mess,"Detector locked by %s\n",lastClientIP); - cprintf(RED, "Warning: %s", mess); - } - else { -#ifdef VERBOSE - int i; - //#ifdef GOTTHARD - //printf("\ndigital_test_bit in server %d\t",digitalTestBit); - //#endif - printf("\nipadd %x\t",ipad); - printf("destination ip is %d.%d.%d.%d = 0x%x \n",(ipad>>24)&0xff,(ipad>>16)&0xff,(ipad>>8)&0xff,(ipad)&0xff,ipad); - printf("macad:%llx\n",imacadd); - for (i=0;i<6;i++) - printf("mac adress %d is 0x%x \n",6-i,(unsigned int)(((imacadd>>(8*i))&0xFF))); - printf("udp port:0x%x\n",udpport); - printf("detector macad:%llx\n",idetectormacadd); - for (i=0;i<6;i++) - printf("detector mac adress %d is 0x%x \n",6-i,(unsigned int)(((idetectormacadd>>(8*i))&0xFF))); - printf("detipad %x\n",detipad); - printf("udp port2:0x%x\n",udpport2); - printf("\n"); - printf("Configuring MAC at port %x\n", udpport); - -#if defined(JUNGFRAUD) || defined(EIGERD) - printf("Position: [%d,%d,%d]\n", pos[0],pos[1],pos[2]); -#endif -#endif - if(getRunStatus() == RUNNING){ - ret = stopStateMachine(); + FILE_LOG(logDEBUG5, ("Dst Mac Addr: (0x) ")); + { + int iloop = 5; + for (iloop = 5; iloop >= 0; --iloop) { + FILE_LOG(logDEBUG5, ("%x", (unsigned int)(((dstMac >> (8 * iloop)) & 0xFF)))); + if (iloop > 0) { + FILE_LOG(logDEBUG5, (":")); + } } - if(ret==FAIL) { - sprintf(mess,"Could not stop detector acquisition to configure mac\n"); - cprintf(RED, "Warning: %s", mess); - } - else { -#ifdef EIGERD - // change mac to hardware mac, (for 1 gbe) change ip to hardware ip - if (idetectormacadd != getDetectorMAC()){ - printf("*************************************************\n"); - printf("WARNING: actual detector mac address %llx does not match " - "the one from client %llx\n", - (long long unsigned int)getDetectorMAC(), - (long long unsigned int)idetectormacadd); - idetectormacadd = getDetectorMAC(); - printf("WARNING: Matched detectormac to the hardware mac now\n"); - printf("*************************************************\n"); - } - - // always remember the ip sent from the client (could be for 10g(if not dhcp)) - if (detipad != getDetectorIP()) - dhcpipad = detipad; - - //only for 1Gbe - if(!enableTenGigabitEthernet(-1)){ - printf("*************************************************\n"); - printf("WARNING: Using DHCP IP for Configuring MAC\n"); - printf("*************************************************\n"); - detipad = getDetectorIP(); - } else - detipad = dhcpipad; + } + FILE_LOG(logDEBUG5, (" = %llx\n", dstMac)); + uint32_t dstPort = 0; + sscanf(args[2], "%x", &dstPort); + FILE_LOG(logDEBUG5, ("Dst Port: %x\n", dstPort)); + uint32_t dstPort2 = 0; + sscanf(args[5], "%x", &dstPort2); + FILE_LOG(logDEBUG5, ("Dst Port2: %x\n", dstPort2)); + uint64_t srcMac = 0; +#ifdef VIRTUAL + sscanf(args[3], "%lx", &srcMac); +#else + sscanf(args[3], "%llx", &srcMac); #endif - retval=configureMAC(ipad,imacadd,idetectormacadd,detipad,udpport,udpport2,0); //digitalTestBit); - if(retval==-1) { - ret = FAIL; - sprintf(mess,"Configure Mac failed\n"); - cprintf(RED, "Warning: %s", mess); - } - else { - printf("Configure MAC successful\n"); + FILE_LOG(logDEBUG5, ("Src Mac Addr: (0x) ")); + { + int iloop = 5; + for (iloop = 5; iloop >= 0; --iloop) { + FILE_LOG(logDEBUG5, ("%x", (unsigned int)(((srcMac >> (8 * iloop)) & 0xFF)))); + if (iloop > 0) { + FILE_LOG(logDEBUG5, (":")); + } + } + } + FILE_LOG(logDEBUG5, (" = %llx\n", srcMac)); + uint32_t srcIp = 0; + sscanf(args[4], "%x", &srcIp); + FILE_LOG(logDEBUG5, ("Src Ip Addr: %d.%d.%d.%d = 0x%x \n", + (srcIp >> 24) & 0xff, (srcIp >> 16) & 0xff, (srcIp >> 8) & 0xff, (srcIp) & 0xff, + srcIp)); #if defined(JUNGFRAUD) || defined(EIGERD) - ret = setDetectorPosition(pos); - if (ret == FAIL) { - sprintf(mess,"could not set detector position\n"); - cprintf(RED, "Warning: %s", mess); - } -#endif - } -#ifdef VERBOSE - printf("Configured MAC with retval %d\n", retval); + int pos[3] = {0, 0, 0}; + sscanf(args[6], "%x", &pos[0]); + sscanf(args[7], "%x", &pos[1]); + sscanf(args[8], "%x", &pos[2]); + FILE_LOG(logDEBUG5, ("Position: [%d, %d, %d]\n", pos[0], pos[1], pos[2])); #endif + + // set only + if ((Server_VerifyLock() != FAIL)) { + + // stop detector if it was running + if (getRunStatus() != IDLE) { + ret = FAIL; + sprintf(mess, "Cannot configure mac when detector is not idle\n"); + FILE_LOG(logERROR,(mess)); + } + + else { +#ifdef EIGERD + // change mac to hardware mac + if (srcMac != getDetectorMAC()) { + FILE_LOG(logERROR, ("actual detector mac address %llx does not match " + "the one from client %llx\n", + (long long unsigned int)getDetectorMAC(), + (long long unsigned int)srcMac)); + srcMac = getDetectorMAC(); + FILE_LOG(logERROR,("matched detectormac to the hardware mac now\n")); } - } + // always remember the ip sent from the client (could be for 10g(if not dhcp)) + if (srcIp != getDetectorIP()) + dhcpipad = srcIp; - Server_SendResult(file_des, INT32, 1, &retval, sizeof(retval)); + //only for 1Gbe, change ip to hardware ip + if (!enableTenGigabitEthernet(-1)) { + FILE_LOG(logERROR, ("using DHCP IP for Configuring MAC\n")); + srcIp = getDetectorIP(); + } + // 10 gbe (use ip given from client) + else + srcIp = dhcpipad; -#ifdef EIGERD - if (ret != FAIL) { - char arg[2][50]; - memset(arg, 0, sizeof(arg)); - sprintf(arg[0],"%llx",(long long unsigned int)idetectormacadd); - sprintf(arg[1],"%x",detipad); - n += sendData(file_des,arg,sizeof(arg),OTHER); - } #endif +#ifdef GOTTHARDD + iretval = configureMAC(dstIp, dstMac, srcMac, srcIp, dstPort, dstPort2, digitalTestBit); + FILE_LOG(logDEBUG5, ("Configure mac retval: %d\n", iretval)); + FILE_LOG(logINFO, ("Configure MAC successful: %d\n", iretval)); +#else + iretval = configureMAC(dstIp, dstMac, srcMac, srcIp, dstPort, dstPort2); + FILE_LOG(logDEBUG5, ("Configure mac retval: %d\n", iretval)); - return ret; + if (iretval == -1) { + ret = FAIL; + sprintf(mess,"Configure Mac failed\n"); + FILE_LOG(logERROR,(mess)); + } else { + FILE_LOG(logINFO, ("Configure MAC successful\n")); + ret = setDetectorPosition(pos); + if (ret == FAIL) { + sprintf(mess, "Could not set detector position\n"); + FILE_LOG(logERROR,(mess)); + } + } +#endif + // set retval vals + if (ret != FAIL) { + sprintf(retvals[0],"%x", iretval); + sprintf(retvals[1],"%llx", (long long unsigned int)srcMac); + sprintf(retvals[2],"%x", srcIp); + } + } + } + + return Server_SendResult(file_des, OTHER, 1, retvals, sizeof(retvals)); } @@ -2408,63 +2005,49 @@ int configure_mac(int file_des) { int load_image(int file_des) { - int ret=OK,ret1=OK; - int n=0; - int retval=-1; - sprintf(mess,"Loading image failed\n"); + ret = OK; + memset(mess, 0, sizeof(mess)); + int args[2] = {-1, -1}; + int retval = -1; + + if (receiveData(file_des, args, sizeof(args), INT32) < 0) + return printSocketReadError(); + enum imageType index = args[0]; + char* ImageVals = NULL; + if (args[1] > 0) { + ImageVals = (char*)malloc(args[1]); + if (receiveData(file_des, ImageVals, args[1], OTHER) < 0) { + free(ImageVals); + return printSocketReadError(); + } + } + FILE_LOG(logDEBUG5, ("Loading %s image (ind:%d)\n", (index == DARK_IMAGE) ? "dark" : + ((index == GAIN_IMAGE) ? "gain" : "unknown"), index)); #ifndef GOTTHARDD - //to receive any arguments - while (n > 0) - n = receiveData(file_des,mess,MAX_STR_LENGTH,OTHER); - ret = FAIL; - sprintf(mess,"Function (Load Image) is not implemented for this detector\n"); - cprintf(RED, "Warning: %s", mess); + functionNotImplemented(); #else - // receive arguments - enum imageType index=0; - char ImageVals[dataBytes] = {0}; - n = receiveData(file_des,&index,sizeof(index),INT32); - if (n < 0) return printSocketReadError(); - - n = receiveData(file_des,ImageVals,dataBytes,OTHER); - if (n < 0) return printSocketReadError(); - - // execute action - if (differentClients && lockStatus) { - ret = FAIL; - sprintf(mess,"Detector locked by %s\n",lastClientIP); - cprintf(RED, "Warning: %s", mess); - } - else { + // set only + if (Server_VerifyLock() != FAIL) { switch (index) { case DARK_IMAGE : -#ifdef VERBOSE - printf("Loading Dark image\n"); -#endif case GAIN_IMAGE : -#ifdef VERBOSE - printf("Loading Gain image\n"); -#endif - retval=loadImage(index,ImageVals); - if (retval==-1) { + retval = loadImage(index, ImageVals); + FILE_LOG(logDEBUG5, ("Loading image retval: %d\n", retval)); + if (retval == -1) { ret = FAIL; - cprintf(RED, "Warning: %s", mess); + sprintf(mess, "Could not load image\n"); + FILE_LOG(logERROR,(mess)); } break; default: - ret = FAIL; - sprintf(mess,"Load Image Index (%d) is not implemented for this detector\n", (int)index); - cprintf(RED, "Warning: %s", mess); + modeNotImplemented("Image index", (int)index); break; } } #endif - - Server_SendResult(file_des, INT32, 1, &retval, sizeof(retval)); - - return ret; + return Server_SendResult(file_des, INT32, 1, &retval, sizeof(retval)); } @@ -2473,47 +2056,30 @@ int load_image(int file_des) { int read_counter_block(int file_des) { - int ret=OK,ret1=OK; - int n=0; - char CounterVals[dataBytes]; - memset(CounterVals, 0, dataBytes); - sprintf(mess,"Read counter block failed\n"); + ret = OK; + memset(mess, 0, sizeof(mess)); + int startACQ = -1; + char retval[dataBytes]; + memset(retval, 0, dataBytes); + + if (receiveData(file_des, &startACQ, sizeof(startACQ), INT32) < 0) + return printSocketReadError(); + FILE_LOG(logDEBUG5, ("Read counter block with start acq bit: %d\n", startACQ)); #ifndef GOTTHARDD - //to receive any arguments - while (n > 0) - n = receiveData(file_des,mess,MAX_STR_LENGTH,OTHER); - ret = FAIL; - sprintf(mess,"Function (Read Counter Block) is not implemented for this detector\n"); - cprintf(RED, "Warning: %s", mess); + functionNotImplemented(); #else - // receive arguments - int startACQ=-1; - n = receiveData(file_des,&startACQ,sizeof(startACQ),INT32); - if (n < 0) return printSocketReadError(); - - // execute action - if (differentClients && lockStatus) { - ret = FAIL; - sprintf(mess,"Detector locked by %s\n",lastClientIP); - cprintf(RED, "Warning: %s", mess); - } - else { - ret=readCounterBlock(startACQ,CounterVals); - if (ret == FAIL) - cprintf(RED, "Warning: %s", mess); -#ifdef VERBOSE - int i; - for(i=0;i<6;i++) - printf("%d:%d\t",i,CounterVals[i]); -#endif + // only set + if (Server_VerifyLock() != FAIL) { + ret = readCounterBlock(startACQ, retval); + if (ret == FAIL) { + strcpy(mess, "Could not read counter block\n"); + FILE_LOG(logERROR,(mess)); + } } #endif - - Server_SendResult(file_des, OTHER, 1, CounterVals, dataBytes); - - return ret; + return Server_SendResult(file_des, OTHER, 1, retval, dataBytes); } @@ -2521,84 +2087,48 @@ int read_counter_block(int file_des) { int reset_counter_block(int file_des) { - int ret=OK,ret1=OK; - int n=0; - sprintf(mess,"Reset counter block failed\n"); + ret = OK; + memset(mess, 0, sizeof(mess)); + int startACQ = -1; + char retval[dataBytes]; + memset(retval, 0, dataBytes); + + if (receiveData(file_des, &startACQ, sizeof(startACQ), INT32) < 0) + return printSocketReadError(); + FILE_LOG(logDEBUG5, ("Reset counter block with start acq bit: %d\n", startACQ)); #ifndef GOTTHARDD - //to receive any arguments - while (n > 0) - n = receiveData(file_des,mess,MAX_STR_LENGTH,OTHER); - ret = FAIL; - sprintf(mess,"Function (Reset Counter Block) is not implemented for this detector\n"); - cprintf(RED, "Warning: %s", mess); + functionNotImplemented(); #else - // receive arguments - int startACQ=-1; - n = receiveData(file_des,&startACQ,sizeof(startACQ),INT32); - if (n < 0) return printSocketReadError(); - - // execute action - if (differentClients && lockStatus) { - ret = FAIL; - sprintf(mess,"Detector locked by %s\n",lastClientIP); - cprintf(RED, "Warning: %s", mess); - } - else { - ret=resetCounterBlock(startACQ); - if (ret == FAIL) - cprintf(RED, "Warning: %s", mess); + // only set + if (Server_VerifyLock() != FAIL) { + ret = resetCounterBlock(startACQ, retval); + if (ret == FAIL) { + strcpy(mess, "Could not reset counter block\n"); + FILE_LOG(logERROR, (mess)); + } } #endif - - Server_SendResult(file_des, INT32, 1, NULL, 0); - - return ret; + return Server_SendResult(file_des, INT32, 1, NULL, 0); } -int calibrate_pedestal(int file_des){ - int ret=OK,ret1=OK; - int n=0; - int retval=-1; - sprintf(mess,"calibrate pedestal failed\n"); +int calibrate_pedestal(int file_des) { + ret = OK; + memset(mess, 0, sizeof(mess)); + int frames = -1; + int retval = -1; + if (receiveData(file_des, &frames, sizeof(frames), INT32) < 0) + return printSocketReadError(); + FILE_LOG(logDEBUG5, ("Calibrate pedestal, frames: %d\n", frames)); -#ifndef GOTTHARDD - //to receive any arguments - while (n > 0) - n = receiveData(file_des,mess,MAX_STR_LENGTH,OTHER); - ret = FAIL; - sprintf(mess,"Function (Calibrate Pedestal) is not implemented for this detector\n"); - cprintf(RED, "Warning: %s", mess); -#else - - // receive arguments - int frames=-1; - n = receiveData(file_des,&frames,sizeof(frames),INT32); - if (n < 0) return printSocketReadError(); - - - // execute action - if (differentClients && lockStatus) { - ret = FAIL; - sprintf(mess,"Detector locked by %s\n",lastClientIP); - cprintf(RED, "Warning: %s", mess); - } - else { - ret=calibratePedestal(frames); - if (ret == FAIL) - cprintf(RED, "Warning: %s", mess); - } -#endif - - Server_SendResult(file_des, INT32, 1, &retval, sizeof(retval)); - - return ret; + functionNotImplemented(); + return Server_SendResult(file_des, INT32, 1, &retval, sizeof(retval)); } @@ -2609,432 +2139,177 @@ int calibrate_pedestal(int file_des){ int enable_ten_giga(int file_des) { - int ret=OK,ret1=OK; - int n=0; - int retval=-1; - sprintf(mess,"Enabling/disabling 10GbE failed\n"); + ret = OK; + memset(mess, 0, sizeof(mess)); + int arg = -1; + int retval = -1; + + if (receiveData(file_des, &arg, sizeof(arg), INT32) < 0) + return printSocketReadError(); + FILE_LOG(logDEBUG5, ("Enable/ Disable 10GbE : %d\n", arg)); - // execute action #ifndef EIGERD - //to receive any arguments - while (n > 0) - n = receiveData(file_des,mess,MAX_STR_LENGTH,OTHER); - ret = FAIL; - sprintf(mess,"Function (Enable 10 GbE) is not implemented for this detector\n"); - cprintf(RED, "Warning: %s", mess); + functionNotImplemented(); #else - - // receive arguments - int arg=-1; - n = receiveData(file_des,&arg,sizeof(arg),INT32); - if (n < 0) return printSocketReadError(); - - // execute action - if (differentClients && lockStatus && arg!=-1) { - ret = FAIL; - sprintf(mess,"Detector locked by %s\n",lastClientIP); - cprintf(RED, "Warning: %s", mess); - } - else { -#ifdef VERBOSE - printf("Enabling/Disabling 10Gbe :%d \n",arg); -#endif - retval=enableTenGigabitEthernet(arg); - if((arg != -1) && (retval != arg)) { - ret=FAIL; - cprintf(RED, "Warning: %s", mess); - } + // set & get + if ((arg == -1) || ((arg != -1) && (Server_VerifyLock() != FAIL))) { + retval = enableTenGigabitEthernet(arg); + FILE_LOG(logDEBUG5, ("10GbE: %d\n", retval)); + validate(arg, retval, "enable/disable 10GbE", 0); } #endif - - Server_SendResult(file_des, INT32, 1, &retval, sizeof(retval)); - - return ret; + return Server_SendResult(file_des, INT32, 1, &retval, sizeof(retval)); } -int set_all_trimbits(int file_des){ - int ret=OK,ret1=OK; - int n=0; - int retval=-1; - sprintf(mess,"setting all trimbits failed\n"); +int set_all_trimbits(int file_des) { + ret = OK; + memset(mess, 0, sizeof(mess)); + int arg = -1; + int retval = -1; + + if (receiveData(file_des, &arg, sizeof(arg), INT32) < 0) + return printSocketReadError(); + FILE_LOG(logDEBUG5, ("Set all trmbits to %d\n", arg)); #ifndef EIGERD - //to receive any arguments - while (n > 0) - n = receiveData(file_des,mess,MAX_STR_LENGTH,OTHER); - ret = FAIL; - sprintf(mess,"Function (Set All Trimbits) is not implemented for this detector\n"); - cprintf(RED, "Warning: %s", mess); + functionNotImplemented(); #else - // receive arguments - int arg=-1; - n = receiveData(file_des,&arg,sizeof(arg),INT32); - if (n < 0) return printSocketReadError(); - - - // execute action - if (differentClients && lockStatus && arg!=-1) { - ret = FAIL; - sprintf(mess,"Detector locked by %s\n",lastClientIP); - cprintf(RED, "Warning: %s", mess); + // set + if (arg >= 0 && Server_VerifyLock() != FAIL) { + ret = setAllTrimbits(arg); + //changes settings to undefined + setSettings(UNDEFINED); + FILE_LOG(logERROR, ("Settings has been changed to undefined (change all trimbits)\n")); } - else { -#ifdef VERBOSE - printf("setting all trimbits to %d\n",arg); + // get + retval = getAllTrimbits(); + FILE_LOG(logDEBUG5, ("All trimbits: %d\n", retval)); + validate(arg, retval, "set all trimbits", 0); #endif - if(arg < -1){ - ret = FAIL; - strcpy(mess,"Cant set trimbits to this value\n"); - cprintf(RED, "Warning: %s", mess); - }else { - if(arg >= 0){ - ret = setAllTrimbits(arg); - //changes settings to undefined - setSettings(UNDEFINED); - cprintf(RED,"Settings has been changed to undefined (change all trimbits)\n"); - } - retval = getAllTrimbits(); - if (arg!=-1 && arg!=retval) { - ret=FAIL; - sprintf(mess,"Could not set all trimbits: should be %d but is %d\n", arg, retval); - cprintf(RED, "Warning: %s", mess); - } - } - } -#endif - - Server_SendResult(file_des, INT32, 1, &retval, sizeof(retval)); - - return ret; + return Server_SendResult(file_des, INT32, 1, &retval, sizeof(retval)); } + + int set_ctb_pattern(int file_des) { - int ret=OK,ret1=OK; - int n=0; - sprintf(mess,"Could not set pattern\n"); - -#ifndef MYTHEN3D - //to receive any arguments - while (n > 0) - n = receiveData(file_des,mess,MAX_STR_LENGTH,OTHER); - - ret = FAIL; - sprintf(mess,"Function (Set CTB Pattern) is not implemented for this detector\n"); - cprintf(RED, "Error: %s", mess); - - Server_SendResult(file_des, INT32, 0, NULL, 0);// make sure client doesnt expect a retval if not jctb - - return ret; - -#else - - int retval=-1; - int mode = -1; - int addr = -1, level = -1, nl = -1, start = -1, stop = -1; - uint64_t word = -1,retval64 = -1, t = -1; - - n = receiveDataOnly(file_des, &mode, sizeof(mode)); - printf("pattern mode is %d\n",mode); - - switch (mode) { - - case 0: //sets word - n = receiveDataOnly(file_des,&addr,sizeof(addr)); - n = receiveDataOnly(file_des,&word,sizeof(word)); - ret=OK; - - printf("pattern addr is %d %llx\n",addr, word); - switch (addr) { - case -1: - retval64=writePatternIOControl(word); - break; - case -2: - retval64=writePatternClkControl(word); - break; - default: - retval64=writePatternWord(addr,word); - }; - - - //write word; - //@param addr address of the word, -1 is I/O control register, -2 is clk control register - //@param word 64bit word to be written, -1 gets - - Server_SendResult(file_des, INT32, 0, &retval64, sizeof(retval64)); - - break; - - case 1: //pattern loop - // printf("loop\n"); - n = receiveDataOnly(file_des,&level,sizeof(level)); - n = receiveDataOnly(file_des,&start,sizeof(start)); - n = receiveDataOnly(file_des,&stop,sizeof(stop)); - n = receiveDataOnly(file_des,&nl,sizeof(nl)); - - - - // printf("level %d start %x stop %x nl %d\n",level, start, stop, nl); - /** Sets the pattern or loop limits in the CTB - @param level -1 complete pattern, 0,1,2, loop level - @param start start address if >=0 - @param stop stop address if >=0 - @param n number of loops (if level >=0) - @returns OK/FAIL - */ - ret=setPatternLoop(level, &start, &stop, &nl); - - Server_SendResult(file_des, INT32, 0, retval, sizeof(retval)); -/* 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 - printf("wait\n"); - n = receiveDataOnly(file_des,&level,sizeof(level)); - n = receiveDataOnly(file_des,&addr,sizeof(addr)); - - - - /** Sets the wait address in the CTB - @param level 0,1,2, wait level - @param addr wait address, -1 gets - @returns actual value - */ - printf("wait addr %d %x\n",level, addr); - retval=setPatternWaitAddress(level,addr); - printf("ret: wait addr %d %x\n",level, retval); - ret=OK; - - Server_SendResult(file_des, INT32, 0, &retval, sizeof(retval)); - - break; - - - case 3: //wait time - printf("wait time\n"); - 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); - - Server_SendResult(file_des, INT32, 0, &retval64, sizeof(retval64)); - break; - - - - case 4: - n = receiveDataOnly(file_des,pat,sizeof(pat)); - for (addr=0; addr<1024; addr++) - writePatternWord(addr,word); - ret=OK; - retval=0; - - Server_SendResult(file_des, INT32, 0, &retval64, sizeof(retval64)); - - break; - - - - default: - ret=FAIL; - printf(mess); - sprintf(mess,"%s - wrong mode %d\n",mess, mode); - - Server_SendResult(file_des, INT32, 0, NULL, 0); - } - - - return ret; -#endif + ret = OK; + memset(mess, 0, sizeof(mess)); + functionNotImplemented(); + return Server_SendResult(file_des, INT32, 1, NULL, 0); } + int write_adc_register(int file_des) { - int ret=OK, ret1=OK; - int n=0; - int retval=-1; - sprintf(mess,"write to adc register failed\n"); + ret = OK; + memset(mess, 0, sizeof(mess)); + int args[2] = {-1, -1}; + + if (receiveData(file_des, args, sizeof(args), INT32) < 0) + return printSocketReadError(); + int addr = args[0]; + int val = args[1]; + FILE_LOG(logDEBUG5, ("Writing 0x%x to ADC Register 0x%x\n", val, addr)); #ifndef JUNGFRAUD - //to receive any arguments - while (n > 0) - n = receiveData(file_des,mess,MAX_STR_LENGTH,OTHER); - ret = FAIL; - sprintf(mess,"Function (Write ADC Register) is not implemented for this detector\n"); - cprintf(RED, "Warning: %s", mess); + functionNotImplemented(); #else - - // receive arguments - int arg[2]={-1,-1}; - n = receiveData(file_des,arg,sizeof(arg),INT32); - if (n < 0) return printSocketReadError(); - int addr=arg[0]; - int val=arg[1]; - - // execute action - if (differentClients && lockStatus) { - ret = FAIL; - sprintf(mess,"Detector locked by %s\n",lastClientIP); - cprintf(RED, "Warning: %s", mess); - } - else { -#ifdef VERBOSE - printf("writing to register 0x%x data 0x%x\n", addr, val); + // only set + if (Server_VerifyLock() != FAIL) + setAdc(addr, val); #endif - setAdc(addr,val); -#ifdef VERBOSE - printf("Data set to 0x%x\n", retval); -#endif -#endif - - Server_SendResult(file_des, INT32, 1, &retval, sizeof(retval)); - - return ret; + return Server_SendResult(file_des, INT32, 1, NULL, 0); } int set_counter_bit(int file_des) { - int ret=OK,ret1=OK; - int n=0; - int retval=-1; - sprintf(mess,"set counter bit failed \n"); + ret = OK; + memset(mess, 0, sizeof(mess)); + int arg = -1; + int retval = -1; + + if (receiveData(file_des, &arg, sizeof(arg), INT32) < 0) + return printSocketReadError(); + FILE_LOG(logDEBUG5, ("Set counter bit with value: %d\n", arg)); #ifndef EIGERD - //to receive any arguments - while (n > 0) - n = receiveData(file_des,mess,MAX_STR_LENGTH,OTHER); - ret = FAIL; - strcpy(mess,"Function (Set Counter Bit) is not implemented for this detector\n"); - cprintf(RED, "Warning: %s", mess); + functionNotImplemented(); #else - // receive arguments - int arg=-1; - n = receiveData(file_des,&arg,sizeof(arg),INT32); - if (n < 0) return printSocketReadError(); - - // execute action - if (differentClients && lockStatus && arg!=-1) { - ret = FAIL; - sprintf(mess,"Detector locked by %s\n",lastClientIP); - cprintf(RED, "Warning: %s", mess); + // set + if (arg >= 0 && Server_VerifyLock() != FAIL) { + setCounterBit(arg); } - else { -#ifdef VERBOSE - printf("Getting/Setting/Resetting counter bit :%d \n",arg); + // get + retval = setCounterBit(-1); + FILE_LOG(logDEBUG5, ("Set counter bit retval: %d\n", retval)); + validate(arg, retval, "set counter bit", 0); #endif - retval=setCounterBit(arg); - if((arg != -1) && (retval != arg)) { - ret=FAIL; - cprintf(RED, "Warning: %s", mess); - } - } -#endif - - Server_SendResult(file_des, INT32, 1, &retval, sizeof(retval)); - - return ret; + return Server_SendResult(file_des, INT32, 1, &retval, sizeof(retval)); } + int pulse_pixel(int file_des) { - int ret=OK,ret1=OK; - int n=0; - sprintf(mess,"pulse pixel failed\n"); + ret = OK; + memset(mess, 0, sizeof(mess)); + int args[3] = {-1,-1,-1}; + + if (receiveData(file_des, args, sizeof(args), INT32) < 0) + return printSocketReadError(); + FILE_LOG(logDEBUG5, ("Pulse pixel, n: %d, x: %d, y: %d\n", args[0], args[1], args[2])); #ifndef EIGERD - //to receive any arguments - while (n > 0) - n = receiveData(file_des,mess,MAX_STR_LENGTH,OTHER); - ret = FAIL; - strcpy(mess,"Function (Pulse Pixel) is not implemented for this detector\n"); - cprintf(RED, "Warning: %s", mess); + functionNotImplemented(); #else - - // receive arguments - int arg[3]={-1,-1,-1}; - n = receiveData(file_des,arg,sizeof(arg),INT32); - if (n < 0) return printSocketReadError(); - - // execute action - if (differentClients && lockStatus) { - ret = FAIL; - sprintf(mess,"Detector locked by %s\n",lastClientIP); - cprintf(RED, "Warning: %s", mess); - } - else { - ret=pulsePixel(arg[0],arg[1],arg[2]); - if (ret == FAIL) - cprintf(RED, "Warning: %s", mess); + // only set + if (Server_VerifyLock() != FAIL) { + ret = pulsePixel(args[0], args[1], args[2]); + if (ret == FAIL) { + strcpy(mess, "Could not pulse pixel\n"); + FILE_LOG(logERROR,(mess)); + } } #endif - - Server_SendResult(file_des, INT32, 1, NULL, 0); - - return ret; + return Server_SendResult(file_des, INT32, 1, NULL, 0); } int pulse_pixel_and_move(int file_des) { - int ret=OK,ret1=OK; - int n=0; - sprintf(mess,"pulse pixel and move failed\n"); + ret = OK; + memset(mess, 0, sizeof(mess)); + int args[3] = {-1,-1,-1}; + + if (receiveData(file_des, args, sizeof(args), INT32) < 0) + return printSocketReadError(); + FILE_LOG(logDEBUG5, ("Pulse pixel and move, n: %d, x: %d, y: %d\n", + args[0], args[1], args[2])); #ifndef EIGERD - //to receive any arguments - while (n > 0) - n = receiveData(file_des,mess,MAX_STR_LENGTH,OTHER); - ret = FAIL; - strcpy(mess,"Function (Pulse Pixel and Move) is not implemented for this detector\n"); - cprintf(RED, "Warning: %s", mess); + functionNotImplemented(); #else - - // receive arguments - int arg[3]={-1,-1,-1}; - n = receiveData(file_des,arg,sizeof(arg),INT32); - if (n < 0) return printSocketReadError(); - - // execute action - if (differentClients && lockStatus) { - ret = FAIL; - sprintf(mess,"Detector locked by %s\n",lastClientIP); - cprintf(RED, "Warning: %s", mess); - } - else { - ret=pulsePixelNMove(arg[0],arg[1],arg[2]); - if (ret == FAIL) - cprintf(RED, "Warning: %s", mess); + // only set + if (Server_VerifyLock() != FAIL) { + ret = pulsePixelNMove(args[0], args[1], args[2]); + if (ret == FAIL) { + strcpy(mess, "Could not pulse pixel and move\n"); + FILE_LOG(logERROR,(mess)); + } } #endif - - Server_SendResult(file_des, INT32, 1, NULL, 0); - - return ret; + return Server_SendResult(file_des, INT32, 1, NULL, 0); } @@ -3043,40 +2318,27 @@ int pulse_pixel_and_move(int file_des) { int pulse_chip(int file_des) { - int ret=OK,ret1=OK; - int n=0; - sprintf(mess,"pulse chip failed\n"); + ret = OK; + memset(mess, 0, sizeof(mess)); + int arg = -1; + + if (receiveData(file_des, &arg, sizeof(arg), INT32) < 0) + return printSocketReadError(); + FILE_LOG(logDEBUG5, ("Pulse chip: %d\n", arg)); #ifndef EIGERD - //to receive any arguments - while (n > 0) - n = receiveData(file_des,mess,MAX_STR_LENGTH,OTHER); - ret = FAIL; - strcpy(mess,"Function (Pulse Chip) is not implemented for this detector\n"); - cprintf(RED, "Warning: %s", mess); + functionNotImplemented(); #else - - // receive arguments - int arg = -1; - n = receiveData(file_des,&arg,sizeof(arg),INT32); - if (n < 0) return printSocketReadError(); - - // execute action - if (differentClients && lockStatus) { - ret = FAIL; - sprintf(mess,"Detector locked by %s\n",lastClientIP); - cprintf(RED, "Warning: %s", mess); - } - else { - ret=pulseChip(arg); - if (ret == FAIL) - cprintf(RED, "Warning: %s", mess); + // only set + if (Server_VerifyLock() != FAIL) { + ret = pulseChip(arg); + if (ret == FAIL) { + strcpy(mess, "Could not pulse chip\n"); + FILE_LOG(logERROR,(mess)); + } } #endif - - Server_SendResult(file_des, INT32, 1, NULL, 0); - - return ret; + return Server_SendResult(file_des, INT32, 1, NULL, 0); } @@ -3084,61 +2346,44 @@ int pulse_chip(int file_des) { int set_rate_correct(int file_des) { - int ret=OK,ret1=OK; - int n=0; - sprintf(mess,"Set rate correct failed\n"); + ret = OK; + memset(mess, 0, sizeof(mess)); + int64_t tau_ns = -1; + + if (receiveData(file_des, &tau_ns, sizeof(tau_ns), INT64) < 0) + return printSocketReadError(); + FILE_LOG(logDEBUG5, ("Set rate correct with tau %lld\n", (long long int)tau_ns)); #ifndef EIGERD - //to receive any arguments - while (n > 0) - n = receiveData(file_des,mess,MAX_STR_LENGTH,OTHER); - ret=FAIL; - sprintf(mess,"Function (Rate Correction) is not implemented for this detector\n"); - cprintf(RED, "Warning: %s", mess); + functionNotImplemented(); #else + // only set + if (Server_VerifyLock() != FAIL) { - // receive arguments - int64_t tau_ns=-1; - n = receiveData(file_des,&tau_ns,sizeof(tau_ns),INT64); - if (n < 0) return printSocketReadError(); + int dr = setDynamicRange(-1); - // execute action - if (differentClients && lockStatus) { - ret = FAIL; - sprintf(mess,"Detector locked by %s\n",lastClientIP); - cprintf(RED, "Warning: %s", mess); - } - else { - printf("Setting rate correction to %lld ns\n",(long long int)tau_ns); - //set rate - //wrong bit mode - if((setDynamicRange(-1)!=32) && (setDynamicRange(-1)!=16) && (tau_ns!=0)){ - ret=FAIL; + // switching on in wrong bit mode + if ((tau_ns != 0) && (dr != 32) && (dr != 16)) { + ret = FAIL; strcpy(mess,"Rate correction Deactivated, must be in 32 or 16 bit mode\n"); - cprintf(RED, "Warning: %s", mess); + FILE_LOG(logERROR,(mess)); } - //16 or 32 bit mode - else{ - if(tau_ns < 0) + + // switching on in right mode + else { + if (tau_ns < 0) tau_ns = getDefaultSettingsTau_in_nsec(); - else if(tau_ns > 0){ + else if (tau_ns > 0) { //changing tau to a user defined value changes settings to undefined setSettings(UNDEFINED); - cprintf(RED,"Settings has been changed to undefined (tau changed)\n"); + FILE_LOG(logERROR, ("Settings has been changed to undefined (tau changed)\n")); } - int64_t retval = setRateCorrection(tau_ns); - if(tau_ns != retval){ - ret=FAIL; - cprintf(RED, "Warning: %s", mess); - } + validate64(tau_ns, retval, "set rate correction", 0); } } #endif - - Server_SendResult(file_des, INT32, 1, NULL, 0); - - return ret; + return Server_SendResult(file_des, INT32, 1, NULL, 0); } @@ -3146,30 +2391,18 @@ int set_rate_correct(int file_des) { int get_rate_correct(int file_des) { - int ret=OK,ret1=OK; - int n=0; - int64_t retval=-1; - sprintf(mess,"Get Rate correct failed\n"); + ret = OK; + memset(mess, 0, sizeof(mess)); + int64_t retval = -1; + FILE_LOG(logDEBUG5, ("Getting rate correction\n")); #ifndef EIGERD - //to receive any arguments - while (n > 0) - n = receiveData(file_des,mess,MAX_STR_LENGTH,OTHER); - ret=FAIL; - sprintf(mess,"Function (Get Rate Correction) is not implemented for this detector\n"); - cprintf(RED, "Warning: %s", mess); + functionNotImplemented(); #else - - - // execute action retval = getCurrentTau(); - printf("Getting rate correction %lld\n",(long long int)retval); - + FILE_LOG(logDEBUG5, ("Tau: %lld\n", (long long int)retval)); #endif - - Server_SendResult(file_des, INT64, 1, &retval, sizeof(retval)); - - return ret; + return Server_SendResult(file_des, INT64, 1, &retval, sizeof(retval)); } @@ -3177,84 +2410,60 @@ int get_rate_correct(int file_des) { int set_network_parameter(int file_des) { - int ret=OK,ret1=OK; - int n=0; - int retval=-1; - sprintf(mess,"set network parameter failed\n"); + ret = OK; + memset(mess, 0, sizeof(mess)); + int args[2] = {-1,-1}; + int retval = -1; -#if !defined(EIGERD) && !defined(JUNGFRAUD) - //to receive any arguments - while (n > 0) - n = receiveData(file_des,mess,MAX_STR_LENGTH,OTHER); - ret=FAIL; - sprintf(mess,"Function(Set Network Parmaeter) is not implemented for this detector\n"); - cprintf(RED, "Warning: %s", mess); + if (receiveData(file_des, args, sizeof(args), INT32) < 0) + return printSocketReadError(); + enum networkParameter mode = args[0]; + int value = args[1]; + enum NETWORKINDEX serverIndex = 0; + FILE_LOG(logDEBUG5, ("Set network parameter index %d to %d\n", mode, value)); + +#ifdef GOTTHARDD + functionNotImplemented(); #else - - enum NETWORKINDEX index; - - // receive arguments - enum networkParameter mode=0; - int value=-1; - n = receiveData(file_des,&mode,sizeof(mode),INT32); - if (n < 0) return printSocketReadError(); - - n = receiveData(file_des,&value,sizeof(value),INT32); - if (n < 0) return printSocketReadError(); - - // execute action - if (differentClients && lockStatus && value >= 0) { - ret = FAIL; - sprintf(mess,"Detector locked by %s\n",lastClientIP); - cprintf(RED, "Warning: %s", mess); - } - else { -#ifdef VERBOSE - printf("setting network parameter mode %d to %d\n",(int)mode,value); -#endif + // set & get + if ((value == -1) || ((value != -1) && (Server_VerifyLock() != FAIL))) { + // check index switch (mode) { - #ifdef EIGERD case FLOW_CONTROL_10G: - index = FLOWCTRL_10G; + serverIndex = FLOWCTRL_10G; break; case DETECTOR_TXN_DELAY_LEFT: - index = TXN_LEFT; + serverIndex = TXN_LEFT; break; case DETECTOR_TXN_DELAY_RIGHT: - index = TXN_RIGHT; + serverIndex = TXN_RIGHT; break; #endif case DETECTOR_TXN_DELAY_FRAME: - index = TXN_FRAME; + serverIndex = TXN_FRAME; #ifdef JUNGFRAUD if (value > MAX_TIMESLOT_VAL) { - ret=FAIL; - sprintf(mess,"Transmission delay %d should be in range: 0 - %d\n", value, MAX_TIMESLOT_VAL); - cprintf(RED, "Warning: %s", mess); + ret = FAIL; + sprintf(mess,"Transmission delay %d should be in range: 0 - %d\n", + value, MAX_TIMESLOT_VAL); + FILE_LOG(logERROR, (mess)); } #endif break; default: - ret=FAIL; - sprintf(mess,"Network Parameter Index (%d) is not implemented for this detector\n",(int) mode); - cprintf(RED, "Warning: %s", mess); + modeNotImplemented("Image index", (int)serverIndex); break; } - if (ret==OK) { - retval=setNetworkParameter(index, value); - if ((retval!=value) && (value>=0)) { - ret=FAIL; - sprintf(mess,"could not change network parameter mode %d: should be %d but is %d \n",index, value, retval); - cprintf(RED, "Warning: %s", mess); - } + // valid index + if (ret == OK) { + retval = setNetworkParameter(serverIndex, value); + FILE_LOG(logDEBUG5, ("Network Parameter index %d: %d\n", serverIndex, retval)); + validate(value, retval, "set network parameter", 0); } } #endif - - Server_SendResult(file_des, INT32, 1, &retval, sizeof(retval)); - - return ret; + return Server_SendResult(file_des, INT32, 1, &retval, sizeof(retval)); } @@ -3263,131 +2472,115 @@ int set_network_parameter(int file_des) { int program_fpga(int file_des) { - int ret=OK,ret1=OK; - int n=0; - sprintf(mess,"program FPGA failed\n"); + ret = OK; + memset(mess, 0, sizeof(mess)); + FILE_LOG(logDEBUG5, ("Programming FPGA\n")); #ifndef JUNGFRAUD //to receive any arguments + int n = 0; while (n > 0) n = receiveData(file_des,mess,MAX_STR_LENGTH,OTHER); - ret=FAIL; - sprintf(mess,"Function (Program FPGA) is not implemented for this detector\n"); - cprintf(RED, "Warning: %s", mess); + functionNotImplemented(); #else - if (!debugflag) { - //to receive any arguments - while (n > 0) - n = receiveData(file_des,mess,MAX_STR_LENGTH,OTHER); - ret=FAIL; - sprintf(mess,"FPGA cannot be programmed in this mode. " - "Restart on-board detector server with -update for update mode to continue.\n"); - cprintf(RED, "Warning: %s", mess); - } + // only set + if (Server_VerifyLock() != FAIL) { - else { - printf("Programming FPGA..."); - size_t filesize = 0; - size_t totalsize = 0; - size_t unitprogramsize = 0; - char* fpgasrc = NULL; - FILE* fp = NULL; - - // receive arguments - filesize - n = receiveData(file_des,&filesize,sizeof(filesize),INT32); - if (n < 0) return printSocketReadError(); - totalsize = filesize; -#ifdef VERY_VERBOSE - printf("\n\n Total size is:%d\n",totalsize); -#endif - - // execute action - if (differentClients && lockStatus) { + // not in programming mode + if (debugflag != PROGRAMMING_MODE) { + //to receive any arguments + int n = 1; + while (n > 0) + n = receiveData(file_des, mess, MAX_STR_LENGTH, OTHER); ret = FAIL; - sprintf(mess,"Detector locked by %s\n",lastClientIP); - cprintf(RED, "Warning: %s", mess); + sprintf(mess,"FPGA cannot be programmed in this mode. " + "Restart on-board detector server with -update for programming mode.\n"); + FILE_LOG(logERROR,(mess)); } + else { - //opening file pointer to flash and telling FPGA to not touch flash - if(startWritingFPGAprogram(&fp) != OK) { - ret=FAIL; + FILE_LOG(logINFOBLUE, ("Programming FPGA...\n")); + + size_t filesize = 0; + size_t totalsize = 0; + size_t unitprogramsize = 0; + char* fpgasrc = NULL; + FILE* fp = NULL; + + // filesize + if (receiveData(file_des,&filesize,sizeof(filesize),INT32) < 0) + return printSocketReadError(); + totalsize = filesize; + FILE_LOG(logDEBUG5, ("Total program size is: %d\n", totalsize); + + // opening file pointer to flash and telling FPGA to not touch flash + if (startWritingFPGAprogram(&fp) != OK) { + ret = FAIL; sprintf(mess,"Could not write to flash. Error at startup.\n"); - cprintf(RED,"%s",mess); + FILE_LOG(logERROR,(mess)); } //---------------- first ret ---------------- - // ret could be swapped during sendData - ret1 = ret; - // send ok / fail - n = sendData(file_des,&ret1,sizeof(ret),INT32); - // send return argument - if (ret==FAIL) { - n += sendData(file_des,mess,sizeof(mess),OTHER); - } - //---------------- first ret ---------------- + Server_SendResult(file_des, INT32, 0, NULL, 0); - if(ret!=FAIL) { + if (ret != FAIL) { //erasing flash eraseFlash(); fpgasrc = (char*)malloc(MAX_FPGAPROGRAMSIZE); } //writing to flash part by part - while(ret != FAIL && filesize){ + while(ret != FAIL && filesize) { unitprogramsize = MAX_FPGAPROGRAMSIZE; //2mb - if(unitprogramsize > filesize) //less than 2mb + if (unitprogramsize > filesize) //less than 2mb unitprogramsize = filesize; -#ifdef VERY_VERBOSE - printf("unit size to receive is:%d\n",unitprogramsize); - printf("filesize:%d currentpointer:%d\n",filesize,currentPointer); -#endif + FILE_LOG(logDEBUG5, ("unit size to receive is:%d\n" + "filesize:%d currentpointer:%d\n", + unitprogramsize, filesize, currentPointer)); - //receive - n = receiveData(file_des,fpgasrc,unitprogramsize,OTHER); - if (n < 0) return printSocketReadError(); - if(!(unitprogramsize - filesize)){ - fpgasrc[unitprogramsize]='\0'; - filesize-=unitprogramsize; + //receive part of program + if (receiveData(file_des,fpgasrc,unitprogramsize,OTHER) < 0) + return printSocketReadError(); + + if (!(unitprogramsize - filesize)) { + fpgasrc[unitprogramsize] = '\0'; + filesize -= unitprogramsize; unitprogramsize++; - }else - filesize-=unitprogramsize; + } else + filesize -= unitprogramsize; - ret = writeFPGAProgram(fpgasrc,unitprogramsize,fp); + // write part to flash + ret = writeFPGAProgram(fpgasrc, unitprogramsize, fp); //---------------- middle rets ---------------- - // ret could be swapped during sendData - ret1 = ret; - // send ok / fail - n = sendData(file_des,&ret1,sizeof(ret),INT32); - // send return argument - if (ret==FAIL) { - n += sendData(file_des,mess,sizeof(mess),OTHER); + Server_SendResult(file_des, INT32, 0, NULL, 0); + + + + if (ret == FAIL) { cprintf(RED,"Failure: Breaking out of program receiving\n"); - } - //---------------- middle rets ---------------- - - if(ret != FAIL){ + } else { //print progress - printf("Writing to Flash:%d%%\r",(int) (((double)(totalsize-filesize)/totalsize)*100) ); + FILE_LOG(logINFO, ("Writing to Flash:%d%%\r", + (int) (((double)(totalsize-filesize)/totalsize)*100) )); fflush(stdout); } } - printf("\n"); + FILE_LOG(logINFO("\nDone copying program\n")); - //closing file pointer to flash and informing FPGA + // closing file pointer to flash and informing FPGA stopWritingFPGAprogram(fp); //free resources - if(fpgasrc != NULL) + if (fpgasrc != NULL) free(fpgasrc); - if(fp!=NULL) + if (fp != NULL) fclose(fp); -#ifdef VERY_VERBOSE - printf("Done with program receiving command\n"); -#endif + + FILE_LOG(logDEBUG5, ("Done with program receiving command\n")); if (isControlServer) { basictests(debugflag); @@ -3396,10 +2589,7 @@ int program_fpga(int file_des) { } } #endif - - Server_SendResult(file_des, INT32, 1, NULL, 0); - - return ret; + return Server_SendResult(file_des, INT32, 1, NULL, 0); } @@ -3407,177 +2597,106 @@ int program_fpga(int file_des) { int reset_fpga(int file_des) { - int ret=OK,ret1=OK; - int n=0; - sprintf(mess,"Reset FPGA unsuccessful\n"); + ret = OK; + memset(mess, 0, sizeof(mess)); + FILE_LOG(logDEBUG5, ("Reset FPGA\n")); #ifndef JUNGFRAUD - //to receive any arguments - while (n > 0) - n = receiveData(file_des,mess,MAX_STR_LENGTH,OTHER); - ret = FAIL; - sprintf(mess,"Function (Reset FPGA) is not implemented for this detector\n"); cprintf(RED, "%s", mess); + functionNotImplemented(); #else - - // execute action - if (differentClients && lockStatus) { - ret = FAIL; - sprintf(mess,"Detector locked by %s\n",lastClientIP); - cprintf(RED, "Warning: %s", mess); - } - else { - if (isControlServer) { - basictests(debugflag); // mapping of control server at lease -#ifdef JUNGFRAUD - if (debugflag != PROGRAMMING_MODE) -#endif - initControlServer(); - } - else initStopServer(); //remapping of stop server + // only set + if (Server_VerifyLock() != FAIL) { + if (isControlServer) { + basictests(debugflag); // mapping of control server at least + if (debugflag != PROGRAMMING_MODE) + initControlServer(); + } + else initStopServer(); //remapping of stop server ret = FORCE_UPDATE; } #endif - - Server_SendResult(file_des, INT32, 1, NULL, 0); - - return ret; + return Server_SendResult(file_des, INT32, 1, NULL, 0); } int power_chip(int file_des) { - int ret=OK,ret1=OK; - int n=0; - int retval=-1; - sprintf(mess,"power chip failed\n"); + ret = OK; + memset(mess, 0, sizeof(mess)); + int arg = -1; + int retval = -1; + + if (receiveData(file_des, &arg, sizeof(arg), INT32) < 0) + return printSocketReadError(); + FILE_LOG(logDEBUG5, ("Powering chip to %d\n", arg)); #ifndef JUNGFRAUD - //to receive any arguments - while (n > 0) - n = receiveData(file_des,mess,MAX_STR_LENGTH,OTHER); - ret = FAIL; - sprintf(mess,"Function (Power Chip) is not implemented for this detector\n"); - cprintf(RED, "%s", mess); + functionNotImplemented(); #else - - // receive arguments - int arg=-1; - n = receiveData(file_des,&arg,sizeof(arg),INT32); - if (n < 0) return printSocketReadError(); - - // execute action - if (differentClients && lockStatus && arg!=-1) { - ret = FAIL; - sprintf(mess,"Detector locked by %s\n",lastClientIP); - cprintf(RED, "Warning: %s", mess); - } - else { -#ifdef VERBOSE - printf("Power chip to %d\n", arg); -#endif - retval=powerChip(arg); - -#ifdef VERBOSE - printf("Chip powered: %d\n",retval); -#endif - if (retval==arg || arg<0) { - ret=OK; - } else { - ret=FAIL; - if(setTemperatureEvent(-1) == 1) - sprintf(mess,"Powering chip failed due to over-temperature event. Clear event & power chip again. Wrote %d, read %d \n", arg, retval); - else - sprintf(mess,"Powering chip failed, wrote %d but read %d\n", arg, retval); - cprintf(RED, "Warning: %s", mess); + // set & get + if ((arg == -1) || ((arg != -1) && (Server_VerifyLock() != FAIL))) { + retval = powerChip(arg); + FILE_LOG(logDEBUG5, ("Power chip: %d\n", retval)); + validate(arg, retval, "power on/off chip", 0); + // narrow down error when powering on + if (ret == FAIL && arg > 0) { + if (setTemperatureEvent(-1) == 1) + sprintf(mess,"Powering chip failed due to over-temperature event. " + "Clear event & power chip again. Set %d, read %d \n", arg, retval); + FILE_LOG(logERROR, (mess)); } } #endif - - Server_SendResult(file_des, INT32, 1, &retval, sizeof(retval)); - - return ret; + return Server_SendResult(file_des, INT32, 1, &retval, sizeof(retval)); } int set_activate(int file_des) { - int ret=OK,ret1=OK; - int n=0; - int retval=-1; - sprintf(mess,"Activate/Deactivate failed\n"); + ret = OK; + memset(mess, 0, sizeof(mess)); + int arg = -1; + int retval = -1; + + if (receiveData(file_des, &arg, sizeof(arg), INT32) < 0) + return printSocketReadError(); + FILE_LOG(logDEBUG5, ("Setting activate mode to %d\n", arg)); #ifndef EIGERD - //to receive any arguments - while (n > 0) - n = receiveData(file_des,mess,MAX_STR_LENGTH,OTHER); - ret=FAIL; - sprintf(mess,"Function (Set Activate) is not implemented for this detector\n"); - cprintf(RED, "Warning: %s", mess); + functionNotImplemented(); #else - - // receive arguments - int arg=-1; - n = receiveData(file_des,&arg,sizeof(arg),INT32); - if (n < 0) return printSocketReadError(); - - // execute action - if (differentClients && lockStatus && arg!=-1) { - ret = FAIL; - sprintf(mess,"Detector locked by %s\n",lastClientIP); - cprintf(RED, "Warning: %s", mess); - } - else { -#ifdef VERBOSE - printf("Setting activate mode of detector to %d\n",arg); -#endif - retval=activate(arg); - if ((retval!=arg) && (arg!=-1)) { - ret=FAIL; - sprintf(mess,"Could not set activate mode to %d, is set to %d\n",arg, retval); - cprintf(RED, "Warning: %s", mess); - } + // set & get + if ((arg == -1) || ((arg != -1) && (Server_VerifyLock() != FAIL))) { + retval = activate(arg); + FILE_LOG(logDEBUG5, ("Activate: %d\n", retval)); + validate(arg, retval, "set activate", 0); } #endif - - Server_SendResult(file_des, INT32, 1, &retval, sizeof(retval)); - - return ret; + return Server_SendResult(file_des, INT32, 1, &retval, sizeof(retval)); } int prepare_acquisition(int file_des) { - int ret=OK,ret1=OK; - int n=0; - strcpy(mess,"prepare acquisition failed\n"); + ret = OK; + memset(mess, 0, sizeof(mess)); -#if !defined(GOTTHARDD) && !defined(EIGERD) - //to receive any arguments - while (n > 0) - n = receiveData(file_des,mess,MAX_STR_LENGTH,OTHER); - ret = FAIL; - sprintf(mess,"Function (Prepare Acquisition) is not implemented for this detector\n"); - cprintf(RED, "Warning: %s", mess); + FILE_LOG(logDEBUG5, ("Preparing Acquisition\n")); +#ifndef EIGERD + functionNotImplemented(); #else - - // execute action - if (differentClients && lockStatus) { - ret = FAIL; - sprintf(mess,"Detector locked by %s\n",lastClientIP); - cprintf(RED, "Warning: %s", mess); - } - else { + // only set + if (Server_VerifyLock() != FAIL) { ret = prepareAcquisition(); - if (ret == FAIL) - cprintf(RED, "Warning: %s", mess); + if (ret == FAIL) { + strcpy(mess, "Could not prepare acquisition\n"); + FILE_LOG(logERROR, (mess)); + } } #endif - - Server_SendResult(file_des, INT32, 1 , NULL, 0); - - return ret; + return Server_SendResult(file_des, INT32, 1 , NULL, 0); } @@ -3585,130 +2704,86 @@ int prepare_acquisition(int file_des) { int threshold_temp(int file_des) { - int ret=OK,ret1=OK; - int n=0; - int retval=-1; - sprintf(mess,"could not set/get threshold temperature\n"); + ret = OK; + memset(mess, 0, sizeof(mess)); + int arg = -1; + int retval = -1; + + if (receiveData(file_des, &arg, sizeof(arg), INT32) < 0) + return printSocketReadError(); + FILE_LOG(logDEBUG5, ("Setting threshold temperature to %d\n", arg)); #ifndef JUNGFRAUD - //to receive any arguments - while (n > 0) - n = receiveData(file_des,mess,MAX_STR_LENGTH,OTHER); - ret = FAIL; - sprintf(mess,"Function (Threshold Temp) is not implemented for this detector\n"); - cprintf(RED, "%s", mess); + functionNotImplemented(); #else - int arg=-1; - int val=-1; - - // receive arguments - n = receiveData(file_des,&arg,sizeof(arg),INT32); - if (n < 0) return printSocketReadError(); - - val=arg; - if (val > MAX_THRESHOLD_TEMP_VAL) { - ret=FAIL; - sprintf(mess,"Threshold Temp %d should be in range: 0 - %d\n", val, MAX_THRESHOLD_TEMP_VAL); - cprintf(RED, "Warning: %s", mess); - } - - - if (ret==OK) { -#ifdef VERBOSE - printf("Setting Threshold Temperature to %d\n", val); + // set & get + if ((arg == -1) || ((arg != -1) && (Server_VerifyLock() != FAIL))) { + if (arg > MAX_THRESHOLD_TEMP_VAL) { + ret = FAIL; + sprintf(mess,"Threshold Temp %d should be in range: 0 - %d\n", + arg, MAX_THRESHOLD_TEMP_VAL); + FILE_LOG(logERROR, (mess)); + } + // valid temp + else { + retval = setThresholdTemperature(arg); + FILE_LOG(logDEBUG5, ("Threshold temperature: %d\n", retval)); + validate(arg, retval, "set threshold temperature", 0); + } + } #endif - retval=setThresholdTemperature(val); - } -#ifdef VERBOSE - printf("Threshold temperature is %d\n", retval); -#endif -#endif - - Server_SendResult(file_des, INT32, 1, &retval, sizeof(retval)); - - return ret; + return Server_SendResult(file_des, INT32, 1, &retval, sizeof(retval)); } int temp_control(int file_des) { - int ret=OK,ret1=OK; - int n=0; - int retval=-1; - sprintf(mess,"could not set/get temperature control\n"); + ret = OK; + memset(mess, 0, sizeof(mess)); + int arg = -1; + int retval = -1; + + if (receiveData(file_des, &arg, sizeof(arg), INT32) < 0) + return printSocketReadError(); + FILE_LOG(logDEBUG5, ("Setting temperature control to %d\n", arg)); #ifndef JUNGFRAUD - //to receive any arguments - while (n > 0) - n = receiveData(file_des,mess,MAX_STR_LENGTH,OTHER); - ret = FAIL; - sprintf(mess,"Function (Temperature control) is not implemented for this detector\n"); - cprintf(RED, "%s", mess); + functionNotImplemented(); #else - int arg=-1; - int val=-1; - - // receive arguments - n = receiveData(file_des,&arg,sizeof(arg),INT32); - if (n < 0) return printSocketReadError(); - val=arg; - - if (ret==OK) { -#ifdef VERBOSE - printf("Setting Temperature control to %d\n", val); + // set & get + if ((arg == -1) || ((arg != -1) && (Server_VerifyLock() != FAIL))) { + retval = setTemperatureControl(arg); + FILE_LOG(logDEBUG5, ("Temperature control: %d\n", retval)); + validate(arg, retval, "set temperature control", 0); + } #endif - retval=setTemperatureControl(val); - } -#ifdef VERBOSE - printf("Temperature control is %d\n", retval); -#endif -#endif - - Server_SendResult(file_des, INT32, 1, &retval, sizeof(retval)); - - return ret; + return Server_SendResult(file_des, INT32, 1, &retval, sizeof(retval)); } int temp_event(int file_des) { - int ret=OK,ret1=OK; - int n=0; - int retval=-1; - sprintf(mess,"could not set/get temperature event\n"); + ret = OK; + memset(mess, 0, sizeof(mess)); + int arg = -1; + int retval = -1; + + if (receiveData(file_des, &arg, sizeof(arg), INT32) < 0) + return printSocketReadError(); + FILE_LOG(logDEBUG5, ("Setting temperature event to %d\n", arg)); #ifndef JUNGFRAUD - //to receive any arguments - while (n > 0) - n = receiveData(file_des,mess,MAX_STR_LENGTH,OTHER); - ret = FAIL; - sprintf(mess,"Function (Temperature Event) is not implemented for this detector\n"); - cprintf(RED, "%s", mess); + functionNotImplemented(); #else - int arg=-1; - int val=-1; - - // receive arguments - n = receiveData(file_des,&arg,sizeof(arg),INT32); - if (n < 0) return printSocketReadError(); - val=arg; - - if (ret==OK) { -#ifdef VERBOSE - printf("Setting Temperature Event to %d\n", val); + // set & get + if ((arg == -1) || ((arg != -1) && (Server_VerifyLock() != FAIL))) { + retval = setTemperatureEvent(arg); + FILE_LOG(logDEBUG5, ("Temperature event: %d\n", retval)); + validate(arg, retval, "set temperature event", 0); + } #endif - retval=setTemperatureEvent(val); - } -#ifdef VERBOSE - printf("Temperature Event is %d\n", retval); -#endif - -#endif - - Server_SendResult(file_des, INT32, 1, &retval, sizeof(retval)); - - return ret; + return Server_SendResult(file_des, INT32, 1, &retval, sizeof(retval)); } @@ -3716,60 +2791,26 @@ int temp_event(int file_des) { int auto_comp_disable(int file_des) { - int ret=OK,ret1=OK; - int n=0; - int retval=-1; - sprintf(mess,"auto comp disable failed\n"); + ret = OK; + memset(mess, 0, sizeof(mess)); + int arg = -1; + int retval = -1; + + if (receiveData(file_des, &arg, sizeof(arg), INT32) < 0) + return printSocketReadError(); + FILE_LOG(logDEBUG5, ("Setting Auto comp disable to %d\n", arg)); #ifndef JUNGFRAUD - //to receive any arguments - while (n > 0) - n = receiveData(file_des,mess,MAX_STR_LENGTH,OTHER); - ret = FAIL; - sprintf(mess,"Function (Auto Comp Disable) is not implemented for this detector\n"); - cprintf(RED, "%s", mess); + functionNotImplemented(); #else - - //to receive any arguments - while (n > 0) - n = receiveData(file_des,mess,MAX_STR_LENGTH,OTHER); - ret = FAIL; - sprintf(mess,"Function (Auto Comp Disable) is not yet implemented for this detector\n"); - cprintf(RED, "%s", mess); - - // receive arguments - int arg=-1; - n = receiveData(file_des,&arg,sizeof(arg),INT32); - if (n < 0) return printSocketReadError(); - - // execute action - if (differentClients && lockStatus && arg!=-1) { - ret = FAIL; - sprintf(mess,"Detector locked by %s\n",lastClientIP); - cprintf(RED, "Warning: %s", mess); - } - else { -#ifdef VERBOSE - printf("Auto Comp Disable to %d\n", arg); + // set & get + if ((arg == -1) || ((arg != -1) && (Server_VerifyLock() != FAIL))) { + retval = autoCompDisable(arg); + FILE_LOG(logDEBUG5, ("Auto comp disable: %d\n", retval)); + validate(arg, retval, "set auto comp disable", 0); + } #endif - retval=autoCompDisable(arg); - -#ifdef VERBOSE - printf("Auto comp disable set to: %d\n",retval); -#endif - if (retval==arg || arg<0) { - ret=OK; - } else { - ret=FAIL; - sprintf(mess,"Atuo Comp Disable failed, wrote %d but read %d\n", arg, retval); - cprintf(RED, "Warning: %s", mess); - } - } -#endif - - Server_SendResult(file_des, INT32, 1, &retval, sizeof(retval)); - - return ret; + return Server_SendResult(file_des, INT32, 1, &retval, sizeof(retval)); } @@ -3777,87 +2818,48 @@ int auto_comp_disable(int file_des) { int storage_cell_start(int file_des) { - int ret=OK,ret1=OK; - int n=0; - int retval=-1; - sprintf(mess,"storage cell start failed\n"); + ret = OK; + memset(mess, 0, sizeof(mess)); + int arg = -1; + int retval = -1; + + if (receiveData(file_des, &arg, sizeof(arg), INT32) < 0) + return printSocketReadError(); + FILE_LOG(logDEBUG5, ("Setting Storage cell start to %d\n", arg)); #ifndef JUNGFRAUD - //to receive any arguments - while (n > 0) - n = receiveData(file_des,mess,MAX_STR_LENGTH,OTHER); - ret = FAIL; - sprintf(mess,"Function (Storage cell start) is not implemented for this detector\n"); - cprintf(RED, "%s", mess); + functionNotImplemented(); #else - - // receive arguments - int arg=-1; - n = receiveData(file_des,&arg,sizeof(arg),INT32); - if (n < 0) return printSocketReadError(); - - // execute action - if (differentClients && lockStatus && arg!=-1) { - ret = FAIL; - sprintf(mess,"Detector locked by %s\n",lastClientIP); - cprintf(RED, "Warning: %s", mess); - } - else if (arg > MAX_STORAGE_CELL_VAL) { - ret=FAIL; - strcpy(mess,"Max Storage cell number should not exceed 15\n"); - cprintf(RED, "Warning: %s", mess); - } else { -#ifdef VERBOSE - printf("Storage cell start to %d\n", arg); + // set & get + if ((arg == -1) || ((arg != -1) && (Server_VerifyLock() != FAIL))) { + if (arg > MAX_STORAGE_CELL_VAL) { + ret = FAIL; + strcpy(mess,"Max Storage cell number should not exceed 15\n"); + FILE_LOG(logERROR, (mess)); + } else { + retval = selectStoragecellStart(arg); + FILE_LOG(logDEBUG5, ("Storage cell start: %d\n", retval)); + validate(arg, retval, "set storage cell start", 0); + } #endif - retval=selectStoragecellStart(arg); - -#ifdef VERBOSE - printf("Storage cell start: %d\n",retval); -#endif - if (retval==arg || arg<0) { - ret=OK; - } else { - sprintf(mess,"Storage cell start select failed, wrote %d but read %d\n", arg, retval); - cprintf(RED, "Warning: %s", mess); - } - } -#endif - - Server_SendResult(file_des, INT32, 1, &retval, sizeof(retval)); - - return ret; + return Server_SendResult(file_des, INT32, 1, &retval, sizeof(retval)); } int check_version(int file_des) { - int ret=OK,ret1=OK; - int n=0; - sprintf(mess,"check version failed\n"); + ret = OK; + memset(mess, 0, sizeof(mess)); + int64_t arg = -1; -#if !defined(EIGERD) && !defined(JUNGFRAUD) && !defined(GOTTHARD) - //to receive any arguments - while (n > 0) - n = receiveData(file_des,mess,MAX_STR_LENGTH,OTHER); - ret=FAIL; - sprintf(mess,"Function (Check Version Compatibility) is not implemented for this detector\n"); - cprintf(RED, "Warning: %s", mess); -#else - - // receive arguments - int64_t arg=-1; - n = receiveData(file_des,&arg,sizeof(arg),INT64); - if (n < 0) return printSocketReadError(); - - // execute action + if (receiveData(file_des, &arg, sizeof(arg), INT64) < 0) + return printSocketReadError(); // check software- firmware compatibility and basic tests if (isControlServer) { -#ifdef VERBOSE - printf("Checking software-firmware compatibility and basic test result\n"); -#endif + FILE_LOG(logDEBUG5, ("Checking software-firmware compatibility and basic test result\n")); + // check if firmware check is done if (!isFirmwareCheckDone()) { usleep(3 * 1000 * 1000); @@ -3865,7 +2867,7 @@ int check_version(int file_des) { ret = FAIL; strcpy(mess,"Firmware Software Compatibility Check (Server Initialization) " "still not done done in server. Unexpected.\n"); - cprintf(RED, "Warning: %s", mess); + FILE_LOG(logERROR,(mess)); } } // check firmware check result @@ -3874,15 +2876,14 @@ int check_version(int file_des) { if (getFirmwareCheckResult(&firmware_message) == FAIL) { ret = FAIL; strcpy(mess, firmware_message); - cprintf(RED, "Warning: %s", mess); + FILE_LOG(logERROR,(mess)); } } } if (ret == OK) { -#ifdef VERBOSE - printf("Checking versioning compatibility with value %d\n",arg); -#endif + FILE_LOG(logDEBUG5, ("Checking versioning compatibility with value %d\n",arg)); + int64_t client_requiredVersion = arg; int64_t det_apiVersion = getDetectorId(CLIENT_SOFTWARE_API_VERSION); int64_t det_version = getDetectorId(DETECTOR_SOFTWARE_VERSION); @@ -3894,7 +2895,7 @@ int check_version(int file_des) { "Detector's SW API Version: (0x%llx). " "Incompatible, update client!\n", (long long int)client_requiredVersion, (long long int)det_apiVersion); - cprintf(RED, "Warning: %s", mess); + FILE_LOG(logERROR,(mess)); } // old software @@ -3904,48 +2905,33 @@ int check_version(int file_des) { "Client's detector SW API Version: (0x%llx). " "Incompatible, update detector software!\n", (long long int)det_version, (long long int)client_requiredVersion); - cprintf(RED, "Warning: %s", mess); + FILE_LOG(logERROR,(mess)); } } -#endif - - Server_SendResult(file_des, INT32, 1 , NULL, 0); - return ret; + return Server_SendResult(file_des, INT32, 1 , NULL, 0); } int software_trigger(int file_des) { - int ret=OK,ret1=OK; - int n=0; - sprintf(mess,"software trigger failed\n"); + ret = OK; + memset(mess, 0, sizeof(mess)); + FILE_LOG(logDEBUG5, ("Software Trigger\n")); #ifndef EIGERD - //to receive any arguments - while (n > 0) - n = receiveData(file_des,mess,MAX_STR_LENGTH,OTHER); - ret = FAIL; - sprintf(mess,"Function (Software Trigger) is not implemented for this detector\n"); - cprintf(RED, "%s", mess); + functionNotImplemented(); #else - - // execute action - if (differentClients && lockStatus) { - ret = FAIL; - sprintf(mess,"Detector locked by %s\n",lastClientIP); - cprintf(RED, "Warning: %s", mess); - } - else { - printf("Software Trigger\n"); - ret=softwareTrigger(); - if (ret==FAIL) - cprintf(RED, "Warning: %s", mess); + // only set + if (Server_VerifyLock() != FAIL) { + ret = softwareTrigger(); + if (ret == FAIL) { + sprintf(mess, "Could not send software trigger\n"); + FILE_LOG(logERROR,(mess)); + } + FILE_LOG(logDEBUG5, ("Software trigger ret: %d\n", ret)); } #endif - - Server_SendResult(file_des, INT32, 1 , NULL, 0); - - return ret; + return Server_SendResult(file_des, INT32, 1 , NULL, 0); } diff --git a/slsDetectorServers/slsDetectorServer/slsDetectorServer_funcs.h b/slsDetectorServers/slsDetectorServer/slsDetectorServer_funcs.h index 0ac890f86..72829ec43 100755 --- a/slsDetectorServers/slsDetectorServer/slsDetectorServer_funcs.h +++ b/slsDetectorServers/slsDetectorServer/slsDetectorServer_funcs.h @@ -1,6 +1,4 @@ -#ifndef SERVER_FUNCS_H -#define SERVER_FUNCS_H - +#pragma once #include "sls_detector_defs.h" #include @@ -14,6 +12,7 @@ void function_table(); void functionNotImplemented(); void modeNotImplemented(char* modename, int mode); void validate(int arg, int retval, char* modename, int hex); +void validate64(int64_t arg, int64_t retval, char* modename, int hex); int M_nofunc(int); int M_nofuncMode(int); @@ -79,4 +78,3 @@ int storage_cell_start(int); int check_version(int); int software_trigger(int); -#endif diff --git a/slsDetectorSoftware/slsDetector/slsDetector.cpp b/slsDetectorSoftware/slsDetector/slsDetector.cpp index d0a446944..bf92c04a2 100644 --- a/slsDetectorSoftware/slsDetector/slsDetector.cpp +++ b/slsDetectorSoftware/slsDetector/slsDetector.cpp @@ -2867,27 +2867,21 @@ int slsDetector::setDynamicRange(int n) { if (connectControl() == OK){ controlSocket->SendDataOnly(&fnum,sizeof(fnum)); controlSocket->SendDataOnly(&n,sizeof(n)); - //rate correction is switched off if not 32 bit mode - if(thisDetector->myDetectorType == EIGER){ - controlSocket->ReceiveDataOnly(&rateret,sizeof(rateret)); - if (rateret==FAIL) { - controlSocket->ReceiveDataOnly(mess,sizeof(mess)); - std::cout<< "Detector returned error: " << mess << std::endl; - if(strstr(mess,"Rate Correction")!=NULL){ - if(strstr(mess,"32")!=NULL) - setErrorMask((getErrorMask())|(RATE_CORRECTION_NOT_32or16BIT)); - else - setErrorMask((getErrorMask())|(COULD_NOT_SET_RATE_CORRECTION)); - } - } - } controlSocket->ReceiveDataOnly(&ret,sizeof(ret)); if (ret==FAIL) { controlSocket->ReceiveDataOnly(mess,sizeof(mess)); std::cout<< "Detector returned error: " << mess << std::endl; - } else { - controlSocket->ReceiveDataOnly(&retval,sizeof(retval)); + if(strstr(mess,"Rate Correction")!=NULL){ + // rate correction is switched off if not 32 bit mode + if(strstr(mess,"32")!=NULL) + setErrorMask((getErrorMask())|(RATE_CORRECTION_NOT_32or16BIT)); + else + setErrorMask((getErrorMask())|(COULD_NOT_SET_RATE_CORRECTION)); + } + else ret = OK; } + controlSocket->ReceiveDataOnly(&retval,sizeof(retval)); + disconnectControl(); if (ret==FORCE_UPDATE) updateDetector(); @@ -4268,13 +4262,24 @@ int slsDetector::sendROI(int n,ROI roiLimits[]) { #ifdef VERBOSE std::cout << "Sending ROI of size " << arg << " to detector" << std::endl; #endif - controlSocket->SendDataOnly(roiLimits,arg*sizeof(ROI)); + for(int i = 0; i < n; ++i){ + controlSocket->SendDataOnly(&roiLimits[i].xmin, sizeof(int)); + controlSocket->SendDataOnly(&roiLimits[i].xmax, sizeof(int)); + controlSocket->SendDataOnly(&roiLimits[i].ymin, sizeof(int)); + controlSocket->SendDataOnly(&roiLimits[i].ymax, sizeof(int)); + } + //controlSocket->SendDataOnly(roiLimits,arg*sizeof(ROI)); } controlSocket->ReceiveDataOnly(&ret,sizeof(ret)); if (ret!=FAIL){ controlSocket->ReceiveDataOnly(&retvalsize,sizeof(retvalsize)); - nrec = controlSocket->ReceiveDataOnly(retval,retvalsize*sizeof(ROI)); + nrec = 0; + nrec += controlSocket->ReceiveDataOnly(&retval[i].xmin, sizeof(int)); + nrec += controlSocket->ReceiveDataOnly(&retval[i].xmax, sizeof(int)); + nrec += controlSocket->ReceiveDataOnly(&retval[i].ymin, sizeof(int)); + nrec += controlSocket->ReceiveDataOnly(&retval[i].ymax, sizeof(int)); + //nrec = controlSocket->ReceiveDataOnly(retval,retvalsize*sizeof(ROI)); if(nrec!=(retvalsize*(int)sizeof(ROI))){ ret=FAIL; std::cout << " wrong size received: received " << nrec << diff --git a/slsReceiverSoftware/src/slsReceiverTCPIPInterface.cpp b/slsReceiverSoftware/src/slsReceiverTCPIPInterface.cpp index d7af5d8d2..d1ad6bace 100644 --- a/slsReceiverSoftware/src/slsReceiverTCPIPInterface.cpp +++ b/slsReceiverSoftware/src/slsReceiverTCPIPInterface.cpp @@ -290,9 +290,7 @@ int slsReceiverTCPIPInterface::M_nofunc(){ strcpy(mess,"Unrecognized Function. Please do not proceed.\n"); FILE_LOG(logERROR) << mess; - interface->Server_SendResult(false, ret, NULL, 0, mess); - - return ret; + return interface->Server_SendResult(false, ret, NULL, 0, mess); } @@ -329,21 +327,17 @@ int slsReceiverTCPIPInterface::exec_command() { } } - interface->Server_SendResult(false, ret, retval, MAX_STR_LENGTH, mess); - - return ret; + return interface->Server_SendResult(false, ret, retval, MAX_STR_LENGTH, mess); } int slsReceiverTCPIPInterface::exit_server() { - cprintf(RED,"Closing receiver server\n"); + cprintf(RED,"Closing server\n"); ret = OK; interface->Server_SendResult(false, ret, NULL, 0); - - ret = GOODBYE; - return ret; + return GOODBYE; } @@ -361,7 +355,7 @@ int slsReceiverTCPIPInterface::lock_receiver() { if (lock >= 0) { if (!lockStatus || // if it was unlocked, anyone can lock (!strcmp(mySock->lastClientIP,mySock->thisClientIP)) || // if it was locked, need same ip - (!strcmp(mySock->lastClientIP,"none"))) //if it was locked, must be by "none" + (!strcmp(mySock->lastClientIP,"none"))) // if it was locked, must be by "none" { lockStatus = lock; strcpy(mySock->lastClientIP,mySock->thisClientIP); @@ -369,18 +363,14 @@ int slsReceiverTCPIPInterface::lock_receiver() { interface->Server_LockedError(ret, mess); } - interface->Server_SendResult(true, ret, &lockStatus,sizeof(lockStatus), mess); - - return ret; + return interface->Server_SendResult(true, ret, &lockStatus,sizeof(lockStatus), mess); } int slsReceiverTCPIPInterface::get_last_client_ip() { ret = OK; - interface->Server_SendResult(true, ret,mySock->lastClientIP, sizeof(mySock->lastClientIP)); - - return ret; + return interface->Server_SendResult(true, ret,mySock->lastClientIP, sizeof(mySock->lastClientIP)); } @@ -560,9 +550,7 @@ int slsReceiverTCPIPInterface::get_id(){ ret = OK; int64_t retval = getReceiverVersion(); - interface->Server_SendResult(true, ret, &retval, sizeof(retval)); - - return ret; + return interface->Server_SendResult(true, ret, &retval, sizeof(retval)); } @@ -622,9 +610,7 @@ int slsReceiverTCPIPInterface::set_detector_type(){ //get retval = myDetectorType; - interface->Server_SendResult(true, ret, &retval, sizeof(retval), mess); - - return ret; + return interface->Server_SendResult(true, ret, &retval, sizeof(retval), mess); } @@ -679,7 +665,13 @@ int slsReceiverTCPIPInterface::set_roi() { int iloop = 0; for (iloop = 0; iloop < nroi; iloop++) { ROI temp; - if ( mySock->ReceiveDataOnly(&temp,sizeof(ROI)) < 0 ) + if ( mySock->ReceiveDataOnly(&temp.xmin,sizeof(int)) < 0 ) + return interface->Server_SocketCrash(); + if ( mySock->ReceiveDataOnly(&temp.xmax,sizeof(int)) < 0 ) + return interface->Server_SocketCrash(); + if ( mySock->ReceiveDataOnly(&temp.ymin,sizeof(int)) < 0 ) + return interface->Server_SocketCrash(); + if ( mySock->ReceiveDataOnly(&temp.ymax,sizeof(int)) < 0 ) return interface->Server_SocketCrash(); roiLimits.push_back(temp); } @@ -766,9 +758,7 @@ int slsReceiverTCPIPInterface::setup_udp(){ } } - interface->Server_SendResult(true, ret, retval, sizeof(retval), mess); - - return ret; + return interface->Server_SendResult(true, ret, retval, sizeof(retval), mess); } @@ -865,9 +855,7 @@ int slsReceiverTCPIPInterface::set_timer() { FILE_LOG(logDEBUG1) << slsDetectorDefs::getTimerType((timerIndex)(index[0])) << ":" << retval; } - interface->Server_SendResult(true, ret, &retval, sizeof(retval), mess); - - return ret; + return interface->Server_SendResult(true, ret, &retval, sizeof(retval), mess); } @@ -927,9 +915,7 @@ int slsReceiverTCPIPInterface::set_dynamic_range() { FILE_LOG(logDEBUG1) << "dynamic range: " << retval; } - interface->Server_SendResult(true, ret, &retval, sizeof(retval), mess); - - return ret; + return interface->Server_SendResult(true, ret, &retval, sizeof(retval), mess); } @@ -966,9 +952,7 @@ int slsReceiverTCPIPInterface::set_streaming_frequency(){ } } - interface->Server_SendResult(true, ret, &retval, sizeof(retval), mess); - - return ret; + return interface->Server_SendResult(true, ret, &retval, sizeof(retval), mess); } @@ -984,9 +968,7 @@ int slsReceiverTCPIPInterface::get_status(){ if (ret == OK) retval = receiver->getStatus(); - interface->Server_SendResult(true, ret, &retval, sizeof(retval), mess); - - return ret; + return interface->Server_SendResult(true, ret, &retval, sizeof(retval), mess); } @@ -1017,11 +999,7 @@ int slsReceiverTCPIPInterface::start_receiver(){ } } - interface->Server_SendResult(true, ret, NULL, 0, mess); - - return ret; - - + return interface->Server_SendResult(true, ret, NULL, 0, mess); } @@ -1050,9 +1028,7 @@ int slsReceiverTCPIPInterface::stop_receiver(){ } } - interface->Server_SendResult(true, ret, NULL, 0, mess); - - return ret; + return interface->Server_SendResult(true, ret, NULL, 0, mess); } @@ -1162,9 +1138,7 @@ int slsReceiverTCPIPInterface::set_file_index() { FILE_LOG(logDEBUG1) << "file index:" << retval; } - interface->Server_SendResult(true, ret, &retval,sizeof(retval), mess); - - return ret; + return interface->Server_SendResult(true, ret, &retval,sizeof(retval), mess); } @@ -1182,9 +1156,7 @@ int slsReceiverTCPIPInterface::get_frame_index(){ if (ret == OK) retval=receiver->getAcquisitionIndex(); - interface->Server_SendResult(true, ret, &retval,sizeof(retval), mess); - - return ret; + return interface->Server_SendResult(true, ret, &retval,sizeof(retval), mess); } @@ -1199,9 +1171,7 @@ int slsReceiverTCPIPInterface::get_frames_caught(){ if (ret == OK) retval=receiver->getTotalFramesCaught(); - interface->Server_SendResult(true, ret, &retval,sizeof(retval), mess); - - return ret; + return interface->Server_SendResult(true, ret, &retval,sizeof(retval), mess); } @@ -1221,9 +1191,7 @@ int slsReceiverTCPIPInterface::reset_frames_caught(){ } } - interface->Server_SendResult(true, ret, NULL, 0, mess); - - return ret; + return interface->Server_SendResult(true, ret, NULL, 0, mess); } @@ -1256,9 +1224,7 @@ int slsReceiverTCPIPInterface::enable_file_write(){ FILE_LOG(logDEBUG1) << "file write enable:" << retval; } - interface->Server_SendResult(true, ret, &retval, sizeof(retval), mess); - - return ret; + return interface->Server_SendResult(true, ret, &retval, sizeof(retval), mess); } @@ -1293,9 +1259,7 @@ int slsReceiverTCPIPInterface::enable_overwrite() { FILE_LOG(logDEBUG1) << "file overwrite enable:" << retval; } - interface->Server_SendResult(true, ret, &retval, sizeof(retval), mess); - - return ret; + return interface->Server_SendResult(true, ret, &retval, sizeof(retval), mess); } @@ -1331,9 +1295,7 @@ int slsReceiverTCPIPInterface::enable_tengiga() { FILE_LOG(logDEBUG1) << "10Gbe:" << retval; } - interface->Server_SendResult(true, ret, &retval, sizeof(retval), mess); - - return ret; + return interface->Server_SendResult(true, ret, &retval, sizeof(retval), mess); } @@ -1371,9 +1333,7 @@ int slsReceiverTCPIPInterface::set_fifo_depth() { FILE_LOG(logDEBUG1) << "fifo depth:" << retval; } - interface->Server_SendResult(true, ret, &retval, sizeof(retval), mess); - - return ret; + return interface->Server_SendResult(true, ret, &retval, sizeof(retval), mess); } @@ -1409,9 +1369,7 @@ int slsReceiverTCPIPInterface::set_activate() { FILE_LOG(logDEBUG1) << "Activate: " << retval; } - interface->Server_SendResult(true, ret, &retval, sizeof(retval), mess); - - return ret; + return interface->Server_SendResult(true, ret, &retval, sizeof(retval), mess); } @@ -1444,9 +1402,7 @@ int slsReceiverTCPIPInterface::set_data_stream_enable(){ FILE_LOG(logDEBUG1) << "data streaming enable:" << retval; } - interface->Server_SendResult(true, ret, &retval, sizeof(retval), mess); - - return ret; + return interface->Server_SendResult(true, ret, &retval, sizeof(retval), mess); } @@ -1479,9 +1435,7 @@ int slsReceiverTCPIPInterface::set_streaming_timer(){ FILE_LOG(logDEBUG1) << "Streaming timer:" << retval; } - interface->Server_SendResult(true, ret, &retval, sizeof(retval), mess); - - return ret; + return interface->Server_SendResult(true, ret, &retval, sizeof(retval), mess); } @@ -1517,9 +1471,7 @@ int slsReceiverTCPIPInterface::set_flipped_data(){ FILE_LOG(logDEBUG1) << "Flipped Data:" << retval; } - interface->Server_SendResult(true, ret, &retval, sizeof(retval), mess); - - return ret; + return interface->Server_SendResult(true, ret, &retval, sizeof(retval), mess); } @@ -1554,9 +1506,7 @@ int slsReceiverTCPIPInterface::set_file_format() { FILE_LOG(logDEBUG1) << "File Format: " << retval; } - interface->Server_SendResult(true, ret, &retval, sizeof(retval), mess); - - return ret; + return interface->Server_SendResult(true, ret, &retval, sizeof(retval), mess); } @@ -1589,9 +1539,7 @@ int slsReceiverTCPIPInterface::set_detector_posid() { FILE_LOG(logDEBUG1) << "Position Id:" << retval; } - interface->Server_SendResult(true, ret, &retval, sizeof(retval), mess); - - return ret; + return interface->Server_SendResult(true, ret, &retval, sizeof(retval), mess); } @@ -1628,9 +1576,7 @@ int slsReceiverTCPIPInterface::set_multi_detector_size() { FILE_LOG(logDEBUG1) << "Multi Detector Size:" << retval; } - interface->Server_SendResult(true, ret, &retval, sizeof(retval), mess); - - return ret; + return interface->Server_SendResult(true, ret, &retval, sizeof(retval), mess); } @@ -1659,9 +1605,7 @@ int slsReceiverTCPIPInterface::set_streaming_port() { FILE_LOG(logDEBUG1) << "streaming port:" << retval; } - interface->Server_SendResult(true, ret, &retval, sizeof(retval), mess); - - return ret; + return interface->Server_SendResult(true, ret, &retval, sizeof(retval), mess); } @@ -1727,9 +1671,7 @@ int slsReceiverTCPIPInterface::set_silent_mode() { FILE_LOG(logDEBUG1) << "silent mode:" << retval; } - interface->Server_SendResult(true, ret, &retval, sizeof(retval), mess); - - return ret; + return interface->Server_SendResult(true, ret, &retval, sizeof(retval), mess); } @@ -1768,9 +1710,7 @@ int slsReceiverTCPIPInterface::enable_gap_pixels() { FILE_LOG(logDEBUG1) << "Gap Pixels Enable: " << retval; } - interface->Server_SendResult(true, ret, &retval, sizeof(retval), mess); - - return ret; + return interface->Server_SendResult(true, ret, &retval, sizeof(retval), mess); } @@ -1801,9 +1741,7 @@ int slsReceiverTCPIPInterface::restream_stop(){ } } - interface->Server_SendResult(true, ret, NULL, 0, mess); - - return ret; + return interface->Server_SendResult(true, ret, NULL, 0, mess); } @@ -1871,9 +1809,7 @@ int slsReceiverTCPIPInterface::set_udp_socket_buffer_size() { FILE_LOG(logDEBUG1) << "UDP Socket Buffer Size:" << retval; } - interface->Server_SendResult(true, ret, &retval, sizeof(retval), mess); - - return ret; + return interface->Server_SendResult(true, ret, &retval, sizeof(retval), mess); } @@ -1888,9 +1824,7 @@ int slsReceiverTCPIPInterface::get_real_udp_socket_buffer_size(){ if (ret == OK) retval = receiver->getActualUDPSocketBufferSize(); - interface->Server_SendResult(true, ret, &retval, sizeof(retval), mess); - - return ret; + return interface->Server_SendResult(true, ret, &retval, sizeof(retval), mess); } @@ -1924,9 +1858,7 @@ int slsReceiverTCPIPInterface::set_frames_per_file() { FILE_LOG(logDEBUG1) << "frames per file:" << retval; } - interface->Server_SendResult(true, ret, &retval, sizeof(retval), mess); - - return ret; + return interface->Server_SendResult(true, ret, &retval, sizeof(retval), mess); } @@ -1971,9 +1903,7 @@ int slsReceiverTCPIPInterface::check_version_compatibility() { } else FILE_LOG(logINFO) << "Compatibility with Client: Successful"; - interface->Server_SendResult(true, ret, NULL, 0, mess); - - return ret; + return interface->Server_SendResult(true, ret, NULL, 0, mess); } @@ -2007,9 +1937,7 @@ int slsReceiverTCPIPInterface::set_discard_policy() { FILE_LOG(logDEBUG1) << "frame discard policy:" << retval; } - interface->Server_SendResult(true, ret, &retval, sizeof(retval), mess); - - return ret; + return interface->Server_SendResult(true, ret, &retval, sizeof(retval), mess); } @@ -2045,9 +1973,7 @@ int slsReceiverTCPIPInterface::set_padding_enable() { FILE_LOG(logDEBUG1) << "Frame Padding Enable:" << retval; } - interface->Server_SendResult(true, ret, &retval, sizeof(retval), mess); - - return ret; + return interface->Server_SendResult(true, ret, &retval, sizeof(retval), mess); } @@ -2084,7 +2010,5 @@ int slsReceiverTCPIPInterface::set_deactivated_receiver_padding_enable() { FILE_LOG(logDEBUG1) << "Deactivated Padding Enable: " << retval; } - interface->Server_SendResult(true, ret, &retval, sizeof(retval), mess); - - return ret; + return interface->Server_SendResult(true, ret, &retval, sizeof(retval), mess); } diff --git a/slsSupportLib/include/ClientInterface.cpp b/slsSupportLib/include/ClientInterface.cpp index 78bd1bbbd..4d387da76 100644 --- a/slsSupportLib/include/ClientInterface.cpp +++ b/slsSupportLib/include/ClientInterface.cpp @@ -53,7 +53,7 @@ int ClientInterface::Client_Send(int fnum, } -void ClientInterface::Server_SendResult(bool update, int ret, +int ClientInterface::Server_SendResult(bool update, int ret, void* retval, int retvalSize, char* mess) { // update if different clients @@ -72,6 +72,8 @@ void ClientInterface::Server_SendResult(bool update, int ret, } // send return value mySocket->SendDataOnly(retval, retvalSize); + + return ret; } diff --git a/slsSupportLib/include/ClientInterface.h b/slsSupportLib/include/ClientInterface.h index 536c8c984..049de62aa 100644 --- a/slsSupportLib/include/ClientInterface.h +++ b/slsSupportLib/include/ClientInterface.h @@ -65,8 +65,9 @@ public: * @param retval pointer to result * @param retvalSize size of result * @param mess message + * @returns success of operation */ - void Server_SendResult(bool update, int ret, void* retval, int retvalSize, char* mess = 0); + int Server_SendResult(bool update, int ret, void* retval, int retvalSize, char* mess = 0); /** only Receiver * Server receives arguments and checks if base object is null (if checkbase is true) diff --git a/slsSupportLib/include/sls_detector_defs.h b/slsSupportLib/include/sls_detector_defs.h index 8649fd686..3d5bc07e4 100755 --- a/slsSupportLib/include/sls_detector_defs.h +++ b/slsSupportLib/include/sls_detector_defs.h @@ -82,9 +82,7 @@ public: EIGER, /**< eiger */ GOTTHARD, /**< gotthard */ JUNGFRAU, /**< jungfrau */ - JUNGFRAUCTB, /**< jungfrauCTBversion */ - MYTHEN3, /**< mythen 3 */ - MOENCH /**< moench */ + JUNGFRAUCTB /**< jungfrauCTBversion */ };