diff --git a/A1931.c b/A1931.c index c4fb79a..f80204a 100644 --- a/A1931.c +++ b/A1931.c @@ -18,65 +18,66 @@ #include #include #include -#include +#include #include #include "A1931.h" /*========================== private data structure ====================*/ typedef struct { - int sensor; /* the control sensor */ - pGPIB gpib; /* the GPIB interface to use in order to talk to the thing*/ - int gpibAddress; /* address on bus */ - int devID; /* deviceID of the controller on the GPIB */ - char errorBuffer[132]; /* a buffer for error messages from the thing*/ - char commandLine[132]; /* buffer to keep the offending command line */ - int errorCode; /* error indicator */ -}A1931, *pA1931; + int sensor; /* the control sensor */ + pGPIB gpib; /* the GPIB interface to use in order to talk to the thing */ + int gpibAddress; /* address on bus */ + int devID; /* deviceID of the controller on the GPIB */ + char errorBuffer[132]; /* a buffer for error messages from the thing */ + char commandLine[132]; /* buffer to keep the offending command line */ + int errorCode; /* error indicator */ +} A1931, *pA1931; /*============================ defines ================================*/ #define COMMERROR -300 #define A1931ERROR -301 #define FILEERROR -302 /*====================================================================*/ -static char *A1931comm(pEVDriver pData, char *command){ +static char *A1931comm(pEVDriver pData, char *command) +{ char buffer[256], *pPtr; int status; pA1931 self = NULL; Tcl_DString reply; - self = (pA1931)pData->pPrivate; + self = (pA1931) pData->pPrivate; assert(self); - + /* - send - */ - strncpy(buffer,command,250); - strcat(buffer,"\n"); - status = GPIBsend(self->gpib,self->devID,buffer,(int)strlen(buffer)); - if(status < 0){ + send + */ + strncpy(buffer, command, 250); + strcat(buffer, "\n"); + status = GPIBsend(self->gpib, self->devID, buffer, (int) strlen(buffer)); + if (status < 0) { self->errorCode = COMMERROR; - GPIBerrorDescription(self->gpib,status,self->errorBuffer,131); + GPIBerrorDescription(self->gpib, status, self->errorBuffer, 131); return NULL; } /* - read until > is found - */ + read until > is found + */ Tcl_DStringInit(&reply); - while(1){ - pPtr = GPIBreadTillTerm(self->gpib,self->devID,10); - if(strstr(pPtr,"GPIB READ ERROR") != NULL){ + while (1) { + pPtr = GPIBreadTillTerm(self->gpib, self->devID, 10); + if (strstr(pPtr, "GPIB READ ERROR") != NULL) { free(pPtr); self->errorCode = COMMERROR; Tcl_DStringFree(&reply); return NULL; } else { - Tcl_DStringAppend(&reply,pPtr,-1); - if(strchr(pPtr,'>') != NULL){ - /* - finished - */ - free(pPtr); - break; + Tcl_DStringAppend(&reply, pPtr, -1); + if (strchr(pPtr, '>') != NULL) { + /* + finished + */ + free(pPtr); + break; } free(pPtr); } @@ -84,146 +85,163 @@ static char *A1931comm(pEVDriver pData, char *command){ pPtr = NULL; pPtr = strdup(Tcl_DStringValue(&reply)); Tcl_DStringFree(&reply); - if(pPtr[0] == '#'){ + if (pPtr[0] == '#') { /* - error - */ + error + */ self->errorCode = A1931ERROR; - strncpy(self->errorBuffer,pPtr,131); + strncpy(self->errorBuffer, pPtr, 131); free(pPtr); return NULL; } return pPtr; } + /*--------------------------------------------------------------------*/ static int A1931command(pEVDriver pData, char *command, char *replyBuffer, - int replyBufferLen){ + int replyBufferLen) +{ pA1931 self = NULL; char *pReply = NULL; - self = (pA1931)pData->pPrivate; + self = (pA1931) pData->pPrivate; assert(self); - pReply = A1931comm(pData,command); - if(pReply != NULL){ - strncpy(replyBuffer,pReply,replyBufferLen); + pReply = A1931comm(pData, command); + if (pReply != NULL) { + strncpy(replyBuffer, pReply, replyBufferLen); free(pReply); return 1; } else { - strncpy(replyBuffer,self->errorBuffer,replyBufferLen); + strncpy(replyBuffer, self->errorBuffer, replyBufferLen); return 0; } } + /*====================================================================*/ -static int A1931Init(pEVDriver pData){ +static int A1931Init(pEVDriver pData) +{ pA1931 self = NULL; - self = (pA1931)pData->pPrivate; + self = (pA1931) pData->pPrivate; assert(self); - self->devID = GPIBattach(self->gpib,0,self->gpibAddress,0,13,0,0); - if(self->devID < 0){ + self->devID = GPIBattach(self->gpib, 0, self->gpibAddress, 0, 13, 0, 0); + if (self->devID < 0) { return 0; } return 1; } -/*====================================================================*/ -static int A1931Close(pEVDriver pData){ - pA1931 self = NULL; - self = (pA1931)pData->pPrivate; +/*====================================================================*/ +static int A1931Close(pEVDriver pData) +{ + pA1931 self = NULL; + + self = (pA1931) pData->pPrivate; assert(self); - GPIBdetach(self->gpib,self->devID); + GPIBdetach(self->gpib, self->devID); self->devID = 0; return 1; } + /*===================================================================*/ -static int A1931Get(pEVDriver pData,float *fPos){ +static int A1931Get(pEVDriver pData, float *fPos) +{ pA1931 self = NULL; char buffer[132], command[50]; int status; - self = (pA1931)pData->pPrivate; + self = (pA1931) pData->pPrivate; assert(self); - sprintf(command,"?TEMP%1.1d",self->sensor); - status = A1931command(pData,command,buffer,131); - if(!status){ + sprintf(command, "?TEMP%1.1d", self->sensor); + status = A1931command(pData, command, buffer, 131); + if (!status) { return 0; } - sscanf(buffer,"%f",fPos); + sscanf(buffer, "%f", fPos); return 1; } + /*=====================================================================*/ -static int A1931Set(pEVDriver pData, float fNew){ +static int A1931Set(pEVDriver pData, float fNew) +{ pA1931 self = NULL; char buffer[132], command[50]; int status; - self = (pA1931)pData->pPrivate; + self = (pA1931) pData->pPrivate; assert(self); - sprintf(command,"SET%1.1d=%f",self->sensor,fNew); - status = A1931command(pData,command,buffer,131); - if(!status){ + sprintf(command, "SET%1.1d=%f", self->sensor, fNew); + status = A1931command(pData, command, buffer, 131); + if (!status) { return 0; } return 1; } + /*====================================================================*/ -static int A1931error(pEVDriver pData, int *iCode, char *errBuff, int bufLen){ +static int A1931error(pEVDriver pData, int *iCode, char *errBuff, + int bufLen) +{ pA1931 self = NULL; char pError[256]; - self = (pA1931)pData->pPrivate; + self = (pA1931) pData->pPrivate; assert(self); *iCode = self->errorCode; - sprintf(pError,"ERROR: %s",self->errorBuffer); - strncpy(errBuff,pError,bufLen); + sprintf(pError, "ERROR: %s", self->errorBuffer); + strncpy(errBuff, pError, bufLen); return 1; } + /*====================================================================*/ -static int A1931fix(pEVDriver pData, int iCode){ +static int A1931fix(pEVDriver pData, int iCode) +{ pA1931 self = NULL; char pError[256]; - self = (pA1931)pData->pPrivate; + self = (pA1931) pData->pPrivate; assert(self); - if(iCode == COMMERROR){ - GPIBclear(self->gpib,self->devID); + if (iCode == COMMERROR) { + GPIBclear(self->gpib, self->devID); return DEVREDO; - } + } return DEVFAULT; } + /*=====================================================================*/ -pEVDriver CreateA1931Driver(int argc, char *argv[]){ +pEVDriver CreateA1931Driver(int argc, char *argv[]) +{ pEVDriver self = NULL; pA1931 priv = NULL; - if(argc < 2){ + if (argc < 2) { return NULL; } /* - allocate space - */ - self = CreateEVDriver(argc,argv); - priv = (pA1931)malloc(sizeof(A1931)); - if(self == NULL || priv == NULL){ + allocate space + */ + self = CreateEVDriver(argc, argv); + priv = (pA1931) malloc(sizeof(A1931)); + if (self == NULL || priv == NULL) { return NULL; } - memset(priv,0,sizeof(A1931)); + memset(priv, 0, sizeof(A1931)); self->pPrivate = priv; self->KillPrivate = free; /* - initialize - */ - priv->gpib = (pGPIB)FindCommandData(pServ->pSics,argv[0],"GPIB"); - if(!priv->gpib){ + initialize + */ + priv->gpib = (pGPIB) FindCommandData(pServ->pSics, argv[0], "GPIB"); + if (!priv->gpib) { DeleteEVDriver(self); return NULL; } @@ -231,9 +249,9 @@ pEVDriver CreateA1931Driver(int argc, char *argv[]){ priv->gpibAddress = atoi(argv[1]); /* - initialize function pointers - */ - self->Send = A1931command; + initialize function pointers + */ + self->Send = A1931command; self->Init = A1931Init; self->Close = A1931Close; self->GetValue = A1931Get; @@ -243,31 +261,34 @@ pEVDriver CreateA1931Driver(int argc, char *argv[]){ return self; } + /*=======================================================================*/ -static int downloadFile(pA1931 self, FILE *fd){ +static int downloadFile(pA1931 self, FILE * fd) +{ char buffer[132], *pPtr; int status; - while(1){ - if(fgets(buffer,130,fd) == NULL){ + while (1) { + if (fgets(buffer, 130, fd) == NULL) { self->errorCode = FILEERROR; - strcpy(self->errorBuffer,"Failed to read from file"); + strcpy(self->errorBuffer, "Failed to read from file"); return 0; } - if(strstr(buffer,"$END") != NULL){ + if (strstr(buffer, "$END") != NULL) { break; } - status = GPIBsend(self->gpib,self->devID,buffer,(int)strlen(buffer)); - if(status < 0){ + status = + GPIBsend(self->gpib, self->devID, buffer, (int) strlen(buffer)); + if (status < 0) { self->errorCode = COMMERROR; - GPIBerrorDescription(self->gpib,status,self->errorBuffer,131); + GPIBerrorDescription(self->gpib, status, self->errorBuffer, 131); return 0; } - pPtr = GPIBreadTillTerm(self->gpib,self->devID,10); - if(pPtr[0] == '#'){ + pPtr = GPIBreadTillTerm(self->gpib, self->devID, 10); + if (pPtr[0] == '#') { self->errorCode = A1931ERROR; - strncpy(self->errorBuffer,pPtr,131); - strncpy(self->commandLine,buffer,131); + strncpy(self->errorBuffer, pPtr, 131); + strncpy(self->commandLine, buffer, 131); free(pPtr); return 0; } @@ -276,9 +297,11 @@ static int downloadFile(pA1931 self, FILE *fd){ } return 1; } + /*=======================================================================*/ -int A1931Action(SConnection *pCon, SicsInterp *pSics, void *pData, - int argc, char *argv[]){ +int A1931Action(SConnection * pCon, SicsInterp * pSics, void *pData, + int argc, char *argv[]) +{ pEVControl pEV = NULL; pA1931 self = NULL; char buffer[256]; @@ -286,59 +309,59 @@ int A1931Action(SConnection *pCon, SicsInterp *pSics, void *pData, FILE *fd = NULL; int status, iCode; - pEV = (pEVControl)pData; + pEV = (pEVControl) pData; assert(pEV); - self = (pA1931)pEV->pDriv->pPrivate; + self = (pA1931) pEV->pDriv->pPrivate; assert(self); - if(argc > 1){ + if (argc > 1) { strtolower(argv[1]); - if(strcmp(argv[1],"sensor") == 0){ - if(argc > 2){ - /* set case */ - if(!SCMatchRights(pCon,usUser)){ - return 0; - } - self->sensor = atoi(argv[2]); - SCSendOK(pCon); - return 1; + if (strcmp(argv[1], "sensor") == 0) { + if (argc > 2) { + /* set case */ + if (!SCMatchRights(pCon, usUser)) { + return 0; + } + self->sensor = atoi(argv[2]); + SCSendOK(pCon); + return 1; } else { - /* get case */ - sprintf(buffer,"%s.sensor = %d",argv[0],self->sensor); - SCWrite(pCon,buffer,eValue); - return 1; + /* get case */ + sprintf(buffer, "%s.sensor = %d", argv[0], self->sensor); + SCWrite(pCon, buffer, eValue); + return 1; } - }else if(strcmp(argv[1],"list") == 0){ - sprintf(buffer,"%s.sensor = %d",argv[0],self->sensor); - SCWrite(pCon,buffer,eValue); - return EVControlWrapper(pCon,pSics,pData,argc,argv); - } else if(strcmp(argv[1],"file") == 0){ - if(!SCMatchRights(pCon,usUser)){ - return 0; + } else if (strcmp(argv[1], "list") == 0) { + sprintf(buffer, "%s.sensor = %d", argv[0], self->sensor); + SCWrite(pCon, buffer, eValue); + return EVControlWrapper(pCon, pSics, pData, argc, argv); + } else if (strcmp(argv[1], "file") == 0) { + if (!SCMatchRights(pCon, usUser)) { + return 0; } - if(argc < 3){ - SCWrite(pCon,"ERROR: need filename argument",eError); - return 0; + if (argc < 3) { + SCWrite(pCon, "ERROR: need filename argument", eError); + return 0; } - fd = fopen(argv[2],"r"); - if(fd == NULL){ - sprintf(buffer,"ERROR: failed to open %s", argv[2]); - SCWrite(pCon,buffer,eError); - return 0; + fd = fopen(argv[2], "r"); + if (fd == NULL) { + sprintf(buffer, "ERROR: failed to open %s", argv[2]); + SCWrite(pCon, buffer, eError); + return 0; } - status = downloadFile(self,fd); + status = downloadFile(self, fd); fclose(fd); - if(!status){ - A1931error(pEV->pDriv,&iCode,error,131); - sprintf(buffer,"%s while transfering file", error); - SCWrite(pCon,buffer,eError); - sprintf(buffer,"Offending command: %s",self->commandLine); - SCWrite(pCon,buffer,eError); - return 0; + if (!status) { + A1931error(pEV->pDriv, &iCode, error, 131); + sprintf(buffer, "%s while transfering file", error); + SCWrite(pCon, buffer, eError); + sprintf(buffer, "Offending command: %s", self->commandLine); + SCWrite(pCon, buffer, eError); + return 0; } SCSendOK(pCon); return 1; } - } - return EVControlWrapper(pCon,pSics,pData,argc,argv); + } + return EVControlWrapper(pCon, pSics, pData, argc, argv); } diff --git a/A1931.h b/A1931.h index 954813f..3f24667 100644 --- a/A1931.h +++ b/A1931.h @@ -13,8 +13,8 @@ pEVDriver CreateA1931Driver(int argc, char *argv[]); -int A1931Action(SConnection *pCon, SicsInterp *pSics, void *pData, - int argc, char *argv[]); +int A1931Action(SConnection * pCon, SicsInterp * pSics, void *pData, + int argc, char *argv[]); #endif diff --git a/amilevel.c b/amilevel.c index 527c7fe..0cd8768 100644 --- a/amilevel.c +++ b/amilevel.c @@ -42,59 +42,76 @@ typedef struct { static ParClass amiClass = { "AMILEVEL", sizeof(Ami) }; /*----------------------------------------------------------------------------*/ -static void AmiParDef(void *object) { +static void AmiParDef(void *object) +{ Ami *drv = ParCast(&amiClass, object); EaseBase *eab = object; - ParName(""); ParTail("cm"); + ParName(""); + ParTail("cm"); ParFloat(&drv->level, PAR_NAN); - + EaseBasePar(drv); EaseSendPar(drv); ParStdDef(); EaseMsgPar(drv); } + /*----------------------------------------------------------------------------*/ -static long AmiRead(long pc, void *object) { +static long AmiRead(long pc, void *object) +{ Ami *drv = ParCast(&amiClass, object); EaseBase *eab = object; - switch (pc) { default: /* FSM BEGIN *******************************/ + switch (pc) { + default: /* FSM BEGIN ****************************** */ EaseWrite(eab, "level"); - return __LINE__; case __LINE__: /**********************************/ + return __LINE__; + case __LINE__: /**********************************/ drv->level = atof(eab->ans); ParLog(drv); - fsm_quit: return 0; } /* FSM END *********************************/ + fsm_quit:return 0; + } /* FSM END ******************************** */ } + /*----------------------------------------------------------------------------*/ -static long AmiStart(long pc, void *object) { +static long AmiStart(long pc, void *object) +{ Ami *drv = ParCast(&amiClass, object); EaseBase *eab = object; - - switch (pc) { default: /* FSM BEGIN *******************************/ + + switch (pc) { + default: /* FSM BEGIN ****************************** */ EaseWrite(eab, "cm"); - return __LINE__; case __LINE__: /**********************************/ - + return __LINE__; + case __LINE__: /**********************************/ + quit: - return 0; } /* FSM END ********************************************/ + return 0; + } /* FSM END ******************************************* */ } + /*----------------------------------------------------------------------------*/ -static int AmiInit(SConnection *con, int argc, char *argv[], int dynamic) { +static int AmiInit(SConnection * con, int argc, char *argv[], int dynamic) +{ /* args: - MakeObject objectname ami - MakeObject objectname ami + MakeObject objectname ami + MakeObject objectname ami */ Ami *drv; - + drv = EaseMakeBase(con, &amiClass, argc, argv, dynamic, 7, - AmiParDef, LscHandler, AmiStart, NULL, AmiRead); - if (drv == NULL) return 0; - setRS232ReplyTerminator(drv->b.ser,"\n"); - setRS232SendTerminator(drv->b.ser,"\n"); + AmiParDef, LscHandler, AmiStart, NULL, AmiRead); + if (drv == NULL) + return 0; + setRS232ReplyTerminator(drv->b.ser, "\n"); + setRS232SendTerminator(drv->b.ser, "\n"); return 1; } + /*----------------------------------------------------------------------------*/ -void AmiStartup(void) { +void AmiStartup(void) +{ ParMakeClass(&amiClass, EaseBaseClass()); MakeDriver("AMILEVEL", AmiInit, 0, "Ami 135/136 level meter"); } diff --git a/amor2t.c b/amor2t.c index 047b3a0..fab8b6b 100644 --- a/amor2t.c +++ b/amor2t.c @@ -58,7 +58,7 @@ #define MOTSTZ 4 /* whole sample table height movement */ #define MOTSOZ 5 -/* lift for diaphragm 4*/ +/* lift for diaphragm 4*/ #define MOTD4B 6 /* lift for diaphragm 5 */ #define MOTD5B 7 @@ -76,964 +76,887 @@ The core of it all: The calculation of the settings for the various motors. ========================================================================*/ - static void clearRunFlags(pAmor2T self) - { - int i; - - for(i = 0; i < MAXMOT; i++) - { - self->toStart[i].pMot = NULL; - } - } - /*---------------------------------------------------------------------*/ - static int CalculateAMORE(pAmor2T self, SConnection *pCon, float fNew) - { - float fMOM, fSOM, fSTZ, fSOZ, fAOM, fAOZ, fC3Z, fconstAOM; - double fAngle, fX, fZ, fZ2, fBase, fPIR; - float fCOZ, fCOX, fCOM; - int iRet; +static void clearRunFlags(pAmor2T self) +{ + int i; + + for (i = 0; i < MAXMOT; i++) { + self->toStart[i].pMot = NULL; + } +} + + /*---------------------------------------------------------------------*/ +static int CalculateAMORE(pAmor2T self, SConnection * pCon, float fNew) +{ + float fMOM, fSOM, fSTZ, fSOZ, fAOM, fAOZ, fC3Z, fconstAOM; + double fAngle, fX, fZ, fZ2, fBase, fPIR; + float fCOZ, fCOX, fCOM; + int iRet; #ifdef DEBUG - char pBueffel[132]; + char pBueffel[132]; #endif - /* get the necessary angles first */ - iRet = MotorGetSoftPosition(self->aEngine[MOTMOM],pCon,&fMOM); - if(iRet != 1) - { - return iRet; - } - iRet = MotorGetSoftPosition(self->aEngine[MOTSOM],pCon,&fSOM); - if(iRet != 1) - { - return iRet; - } - iRet = MotorGetSoftPosition(self->aEngine[MOTSTZ],pCon,&fSTZ); - if(iRet != 1) - { - return iRet; - } - iRet = MotorGetSoftPosition(self->aEngine[MOTSOZ],pCon,&fSOZ); - if(iRet != 1) - { - return iRet; - } + /* get the necessary angles first */ + iRet = MotorGetSoftPosition(self->aEngine[MOTMOM], pCon, &fMOM); + if (iRet != 1) { + return iRet; + } + iRet = MotorGetSoftPosition(self->aEngine[MOTSOM], pCon, &fSOM); + if (iRet != 1) { + return iRet; + } + iRet = MotorGetSoftPosition(self->aEngine[MOTSTZ], pCon, &fSTZ); + if (iRet != 1) { + return iRet; + } + iRet = MotorGetSoftPosition(self->aEngine[MOTSOZ], pCon, &fSOZ); + if (iRet != 1) { + return iRet; + } - /* calculate base height of sample table */ - fBase = fSOZ + ObVal(self->aParameter,PARDH); - fPIR = 180. / 3.1415926; + /* calculate base height of sample table */ + fBase = fSOZ + ObVal(self->aParameter, PARDH); + fPIR = 180. / 3.1415926; - clearRunFlags(self); - - /* calculation for detector */ - fAngle = fNew - 2*fMOM; - if(fAngle < 0) - { - fAngle = fAngle + 360.; - } - fAngle /= fPIR; - fX = ObVal(self->aParameter,PARDS)*cos(fAngle); - fZ = ObVal(self->aParameter,PARDS)*sin(fAngle); - self->toStart[0].pMot = self->aEngine[MOTCOX]; - strcpy(self->toStart[0].pName,self->aEngine[MOTCOX]->name); - self->toStart[0].fTarget = fX - ObVal(self->aParameter,PARDS); - self->toStart[1].pMot = self->aEngine[MOTCOZ]; - strcpy(self->toStart[1].pName,self->aEngine[MOTCOZ]->name); - self->toStart[1].fTarget = fZ + fBase - - ObVal(self->aParameter,PARDDH); - self->toStart[2].pMot = self->aEngine[MOTCOM]; - strcpy(self->toStart[2].pName,self->aEngine[MOTCOM]->name); - self->toStart[2].fTarget = fNew - 2*fMOM; + clearRunFlags(self); - if(ObVal(self->aParameter,DIAFLAG) > .0) - { - /* calculation for diaphragm 4 */ - fZ = ObVal(self->aParameter,PARDD4) * sin(fAngle); - self->toStart[3].pMot = self->aEngine[MOTD4B]; - strcpy(self->toStart[3].pName,self->aEngine[MOTD4B]->name); - self->toStart[3].fTarget = fBase + fZ - - ObVal(self->aParameter,PARD4H); + /* calculation for detector */ + fAngle = fNew - 2 * fMOM; + if (fAngle < 0) { + fAngle = fAngle + 360.; + } + fAngle /= fPIR; + fX = ObVal(self->aParameter, PARDS) * cos(fAngle); + fZ = ObVal(self->aParameter, PARDS) * sin(fAngle); + self->toStart[0].pMot = self->aEngine[MOTCOX]; + strcpy(self->toStart[0].pName, self->aEngine[MOTCOX]->name); + self->toStart[0].fTarget = fX - ObVal(self->aParameter, PARDS); + self->toStart[1].pMot = self->aEngine[MOTCOZ]; + strcpy(self->toStart[1].pName, self->aEngine[MOTCOZ]->name); + self->toStart[1].fTarget = fZ + fBase - ObVal(self->aParameter, PARDDH); + self->toStart[2].pMot = self->aEngine[MOTCOM]; + strcpy(self->toStart[2].pName, self->aEngine[MOTCOM]->name); + self->toStart[2].fTarget = fNew - 2 * fMOM; - /* calculation for diaphragm 5 */ - fZ = ObVal(self->aParameter,PARDD5) * sin(fAngle); - self->toStart[4].pMot = self->aEngine[MOTD5B]; - strcpy(self->toStart[4].pName,self->aEngine[MOTD5B]->name); - self->toStart[4].fTarget = fBase + fZ - - ObVal(self->aParameter,PARD5H); + if (ObVal(self->aParameter, DIAFLAG) > .0) { + /* calculation for diaphragm 4 */ + fZ = ObVal(self->aParameter, PARDD4) * sin(fAngle); + self->toStart[3].pMot = self->aEngine[MOTD4B]; + strcpy(self->toStart[3].pName, self->aEngine[MOTD4B]->name); + self->toStart[3].fTarget = fBase + fZ - + ObVal(self->aParameter, PARD4H); + + /* calculation for diaphragm 5 */ + fZ = ObVal(self->aParameter, PARDD5) * sin(fAngle); + self->toStart[4].pMot = self->aEngine[MOTD5B]; + strcpy(self->toStart[4].pName, self->aEngine[MOTD5B]->name); + self->toStart[4].fTarget = fBase + fZ - + ObVal(self->aParameter, PARD5H); #ifdef DEBUG - sprintf(pBueffel,"2T COZ COX COM D4B D5B "); - SCWrite(pCon,pBueffel,eValue); - sprintf(pBueffel,"%6.2f %6.2f %6.2f %6.2f %6.2f %6.2f", - fNew, self->toStart[1].fTarget, self->toStart[0].fTarget, - self->toStart[2].fTarget, self->toStart[3].fTarget, - self->toStart[4].fTarget); - SCWrite(pCon,pBueffel,eValue); + sprintf(pBueffel, "2T COZ COX COM D4B D5B "); + SCWrite(pCon, pBueffel, eValue); + sprintf(pBueffel, "%6.2f %6.2f %6.2f %6.2f %6.2f %6.2f", + fNew, self->toStart[1].fTarget, self->toStart[0].fTarget, + self->toStart[2].fTarget, self->toStart[3].fTarget, + self->toStart[4].fTarget); + SCWrite(pCon, pBueffel, eValue); #endif - } + } - if(ObVal(self->aParameter,ANAFLAG) > 0) - { - /* the analyzer height */ - fZ = ObVal(self->aParameter,PARADIS)*sin(fAngle); - fAOZ = fBase + fZ - ObVal(self->aParameter,PARANA); - self->toStart[5].pMot = self->aEngine[MOTAOZ]; - strcpy(self->toStart[5].pName,self->aEngine[MOTAOZ]->name); - self->toStart[5].fTarget = fAOZ; + if (ObVal(self->aParameter, ANAFLAG) > 0) { + /* the analyzer height */ + fZ = ObVal(self->aParameter, PARADIS) * sin(fAngle); + fAOZ = fBase + fZ - ObVal(self->aParameter, PARANA); + self->toStart[5].pMot = self->aEngine[MOTAOZ]; + strcpy(self->toStart[5].pName, self->aEngine[MOTAOZ]->name); + self->toStart[5].fTarget = fAOZ; - /* analyzer omega */ - self->toStart[6].pMot = self->aEngine[MOTAOM]; - strcpy(self->toStart[6].pName,self->aEngine[MOTAOM]->name); - self->toStart[6].fTarget = fNew/2. - + ObVal(self->aParameter,PARAOM); + /* analyzer omega */ + self->toStart[6].pMot = self->aEngine[MOTAOM]; + strcpy(self->toStart[6].pName, self->aEngine[MOTAOM]->name); + self->toStart[6].fTarget = fNew / 2. + ObVal(self->aParameter, PARAOM); - /* C3Z */ - fZ2 = (ObVal(self->aParameter,PARDS) - ObVal(self->aParameter, - PARADIS))*sin(fAngle + (fNew/fPIR) ); - - self->toStart[7].pMot = self->aEngine[MOTC3Z]; - strcpy(self->toStart[7].pName,self->aEngine[MOTC3Z]->name); - self->toStart[7].fTarget = fBase + fZ + fZ2 - - ObVal(self->aParameter,PARDDD) - - self->toStart[1].fTarget; + /* C3Z */ + fZ2 = (ObVal(self->aParameter, PARDS) - ObVal(self->aParameter, + PARADIS)) * sin(fAngle + + (fNew / + fPIR)); + + self->toStart[7].pMot = self->aEngine[MOTC3Z]; + strcpy(self->toStart[7].pName, self->aEngine[MOTC3Z]->name); + self->toStart[7].fTarget = fBase + fZ + fZ2 - + ObVal(self->aParameter, PARDDD) - self->toStart[1].fTarget; #ifdef DEBUG - sprintf(pBueffel,"2T AOZ AOM C3Z"); - SCWrite(pCon,pBueffel,eValue); - sprintf(pBueffel,"%6.2f %6.2f %6.2f %6.2f", - fNew, self->toStart[5].fTarget, self->toStart[6].fTarget, - self->toStart[7].fTarget); - SCWrite(pCon,pBueffel,eValue); + sprintf(pBueffel, "2T AOZ AOM C3Z"); + SCWrite(pCon, pBueffel, eValue); + sprintf(pBueffel, "%6.2f %6.2f %6.2f %6.2f", + fNew, self->toStart[5].fTarget, self->toStart[6].fTarget, + self->toStart[7].fTarget); + SCWrite(pCon, pBueffel, eValue); #endif - - } - return 1; - } + + } + return 1; +} + /*======================================================================= Calculations for Analyzer two theta =========================================================================*/ - static int CalculateANA2T(pAmor2T self, SConnection *pCon, float fNew) - { - double fBase, fPIR; - float fAOZ, fIncident, fSOM, fMOM, fDiffracted, fDistance, fX, fZ; - int iRet; +static int CalculateANA2T(pAmor2T self, SConnection * pCon, float fNew) +{ + double fBase, fPIR; + float fAOZ, fIncident, fSOM, fMOM, fDiffracted, fDistance, fX, fZ; + int iRet; #ifdef DEBUG - char pBueffel[132]; + char pBueffel[132]; #endif - /* calculate base height of analyzer table */ - iRet = MotorGetSoftPosition(self->aEngine[MOTSOZ],pCon,&fAOZ); - if(iRet != 1) - { - return iRet; - } - fBase = fAOZ + ObVal(self->aParameter,PARANA); - fPIR = 180. / 3.1415926; + /* calculate base height of analyzer table */ + iRet = MotorGetSoftPosition(self->aEngine[MOTSOZ], pCon, &fAOZ); + if (iRet != 1) { + return iRet; + } + fBase = fAOZ + ObVal(self->aParameter, PARANA); + fPIR = 180. / 3.1415926; - /* Calculate the incident angle at the analyzer */ - iRet = MotorGetSoftPosition(self->aEngine[MOTSOM],pCon,&fSOM); - if(iRet != 1) - { - return iRet; - } - iRet = MotorGetSoftPosition(self->aEngine[MOTMOM],pCon,&fMOM); - if(iRet != 1) - { - return iRet; - } - fIncident = fMOM + 2. * fSOM; - - /* calculate the angle of the diffracted beam against the - horizon at the analyzer. + /* Calculate the incident angle at the analyzer */ + iRet = MotorGetSoftPosition(self->aEngine[MOTSOM], pCon, &fSOM); + if (iRet != 1) { + return iRet; + } + iRet = MotorGetSoftPosition(self->aEngine[MOTMOM], pCon, &fMOM); + if (iRet != 1) { + return iRet; + } + fIncident = fMOM + 2. * fSOM; - fDiffracted = fIncident - 2. * AOM. - - There is a problem here. We should read AOM in order to get the - value. However in the context of an omega - two-theta scan on AOM - and ana2t, it is fNew. - */ - fDiffracted = fIncident - fNew; + /* calculate the angle of the diffracted beam against the + horizon at the analyzer. - clearRunFlags(self); - - /* calculation for detector */ - fDiffracted /= fPIR; - fDistance = ObVal(self->aParameter,PARDS) - - ObVal(self->aParameter, PARANA); - fX = fDistance*cos(fDiffracted); - fZ = fDistance*sin(fDiffracted); - self->toStart[0].pMot = self->aEngine[MOTCOX]; - strcpy(self->toStart[0].pName,self->aEngine[MOTCOX]->name); - self->toStart[0].fTarget = fX - fDistance; + fDiffracted = fIncident - 2. * AOM. - self->toStart[1].pMot = self->aEngine[MOTCOZ]; - strcpy(self->toStart[1].pName,self->aEngine[MOTCOZ]->name); - self->toStart[1].fTarget = fZ + fBase - - ObVal(self->aParameter,PARDDH); + There is a problem here. We should read AOM in order to get the + value. However in the context of an omega - two-theta scan on AOM + and ana2t, it is fNew. + */ + fDiffracted = fIncident - fNew; - self->toStart[2].pMot = self->aEngine[MOTCOM]; - strcpy(self->toStart[2].pName,self->aEngine[MOTCOM]->name); - self->toStart[2].fTarget = -fDiffracted*fPIR; + clearRunFlags(self); - /* calculation for diaphragm 5 */ - if(ObVal(self->aParameter,DIAFLAG) > .0) - { - fZ = ObVal(self->aParameter,PARDD5) * sin(fDiffracted); - self->toStart[3].pMot = self->aEngine[MOTD5B]; - strcpy(self->toStart[3].pName,self->aEngine[MOTD5B]->name); - self->toStart[3].fTarget = fBase + fZ - - ObVal(self->aParameter,PARD5H); - } + /* calculation for detector */ + fDiffracted /= fPIR; + fDistance = ObVal(self->aParameter, PARDS) - + ObVal(self->aParameter, PARANA); + fX = fDistance * cos(fDiffracted); + fZ = fDistance * sin(fDiffracted); + self->toStart[0].pMot = self->aEngine[MOTCOX]; + strcpy(self->toStart[0].pName, self->aEngine[MOTCOX]->name); + self->toStart[0].fTarget = fX - fDistance; + + self->toStart[1].pMot = self->aEngine[MOTCOZ]; + strcpy(self->toStart[1].pName, self->aEngine[MOTCOZ]->name); + self->toStart[1].fTarget = fZ + fBase - ObVal(self->aParameter, PARDDH); + + self->toStart[2].pMot = self->aEngine[MOTCOM]; + strcpy(self->toStart[2].pName, self->aEngine[MOTCOM]->name); + self->toStart[2].fTarget = -fDiffracted * fPIR; + + /* calculation for diaphragm 5 */ + if (ObVal(self->aParameter, DIAFLAG) > .0) { + fZ = ObVal(self->aParameter, PARDD5) * sin(fDiffracted); + self->toStart[3].pMot = self->aEngine[MOTD5B]; + strcpy(self->toStart[3].pName, self->aEngine[MOTD5B]->name); + self->toStart[3].fTarget = fBase + fZ - + ObVal(self->aParameter, PARD5H); + } #ifdef DEBUG - sprintf(pBueffel,"2T COX COZ COM D5B "); - SCWrite(pCon,pBueffel,eValue); - sprintf(pBueffel,"%6.2f %6.2f %6.2f %6.2f %6.2f ", - fNew, self->toStart[0].fTarget, self->toStart[1].fTarget, - self->toStart[2].fTarget,self->toStart[3].fTarget); - SCWrite(pCon,pBueffel,eValue); + sprintf(pBueffel, "2T COX COZ COM D5B "); + SCWrite(pCon, pBueffel, eValue); + sprintf(pBueffel, "%6.2f %6.2f %6.2f %6.2f %6.2f ", + fNew, self->toStart[0].fTarget, self->toStart[1].fTarget, + self->toStart[2].fTarget, self->toStart[3].fTarget); + SCWrite(pCon, pBueffel, eValue); #endif - return 1; - } + return 1; +} + /*======================================================================== Definition of interface functions. =========================================================================*/ - static long A2TSetValue(void *pData, SConnection *pCon, float fNew) - { - int i, iRet; - pIDrivable pDriv = NULL; - pAmor2T self = (pAmor2T) pData; +static long A2TSetValue(void *pData, SConnection * pCon, float fNew) +{ + int i, iRet; + pIDrivable pDriv = NULL; + pAmor2T self = (pAmor2T) pData; - assert(self); + assert(self); - /* calculation */ - iRet = CalculateAMORE(self,pCon,fNew); - if(iRet != 1) - { + /* calculation */ + iRet = CalculateAMORE(self, pCon, fNew); + if (iRet != 1) { + return iRet; + } + + /* start them all */ + for (i = 0; i < MAXMOT; i++) { + if (self->toStart[i].pMot == NULL) { + continue; + } + pDriv = + self->toStart[i].pMot->pDescriptor->GetInterface(self->toStart[i]. + pMot, DRIVEID); + if (pDriv != NULL) { + iRet = pDriv->SetValue(self->toStart[i].pMot, pCon, + self->toStart[i].fTarget); + if (iRet != OKOK) { return iRet; } - - /* start them all */ - for(i = 0; i < MAXMOT; i++) - { - if(self->toStart[i].pMot == NULL) - { - continue; - } - pDriv = self->toStart[i].pMot->pDescriptor->GetInterface( - self->toStart[i].pMot,DRIVEID); - if(pDriv != NULL) - { - iRet = pDriv->SetValue(self->toStart[i].pMot,pCon, - self->toStart[i].fTarget); - if(iRet != OKOK) - { - return iRet; - } - } - } - return OKOK; - } + } + } + return OKOK; +} + /*--------------------------------------------------------------------*/ - static long ANA2TSetValue(void *pData, SConnection *pCon, float fNew) - { - int i, iRet; - pIDrivable pDriv = NULL; - pAmor2T self = (pAmor2T) pData; +static long ANA2TSetValue(void *pData, SConnection * pCon, float fNew) +{ + int i, iRet; + pIDrivable pDriv = NULL; + pAmor2T self = (pAmor2T) pData; - assert(self); + assert(self); - /* calculation */ - iRet = CalculateANA2T(self,pCon,fNew); - if(iRet != 1) - { + /* calculation */ + iRet = CalculateANA2T(self, pCon, fNew); + if (iRet != 1) { + return iRet; + } + + /* start them all */ + for (i = 0; i < MAXMOT; i++) { + if (self->toStart[i].pMot == NULL) { + continue; + } + pDriv = + self->toStart[i].pMot->pDescriptor->GetInterface(self->toStart[i]. + pMot, DRIVEID); + if (pDriv != NULL) { + iRet = pDriv->SetValue(self->toStart[i].pMot, pCon, + self->toStart[i].fTarget); + if (iRet != OKOK) { return iRet; } - - /* start them all */ - for(i = 0; i < MAXMOT; i++) - { - if(self->toStart[i].pMot == NULL) - { - continue; - } - pDriv = self->toStart[i].pMot->pDescriptor->GetInterface( - self->toStart[i].pMot,DRIVEID); - if(pDriv != NULL) - { - iRet = pDriv->SetValue(self->toStart[i].pMot,pCon, - self->toStart[i].fTarget); - if(iRet != OKOK) - { - return iRet; - } - } - } - return OKOK; - } + } + } + return OKOK; +} + /*-------------------------------------------------------------------------*/ - static int A2THalt(void *pData) - { - int i, iRet; - pIDrivable pDriv = NULL; - pAmor2T self = (pAmor2T) pData; +static int A2THalt(void *pData) +{ + int i, iRet; + pIDrivable pDriv = NULL; + pAmor2T self = (pAmor2T) pData; - assert(self); + assert(self); + + /* stop them all */ + for (i = 0; i < MAXMOT; i++) { + if (self->toStart[i].pMot == NULL) { + continue; + } + pDriv = + self->toStart[i].pMot->pDescriptor->GetInterface(self->toStart[i]. + pMot, DRIVEID); + if (pDriv != NULL) { + iRet = pDriv->Halt(self->toStart[i].pMot); + } + } + return OKOK; +} - /* stop them all */ - for(i = 0; i < MAXMOT; i++) - { - if(self->toStart[i].pMot == NULL) - { - continue; - } - pDriv = self->toStart[i].pMot->pDescriptor->GetInterface( - self->toStart[i].pMot,DRIVEID); - if(pDriv != NULL) - { - iRet = pDriv->Halt(self->toStart[i].pMot); - } - } - return OKOK; - } /*-----------------------------------------------------------------------*/ - static int A2TCheck(void *pData, float fNew, char *error, int iErrLen) - { - int i, iRet; - pIDrivable pDriv = NULL; - pAmor2T self = (pAmor2T) pData; - SConnection *pDumCon = NULL; +static int A2TCheck(void *pData, float fNew, char *error, int iErrLen) +{ + int i, iRet; + pIDrivable pDriv = NULL; + pAmor2T self = (pAmor2T) pData; + SConnection *pDumCon = NULL; - assert(self); - pDumCon = SCCreateDummyConnection(pServ->pSics); - assert(pDumCon); + assert(self); + pDumCon = SCCreateDummyConnection(pServ->pSics); + assert(pDumCon); - /* calculation */ - iRet = CalculateAMORE(self,pDumCon,fNew); - SCDeleteConnection(pDumCon); - if(iRet != 1) - { + /* calculation */ + iRet = CalculateAMORE(self, pDumCon, fNew); + SCDeleteConnection(pDumCon); + if (iRet != 1) { + return iRet; + } + + /* check them all */ + for (i = 0; i < MAXMOT; i++) { + if (self->toStart[i].pMot == NULL) { + continue; + } + pDriv = + self->toStart[i].pMot->pDescriptor->GetInterface(self->toStart[i]. + pMot, DRIVEID); + if (pDriv != NULL) { + iRet = pDriv->CheckLimits(self->toStart[i].pMot, + self->toStart[i].fTarget, error, iErrLen); + if (iRet != 1) { return iRet; } - - /* check them all */ - for(i = 0; i < MAXMOT; i++) - { - if(self->toStart[i].pMot == NULL) - { - continue; - } - pDriv = self->toStart[i].pMot->pDescriptor->GetInterface( - self->toStart[i].pMot,DRIVEID); - if(pDriv != NULL) - { - iRet = pDriv->CheckLimits(self->toStart[i].pMot, - self->toStart[i].fTarget, - error,iErrLen); - if(iRet != 1) - { - return iRet; - } - } - } - return 1; - } + } + } + return 1; +} + /*-------------------------------------------------------------------*/ - static int ANA2TCheck(void *pData, float fNew, char *error, int iErrLen) - { - int i, iRet; - pIDrivable pDriv = NULL; - pAmor2T self = (pAmor2T) pData; - SConnection *pDumCon = NULL; +static int ANA2TCheck(void *pData, float fNew, char *error, int iErrLen) +{ + int i, iRet; + pIDrivable pDriv = NULL; + pAmor2T self = (pAmor2T) pData; + SConnection *pDumCon = NULL; - assert(self); - pDumCon = SCCreateDummyConnection(pServ->pSics); - assert(pDumCon); + assert(self); + pDumCon = SCCreateDummyConnection(pServ->pSics); + assert(pDumCon); - /* calculation */ - iRet = CalculateANA2T(self,pDumCon,fNew); - SCDeleteConnection(pDumCon); - if(iRet != 1) - { + /* calculation */ + iRet = CalculateANA2T(self, pDumCon, fNew); + SCDeleteConnection(pDumCon); + if (iRet != 1) { + return iRet; + } + + /* check them all */ + for (i = 0; i < MAXMOT; i++) { + if (self->toStart[i].pMot == NULL) { + continue; + } + pDriv = + self->toStart[i].pMot->pDescriptor->GetInterface(self->toStart[i]. + pMot, DRIVEID); + if (pDriv != NULL) { + iRet = pDriv->CheckLimits(self->toStart[i].pMot, + self->toStart[i].fTarget, error, iErrLen); + if (iRet != 1) { return iRet; } - - /* check them all */ - for(i = 0; i < MAXMOT; i++) - { - if(self->toStart[i].pMot == NULL) - { - continue; - } - pDriv = self->toStart[i].pMot->pDescriptor->GetInterface( - self->toStart[i].pMot,DRIVEID); - if(pDriv != NULL) - { - iRet = pDriv->CheckLimits(self->toStart[i].pMot, - self->toStart[i].fTarget, - error,iErrLen); - if(iRet != 1) - { - return iRet; - } - } + } + } + return 1; +} + +/*------------------------------------------------------------------------*/ +static int A2TStatus(void *pData, SConnection * pCon) +{ + int i, iRet; + pIDrivable pDriv = NULL; + pAmor2T self = (pAmor2T) pData; + + assert(self); + + /* check them all */ + for (i = 0; i < MAXMOT; i++) { + if (self->toStart[i].pMot == NULL) { + continue; + } + pDriv = + self->toStart[i].pMot->pDescriptor->GetInterface(self->toStart[i]. + pMot, DRIVEID); + if (pDriv != NULL) { + iRet = pDriv->CheckStatus(self->toStart[i].pMot, pCon); + if ((iRet != OKOK) && (iRet != HWIdle)) { + return iRet; } - return 1; - } + } + } + return iRet; +} + /*------------------------------------------------------------------------*/ - static int A2TStatus(void *pData, SConnection *pCon) - { - int i, iRet; - pIDrivable pDriv = NULL; - pAmor2T self = (pAmor2T) pData; +static float A2TGetValue(void *pData, SConnection * pCon) +{ + float fVal, fMOM, fResult; + int iRet; + pAmor2T self = (pAmor2T) pData; - assert(self); + assert(self); + + /* get COM */ + iRet = MotorGetSoftPosition(self->aEngine[MOTCOM], pCon, &fVal); + if (!iRet) { + return -9999.99; + } + /* get MOM */ + iRet = MotorGetSoftPosition(self->aEngine[MOTMOM], pCon, &fMOM); + if (!iRet) { + return -9999.99; + } + + /* retrocalculate 2 theta */ + fResult = fVal + 2 * fMOM; + return fResult; +} - /* check them all */ - for(i = 0; i < MAXMOT; i++) - { - if(self->toStart[i].pMot == NULL) - { - continue; - } - pDriv = self->toStart[i].pMot->pDescriptor->GetInterface( - self->toStart[i].pMot,DRIVEID); - if(pDriv != NULL) - { - iRet = pDriv->CheckStatus(self->toStart[i].pMot,pCon); - if( (iRet != OKOK) && (iRet != HWIdle) ) - { - return iRet; - } - } - } - return iRet; - } /*------------------------------------------------------------------------*/ - static float A2TGetValue(void *pData, SConnection *pCon) - { - float fVal, fMOM, fResult; - int iRet; - pAmor2T self = (pAmor2T) pData; - - assert(self); +static float ANA2TGetValue(void *pData, SConnection * pCon) +{ + float fVal, fMOM, fResult; + int iRet; + pAmor2T self = (pAmor2T) pData; - /* get COM */ - iRet = MotorGetSoftPosition(self->aEngine[MOTCOM], pCon, &fVal); - if(!iRet) - { - return -9999.99; - } - /* get MOM */ - iRet = MotorGetSoftPosition(self->aEngine[MOTMOM], pCon, &fMOM); - if(!iRet) - { - return -9999.99; - } - - /* retrocalculate 2 theta */ - fResult = fVal + 2*fMOM; - return fResult; - } -/*------------------------------------------------------------------------*/ - static float ANA2TGetValue(void *pData, SConnection *pCon) - { - float fVal, fMOM, fResult; - int iRet; - pAmor2T self = (pAmor2T) pData; - - assert(self); + assert(self); - /* get AOM */ - iRet = MotorGetSoftPosition(self->aEngine[MOTAOM], pCon, &fVal); - if(!iRet) - { - return -9999.99; - } + /* get AOM */ + iRet = MotorGetSoftPosition(self->aEngine[MOTAOM], pCon, &fVal); + if (!iRet) { + return -9999.99; + } - return 2. * fVal; + return 2. * fVal; + +} - } /*-----------------------------------------------------------------------*/ - static void *A2TGetInterface(void *pData, int iID) - { - pAmor2T self = (pAmor2T) pData; - - assert(self); - if(iID == DRIVEID) - { - return self->pDriv; - } - return NULL; - } +static void *A2TGetInterface(void *pData, int iID) +{ + pAmor2T self = (pAmor2T) pData; + + assert(self); + if (iID == DRIVEID) { + return self->pDriv; + } + return NULL; +} + /*------------------------------------------------------------------------*/ - static int A2TSave(void *pData, char *name, FILE *fd) - { - int i; - pAmor2T self = (pAmor2T) pData; - - assert(self); +static int A2TSave(void *pData, char *name, FILE * fd) +{ + int i; + pAmor2T self = (pAmor2T) pData; + + assert(self); + + fprintf(fd, "%s detectord %f \n", name, ObVal(self->aParameter, PARDS)); + fprintf(fd, "%s sampleh %f \n", name, ObVal(self->aParameter, PARDH)); + fprintf(fd, "%s d4d %f \n", name, ObVal(self->aParameter, PARDD4)); + fprintf(fd, "%s d5d %f \n", name, ObVal(self->aParameter, PARDD5)); + fprintf(fd, "%s interrupt %f \n", name, ObVal(self->aParameter, PARINT)); + fprintf(fd, "%s detectorh %f \n", name, ObVal(self->aParameter, PARDDH)); + fprintf(fd, "%s d4h %f \n", name, ObVal(self->aParameter, PARD4H)); + fprintf(fd, "%s d5h %f \n", name, ObVal(self->aParameter, PARD5H)); + fprintf(fd, "%s anah %f \n", name, ObVal(self->aParameter, PARANA)); + fprintf(fd, "%s anad %f \n", name, ObVal(self->aParameter, PARADIS)); + fprintf(fd, "%s anaflag %f \n", name, ObVal(self->aParameter, ANAFLAG)); + fprintf(fd, "%s c2h %f \n", name, ObVal(self->aParameter, PARDDD)); + fprintf(fd, "%s aomconst %f \n", name, ObVal(self->aParameter, PARAOM)); + fprintf(fd, "%s diaflag %f \n", name, ObVal(self->aParameter, DIAFLAG)); + return 1; +} - fprintf(fd,"%s detectord %f \n", name, ObVal(self->aParameter,PARDS)); - fprintf(fd,"%s sampleh %f \n", name, ObVal(self->aParameter,PARDH)); - fprintf(fd,"%s d4d %f \n", name, ObVal(self->aParameter,PARDD4)); - fprintf(fd,"%s d5d %f \n", name, ObVal(self->aParameter,PARDD5)); - fprintf(fd,"%s interrupt %f \n", name, ObVal(self->aParameter,PARINT)); - fprintf(fd,"%s detectorh %f \n", name, ObVal(self->aParameter,PARDDH)); - fprintf(fd,"%s d4h %f \n", name, ObVal(self->aParameter,PARD4H)); - fprintf(fd,"%s d5h %f \n", name, ObVal(self->aParameter,PARD5H)); - fprintf(fd,"%s anah %f \n", name, ObVal(self->aParameter,PARANA)); - fprintf(fd,"%s anad %f \n", name, ObVal(self->aParameter,PARADIS)); - fprintf(fd,"%s anaflag %f \n", name, ObVal(self->aParameter,ANAFLAG)); - fprintf(fd,"%s c2h %f \n", name, ObVal(self->aParameter,PARDDD)); - fprintf(fd,"%s aomconst %f \n", name, ObVal(self->aParameter,PARAOM)); - fprintf(fd,"%s diaflag %f \n", name, ObVal(self->aParameter,DIAFLAG)); - return 1; - } /*------------------------------------------------------------------------*/ - static void A2TList(pAmor2T self, SConnection *pCon, char *name) - { - char pBueffel[132]; - Tcl_DString tString; +static void A2TList(pAmor2T self, SConnection * pCon, char *name) +{ + char pBueffel[132]; + Tcl_DString tString; + + assert(pCon); + assert(self); + + Tcl_DStringInit(&tString); + sprintf(pBueffel, + "%s.detectord %f \n", name, ObVal(self->aParameter, PARDS)); + Tcl_DStringAppend(&tString, pBueffel, -1); + sprintf(pBueffel, + "%s.sampleh %f \n", name, ObVal(self->aParameter, PARDH)); + Tcl_DStringAppend(&tString, pBueffel, -1); + sprintf(pBueffel, "%s.d4d %f \n", name, ObVal(self->aParameter, PARDD4)); + Tcl_DStringAppend(&tString, pBueffel, -1); + sprintf(pBueffel, "%s.d5d %f \n", name, ObVal(self->aParameter, PARDD5)); + Tcl_DStringAppend(&tString, pBueffel, -1); + sprintf(pBueffel, + "%s.interrupt %f \n", name, ObVal(self->aParameter, PARINT)); + Tcl_DStringAppend(&tString, pBueffel, -1); + sprintf(pBueffel, + "%s.detectorh %f \n", name, ObVal(self->aParameter, PARDDH)); + Tcl_DStringAppend(&tString, pBueffel, -1); + sprintf(pBueffel, "%s.d4h %f \n", name, ObVal(self->aParameter, PARD4H)); + Tcl_DStringAppend(&tString, pBueffel, -1); + sprintf(pBueffel, "%s.d5h %f \n", name, ObVal(self->aParameter, PARD5H)); + Tcl_DStringAppend(&tString, pBueffel, -1); + sprintf(pBueffel, + "%s.anah %f \n", name, ObVal(self->aParameter, PARANA)); + Tcl_DStringAppend(&tString, pBueffel, -1); + sprintf(pBueffel, + "%s.anad %f \n", name, ObVal(self->aParameter, PARADIS)); + Tcl_DStringAppend(&tString, pBueffel, -1); + sprintf(pBueffel, + "%s.anaflag %f \n", name, ObVal(self->aParameter, ANAFLAG)); + Tcl_DStringAppend(&tString, pBueffel, -1); + sprintf(pBueffel, "%s.c2h %f \n", name, ObVal(self->aParameter, PARDDD)); + Tcl_DStringAppend(&tString, pBueffel, -1); + sprintf(pBueffel, + "%s.aomconst %f \n", name, ObVal(self->aParameter, PARAOM)); + Tcl_DStringAppend(&tString, pBueffel, -1); + sprintf(pBueffel, + "%s.diaflag %f \n", name, ObVal(self->aParameter, DIAFLAG)); + Tcl_DStringAppend(&tString, pBueffel, -1); + SCWrite(pCon, Tcl_DStringValue(&tString), eValue); + Tcl_DStringFree(&tString); +} - assert(pCon); - assert(self); - - Tcl_DStringInit(&tString); - sprintf(pBueffel, - "%s.detectord %f \n", name, ObVal(self->aParameter,PARDS)); - Tcl_DStringAppend(&tString,pBueffel,-1); - sprintf(pBueffel, - "%s.sampleh %f \n", name, ObVal(self->aParameter,PARDH)); - Tcl_DStringAppend(&tString,pBueffel,-1); - sprintf(pBueffel, - "%s.d4d %f \n", name, ObVal(self->aParameter,PARDD4)); - Tcl_DStringAppend(&tString,pBueffel,-1); - sprintf(pBueffel, - "%s.d5d %f \n", name, ObVal(self->aParameter,PARDD5)); - Tcl_DStringAppend(&tString,pBueffel,-1); - sprintf(pBueffel, - "%s.interrupt %f \n", name, ObVal(self->aParameter,PARINT)); - Tcl_DStringAppend(&tString,pBueffel,-1); - sprintf(pBueffel, - "%s.detectorh %f \n", name, ObVal(self->aParameter,PARDDH)); - Tcl_DStringAppend(&tString,pBueffel,-1); - sprintf(pBueffel, - "%s.d4h %f \n", name, ObVal(self->aParameter,PARD4H)); - Tcl_DStringAppend(&tString,pBueffel,-1); - sprintf(pBueffel, - "%s.d5h %f \n", name, ObVal(self->aParameter,PARD5H)); - Tcl_DStringAppend(&tString,pBueffel,-1); - sprintf(pBueffel, - "%s.anah %f \n", name, ObVal(self->aParameter,PARANA)); - Tcl_DStringAppend(&tString,pBueffel,-1); - sprintf(pBueffel, - "%s.anad %f \n", name, ObVal(self->aParameter,PARADIS)); - Tcl_DStringAppend(&tString,pBueffel,-1); - sprintf(pBueffel, - "%s.anaflag %f \n", name, ObVal(self->aParameter,ANAFLAG)); - Tcl_DStringAppend(&tString,pBueffel,-1); - sprintf(pBueffel, - "%s.c2h %f \n", name, ObVal(self->aParameter,PARDDD)); - Tcl_DStringAppend(&tString,pBueffel,-1); - sprintf(pBueffel, - "%s.aomconst %f \n", name, ObVal(self->aParameter,PARAOM)); - Tcl_DStringAppend(&tString,pBueffel,-1); - sprintf(pBueffel, - "%s.diaflag %f \n", name, ObVal(self->aParameter,DIAFLAG)); - Tcl_DStringAppend(&tString,pBueffel,-1); - SCWrite(pCon,Tcl_DStringValue(&tString),eValue); - Tcl_DStringFree(&tString); - } /*------------------------------------------------------------------------*/ - static void A2TKill(void *pData) - { - pAmor2T self = (pAmor2T) pData; - - if(self == NULL) - return; +static void A2TKill(void *pData) +{ + pAmor2T self = (pAmor2T) pData; - if(self->pDes) - DeleteDescriptor(self->pDes); + if (self == NULL) + return; - if(self->pDriv) - free(self->pDriv); + if (self->pDes) + DeleteDescriptor(self->pDes); - if(self->aParameter) - ObParDelete(self->aParameter); + if (self->pDriv) + free(self->pDriv); + + if (self->aParameter) + ObParDelete(self->aParameter); + + free(self); +} - free(self); - } /*-------------------------------------------------------------------------- Initialization: All is done from the Factory function. This takes an Tcl array as parameter which is supposed to hold the names of all motors. This must fail if one of the motors cannot be accessed. --------------------------------------------------------------------------*/ - int Amor2TFactory(SConnection *pCon, SicsInterp *pSics, void *pData, - int argc, char *argv[]) - { - pAmor2T pNew, pAOM = NULL; - int i, iRet; - char pBueffel[512]; - const char *pMot = NULL; +int Amor2TFactory(SConnection * pCon, SicsInterp * pSics, void *pData, + int argc, char *argv[]) +{ + pAmor2T pNew, pAOM = NULL; + int i, iRet; + char pBueffel[512]; + const char *pMot = NULL; - if(argc < 4) - { - SCWrite(pCon, + if (argc < 4) { + SCWrite(pCon, "ERROR: Insufficient number of arguments to Amor2tFactory", - eError); - return 0; - } + eError); + return 0; + } - /* allocate space ..............*/ - pNew = (pAmor2T)malloc(sizeof(Amor2T)); - if(!pNew) - { - SCWrite(pCon,"ERROR: out of memory in Amor2TFactory",eError); - return 0; - } - memset(pNew,0,sizeof(Amor2T)); - pNew->pDes = CreateDescriptor("Amor2T"); - pNew->aParameter = ObParCreate(MAXPAR); - pNew->pDriv = CreateDrivableInterface(); - if( (!pNew->pDes) || (!pNew->aParameter) || (!pNew->pDriv) ) - { - SCWrite(pCon,"ERROR: out of memory in Amor2TFactory",eError); - A2TKill(pNew); - return 0; - } + /* allocate space .............. */ + pNew = (pAmor2T) malloc(sizeof(Amor2T)); + if (!pNew) { + SCWrite(pCon, "ERROR: out of memory in Amor2TFactory", eError); + return 0; + } + memset(pNew, 0, sizeof(Amor2T)); + pNew->pDes = CreateDescriptor("Amor2T"); + pNew->aParameter = ObParCreate(MAXPAR); + pNew->pDriv = CreateDrivableInterface(); + if ((!pNew->pDes) || (!pNew->aParameter) || (!pNew->pDriv)) { + SCWrite(pCon, "ERROR: out of memory in Amor2TFactory", eError); + A2TKill(pNew); + return 0; + } - /* find the motors*/ - pMot = Tcl_GetVar2(pSics->pTcl,argv[2],"mom",TCL_GLOBAL_ONLY); - if(!pMot) - { - SCWrite(pCon,"ERROR: no value for mom motr found",eError); - A2TKill(pNew); - return 0; - } - pNew->aEngine[MOTMOM] = FindMotor(pSics,(char *)pMot); - if(!pNew->aEngine[MOTMOM]) - { - sprintf(pBueffel,"ERROR: motor %s NOT found!", pMot); - SCWrite(pCon,pBueffel,eError); - A2TKill(pNew); - return 0; - } + /* find the motors */ + pMot = Tcl_GetVar2(pSics->pTcl, argv[2], "mom", TCL_GLOBAL_ONLY); + if (!pMot) { + SCWrite(pCon, "ERROR: no value for mom motr found", eError); + A2TKill(pNew); + return 0; + } + pNew->aEngine[MOTMOM] = FindMotor(pSics, (char *) pMot); + if (!pNew->aEngine[MOTMOM]) { + sprintf(pBueffel, "ERROR: motor %s NOT found!", pMot); + SCWrite(pCon, pBueffel, eError); + A2TKill(pNew); + return 0; + } - pMot = Tcl_GetVar2(pSics->pTcl,argv[2],"som",TCL_GLOBAL_ONLY); - if(!pMot) - { - SCWrite(pCon,"ERROR: no value for som motor found",eError); - A2TKill(pNew); - return 0; - } - pNew->aEngine[MOTSOM] = FindMotor(pSics,(char *)pMot); - if(!pNew->aEngine[MOTSOM]) - { - sprintf(pBueffel,"ERROR: motor %s NOT found!", pMot); - SCWrite(pCon,pBueffel,eError); - A2TKill(pNew); - return 0; - } + pMot = Tcl_GetVar2(pSics->pTcl, argv[2], "som", TCL_GLOBAL_ONLY); + if (!pMot) { + SCWrite(pCon, "ERROR: no value for som motor found", eError); + A2TKill(pNew); + return 0; + } + pNew->aEngine[MOTSOM] = FindMotor(pSics, (char *) pMot); + if (!pNew->aEngine[MOTSOM]) { + sprintf(pBueffel, "ERROR: motor %s NOT found!", pMot); + SCWrite(pCon, pBueffel, eError); + A2TKill(pNew); + return 0; + } - pMot = Tcl_GetVar2(pSics->pTcl,argv[2],"coz",TCL_GLOBAL_ONLY); - if(!pMot) - { - SCWrite(pCon,"ERROR: no value for coz motor found",eError); - A2TKill(pNew); - return 0; - } - pNew->aEngine[MOTCOZ] = FindMotor(pSics,(char *)pMot); - if(!pNew->aEngine[MOTCOZ]) - { - sprintf(pBueffel,"ERROR: motor %s NOT found!", pMot); - SCWrite(pCon,pBueffel,eError); - A2TKill(pNew); - return 0; - } + pMot = Tcl_GetVar2(pSics->pTcl, argv[2], "coz", TCL_GLOBAL_ONLY); + if (!pMot) { + SCWrite(pCon, "ERROR: no value for coz motor found", eError); + A2TKill(pNew); + return 0; + } + pNew->aEngine[MOTCOZ] = FindMotor(pSics, (char *) pMot); + if (!pNew->aEngine[MOTCOZ]) { + sprintf(pBueffel, "ERROR: motor %s NOT found!", pMot); + SCWrite(pCon, pBueffel, eError); + A2TKill(pNew); + return 0; + } - pMot = Tcl_GetVar2(pSics->pTcl,argv[2],"cox",TCL_GLOBAL_ONLY); - if(!pMot) - { - SCWrite(pCon,"ERROR: no value for cox motor found",eError); - A2TKill(pNew); - return 0; - } - pNew->aEngine[MOTCOX] = FindMotor(pSics,(char *)pMot); - if(!pNew->aEngine[MOTCOX]) - { - sprintf(pBueffel,"ERROR: motor %s NOT found!", pMot); - SCWrite(pCon,pBueffel,eError); - A2TKill(pNew); - return 0; - } + pMot = Tcl_GetVar2(pSics->pTcl, argv[2], "cox", TCL_GLOBAL_ONLY); + if (!pMot) { + SCWrite(pCon, "ERROR: no value for cox motor found", eError); + A2TKill(pNew); + return 0; + } + pNew->aEngine[MOTCOX] = FindMotor(pSics, (char *) pMot); + if (!pNew->aEngine[MOTCOX]) { + sprintf(pBueffel, "ERROR: motor %s NOT found!", pMot); + SCWrite(pCon, pBueffel, eError); + A2TKill(pNew); + return 0; + } - pMot = Tcl_GetVar2(pSics->pTcl,argv[2],"stz",TCL_GLOBAL_ONLY); - if(!pMot) - { - SCWrite(pCon,"ERROR: no value for stz motor found",eError); - A2TKill(pNew); - return 0; - } - pNew->aEngine[MOTSTZ] = FindMotor(pSics,(char *)pMot); - if(!pNew->aEngine[MOTSTZ]) - { - sprintf(pBueffel,"ERROR: motor %s NOT found!", pMot); - SCWrite(pCon,pBueffel,eError); - A2TKill(pNew); - return 0; - } + pMot = Tcl_GetVar2(pSics->pTcl, argv[2], "stz", TCL_GLOBAL_ONLY); + if (!pMot) { + SCWrite(pCon, "ERROR: no value for stz motor found", eError); + A2TKill(pNew); + return 0; + } + pNew->aEngine[MOTSTZ] = FindMotor(pSics, (char *) pMot); + if (!pNew->aEngine[MOTSTZ]) { + sprintf(pBueffel, "ERROR: motor %s NOT found!", pMot); + SCWrite(pCon, pBueffel, eError); + A2TKill(pNew); + return 0; + } - pMot = Tcl_GetVar2(pSics->pTcl,argv[2],"soz",TCL_GLOBAL_ONLY); - if(!pMot) - { - SCWrite(pCon,"ERROR: no value for soz motor found",eError); - A2TKill(pNew); - return 0; - } - pNew->aEngine[MOTSOZ] = FindMotor(pSics,(char *)pMot); - if(!pNew->aEngine[MOTSOZ]) - { - sprintf(pBueffel,"ERROR: motor %s NOT found!", pMot); - SCWrite(pCon,pBueffel,eError); - A2TKill(pNew); - return 0; - } + pMot = Tcl_GetVar2(pSics->pTcl, argv[2], "soz", TCL_GLOBAL_ONLY); + if (!pMot) { + SCWrite(pCon, "ERROR: no value for soz motor found", eError); + A2TKill(pNew); + return 0; + } + pNew->aEngine[MOTSOZ] = FindMotor(pSics, (char *) pMot); + if (!pNew->aEngine[MOTSOZ]) { + sprintf(pBueffel, "ERROR: motor %s NOT found!", pMot); + SCWrite(pCon, pBueffel, eError); + A2TKill(pNew); + return 0; + } - pMot = Tcl_GetVar2(pSics->pTcl,argv[2],"d4b",TCL_GLOBAL_ONLY); - if(!pMot) - { - SCWrite(pCon,"ERROR: no value for d4b motor found",eError); - A2TKill(pNew); - return 0; - } - pNew->aEngine[MOTD4B] = FindMotor(pSics,(char *)pMot); - if(!pNew->aEngine[MOTD4B]) - { - sprintf(pBueffel,"ERROR: motor %s NOT found!", pMot); - SCWrite(pCon,pBueffel,eError); - A2TKill(pNew); - return 0; - } + pMot = Tcl_GetVar2(pSics->pTcl, argv[2], "d4b", TCL_GLOBAL_ONLY); + if (!pMot) { + SCWrite(pCon, "ERROR: no value for d4b motor found", eError); + A2TKill(pNew); + return 0; + } + pNew->aEngine[MOTD4B] = FindMotor(pSics, (char *) pMot); + if (!pNew->aEngine[MOTD4B]) { + sprintf(pBueffel, "ERROR: motor %s NOT found!", pMot); + SCWrite(pCon, pBueffel, eError); + A2TKill(pNew); + return 0; + } - pMot = Tcl_GetVar2(pSics->pTcl,argv[2],"d5b",TCL_GLOBAL_ONLY); - if(!pMot) - { - SCWrite(pCon,"ERROR: no value for d5b motor found",eError); - A2TKill(pNew); - return 0; - } - pNew->aEngine[MOTD5B] = FindMotor(pSics,(char *)pMot); - if(!pNew->aEngine[MOTD5B]) - { - sprintf(pBueffel,"ERROR: motor %s NOT found!", pMot); - SCWrite(pCon,pBueffel,eError); - A2TKill(pNew); - return 0; - } + pMot = Tcl_GetVar2(pSics->pTcl, argv[2], "d5b", TCL_GLOBAL_ONLY); + if (!pMot) { + SCWrite(pCon, "ERROR: no value for d5b motor found", eError); + A2TKill(pNew); + return 0; + } + pNew->aEngine[MOTD5B] = FindMotor(pSics, (char *) pMot); + if (!pNew->aEngine[MOTD5B]) { + sprintf(pBueffel, "ERROR: motor %s NOT found!", pMot); + SCWrite(pCon, pBueffel, eError); + A2TKill(pNew); + return 0; + } - pMot = Tcl_GetVar2(pSics->pTcl,argv[2],"com",TCL_GLOBAL_ONLY); - if(!pMot) - { - SCWrite(pCon,"ERROR: no value for com motor found",eError); - A2TKill(pNew); - return 0; - } - pNew->aEngine[MOTCOM] = FindMotor(pSics,(char *)pMot); - if(!pNew->aEngine[MOTCOM]) - { - sprintf(pBueffel,"ERROR: motor %s NOT found!", pMot); - SCWrite(pCon,pBueffel,eError); - A2TKill(pNew); - return 0; - } + pMot = Tcl_GetVar2(pSics->pTcl, argv[2], "com", TCL_GLOBAL_ONLY); + if (!pMot) { + SCWrite(pCon, "ERROR: no value for com motor found", eError); + A2TKill(pNew); + return 0; + } + pNew->aEngine[MOTCOM] = FindMotor(pSics, (char *) pMot); + if (!pNew->aEngine[MOTCOM]) { + sprintf(pBueffel, "ERROR: motor %s NOT found!", pMot); + SCWrite(pCon, pBueffel, eError); + A2TKill(pNew); + return 0; + } - pMot = Tcl_GetVar2(pSics->pTcl,argv[2],"aoz",TCL_GLOBAL_ONLY); - if(!pMot) - { - SCWrite(pCon,"ERROR: no value for aoz motor found",eError); - A2TKill(pNew); - return 0; - } - pNew->aEngine[MOTAOZ] = FindMotor(pSics,(char *)pMot); - if(!pNew->aEngine[MOTAOZ]) - { - sprintf(pBueffel,"ERROR: motor %s NOT found!", pMot); - SCWrite(pCon,pBueffel,eError); - A2TKill(pNew); - return 0; - } + pMot = Tcl_GetVar2(pSics->pTcl, argv[2], "aoz", TCL_GLOBAL_ONLY); + if (!pMot) { + SCWrite(pCon, "ERROR: no value for aoz motor found", eError); + A2TKill(pNew); + return 0; + } + pNew->aEngine[MOTAOZ] = FindMotor(pSics, (char *) pMot); + if (!pNew->aEngine[MOTAOZ]) { + sprintf(pBueffel, "ERROR: motor %s NOT found!", pMot); + SCWrite(pCon, pBueffel, eError); + A2TKill(pNew); + return 0; + } - pMot = Tcl_GetVar2(pSics->pTcl,argv[2],"aom",TCL_GLOBAL_ONLY); - if(!pMot) - { - SCWrite(pCon,"ERROR: no value for aom motor found",eError); - A2TKill(pNew); - return 0; - } - pNew->aEngine[MOTAOM] = FindMotor(pSics,(char *)pMot); - if(!pNew->aEngine[MOTAOM]) - { - sprintf(pBueffel,"ERROR: motor %s NOT found!", pMot); - SCWrite(pCon,pBueffel,eError); - A2TKill(pNew); - return 0; - } + pMot = Tcl_GetVar2(pSics->pTcl, argv[2], "aom", TCL_GLOBAL_ONLY); + if (!pMot) { + SCWrite(pCon, "ERROR: no value for aom motor found", eError); + A2TKill(pNew); + return 0; + } + pNew->aEngine[MOTAOM] = FindMotor(pSics, (char *) pMot); + if (!pNew->aEngine[MOTAOM]) { + sprintf(pBueffel, "ERROR: motor %s NOT found!", pMot); + SCWrite(pCon, pBueffel, eError); + A2TKill(pNew); + return 0; + } - pMot = Tcl_GetVar2(pSics->pTcl,argv[2],"c3z",TCL_GLOBAL_ONLY); - if(!pMot) - { - SCWrite(pCon,"ERROR: no value for c3z motor found",eError); - A2TKill(pNew); - return 0; - } - pNew->aEngine[MOTC3Z] = FindMotor(pSics,(char *)pMot); - if(!pNew->aEngine[MOTC3Z]) - { - sprintf(pBueffel,"ERROR: motor %s NOT found!", pMot); - SCWrite(pCon,pBueffel,eError); - A2TKill(pNew); - return 0; - } + pMot = Tcl_GetVar2(pSics->pTcl, argv[2], "c3z", TCL_GLOBAL_ONLY); + if (!pMot) { + SCWrite(pCon, "ERROR: no value for c3z motor found", eError); + A2TKill(pNew); + return 0; + } + pNew->aEngine[MOTC3Z] = FindMotor(pSics, (char *) pMot); + if (!pNew->aEngine[MOTC3Z]) { + sprintf(pBueffel, "ERROR: motor %s NOT found!", pMot); + SCWrite(pCon, pBueffel, eError); + A2TKill(pNew); + return 0; + } - /* initialize parameters */ - ObParInit(pNew->aParameter,PARDS,"detectord",1400.,usMugger); - ObParInit(pNew->aParameter,PARDH,"sampleh",50.,usMugger); - ObParInit(pNew->aParameter,PARDD4,"d4d",100.,usMugger); - ObParInit(pNew->aParameter,PARDD5,"d5d",200.,usMugger); - ObParInit(pNew->aParameter,PARINT,"interrupt",0.,usMugger); - ObParInit(pNew->aParameter,PARDDH,"detectorh",40.,usMugger); - ObParInit(pNew->aParameter,PARD4H,"d4h",40.,usMugger); - ObParInit(pNew->aParameter,PARD5H,"d5h",400.,usMugger); - ObParInit(pNew->aParameter,PARANA,"anah",400.,usMugger); - ObParInit(pNew->aParameter,PARADIS,"anad",600.,usMugger); - ObParInit(pNew->aParameter,ANAFLAG,"anaflag",-1.,usMugger); - ObParInit(pNew->aParameter,PARDDD,"c2h",100.,usMugger); - ObParInit(pNew->aParameter,PARAOM,"aomconst",3.,usMugger); - ObParInit(pNew->aParameter,DIAFLAG,"diaflag",1.,usMugger); + /* initialize parameters */ + ObParInit(pNew->aParameter, PARDS, "detectord", 1400., usMugger); + ObParInit(pNew->aParameter, PARDH, "sampleh", 50., usMugger); + ObParInit(pNew->aParameter, PARDD4, "d4d", 100., usMugger); + ObParInit(pNew->aParameter, PARDD5, "d5d", 200., usMugger); + ObParInit(pNew->aParameter, PARINT, "interrupt", 0., usMugger); + ObParInit(pNew->aParameter, PARDDH, "detectorh", 40., usMugger); + ObParInit(pNew->aParameter, PARD4H, "d4h", 40., usMugger); + ObParInit(pNew->aParameter, PARD5H, "d5h", 400., usMugger); + ObParInit(pNew->aParameter, PARANA, "anah", 400., usMugger); + ObParInit(pNew->aParameter, PARADIS, "anad", 600., usMugger); + ObParInit(pNew->aParameter, ANAFLAG, "anaflag", -1., usMugger); + ObParInit(pNew->aParameter, PARDDD, "c2h", 100., usMugger); + ObParInit(pNew->aParameter, PARAOM, "aomconst", 3., usMugger); + ObParInit(pNew->aParameter, DIAFLAG, "diaflag", 1., usMugger); - /* initialize interfaces */ - pNew->pDes->GetInterface = A2TGetInterface; - pNew->pDes->SaveStatus = A2TSave; - pNew->pDriv->Halt = A2THalt; - pNew->pDriv->CheckLimits = A2TCheck; - pNew->pDriv->SetValue = A2TSetValue; - pNew->pDriv->CheckStatus = A2TStatus; - pNew->pDriv->GetValue = A2TGetValue; + /* initialize interfaces */ + pNew->pDes->GetInterface = A2TGetInterface; + pNew->pDes->SaveStatus = A2TSave; + pNew->pDriv->Halt = A2THalt; + pNew->pDriv->CheckLimits = A2TCheck; + pNew->pDriv->SetValue = A2TSetValue; + pNew->pDriv->CheckStatus = A2TStatus; + pNew->pDriv->GetValue = A2TGetValue; - /* copy data structure for second command for aom2t */ - pAOM = (pAmor2T)malloc(sizeof(Amor2T)); - if(!pAOM) - { - A2TKill(pNew); - SCWrite(pCon,"ERROR: out of memory in Amor2TFactory",eError); - return 0; - } - memcpy(pAOM,pNew,sizeof(Amor2T)); - pAOM->pDriv = CreateDrivableInterface(); - pAOM->pDes = CreateDescriptor("Amor2T"); - if(!pAOM->pDriv || !pAOM->pDes ) - { - A2TKill(pNew); - SCWrite(pCon,"ERROR: out of memory in Amor2TFactory",eError); - return 0; - } - - /* set modified interface functions */ - pAOM->pDes->GetInterface = A2TGetInterface; - pAOM->pDriv->Halt = A2THalt; - pAOM->pDriv->CheckLimits = ANA2TCheck; - pAOM->pDriv->SetValue = ANA2TSetValue; - pAOM->pDriv->GetValue = ANA2TGetValue; - pAOM->pDriv->CheckStatus = A2TStatus; + /* copy data structure for second command for aom2t */ + pAOM = (pAmor2T) malloc(sizeof(Amor2T)); + if (!pAOM) { + A2TKill(pNew); + SCWrite(pCon, "ERROR: out of memory in Amor2TFactory", eError); + return 0; + } + memcpy(pAOM, pNew, sizeof(Amor2T)); + pAOM->pDriv = CreateDrivableInterface(); + pAOM->pDes = CreateDescriptor("Amor2T"); + if (!pAOM->pDriv || !pAOM->pDes) { + A2TKill(pNew); + SCWrite(pCon, "ERROR: out of memory in Amor2TFactory", eError); + return 0; + } + + /* set modified interface functions */ + pAOM->pDes->GetInterface = A2TGetInterface; + pAOM->pDriv->Halt = A2THalt; + pAOM->pDriv->CheckLimits = ANA2TCheck; + pAOM->pDriv->SetValue = ANA2TSetValue; + pAOM->pDriv->GetValue = ANA2TGetValue; + pAOM->pDriv->CheckStatus = A2TStatus; - /* install commands */ - iRet = AddCommand(pSics,argv[1], - Amor2TAction,A2TKill,pNew); - if(!iRet) - { - sprintf(pBueffel,"ERROR: duplicate command %s NOT created", - argv[1]); - SCWrite(pCon,pBueffel,eError); - A2TKill(pNew); - return 0; - } - iRet = AddCommand(pSics,argv[3], - Amor2TAction,free,pAOM); - if(!iRet) - { - sprintf(pBueffel,"ERROR: duplicate command %s NOT created", - argv[1]); - SCWrite(pCon,pBueffel,eError); - A2TKill(pNew); - return 0; - } - return 1; - } + /* install commands */ + iRet = AddCommand(pSics, argv[1], Amor2TAction, A2TKill, pNew); + if (!iRet) { + sprintf(pBueffel, "ERROR: duplicate command %s NOT created", argv[1]); + SCWrite(pCon, pBueffel, eError); + A2TKill(pNew); + return 0; + } + iRet = AddCommand(pSics, argv[3], Amor2TAction, free, pAOM); + if (!iRet) { + sprintf(pBueffel, "ERROR: duplicate command %s NOT created", argv[1]); + SCWrite(pCon, pBueffel, eError); + A2TKill(pNew); + return 0; + } + return 1; +} + /*----------------------------------------------------------------------*/ - int Amor2TAction(SConnection *pCon, SicsInterp *pSics, void *pData, - int argc, char *argv[]) - { - pAmor2T self = (pAmor2T)pData; - char pBueffel[256]; - float fVal; - double dVal; - ObPar *pPar = NULL; - int iRet; +int Amor2TAction(SConnection * pCon, SicsInterp * pSics, void *pData, + int argc, char *argv[]) +{ + pAmor2T self = (pAmor2T) pData; + char pBueffel[256]; + float fVal; + double dVal; + ObPar *pPar = NULL; + int iRet; - assert(self); + assert(self); - if(argc > 1) - { - strtolower(argv[1]); - /* deal with list */ - if(strcmp(argv[1],"list") == 0) - { - A2TList(self,pCon,argv[0]); - return 1; - } - /* otherwise it should be a parameter command */ - if(argc >= 3) - { - iRet = Tcl_GetDouble(pSics->pTcl,argv[2],&dVal); - if(iRet != TCL_OK) - { - sprintf(pBueffel,"ERROR: failed to convert %s to number", - argv[2]); - SCWrite(pCon,pBueffel,eError); - return 0; - } - iRet = ObParSet(self->aParameter,argv[0],argv[1],(float)dVal,pCon); - if(iRet) - { - SCSendOK(pCon); - } - return iRet; - } - else - { - pPar = ObParFind(self->aParameter,argv[1]); - if(!pPar) - { - sprintf(pBueffel,"ERROR: parameter %s NOT found",argv[1]); - SCWrite(pCon,pBueffel,eError); - return 0; - } - sprintf(pBueffel,"%s.%s = %f",argv[0],pPar->name, pPar->fVal); - SCWrite(pCon,pBueffel,eValue); - return 1; - } + if (argc > 1) { + strtolower(argv[1]); + /* deal with list */ + if (strcmp(argv[1], "list") == 0) { + A2TList(self, pCon, argv[0]); + return 1; + } + /* otherwise it should be a parameter command */ + if (argc >= 3) { + iRet = Tcl_GetDouble(pSics->pTcl, argv[2], &dVal); + if (iRet != TCL_OK) { + sprintf(pBueffel, "ERROR: failed to convert %s to number", + argv[2]); + SCWrite(pCon, pBueffel, eError); + return 0; } - else - { - fVal = self->pDriv->GetValue(self,pCon); - sprintf(pBueffel," %s = %f", argv[0], fVal); - SCWrite(pCon,pBueffel,eValue); - return 1; + iRet = + ObParSet(self->aParameter, argv[0], argv[1], (float) dVal, pCon); + if (iRet) { + SCSendOK(pCon); } - } - - - + return iRet; + } else { + pPar = ObParFind(self->aParameter, argv[1]); + if (!pPar) { + sprintf(pBueffel, "ERROR: parameter %s NOT found", argv[1]); + SCWrite(pCon, pBueffel, eError); + return 0; + } + sprintf(pBueffel, "%s.%s = %f", argv[0], pPar->name, pPar->fVal); + SCWrite(pCon, pBueffel, eValue); + return 1; + } + } else { + fVal = self->pDriv->GetValue(self, pCon); + sprintf(pBueffel, " %s = %f", argv[0], fVal); + SCWrite(pCon, pBueffel, eValue); + return 1; + } +} diff --git a/amor2t.h b/amor2t.h index 3890c70..cb61f0b 100644 --- a/amor2t.h +++ b/amor2t.h @@ -11,11 +11,11 @@ #ifndef AMOR2T #define AMOR2T - typedef struct __AMOR2T *pAmor2T; +typedef struct __AMOR2T *pAmor2T; - int Amor2TFactory(SConnection *pCon, SicsInterp *pSics, void *pData, - int argc, char *argv[]); - int Amor2TAction(SConnection *pCon, SicsInterp *pSics, void *pData, - int argc, char *argv[]); +int Amor2TFactory(SConnection * pCon, SicsInterp * pSics, void *pData, + int argc, char *argv[]); +int Amor2TAction(SConnection * pCon, SicsInterp * pSics, void *pData, + int argc, char *argv[]); -#endif +#endif diff --git a/amorcomp.c b/amorcomp.c index 210f3a7..bf8c816 100644 --- a/amorcomp.c +++ b/amorcomp.c @@ -7,109 +7,114 @@ Mark Koennecke, October 2005 -----------------------------------------------------------------------*/ #include "amorcomp.h" -#define ABS(x) (x < 0 ? -(x) : (x)) +#define ABS(x) (x < 0 ? -(x) : (x)) -double calcCompPosition(pamorComp comp){ - return ABS(comp->scaleOffset - comp->markOffset - comp->readPosition); +double calcCompPosition(pamorComp comp) +{ + return ABS(comp->scaleOffset - comp->markOffset - comp->readPosition); } + /*-------------------------------------------------------------------*/ -int handleCompCommand(pamorComp comp, SConnection *pCon, - int argc, char *argv[]){ - char pBueffel[512]; - - if(argc < 3) { - SCWrite(pCon,"ERROR: not enough arguments",eError); - return 0; - } - strtolower(argv[2]); - if(strcmp(argv[2],"list") == 0){ - snprintf(pBueffel,511, -"%s %s active = %d\n%s %s offset = %f\n%s %s scaleoffset = %f\n%s %s read = %f\n%s %s calc = %f\n", - argv[0], argv[1], comp->activeFlag, - argv[0], argv[1], comp->markOffset, - argv[0], argv[1], comp->scaleOffset, - argv[0], argv[1], comp->readPosition, - argv[0], argv[1], calcCompPosition(comp)); - SCWrite(pCon,pBueffel,eValue); - return 1; - } else if (strcmp(argv[2], "active") == 0) { - if(argc > 3) { - if(!SCMatchRights(pCon,usUser)){ - return 0; - } - SCparChange(pCon); - comp->activeFlag = atoi(argv[3]); - SCSendOK(pCon); - return 1; - } else { - snprintf(pBueffel,511," %s %s active = %d", - argv[0], argv[1], comp->activeFlag); - SCWrite(pCon,pBueffel,eValue); - return 1; - } - } else if (strcmp(argv[2], "offset") == 0) { - if(argc > 3) { - if(!SCMatchRights(pCon,usUser)){ - return 0; - } - SCparChange(pCon); - comp->markOffset = atof(argv[3]); - SCSendOK(pCon); - return 1; - } else { - snprintf(pBueffel,511," %s %s offset = %f", - argv[0], argv[1], comp->markOffset); - SCWrite(pCon,pBueffel,eValue); - return 1; - } - } else if (strcmp(argv[2], "scaleoffset") == 0) { - if(argc > 3) { - if(!SCMatchRights(pCon,usUser)){ - return 0; - } - comp->scaleOffset = atof(argv[3]); - SCparChange(pCon); - SCSendOK(pCon); - return 1; - } else { - snprintf(pBueffel,511," %s %s scaleoffset = %f", - argv[0], argv[1], comp->scaleOffset); - SCWrite(pCon,pBueffel,eValue); - return 1; - } - } else if (strcmp(argv[2], "read") == 0) { - if(argc > 3) { - if(!SCMatchRights(pCon,usUser)){ - return 0; - } - comp->readPosition = atof(argv[3]); - SCparChange(pCon); - SCSendOK(pCon); - return 1; - } else { - snprintf(pBueffel,511," %s %s read = %f", - argv[0], argv[1], comp->readPosition); - SCWrite(pCon,pBueffel,eValue); - return 1; - } - } else if (strcmp(argv[2], "calc") == 0) { - snprintf(pBueffel,511," %s %s calc = %f", - argv[0], argv[1], calcCompPosition(comp)); - SCWrite(pCon,pBueffel,eValue); - return 1; +int handleCompCommand(pamorComp comp, SConnection * pCon, + int argc, char *argv[]) +{ + char pBueffel[512]; + + if (argc < 3) { + SCWrite(pCon, "ERROR: not enough arguments", eError); + return 0; + } + strtolower(argv[2]); + if (strcmp(argv[2], "list") == 0) { + snprintf(pBueffel, 511, + "%s %s active = %d\n%s %s offset = %f\n%s %s scaleoffset = %f\n%s %s read = %f\n%s %s calc = %f\n", + argv[0], argv[1], comp->activeFlag, + argv[0], argv[1], comp->markOffset, + argv[0], argv[1], comp->scaleOffset, + argv[0], argv[1], comp->readPosition, + argv[0], argv[1], calcCompPosition(comp)); + SCWrite(pCon, pBueffel, eValue); + return 1; + } else if (strcmp(argv[2], "active") == 0) { + if (argc > 3) { + if (!SCMatchRights(pCon, usUser)) { + return 0; + } + SCparChange(pCon); + comp->activeFlag = atoi(argv[3]); + SCSendOK(pCon); + return 1; } else { - snprintf(pBueffel,511,"ERROR: subcommand %s to %s %s not understood", - argv[2], argv[0], argv[1]); - SCWrite(pCon,pBueffel,eError); - return 0; + snprintf(pBueffel, 511, " %s %s active = %d", + argv[0], argv[1], comp->activeFlag); + SCWrite(pCon, pBueffel, eValue); + return 1; } - return 1; + } else if (strcmp(argv[2], "offset") == 0) { + if (argc > 3) { + if (!SCMatchRights(pCon, usUser)) { + return 0; + } + SCparChange(pCon); + comp->markOffset = atof(argv[3]); + SCSendOK(pCon); + return 1; + } else { + snprintf(pBueffel, 511, " %s %s offset = %f", + argv[0], argv[1], comp->markOffset); + SCWrite(pCon, pBueffel, eValue); + return 1; + } + } else if (strcmp(argv[2], "scaleoffset") == 0) { + if (argc > 3) { + if (!SCMatchRights(pCon, usUser)) { + return 0; + } + comp->scaleOffset = atof(argv[3]); + SCparChange(pCon); + SCSendOK(pCon); + return 1; + } else { + snprintf(pBueffel, 511, " %s %s scaleoffset = %f", + argv[0], argv[1], comp->scaleOffset); + SCWrite(pCon, pBueffel, eValue); + return 1; + } + } else if (strcmp(argv[2], "read") == 0) { + if (argc > 3) { + if (!SCMatchRights(pCon, usUser)) { + return 0; + } + comp->readPosition = atof(argv[3]); + SCparChange(pCon); + SCSendOK(pCon); + return 1; + } else { + snprintf(pBueffel, 511, " %s %s read = %f", + argv[0], argv[1], comp->readPosition); + SCWrite(pCon, pBueffel, eValue); + return 1; + } + } else if (strcmp(argv[2], "calc") == 0) { + snprintf(pBueffel, 511, " %s %s calc = %f", + argv[0], argv[1], calcCompPosition(comp)); + SCWrite(pCon, pBueffel, eValue); + return 1; + } else { + snprintf(pBueffel, 511, "ERROR: subcommand %s to %s %s not understood", + argv[2], argv[0], argv[1]); + SCWrite(pCon, pBueffel, eError); + return 0; + } + return 1; } + /*------------------------------------------------------------------------*/ -int saveAmorComp(FILE *fd, char *name, char *compname, pamorComp comp){ - fprintf(fd,"%s %s active %d\n", name, compname, comp->activeFlag); - fprintf(fd,"%s %s offset %f\n", name, compname, comp->markOffset); - fprintf(fd,"%s %s scaleoffset %f\n", name, compname, comp->scaleOffset); - fprintf(fd,"%s %s read %f\n", name, compname, comp->readPosition); - return 1; -} +int saveAmorComp(FILE * fd, char *name, char *compname, pamorComp comp) +{ + fprintf(fd, "%s %s active %d\n", name, compname, comp->activeFlag); + fprintf(fd, "%s %s offset %f\n", name, compname, comp->markOffset); + fprintf(fd, "%s %s scaleoffset %f\n", name, compname, comp->scaleOffset); + fprintf(fd, "%s %s read %f\n", name, compname, comp->readPosition); + return 1; +} diff --git a/amorcomp.h b/amorcomp.h index 0b697f5..dbe1163 100644 --- a/amorcomp.h +++ b/amorcomp.h @@ -7,22 +7,21 @@ Mark Koennecke, October 2005 -----------------------------------------------------------------------*/ - #ifndef AMORCOMP - #define AMORCOMP - #include - #include - - typedef struct { - int activeFlag; /* component present */ - double markOffset; /* offset mark to real */ - double scaleOffset; /* offset of the scale */ - double readPosition; /* the position as read */ - } amorComp, *pamorComp; +#ifndef AMORCOMP +#define AMORCOMP +#include +#include + +typedef struct { + int activeFlag; /* component present */ + double markOffset; /* offset mark to real */ + double scaleOffset; /* offset of the scale */ + double readPosition; /* the position as read */ +} amorComp, *pamorComp; /*----------------------------------------------------------------------*/ - double calcCompPosition(pamorComp comp); - int handleCompCommand(pamorComp comp, SConnection *pCon, - int argc, char *argv[]); - int saveAmorComp(FILE *fd, char *name, char *compname, pamorComp comp); - - #endif - +double calcCompPosition(pamorComp comp); +int handleCompCommand(pamorComp comp, SConnection * pCon, + int argc, char *argv[]); +int saveAmorComp(FILE * fd, char *name, char *compname, pamorComp comp); + +#endif diff --git a/amordrive.c b/amordrive.c index 540de81..f2f774e 100644 --- a/amordrive.c +++ b/amordrive.c @@ -9,29 +9,33 @@ #include "amordrive.h" /*---------------------------------------------------------------*/ -static void *AMODRIVGetInterface(void *data, int iD){ - pamorDrive self = NULL; +static void *AMODRIVGetInterface(void *data, int iD) +{ + pamorDrive self = NULL; - self = (pamorDrive)data; - - if(iD == DRIVEID && self != NULL){ - return self->pDriv; - } else { - return NULL; - } - return NULL; + self = (pamorDrive) data; + + if (iD == DRIVEID && self != NULL) { + return self->pDriv; + } else { + return NULL; + } + return NULL; } + /*---------------------------------------------------------------- This routine can return either OKOK or HWFault when thing go wrong. However, the return value of Halt is usually ignored! ------------------------------------------------------------------*/ -static int AMODRIVHalt(void *data) { - pamorDrive self = NULL; - - self = (pamorDrive)data; +static int AMODRIVHalt(void *data) +{ + pamorDrive self = NULL; - return self->mama->pDriv->Halt(self->mama); + self = (pamorDrive) data; + + return self->mama->pDriv->Halt(self->mama); } + /*---------------------------------------------------------------- This routine can return either 1 or 0. 1 means the position can be reached, 0 NOT @@ -40,13 +44,15 @@ static int AMODRIVHalt(void *data) { Due to the complex nauture of the calculation: no check here ------------------------------------------------------------------*/ static int AMODRIVCheckLimits(void *data, float val, - char *error, int errlen){ - pamorDrive self = NULL; - - self = (pamorDrive)data; + char *error, int errlen) +{ + pamorDrive self = NULL; - return 1; + self = (pamorDrive) data; + + return 1; } + /*---------------------------------------------------------------- This routine can return 0 when a limit problem occurred OKOK when the motor was successfully started @@ -56,15 +62,17 @@ static int AMODRIVCheckLimits(void *data, float val, to start the motor in question val is the value to drive the motor too ------------------------------------------------------------------*/ -static long AMODRIVSetValue(void *data, SConnection *pCon, float val){ - pamorDrive self = NULL; - - self = (pamorDrive)data; +static long AMODRIVSetValue(void *data, SConnection * pCon, float val) +{ + pamorDrive self = NULL; - amorSetMotor(self->mama, self->type, val); + self = (pamorDrive) data; - return 1; + amorSetMotor(self->mama, self->type, val); + + return 1; } + /*---------------------------------------------------------------- Checks the status of a running motor. Possible return values HWBusy The motor is still running @@ -75,96 +83,106 @@ static long AMODRIVSetValue(void *data, SConnection *pCon, float val){ For real motors CheckStatus again shall try hard to fix any issues with the motor ------------------------------------------------------------------*/ -static int AMODRIVCheckStatus(void *data, SConnection *pCon){ - pamorDrive self = NULL; - - self = (pamorDrive)data; +static int AMODRIVCheckStatus(void *data, SConnection * pCon) +{ + pamorDrive self = NULL; - return self->mama->pDriv->CheckStatus(self->mama, pCon); + self = (pamorDrive) data; + + return self->mama->pDriv->CheckStatus(self->mama, pCon); } + /*---------------------------------------------------------------- GetValue is supposed to read a motor position On errors, -99999999.99 is returned and messages printed to pCon ------------------------------------------------------------------*/ -static float AMODRIVGetValue(void *data, SConnection *pCon){ - pamorDrive self = NULL; - float val = -99999999.99; - - self = (pamorDrive)data; - return amorGetMotor(self->mama,pCon,self->type); +static float AMODRIVGetValue(void *data, SConnection * pCon) +{ + pamorDrive self = NULL; + float val = -99999999.99; + + self = (pamorDrive) data; + return amorGetMotor(self->mama, pCon, self->type); } + /*---------------------------------------------------------------- returns NULL on failure, a new datastrcuture else ------------------------------------------------------------------*/ -static pamorDrive AMODRIVMakeObject(){ - pamorDrive self = NULL; +static pamorDrive AMODRIVMakeObject() +{ + pamorDrive self = NULL; - self = (pamorDrive)malloc(sizeof(amorDrive)); - if(self == NULL){ - return NULL; - } - memset(self,0,sizeof(amorDrive)); - self->pDes = CreateDescriptor("AmorDrive"); - self->pDriv = CreateDrivableInterface(); - if(self->pDes == NULL || self->pDriv == NULL){ - free(self); - return NULL; - } + self = (pamorDrive) malloc(sizeof(amorDrive)); + if (self == NULL) { + return NULL; + } + memset(self, 0, sizeof(amorDrive)); + self->pDes = CreateDescriptor("AmorDrive"); + self->pDriv = CreateDrivableInterface(); + if (self->pDes == NULL || self->pDriv == NULL) { + free(self); + return NULL; + } - self->pDes->GetInterface = AMODRIVGetInterface; - self->pDriv->Halt = AMODRIVHalt; - self->pDriv->CheckLimits = AMODRIVCheckLimits; - self->pDriv->SetValue = AMODRIVSetValue; - self->pDriv->CheckStatus = AMODRIVCheckStatus; - self->pDriv->GetValue = AMODRIVGetValue; + self->pDes->GetInterface = AMODRIVGetInterface; + self->pDriv->Halt = AMODRIVHalt; + self->pDriv->CheckLimits = AMODRIVCheckLimits; + self->pDriv->SetValue = AMODRIVSetValue; + self->pDriv->CheckStatus = AMODRIVCheckStatus; + self->pDriv->GetValue = AMODRIVGetValue; + return self; +} + +/*-----------------------------------------------------------------*/ +void killAmorDrive(void *data) +{ + pamorDrive self = NULL; + + self = (pamorDrive) data; + if (self == NULL) { + return; + } + if (self->pDes != NULL) { + DeleteDescriptor(self->pDes); + } + if (self->pDriv != NULL) { + free(self->pDriv); + } + free(self); +} + +/*-----------------------------------------------------------------*/ +pamorDrive makeAmorDrive(pamorSet papa, int type) +{ + pamorDrive self = NULL; + + self = AMODRIVMakeObject(); + if (self == NULL) { return self; -} -/*-----------------------------------------------------------------*/ -void killAmorDrive(void *data){ - pamorDrive self = NULL; - - self = (pamorDrive)data; - if(self == NULL){ - return; - } - if(self->pDes != NULL){ - DeleteDescriptor(self->pDes); - } - if(self->pDriv != NULL){ - free(self->pDriv); - } - free(self); -} -/*-----------------------------------------------------------------*/ -pamorDrive makeAmorDrive(pamorSet papa, int type){ - pamorDrive self = NULL; - - self = AMODRIVMakeObject(); - if(self == NULL){ - return self; - } - self->mama = papa; - self->type = type; - return self; -} -/*----------------------------------------------------------------*/ -int AmorDriveAction(SConnection *pCon, SicsInterp *pSics, void *pData, - int argc, char *argv[]){ - pamorDrive self = NULL; - float val; - char pBueffel[132]; - - self = (pamorDrive)pData; - assert(self); - val = amorGetMotor(self->mama, pCon,self->type); - if(val > -999999) { - snprintf(pBueffel,131, " %s = %f", argv[0], val); - SCWrite(pCon,pBueffel,eValue); - return 1; - } else { - return 0; - } - return 0; + } + self->mama = papa; + self->type = type; + return self; } +/*----------------------------------------------------------------*/ +int AmorDriveAction(SConnection * pCon, SicsInterp * pSics, void *pData, + int argc, char *argv[]) +{ + pamorDrive self = NULL; + float val; + char pBueffel[132]; + + self = (pamorDrive) pData; + assert(self); + val = amorGetMotor(self->mama, pCon, self->type); + if (val > -999999) { + snprintf(pBueffel, 131, " %s = %f", argv[0], val); + SCWrite(pCon, pBueffel, eValue); + return 1; + } else { + return 0; + } + return 0; +} diff --git a/amordrive.h b/amordrive.h index d1a53c5..1800605 100644 --- a/amordrive.h +++ b/amordrive.h @@ -9,17 +9,16 @@ #ifndef AMORDRIVE #define AMORDRIVE -typedef struct{ - pObjectDescriptor pDes; - pIDrivable pDriv; - pamorSet mama; - int type; +typedef struct { + pObjectDescriptor pDes; + pIDrivable pDriv; + pamorSet mama; + int type; } amorDrive, *pamorDrive; /*-----------------------------------------------------------------*/ pamorDrive makeAmorDrive(pamorSet papa, int type); void killAmorDrive(void *data); -int AmorDriveAction(SConnection *pCon, SicsInterp *pSics, void *pData, - int argc, char *argv[]); +int AmorDriveAction(SConnection * pCon, SicsInterp * pSics, void *pData, + int argc, char *argv[]); #endif - diff --git a/amorscan.c b/amorscan.c index d90e5f2..51be720 100644 --- a/amorscan.c +++ b/amorscan.c @@ -18,123 +18,119 @@ #include "nxamor.h" #include "amorscan.h" -/*--------------------------------------------------------------------*/ - static int AmorHeader(pScanData self) - { - return WriteAmorHeader(self->pFile, self->pCon); - } /*--------------------------------------------------------------------*/ - static int AmorPoints(pScanData self, int iP) - { - /* write only at last scan point */ - if((iP+1) >= self->iNP) - { - return WriteAmorScan(self->pFile,self->pCon,self); +static int AmorHeader(pScanData self) +{ + return WriteAmorHeader(self->pFile, self->pCon); +} + +/*--------------------------------------------------------------------*/ +static int AmorPoints(pScanData self, int iP) +{ + /* write only at last scan point */ + if ((iP + 1) >= self->iNP) { + return WriteAmorScan(self->pFile, self->pCon, self); + } + return 1; +} + +/*--------------------------------------------------------------------*/ +static int AmorCollect(pScanData self, int iP) +{ + pVarEntry pVar = NULL; + void *pDings; + int i, iRet, status; + float fVal; + char pStatus[512], pItem[20]; + char pHead[512]; + CountEntry sCount; + + assert(self); + assert(self->pCon); + + /* prepare output header */ + sprintf(pHead, "%-5.5s", "NP"); + sprintf(pStatus, "%-5d", iP); + + /* loop over all scan variables */ + status = 1; + for (i = 0; i < self->iScanVar; i++) { + DynarGet(self->pScanVar, i, &pDings); + pVar = (pVarEntry) pDings; + if (pVar) { + fVal = pVar->pInter->GetValue(pVar->pObject, self->pCon); + AppendScanVar(pVar, fVal); + sprintf(pItem, " %-9.9s", pVar->Name); + strcat(pHead, pItem); + sprintf(pItem, " %-9.3f", fVal); + strcat(pStatus, pItem); } - return 1; - } -/*--------------------------------------------------------------------*/ - static int AmorCollect(pScanData self, int iP) - { - pVarEntry pVar = NULL; - void *pDings; - int i, iRet, status; - float fVal; - char pStatus[512], pItem[20]; - char pHead[512]; - CountEntry sCount; + } - assert(self); - assert(self->pCon); - - /* prepare output header */ - sprintf(pHead,"%-5.5s","NP"); - sprintf(pStatus,"%-5d",iP); - - /* loop over all scan variables */ - status = 1; - for(i = 0; i < self->iScanVar; i++) - { - DynarGet(self->pScanVar,i,&pDings); - pVar = (pVarEntry)pDings; - if(pVar) - { - fVal = pVar->pInter->GetValue(pVar->pObject,self->pCon); - AppendScanVar(pVar,fVal); - sprintf(pItem," %-9.9s",pVar->Name); - strcat(pHead,pItem); - sprintf(pItem," %-9.3f",fVal); - strcat(pStatus,pItem); - } - } - - /* store counter data */ - /* monitors */ - for(i = 1; i < 10; i++) - { - sCount.Monitors[i-1] = GetMonitor((pCounter)self->pCounterData,i, + /* store counter data */ + /* monitors */ + for (i = 1; i < 10; i++) { + sCount.Monitors[i - 1] = GetMonitor((pCounter) self->pCounterData, i, self->pCon); - } - if( self->iChannel != 0 && self->iChannel != -10 ) - { - sCount.Monitors[self->iChannel - 1] = - GetCounts((pCounter)self->pCounterData, - self->pCon); - } - /* counter1 */ - strcat(pHead,"Counter1 "); - sCount.lCount = GetCounts((pCounter)self->pCounterData,self->pCon); - sprintf(pItem," %-14ld",sCount.lCount); - strcat(pStatus,pItem); - - /* - WARNING - Assignements have to be checked when the Schlumpfes are - ready putting the counter box together. - */ - - /* counter2 */ - strcat(pHead,"Counter2 "); - sCount.Monitors[0] = GetMonitor((pCounter)self->pCounterData, - 1,self->pCon); - sprintf(pItem," %-14ld",sCount.Monitors[0]); - strcat(pStatus,pItem); - - /* monitors */ - sCount.Monitors[3] = GetMonitor((pCounter)self->pCounterData, - 2,self->pCon); - sCount.Monitors[4] = GetMonitor((pCounter)self->pCounterData, - 3,self->pCon); - - /* get time */ - sCount.fTime = GetCountTime((pCounter)self->pCounterData, - self->pCon); - strcat(pHead,"Monitor1 "); - sprintf(pItem," %-11ld",sCount.Monitors[3]); - strcat(pStatus,pItem); - strcat(pHead,"Monitor2 "); - sprintf(pItem," %-11ld",sCount.Monitors[4]); - strcat(pStatus,pItem); - strcat(pHead,"Time "); - sprintf(pItem," %-5.1f",sCount.fTime); - strcat(pStatus,pItem); - - /* write progress */ - strcat(pHead,"\n"); - strcat(pStatus,"\n"); - SCWrite(self->pCon,pHead,eLog); - SCWrite(self->pCon,pStatus,eLog); - - /* stow away */ - DynarReplace(self->pCounts,self->iCounts,&sCount,sizeof(CountEntry)); - self->iCounts++; - return 1; } + if (self->iChannel != 0 && self->iChannel != -10) { + sCount.Monitors[self->iChannel - 1] = + GetCounts((pCounter) self->pCounterData, self->pCon); + } + /* counter1 */ + strcat(pHead, "Counter1 "); + sCount.lCount = GetCounts((pCounter) self->pCounterData, self->pCon); + sprintf(pItem, " %-14ld", sCount.lCount); + strcat(pStatus, pItem); + + /* + WARNING + Assignements have to be checked when the Schlumpfes are + ready putting the counter box together. + */ + + /* counter2 */ + strcat(pHead, "Counter2 "); + sCount.Monitors[0] = GetMonitor((pCounter) self->pCounterData, + 1, self->pCon); + sprintf(pItem, " %-14ld", sCount.Monitors[0]); + strcat(pStatus, pItem); + + /* monitors */ + sCount.Monitors[3] = GetMonitor((pCounter) self->pCounterData, + 2, self->pCon); + sCount.Monitors[4] = GetMonitor((pCounter) self->pCounterData, + 3, self->pCon); + + /* get time */ + sCount.fTime = GetCountTime((pCounter) self->pCounterData, self->pCon); + strcat(pHead, "Monitor1 "); + sprintf(pItem, " %-11ld", sCount.Monitors[3]); + strcat(pStatus, pItem); + strcat(pHead, "Monitor2 "); + sprintf(pItem, " %-11ld", sCount.Monitors[4]); + strcat(pStatus, pItem); + strcat(pHead, "Time "); + sprintf(pItem, " %-5.1f", sCount.fTime); + strcat(pStatus, pItem); + + /* write progress */ + strcat(pHead, "\n"); + strcat(pStatus, "\n"); + SCWrite(self->pCon, pHead, eLog); + SCWrite(self->pCon, pStatus, eLog); + + /* stow away */ + DynarReplace(self->pCounts, self->iCounts, &sCount, sizeof(CountEntry)); + self->iCounts++; + return 1; +} + /*-----------------------------------------------------------------------*/ - int ConfigureAmor(pScanData self) - { - self->WriteHeader = AmorHeader; - self->WriteScanPoints = AmorPoints; - self->CollectScanData = AmorCollect; - return 1; - } +int ConfigureAmor(pScanData self) +{ + self->WriteHeader = AmorHeader; + self->WriteScanPoints = AmorPoints; + self->CollectScanData = AmorCollect; + return 1; +} diff --git a/amorscan.h b/amorscan.h index d97195f..628d39c 100644 --- a/amorscan.h +++ b/amorscan.h @@ -9,7 +9,6 @@ #ifndef AMORSCAN #define AMORSCAN - int ConfigureAmor(pScanData pScan); +int ConfigureAmor(pScanData pScan); #endif - diff --git a/amorset.c b/amorset.c index 401cf22..0bfd20f 100644 --- a/amorset.c +++ b/amorset.c @@ -22,244 +22,254 @@ #define TYS2T 2 #define TYATH 3 -#define ABS(x) (x < 0 ? -(x) : (x)) +#define ABS(x) (x < 0 ? -(x) : (x)) /*------------ The meat of it all: The settings calculation --------*/ -static int readMotors(pamorSet self, SConnection *pCon){ - int result, status; - float val; - - result = LLDcreate(sizeof(MotControl)); - status = addMotorToList(result,"d1t",.0); - if(status != 1){ - SCWrite(pCon,"ERROR: configuration error: d1t not found", eError); - return -1; - } - status = addMotorToList(result,"d2t",.0); - if(status != 1){ - SCWrite(pCon,"ERROR: configuration error: d2t not found", eError); - return -1; - } - status = addMotorToList(result,"d3t",.0); - if(status != 1){ - SCWrite(pCon,"ERROR: configuration error: d3t not found", eError); - return -1; - } - status = addMotorToList(result,"d4t",.0); - if(status != 1){ - SCWrite(pCon,"ERROR: configuration error: d4t not found", eError); - return -1; - } - status = addMotorToList(result,"d5t",.0); - if(status != 1){ - SCWrite(pCon,"ERROR: configuration error: d5t not found", eError); - return -1; - } - val = self->listDrive->GetValue(&result,pCon); - if(val < -99999){ - LLDdelete(result); - return -1; - } - return result; +static int readMotors(pamorSet self, SConnection * pCon) +{ + int result, status; + float val; + + result = LLDcreate(sizeof(MotControl)); + status = addMotorToList(result, "d1t", .0); + if (status != 1) { + SCWrite(pCon, "ERROR: configuration error: d1t not found", eError); + return -1; + } + status = addMotorToList(result, "d2t", .0); + if (status != 1) { + SCWrite(pCon, "ERROR: configuration error: d2t not found", eError); + return -1; + } + status = addMotorToList(result, "d3t", .0); + if (status != 1) { + SCWrite(pCon, "ERROR: configuration error: d3t not found", eError); + return -1; + } + status = addMotorToList(result, "d4t", .0); + if (status != 1) { + SCWrite(pCon, "ERROR: configuration error: d4t not found", eError); + return -1; + } + status = addMotorToList(result, "d5t", .0); + if (status != 1) { + SCWrite(pCon, "ERROR: configuration error: d5t not found", eError); + return -1; + } + val = self->listDrive->GetValue(&result, pCon); + if (val < -99999) { + LLDdelete(result); + return -1; + } + return result; } + /*------------------------------------------------------------------*/ -static int calcAmorSettings(pamorSet self,SConnection *pCon){ - int readList; - double val, dist, com = .0, soz, mot; - - /* - * read motors - */ - readList = readMotors(self,pCon); - if(readList < 0){ - SCWrite(pCon, - "ERROR: failed to read motors for amor settings",eError); - return 0; - } - /** +static int calcAmorSettings(pamorSet self, SConnection * pCon) +{ + int readList; + double val, dist, com = .0, soz, mot; + + /* + * read motors + */ + readList = readMotors(self, pCon); + if (readList < 0) { + SCWrite(pCon, + "ERROR: failed to read motors for amor settings", eError); + return 0; + } + /** * initialize drive list */ - LLDdelete(self->driveList); - self->driveList = LLDcreate(sizeof(MotControl)); - - /* - * soz - */ - dist = ABS(calcCompPosition(&self->S) - calcCompPosition(&self->M)); - soz = dist*Tand(-self->targetm2t); - addMotorToList(self->driveList,"soz",soz); - - /* - * monochromator slit - */ - if(self->DS.activeFlag == 1){ - dist = ABS(calcCompPosition(&self->DS) - calcCompPosition(&self->M)); - val = dist*Tand(-self->targetm2t) - self->dspar; - addMotorToList(self->driveList,"dbs",val); - } + LLDdelete(self->driveList); + self->driveList = LLDcreate(sizeof(MotControl)); - /* - * slit 1 is before the monochromator and does not need to be - * driven when m2t changes. This is here to make sure that d1b is - * in a feasible position. - */ - if(self->D1.activeFlag == 1){ - mot = getListMotorPosition(readList,"d1t"); - if(mot < -99999){ - SCWrite(pCon,"WARNING: skipping d1 because of bad read on d1t", - eWarning); - } else { - val = - .5 * mot; - addMotorToList(self->driveList,"d1b",val); - } - } - - /* - * slit 2 - */ - if(self->D2.activeFlag == 1){ - dist = ABS(calcCompPosition(&self->D2) - calcCompPosition(&self->M)); - mot = getListMotorPosition(readList,"d2t"); - if(mot < -99999){ - SCWrite(pCon,"WARNING: skipping d2 because of bad read on d2t", - eWarning); - } else { - val = dist*Tand(-self->targetm2t) - .5 * mot; - addMotorToList(self->driveList,"d2b",val); - } - } - - /* - * slit 3 - */ - if(self->D3.activeFlag == 1){ - dist = ABS(calcCompPosition(&self->D3) - calcCompPosition(&self->M)); - mot = getListMotorPosition(readList,"d3t"); - if(mot < -99999){ - SCWrite(pCon,"WARNING: skipping d3 because of bad read on d3t", - eWarning); - } else { - val = dist*Tand(-self->targetm2t) - .5 * mot; - addMotorToList(self->driveList,"d3b",val); - } - } - - - /* - * detector - */ - com = self->targets2t - self->targetm2t; - if(self->D.activeFlag == 1){ - addMotorToList(self->driveList,"com",com); - dist = ABS(calcCompPosition(&self->D) - calcCompPosition(&self->S)); - val = -dist*(Cosd(com) - 1.); - addMotorToList(self->driveList,"cox",val); - val = dist*Sind(com) + soz; - addMotorToList(self->driveList,"coz",val); - } + /* + * soz + */ + dist = ABS(calcCompPosition(&self->S) - calcCompPosition(&self->M)); + soz = dist * Tand(-self->targetm2t); + addMotorToList(self->driveList, "soz", soz); - /* - * slit 4 - */ - if(self->D4.activeFlag == 1){ - dist = ABS(calcCompPosition(&self->D4) - calcCompPosition(&self->S)); - mot = getListMotorPosition(readList,"d4t"); - if(mot < -99999){ - SCWrite(pCon,"WARNING: skipping d4 because of bad read on d4t", - eWarning); - } else { - val = soz + dist*Tand(com) - .5 * mot; - addMotorToList(self->driveList,"d4b",val); - } - } - - /* - * slit 5 - */ - if(self->D5.activeFlag == 1){ - dist = ABS(calcCompPosition(&self->D5) - calcCompPosition(&self->S)); - mot = getListMotorPosition(readList,"d5t"); - if(mot < -99999){ - SCWrite(pCon,"WARNING: skipping d5 because of bad read on d5t", - eWarning); - } else { - val = soz + dist*Tand(com) - .5 * mot; - addMotorToList(self->driveList,"d5b",val); - } - } - - /* - * Analyzer - */ - if(self->A.activeFlag == 1){ - dist = ABS(calcCompPosition(&self->A) - calcCompPosition(&self->S)); - val = soz + dist*Tand(com); - addMotorToList(self->driveList,"aoz",val); - addMotorToList(self->driveList,"aom",com + self->targetath); - } - - LLDdelete(readList); - self->mustDrive = 0; - return 1; + /* + * monochromator slit + */ + if (self->DS.activeFlag == 1) { + dist = ABS(calcCompPosition(&self->DS) - calcCompPosition(&self->M)); + val = dist * Tand(-self->targetm2t) - self->dspar; + addMotorToList(self->driveList, "dbs", val); + } + + /* + * slit 1 is before the monochromator and does not need to be + * driven when m2t changes. This is here to make sure that d1b is + * in a feasible position. + */ + if (self->D1.activeFlag == 1) { + mot = getListMotorPosition(readList, "d1t"); + if (mot < -99999) { + SCWrite(pCon, "WARNING: skipping d1 because of bad read on d1t", + eWarning); + } else { + val = -.5 * mot; + addMotorToList(self->driveList, "d1b", val); + } + } + + /* + * slit 2 + */ + if (self->D2.activeFlag == 1) { + dist = ABS(calcCompPosition(&self->D2) - calcCompPosition(&self->M)); + mot = getListMotorPosition(readList, "d2t"); + if (mot < -99999) { + SCWrite(pCon, "WARNING: skipping d2 because of bad read on d2t", + eWarning); + } else { + val = dist * Tand(-self->targetm2t) - .5 * mot; + addMotorToList(self->driveList, "d2b", val); + } + } + + /* + * slit 3 + */ + if (self->D3.activeFlag == 1) { + dist = ABS(calcCompPosition(&self->D3) - calcCompPosition(&self->M)); + mot = getListMotorPosition(readList, "d3t"); + if (mot < -99999) { + SCWrite(pCon, "WARNING: skipping d3 because of bad read on d3t", + eWarning); + } else { + val = dist * Tand(-self->targetm2t) - .5 * mot; + addMotorToList(self->driveList, "d3b", val); + } + } + + + /* + * detector + */ + com = self->targets2t - self->targetm2t; + if (self->D.activeFlag == 1) { + addMotorToList(self->driveList, "com", com); + dist = ABS(calcCompPosition(&self->D) - calcCompPosition(&self->S)); + val = -dist * (Cosd(com) - 1.); + addMotorToList(self->driveList, "cox", val); + val = dist * Sind(com) + soz; + addMotorToList(self->driveList, "coz", val); + } + + /* + * slit 4 + */ + if (self->D4.activeFlag == 1) { + dist = ABS(calcCompPosition(&self->D4) - calcCompPosition(&self->S)); + mot = getListMotorPosition(readList, "d4t"); + if (mot < -99999) { + SCWrite(pCon, "WARNING: skipping d4 because of bad read on d4t", + eWarning); + } else { + val = soz + dist * Tand(com) - .5 * mot; + addMotorToList(self->driveList, "d4b", val); + } + } + + /* + * slit 5 + */ + if (self->D5.activeFlag == 1) { + dist = ABS(calcCompPosition(&self->D5) - calcCompPosition(&self->S)); + mot = getListMotorPosition(readList, "d5t"); + if (mot < -99999) { + SCWrite(pCon, "WARNING: skipping d5 because of bad read on d5t", + eWarning); + } else { + val = soz + dist * Tand(com) - .5 * mot; + addMotorToList(self->driveList, "d5b", val); + } + } + + /* + * Analyzer + */ + if (self->A.activeFlag == 1) { + dist = ABS(calcCompPosition(&self->A) - calcCompPosition(&self->S)); + val = soz + dist * Tand(com); + addMotorToList(self->driveList, "aoz", val); + addMotorToList(self->driveList, "aom", com + self->targetath); + } + + LLDdelete(readList); + self->mustDrive = 0; + return 1; } + /*----------------------------------------------------------------*/ -static int updateActualPositions(pamorSet self, SConnection *pCon){ - int readList, status; - float val, dist, tmp, com; - - /** +static int updateActualPositions(pamorSet self, SConnection * pCon) +{ + int readList, status; + float val, dist, tmp, com; + + /** * read some motors */ - readList = LLDcreate(sizeof(MotControl)); - addMotorToList(readList,"soz",125); - addMotorToList(readList,"com",125); - addMotorToList(readList,"aom",125); - val = self->listDrive->GetValue(&readList,pCon); - if(val < -99999.){ - SCWrite(pCon, - "ERROR: failed to read motors, values for m2t,s2t,ath invalid", - eError); - LLDdelete(readList); - return 0; - } - val = getListMotorPosition(readList,"soz"); - dist = ABS(calcCompPosition(&self->S) - calcCompPosition(&self->M)); - tmp = val/dist; - if(ABS(tmp) > .0001){ - self->actualm2t = -Atand(tmp); - } else { - self->actualm2t = .0; - } - com = getListMotorPosition(readList,"com"); - self->actuals2t = com + self->actualm2t; - - val = getListMotorPosition(readList,"aom"); - self->actualath = val - com; + readList = LLDcreate(sizeof(MotControl)); + addMotorToList(readList, "soz", 125); + addMotorToList(readList, "com", 125); + addMotorToList(readList, "aom", 125); + val = self->listDrive->GetValue(&readList, pCon); + if (val < -99999.) { + SCWrite(pCon, + "ERROR: failed to read motors, values for m2t,s2t,ath invalid", + eError); + LLDdelete(readList); + return 0; + } + val = getListMotorPosition(readList, "soz"); + dist = ABS(calcCompPosition(&self->S) - calcCompPosition(&self->M)); + tmp = val / dist; + if (ABS(tmp) > .0001) { + self->actualm2t = -Atand(tmp); + } else { + self->actualm2t = .0; + } + com = getListMotorPosition(readList, "com"); + self->actuals2t = com + self->actualm2t; - LLDdelete(readList); - self->mustRecalculate = 1; - return 1; + val = getListMotorPosition(readList, "aom"); + self->actualath = val - com; + + LLDdelete(readList); + self->mustRecalculate = 1; + return 1; } + /*=================== SICS internal interface functions============*/ -static void *AMOSETGetInterface(void *data, int iD){ - pamorSet self = NULL; - - /* - * this object shall never be driven directly - */ - return NULL; +static void *AMOSETGetInterface(void *data, int iD) +{ + pamorSet self = NULL; + + /* + * this object shall never be driven directly + */ + return NULL; } + /*---------------------------------------------------------------- This routine can return either OKOK or HWFault when thing go wrong. However, the return value of Halt is usually ignored! ------------------------------------------------------------------*/ -static int AMOSETHalt(void *data) { - pamorSet self = NULL; - - self = (pamorSet)data; +static int AMOSETHalt(void *data) +{ + pamorSet self = NULL; - self->listDrive->Halt(&self->driveList); - return OKOK; + self = (pamorSet) data; + + self->listDrive->Halt(&self->driveList); + return OKOK; } + /*---------------------------------------------------------------- This routine can return either 1 or 0. 1 means the position can be reached, 0 NOT @@ -267,10 +277,12 @@ static int AMOSETHalt(void *data) { about which limit was violated ------------------------------------------------------------------*/ static int AMOSETCheckLimits(void *data, float val, - char *error, int errlen){ - pamorSet self = NULL; - return 1; + char *error, int errlen) +{ + pamorSet self = NULL; + return 1; } + /*---------------------------------------------------------------- This routine can return 0 when a limit problem occurred OKOK when the motor was successfully started @@ -280,10 +292,12 @@ static int AMOSETCheckLimits(void *data, float val, to start the motor in question val is the value to drive the motor too ------------------------------------------------------------------*/ -static long AMOSETSetValue(void *data, SConnection *pCon, float val){ - pamorSet self = NULL; - return OKOK; +static long AMOSETSetValue(void *data, SConnection * pCon, float val) +{ + pamorSet self = NULL; + return OKOK; } + /*---------------------------------------------------------------- Checks the status of a running motor. Possible return values HWBusy The motor is still running @@ -294,392 +308,417 @@ static long AMOSETSetValue(void *data, SConnection *pCon, float val){ For real motors CheckStatus again shall try hard to fix any issues with the motor ------------------------------------------------------------------*/ -static int AMOSETCheckStatus(void *data, SConnection *pCon){ - pamorSet self = NULL; - int status; - - self = (pamorSet)data; - - if(self->mustDrive == 1){ - status = calcAmorSettings(self,pCon); - if(status <= 0){ - return HWFault; - } - if(self->verbose == 1){ - printMotorList(self->driveList,pCon); - } - status = self->listDrive->SetValue(&self->driveList,pCon,.37); - return HWBusy; - } else { - self->mustRecalculate = 1; - return self->listDrive->CheckStatus(&self->driveList,pCon); - } +static int AMOSETCheckStatus(void *data, SConnection * pCon) +{ + pamorSet self = NULL; + int status; + + self = (pamorSet) data; + + if (self->mustDrive == 1) { + status = calcAmorSettings(self, pCon); + if (status <= 0) { + return HWFault; + } + if (self->verbose == 1) { + printMotorList(self->driveList, pCon); + } + status = self->listDrive->SetValue(&self->driveList, pCon, .37); + return HWBusy; + } else { + self->mustRecalculate = 1; + return self->listDrive->CheckStatus(&self->driveList, pCon); + } } + /*---------------------------------------------------------------- GetValue is supposed to read a motor position On errors, -99999999.99 is returned and messages printed to pCon ------------------------------------------------------------------*/ -static float AMOSETGetValue(void *data, SConnection *pCon){ - pamorSet self = NULL; - float val = -99999999.99; - - self = (pamorSet)data; +static float AMOSETGetValue(void *data, SConnection * pCon) +{ + pamorSet self = NULL; + float val = -99999999.99; - return val; + self = (pamorSet) data; + + return val; } + /*================ external functions for amordrive ============*/ -void amorSetMotor(pamorSet amor, int type, double value){ - switch(type){ - case TYM2T: - amor->targetm2t = value; - break; - case TYS2T: - amor->targets2t = value; - break; - case TYATH: - amor->targetath = value; - break; - default: - assert(0); - break; - } - amor->mustDrive = 1; +void amorSetMotor(pamorSet amor, int type, double value) +{ + switch (type) { + case TYM2T: + amor->targetm2t = value; + break; + case TYS2T: + amor->targets2t = value; + break; + case TYATH: + amor->targetath = value; + break; + default: + assert(0); + break; + } + amor->mustDrive = 1; } + /*----------------------------------------------------------------*/ -double amorGetMotor(pamorSet amor, SConnection *pCon, int type){ - if(amor->mustRecalculate == 1){ - updateActualPositions(amor,pCon); - } - switch(type){ - case TYM2T: - return amor->actualm2t; - break; - case TYS2T: - return amor->actuals2t; - break; - case TYATH: - return amor->actualath; - break; - default: - assert(0); - break; - } - return -99999.999; +double amorGetMotor(pamorSet amor, SConnection * pCon, int type) +{ + if (amor->mustRecalculate == 1) { + updateActualPositions(amor, pCon); + } + switch (type) { + case TYM2T: + return amor->actualm2t; + break; + case TYS2T: + return amor->actuals2t; + break; + case TYATH: + return amor->actualath; + break; + default: + assert(0); + break; + } + return -99999.999; } + /*---------------------------------------------------------------- Live and Deatch of objects......... returns NULL on failure, a new datastructure else ------------------------------------------------------------------*/ -static int amorSetSave(void *data, char *name,FILE *fd){ - pamorSet self = NULL; - - self = (pamorSet)data; - if(self == NULL){ - return 0; - } - fprintf(fd,"%s dspar %f\n", name, self->dspar); - fprintf(fd,"%s detectoroffset %f\n", name, self->detectoroffset); - fprintf(fd,"%s verbose %d\n", name, self->verbose); - fprintf(fd,"%s targets %f %f %f\n", name, self->targetath, self->targetm2t, - self->targets2t); - saveAmorComp(fd,name,"chopper",&self->chopper); - saveAmorComp(fd,name,"mono",&self->M); - saveAmorComp(fd,name,"ds",&self->DS); - saveAmorComp(fd,name,"slit1",&self->D2); - saveAmorComp(fd,name,"slit2",&self->D2); - saveAmorComp(fd,name,"slit3",&self->D3); - saveAmorComp(fd,name,"sample",&self->S); - saveAmorComp(fd,name,"slit4",&self->D4); - saveAmorComp(fd,name,"slit5",&self->D5); - saveAmorComp(fd,name,"ana",&self->A); - saveAmorComp(fd,name,"detector",&self->D); - return 1; +static int amorSetSave(void *data, char *name, FILE * fd) +{ + pamorSet self = NULL; + + self = (pamorSet) data; + if (self == NULL) { + return 0; + } + fprintf(fd, "%s dspar %f\n", name, self->dspar); + fprintf(fd, "%s detectoroffset %f\n", name, self->detectoroffset); + fprintf(fd, "%s verbose %d\n", name, self->verbose); + fprintf(fd, "%s targets %f %f %f\n", name, self->targetath, + self->targetm2t, self->targets2t); + saveAmorComp(fd, name, "chopper", &self->chopper); + saveAmorComp(fd, name, "mono", &self->M); + saveAmorComp(fd, name, "ds", &self->DS); + saveAmorComp(fd, name, "slit1", &self->D2); + saveAmorComp(fd, name, "slit2", &self->D2); + saveAmorComp(fd, name, "slit3", &self->D3); + saveAmorComp(fd, name, "sample", &self->S); + saveAmorComp(fd, name, "slit4", &self->D4); + saveAmorComp(fd, name, "slit5", &self->D5); + saveAmorComp(fd, name, "ana", &self->A); + saveAmorComp(fd, name, "detector", &self->D); + return 1; } + /*---------------------------------------------------------------*/ -static pamorSet AMOSETMakeObject(){ - pamorSet self = NULL; +static pamorSet AMOSETMakeObject() +{ + pamorSet self = NULL; - self = (pamorSet)malloc(sizeof(amorSet)); - if(self == NULL){ - return NULL; - } - memset(self,0,sizeof(amorSet)); - self->pDes = CreateDescriptor("AmorSet"); - self->pDriv = CreateDrivableInterface(); - self->listDrive = makeMotListInterface(); - self->driveList = LLDcreate(sizeof(MotControl)); - if(self->pDes == NULL || self->pDriv == NULL || - self->listDrive == NULL || self->driveList < 0){ - free(self); - return NULL; - } + self = (pamorSet) malloc(sizeof(amorSet)); + if (self == NULL) { + return NULL; + } + memset(self, 0, sizeof(amorSet)); + self->pDes = CreateDescriptor("AmorSet"); + self->pDriv = CreateDrivableInterface(); + self->listDrive = makeMotListInterface(); + self->driveList = LLDcreate(sizeof(MotControl)); + if (self->pDes == NULL || self->pDriv == NULL || + self->listDrive == NULL || self->driveList < 0) { + free(self); + return NULL; + } - self->pDes->GetInterface = AMOSETGetInterface; - self->pDes->SaveStatus = amorSetSave; - self->pDriv->Halt = AMOSETHalt; - self->pDriv->CheckLimits = AMOSETCheckLimits; - self->pDriv->SetValue = AMOSETSetValue; - self->pDriv->CheckStatus = AMOSETCheckStatus; - self->pDriv->GetValue = AMOSETGetValue; + self->pDes->GetInterface = AMOSETGetInterface; + self->pDes->SaveStatus = amorSetSave; + self->pDriv->Halt = AMOSETHalt; + self->pDriv->CheckLimits = AMOSETCheckLimits; + self->pDriv->SetValue = AMOSETSetValue; + self->pDriv->CheckStatus = AMOSETCheckStatus; + self->pDriv->GetValue = AMOSETGetValue; - return self; + return self; } + /*-----------------------------------------------------------------*/ -static void killAmorSet(void *data){ - pamorSet self = (pamorSet)data; - - if(self == NULL){ - return; - } - - if(self->pDes != NULL) { - DeleteDescriptor(self->pDes); - } - if(self->pDriv != NULL){ - free(self->pDriv); - } - if(self->listDrive != NULL){ - free(self->listDrive); - } - LLDdelete(self->driveList); - free(self); +static void killAmorSet(void *data) +{ + pamorSet self = (pamorSet) data; + + if (self == NULL) { + return; + } + + if (self->pDes != NULL) { + DeleteDescriptor(self->pDes); + } + if (self->pDriv != NULL) { + free(self->pDriv); + } + if (self->listDrive != NULL) { + free(self->listDrive); + } + LLDdelete(self->driveList); + free(self); } + /*-------------------------------------------------------------------*/ -static int testRequiredMotors(SConnection *pCon){ - char motList[][20] = {"soz", "com", - "cox","coz","dbs", - "d1t", "d1b", - "d2b","d2t", - "d3b", "d3t", "d4b","d4t", - "d5t", "d5b","aoz", "aom"}; - int i = 0, status = 1; - pMotor pMot = NULL; - char pBueffel[132]; - - - for(i = 0; i < 17; i++){ - pMot = NULL; - pMot = FindMotor(pServ->pSics,motList[i]); - if(pMot == NULL){ - snprintf(pBueffel,131,"ERROR: motor %s for amorset not found", - motList[i]); - SCWrite(pCon,pBueffel,eError); - status = 0; - } - } - return status; +static int testRequiredMotors(SConnection * pCon) +{ + char motList[][20] = { "soz", "com", + "cox", "coz", "dbs", + "d1t", "d1b", + "d2b", "d2t", + "d3b", "d3t", "d4b", "d4t", + "d5t", "d5b", "aoz", "aom" + }; + int i = 0, status = 1; + pMotor pMot = NULL; + char pBueffel[132]; + + + for (i = 0; i < 17; i++) { + pMot = NULL; + pMot = FindMotor(pServ->pSics, motList[i]); + if (pMot == NULL) { + snprintf(pBueffel, 131, "ERROR: motor %s for amorset not found", + motList[i]); + SCWrite(pCon, pBueffel, eError); + status = 0; + } + } + return status; } + /*======================= interpreter interface section ============*/ -int AmorSetFactory(SConnection *pCon, SicsInterp *pSics, void *pData, - int argc, char *argv[]){ - int status; - pamorSet pNew = NULL; - pamorDrive pTuk = NULL; - - if(testRequiredMotors(pCon) == 0){ - SCWrite(pCon, - "ERROR: aborting initialization of amorset due to missing motors", - eError); - return 0; - } - - pNew = AMOSETMakeObject(); - if(pNew == NULL){ - SCWrite(pCon,"ERROR: out of memory creating amorset", - eError); - return 0; - } - status = AddCommand(pSics,"amorset",AmorSetAction,killAmorSet,pNew); - if(!status){ - SCWrite(pCon,"ERROR: duplicate command amorset NOT created",eError); - return 0; - } - pTuk = makeAmorDrive(pNew,TYM2T); - if(pTuk == NULL){ - SCWrite(pCon,"ERROR: failed to allocate data for m2t",eError); - return 0; - } - status = AddCommand(pSics,"m2t",AmorDriveAction,killAmorDrive,pTuk); - if(!status){ - SCWrite(pCon,"ERROR: duplicate command amorset m2t reated",eError); - return 0; - } - pTuk = makeAmorDrive(pNew,TYATH); - if(pTuk == NULL){ - SCWrite(pCon,"ERROR: failed to allocate data for ath",eError); - return 0; - } - status = AddCommand(pSics,"ath",AmorDriveAction,killAmorDrive,pTuk); - if(!status){ - SCWrite(pCon,"ERROR: duplicate command amorset ath reated",eError); - return 0; - } - pTuk = makeAmorDrive(pNew,TYS2T); - if(pTuk == NULL){ - SCWrite(pCon,"ERROR: failed to allocate data for s2t",eError); - return 0; - } - status = AddCommand(pSics,"s2t",AmorDriveAction,killAmorDrive,pTuk); - if(!status){ - SCWrite(pCon,"ERROR: duplicate command amorset s2t reated",eError); - return 0; - } - SCSendOK(pCon); - return 1; +int AmorSetFactory(SConnection * pCon, SicsInterp * pSics, void *pData, + int argc, char *argv[]) +{ + int status; + pamorSet pNew = NULL; + pamorDrive pTuk = NULL; + + if (testRequiredMotors(pCon) == 0) { + SCWrite(pCon, + "ERROR: aborting initialization of amorset due to missing motors", + eError); + return 0; + } + + pNew = AMOSETMakeObject(); + if (pNew == NULL) { + SCWrite(pCon, "ERROR: out of memory creating amorset", eError); + return 0; + } + status = AddCommand(pSics, "amorset", AmorSetAction, killAmorSet, pNew); + if (!status) { + SCWrite(pCon, "ERROR: duplicate command amorset NOT created", eError); + return 0; + } + pTuk = makeAmorDrive(pNew, TYM2T); + if (pTuk == NULL) { + SCWrite(pCon, "ERROR: failed to allocate data for m2t", eError); + return 0; + } + status = AddCommand(pSics, "m2t", AmorDriveAction, killAmorDrive, pTuk); + if (!status) { + SCWrite(pCon, "ERROR: duplicate command amorset m2t reated", eError); + return 0; + } + pTuk = makeAmorDrive(pNew, TYATH); + if (pTuk == NULL) { + SCWrite(pCon, "ERROR: failed to allocate data for ath", eError); + return 0; + } + status = AddCommand(pSics, "ath", AmorDriveAction, killAmorDrive, pTuk); + if (!status) { + SCWrite(pCon, "ERROR: duplicate command amorset ath reated", eError); + return 0; + } + pTuk = makeAmorDrive(pNew, TYS2T); + if (pTuk == NULL) { + SCWrite(pCon, "ERROR: failed to allocate data for s2t", eError); + return 0; + } + status = AddCommand(pSics, "s2t", AmorDriveAction, killAmorDrive, pTuk); + if (!status) { + SCWrite(pCon, "ERROR: duplicate command amorset s2t reated", eError); + return 0; + } + SCSendOK(pCon); + return 1; } + /*-----------------------------------------------------------------------*/ -static pamorComp locateComponent(pamorSet self, char *name){ - if(strcmp(name,"mono") == 0){ - return &self->M; - } else if(strcmp(name,"ds") == 0){ - return &self->DS; - }else if(strcmp(name,"slit1") == 0){ - return &self->D1; - }else if(strcmp(name,"slit2") == 0){ - return &self->D2; - }else if(strcmp(name,"slit3") == 0){ - return &self->D3; - }else if(strcmp(name,"sample") == 0){ - return &self->S; - } else if(strcmp(name,"slit4") == 0){ - return &self->D4; - }else if(strcmp(name,"slit5") == 0){ - return &self->D5; - }else if(strcmp(name,"detector") == 0){ - return &self->D; - }else if(strcmp(name,"ana") == 0){ - return &self->A; - } else if(strcmp(name,"chopper") == 0){ - return &self->chopper; - } else { - return NULL; - } -} +static pamorComp locateComponent(pamorSet self, char *name) +{ + if (strcmp(name, "mono") == 0) { + return &self->M; + } else if (strcmp(name, "ds") == 0) { + return &self->DS; + } else if (strcmp(name, "slit1") == 0) { + return &self->D1; + } else if (strcmp(name, "slit2") == 0) { + return &self->D2; + } else if (strcmp(name, "slit3") == 0) { + return &self->D3; + } else if (strcmp(name, "sample") == 0) { + return &self->S; + } else if (strcmp(name, "slit4") == 0) { + return &self->D4; + } else if (strcmp(name, "slit5") == 0) { + return &self->D5; + } else if (strcmp(name, "detector") == 0) { + return &self->D; + } else if (strcmp(name, "ana") == 0) { + return &self->A; + } else if (strcmp(name, "chopper") == 0) { + return &self->chopper; + } else { + return NULL; + } +} + /*----------------------------------------------------------------------*/ -static double calcCD(pamorSet self){ - double soz, cmh, smh, sdh, cd, dist; - - dist = ABS(calcCompPosition(&self->S) - calcCompPosition(&self->M)); - soz = dist*Cotd(self->targetm2t); - cmh = calcCompPosition(&self->M); - smh = calcCompPosition(&self->S) - calcCompPosition(&self->M); - sdh = calcCompPosition(&self->D) - calcCompPosition(&self->M); - cd = cmh + sqrt(smh*smh + soz*soz) + sdh; - return cd; -} -/*-----------------------------------------------------------------------*/ -static double calcChopperDetectorDistance(pamorSet self){ - double dist, diff, soz; +static double calcCD(pamorSet self) +{ + double soz, cmh, smh, sdh, cd, dist; - dist = ABS(calcCompPosition(&self->S) - calcCompPosition(&self->M)); - soz = dist*Tand(-self->targetm2t); - - dist = ABS(calcCompPosition(&self->M) - calcCompPosition(&self->chopper)); - diff = calcCompPosition(&self->M) - calcCompPosition(&self->S); - dist += sqrt(diff*diff + soz*soz); - dist += ABS(calcCompPosition(&self->S) - calcCompPosition(&self->D)); - dist += self->detectoroffset; - return dist; + dist = ABS(calcCompPosition(&self->S) - calcCompPosition(&self->M)); + soz = dist * Cotd(self->targetm2t); + cmh = calcCompPosition(&self->M); + smh = calcCompPosition(&self->S) - calcCompPosition(&self->M); + sdh = calcCompPosition(&self->D) - calcCompPosition(&self->M); + cd = cmh + sqrt(smh * smh + soz * soz) + sdh; + return cd; } + /*-----------------------------------------------------------------------*/ -int AmorSetAction(SConnection *pCon, SicsInterp *pSics, void *pData, - int argc, char *argv[]){ - pamorSet self = NULL; - pamorComp comp = NULL; - char pBueffel[132]; - - self = (pamorSet)pData; - assert(self); - - if(argc < 2){ - SCWrite(pCon,"ERROR: not enough arguments to amorset",eError); - return 0; - } - - /* - * catch component commands - */ - strtolower(argv[1]); - comp = locateComponent(self,argv[1]); - if(comp != NULL){ - return handleCompCommand(comp,pCon,argc,argv); - } - - /* - * now it is for us .... - */ - if(strcmp(argv[1],"dspar") == 0){ - if(argc > 2){ - if(!SCMatchRights(pCon,usMugger)){ - return 0; - } - self->dspar = atof(argv[2]); - SCSendOK(pCon); - return 1; - } else { - snprintf(pBueffel,131,"%s dspar = %f", argv[0], self->dspar); - SCWrite(pCon,pBueffel,eValue); - return 1; - } - }else if(strcmp(argv[1],"targets") == 0){ - if(argc >= 5){ - if(!SCMatchRights(pCon,usMugger)){ - return 0; - } - self->targetath = atof(argv[2]); - self->targetm2t = atof(argv[3]); - self->targets2t = atof(argv[4]); - SCSendOK(pCon); - return 1; - } else { - snprintf(pBueffel,131,"%s targets = %f %f %F", argv[0], - self->targetath, self->targetm2t, self->targets2t); - SCWrite(pCon,pBueffel,eValue); - return 1; - } - }else if(strcmp(argv[1],"verbose") == 0){ - if(argc > 2){ - if(!SCMatchRights(pCon,usMugger)){ - return 0; - } - self->verbose = atoi(argv[2]); - SCSendOK(pCon); - return 1; - } else { - snprintf(pBueffel,131,"%s verbose = %d", argv[0], self->verbose); - SCWrite(pCon,pBueffel,eValue); - return 1; - } - }else if(strcmp(argv[1],"detectoroffset") == 0){ - if(argc > 2){ - if(!SCMatchRights(pCon,usUser)){ - return 0; - } - self->detectoroffset = atof(argv[2]); - SCSendOK(pCon); - return 1; - } else { - snprintf(pBueffel,131,"%s detectoroffset = %f", argv[0], - self->detectoroffset); - SCWrite(pCon,pBueffel,eValue); - return 1; - } - } else if(strcmp(argv[1],"cd") == 0){ - snprintf(pBueffel,131,"%s cd = %f", argv[0], calcCD(self)); - SCWrite(pCon,pBueffel,eValue); - return 1; - } else if(strcmp(argv[1],"cdd") == 0){ - snprintf(pBueffel,131,"%s cdd = %f", argv[0], - calcChopperDetectorDistance(self)); - SCWrite(pCon,pBueffel,eValue); - return 1; +static double calcChopperDetectorDistance(pamorSet self) +{ + double dist, diff, soz; + + dist = ABS(calcCompPosition(&self->S) - calcCompPosition(&self->M)); + soz = dist * Tand(-self->targetm2t); + + dist = + ABS(calcCompPosition(&self->M) - calcCompPosition(&self->chopper)); + diff = calcCompPosition(&self->M) - calcCompPosition(&self->S); + dist += sqrt(diff * diff + soz * soz); + dist += ABS(calcCompPosition(&self->S) - calcCompPosition(&self->D)); + dist += self->detectoroffset; + return dist; +} + +/*-----------------------------------------------------------------------*/ +int AmorSetAction(SConnection * pCon, SicsInterp * pSics, void *pData, + int argc, char *argv[]) +{ + pamorSet self = NULL; + pamorComp comp = NULL; + char pBueffel[132]; + + self = (pamorSet) pData; + assert(self); + + if (argc < 2) { + SCWrite(pCon, "ERROR: not enough arguments to amorset", eError); + return 0; + } + + /* + * catch component commands + */ + strtolower(argv[1]); + comp = locateComponent(self, argv[1]); + if (comp != NULL) { + return handleCompCommand(comp, pCon, argc, argv); + } + + /* + * now it is for us .... + */ + if (strcmp(argv[1], "dspar") == 0) { + if (argc > 2) { + if (!SCMatchRights(pCon, usMugger)) { + return 0; + } + self->dspar = atof(argv[2]); + SCSendOK(pCon); + return 1; } else { - snprintf(pBueffel,131,"ERROR: unknown subcommand %s to amorset", - argv[1]); - SCWrite(pCon,pBueffel,eError); - return 0; + snprintf(pBueffel, 131, "%s dspar = %f", argv[0], self->dspar); + SCWrite(pCon, pBueffel, eValue); + return 1; } - - return 1; -} + } else if (strcmp(argv[1], "targets") == 0) { + if (argc >= 5) { + if (!SCMatchRights(pCon, usMugger)) { + return 0; + } + self->targetath = atof(argv[2]); + self->targetm2t = atof(argv[3]); + self->targets2t = atof(argv[4]); + SCSendOK(pCon); + return 1; + } else { + snprintf(pBueffel, 131, "%s targets = %f %f %F", argv[0], + self->targetath, self->targetm2t, self->targets2t); + SCWrite(pCon, pBueffel, eValue); + return 1; + } + } else if (strcmp(argv[1], "verbose") == 0) { + if (argc > 2) { + if (!SCMatchRights(pCon, usMugger)) { + return 0; + } + self->verbose = atoi(argv[2]); + SCSendOK(pCon); + return 1; + } else { + snprintf(pBueffel, 131, "%s verbose = %d", argv[0], self->verbose); + SCWrite(pCon, pBueffel, eValue); + return 1; + } + } else if (strcmp(argv[1], "detectoroffset") == 0) { + if (argc > 2) { + if (!SCMatchRights(pCon, usUser)) { + return 0; + } + self->detectoroffset = atof(argv[2]); + SCSendOK(pCon); + return 1; + } else { + snprintf(pBueffel, 131, "%s detectoroffset = %f", argv[0], + self->detectoroffset); + SCWrite(pCon, pBueffel, eValue); + return 1; + } + } else if (strcmp(argv[1], "cd") == 0) { + snprintf(pBueffel, 131, "%s cd = %f", argv[0], calcCD(self)); + SCWrite(pCon, pBueffel, eValue); + return 1; + } else if (strcmp(argv[1], "cdd") == 0) { + snprintf(pBueffel, 131, "%s cdd = %f", argv[0], + calcChopperDetectorDistance(self)); + SCWrite(pCon, pBueffel, eValue); + return 1; + } else { + snprintf(pBueffel, 131, "ERROR: unknown subcommand %s to amorset", + argv[1]); + SCWrite(pCon, pBueffel, eError); + return 0; + } + return 1; +} diff --git a/amorset.h b/amorset.h index f772d67..f03b7c1 100644 --- a/amorset.h +++ b/amorset.h @@ -13,42 +13,40 @@ #include "amorcomp.h" typedef struct { - pObjectDescriptor pDes; - pIDrivable pDriv; - pIDrivable listDrive; - amorComp chopper; - amorComp M; - amorComp DS; - amorComp D1; - amorComp D2; - amorComp D3; - amorComp S; - amorComp D4; - amorComp A; - amorComp D5; - amorComp D; - double targetm2t; - double targets2t; - double targetath; - double actualm2t; - double actuals2t; - double actualath; - int mustDrive; - int mustRecalculate; - int driveList; - double dspar; - double detectoroffset; - int verbose; -}amorSet, *pamorSet; + pObjectDescriptor pDes; + pIDrivable pDriv; + pIDrivable listDrive; + amorComp chopper; + amorComp M; + amorComp DS; + amorComp D1; + amorComp D2; + amorComp D3; + amorComp S; + amorComp D4; + amorComp A; + amorComp D5; + amorComp D; + double targetm2t; + double targets2t; + double targetath; + double actualm2t; + double actuals2t; + double actualath; + int mustDrive; + int mustRecalculate; + int driveList; + double dspar; + double detectoroffset; + int verbose; +} amorSet, *pamorSet; /*--------------------------------------------------------------------*/ -int AmorSetFactory(SConnection *pCon, SicsInterp *pSics, void *pData, - int argc, char *argv[]); -int AmorSetAction(SConnection *pCon, SicsInterp *pSics, void *pData, - int argc, char *argv[]); -/*============ helper functions for the virtual motors ===============*/ +int AmorSetFactory(SConnection * pCon, SicsInterp * pSics, void *pData, + int argc, char *argv[]); +int AmorSetAction(SConnection * pCon, SicsInterp * pSics, void *pData, + int argc, char *argv[]); +/*============ helper functions for the virtual motors ===============*/ void amorSetMotor(pamorSet amor, int type, double value); -double amorGetMotor(pamorSet amor, SConnection *pCon, int type); +double amorGetMotor(pamorSet amor, SConnection * pCon, int type); #endif - - diff --git a/amorstat.c b/amorstat.c index c3d4851..439a391 100644 --- a/amorstat.c +++ b/amorstat.c @@ -44,1082 +44,973 @@ /*------------------------------------------------------------------- Manually from SinqHM_def.h --------------------------------------------------------------------*/ -#define PROJECT__FRAME 0x0005 -#define PROJECT__AMOR 0x0006 +#define PROJECT__FRAME 0x0005 +#define PROJECT__AMOR 0x0006 /*------------------------------------------------------------------------- A static which determines if we are in TOF or scan mode. */ - static int iTOF = 0; - static pHistMem pHMHM = NULL; +static int iTOF = 0; +static pHistMem pHMHM = NULL; /*-------------------------------------------------------------------------*/ - static int HMCountStartCallback(int iEvent, void *pEvent, void *pUser) - { - SConnection *pCon = (SConnection *)pUser; - const float *fTime = NULL; - int *iTime = NULL; - int iLength, iRet, i; +static int HMCountStartCallback(int iEvent, void *pEvent, void *pUser) +{ + SConnection *pCon = (SConnection *) pUser; + const float *fTime = NULL; + int *iTime = NULL; + int iLength, iRet, i; - /* check kill condition */ - if(pCon == NULL || !SCisConnected(pCon)) - { - return -1; - } + /* check kill condition */ + if (pCon == NULL || !SCisConnected(pCon)) { + return -1; + } - if(iEvent == COUNTSTART) - { - /* send current time binning */ - iTOF = 1; - fTime = GetHistTimeBin(pHMHM,&iLength); - iTime = (int *)malloc((iLength+1)*sizeof(int)); - if( (!fTime) || (!iTime)) - { - return 0; - } - iTime[0] = htonl(iLength); - for(i = 0 ; i < iLength; i++) - { - iTime[i+1] = htonl((int)((fTime[i]/10.)*65536.)); - } - /* send new time binning to all clients */ - SCWrite(pCon,"TOFClear",eError); - SCWriteUUencoded(pCon,"arrowaxis_time",iTime, - (iLength+1)*sizeof(int)); - free(iTime); - } - return 1; - } -/*-------------------------------------------------------------------------*/ - static int ScanStartCallback(int iEvent, void *pEvent, void *pUser) - { - float *fAxis = NULL; - int *iAxis = NULL; - int iLength, iRet, i; - char pBueffel[80], pName[40]; - SConnection *pCon = (SConnection *)pUser; - pScanData pScan = (pScanData)pEvent; - - assert(pScan); - - /* check kill conditions */ - if(pCon == NULL || !SCisConnected(pCon)) - { - return -1; - } - - if(iEvent == SCANSTART) - { - iTOF = 0; - /* send current axis */ - iLength = GetScanNP(pScan); - fAxis = (float *)malloc((iLength+1)*sizeof(float)); - iAxis = (int *)malloc((iLength+1)*sizeof(int)); - if( (!fAxis) || (!iAxis)) - { - return 0; - } - iAxis[0] = htonl(iLength); - GetSoftScanVar(pScan,0,fAxis,iLength); - GetScanVarName(pScan,0,pName,39); - sprintf(pBueffel,"arrowaxis_%s",pName); - for(i = 0 ; i < iLength; i++) - { - iAxis[i+1] = htonl((int)(fAxis[i]*65536.)); - } - /* send new axis to client */ - SCWrite(pCon,"SCANClear",eError); - SCWriteUUencoded(pCon,pBueffel,iAxis, - (iLength+1)*sizeof(int)); - free(iAxis); - free(fAxis); - } - return 1; - } -/*------------------------------------------------------------------------*/ - static int ScanPointCallback(int iEvent, void *pEvent, void *pUser) - { - long *lData = NULL; - int *iData = NULL; - int iLength, iRet, i; - SConnection *pCon = (SConnection *)pUser; - pScanData pScan = (pScanData)pEvent; - - assert(pScan); - - /* check kill conditions */ - if(pCon == NULL || !SCisConnected(pCon)){ - return -1; - } - - if( (iEvent == SCANPOINT) || (iEvent == SCANEND) ) - { - /* send current data */ - iTOF = 0; - iLength = GetScanNP(pScan); - lData = (long *)malloc((iLength+1)*sizeof(long)); - iData = (int *)malloc((iLength+1)*sizeof(int)); - if( (!lData) || (!iData)) - { - return 0; - } - iData[0] = htonl(iLength); - GetScanCounts(pScan,lData,iLength); - for(i = 0 ; i < iLength; i++) - { - iData[i+1] = htonl((int)(lData[i])); - } - /* send counts to client */ - SCWriteUUencoded(pCon,"arrow_spinupup",iData, - (iLength+1)*sizeof(int)); - /* send counts for other detector */ - GetScanMonitor(pScan,2,lData,iLength); - for(i = 0 ; i < iLength; i++) - { - iData[i+1] = htonl((int)(lData[i])); - } - SCWriteUUencoded(pCon,"arrow_spinuplo",iData, - (iLength+1)*sizeof(int)); - /* to do: check for polarization and send spinlo */ - free(iData); - free(lData); - } - return 1; - } -/*------------------------------------------------------------------------*/ - static int SendLoadedData(pAmorStat self, SConnection *pCon) - { - int i, iRet, *iData = NULL; - char pBueffel[80]; - UserData ud; - - SCWrite(pCon,"loaded_CLEAR",eValue); - iRet = LLDnodePtr2First(self->iUserList); - while(iRet != 0) - { - LLDnodeDataTo(self->iUserList,&ud); - iData = (int *)malloc((ud.iNP*2 + 1)*sizeof(int)); - if(!iData) - { - return 0; - } - iData[0] = htonl(ud.iNP); - for(i = 0; i < ud.iNP; i++) - { - iData[i+1] = htonl((int)(ud.fX[i]*65536)); - iData[i+1+ud.iNP] = htonl((int)(ud.fY[i]*65536)); - } - sprintf(pBueffel,"loaded_%s",ud.name); - SCWriteUUencoded(pCon,pBueffel,iData,(ud.iNP*2+1)*sizeof(int)); - iRet = LLDnodePtr2Next(self->iUserList); - } + if (iEvent == COUNTSTART) { + /* send current time binning */ + iTOF = 1; + fTime = GetHistTimeBin(pHMHM, &iLength); + iTime = (int *) malloc((iLength + 1) * sizeof(int)); + if ((!fTime) || (!iTime)) { return 0; - } -/*------------------------------------------------------------------------*/ - static int LoadCallback(int iEvent, void *pEvent, void *pUser) - { - pAmorStat pAS = NULL; - SConnection *pCon = NULL; + } + iTime[0] = htonl(iLength); + for (i = 0; i < iLength; i++) { + iTime[i + 1] = htonl((int) ((fTime[i] / 10.) * 65536.)); + } + /* send new time binning to all clients */ + SCWrite(pCon, "TOFClear", eError); + SCWriteUUencoded(pCon, "arrowaxis_time", iTime, + (iLength + 1) * sizeof(int)); + free(iTime); + } + return 1; +} - pCon = (SConnection *)pUser; - - /* check kill conditions */ - if(pCon == NULL || !SCisConnected(pCon)) - { - return -1; - } - - if(iEvent == FILELOADED) - { - pAS = (pAmorStat)pEvent; - assert(pAS); - assert(pCon); - SendLoadedData(pAS,pCon); - } - return 1; - } /*-------------------------------------------------------------------------*/ - static void ClearUserData(pAmorStat self) - { - int iRet; - UserData ud; +static int ScanStartCallback(int iEvent, void *pEvent, void *pUser) +{ + float *fAxis = NULL; + int *iAxis = NULL; + int iLength, iRet, i; + char pBueffel[80], pName[40]; + SConnection *pCon = (SConnection *) pUser; + pScanData pScan = (pScanData) pEvent; + + assert(pScan); + + /* check kill conditions */ + if (pCon == NULL || !SCisConnected(pCon)) { + return -1; + } + + if (iEvent == SCANSTART) { + iTOF = 0; + /* send current axis */ + iLength = GetScanNP(pScan); + fAxis = (float *) malloc((iLength + 1) * sizeof(float)); + iAxis = (int *) malloc((iLength + 1) * sizeof(int)); + if ((!fAxis) || (!iAxis)) { + return 0; + } + iAxis[0] = htonl(iLength); + GetSoftScanVar(pScan, 0, fAxis, iLength); + GetScanVarName(pScan, 0, pName, 39); + sprintf(pBueffel, "arrowaxis_%s", pName); + for (i = 0; i < iLength; i++) { + iAxis[i + 1] = htonl((int) (fAxis[i] * 65536.)); + } + /* send new axis to client */ + SCWrite(pCon, "SCANClear", eError); + SCWriteUUencoded(pCon, pBueffel, iAxis, (iLength + 1) * sizeof(int)); + free(iAxis); + free(fAxis); + } + return 1; +} + +/*------------------------------------------------------------------------*/ +static int ScanPointCallback(int iEvent, void *pEvent, void *pUser) +{ + long *lData = NULL; + int *iData = NULL; + int iLength, iRet, i; + SConnection *pCon = (SConnection *) pUser; + pScanData pScan = (pScanData) pEvent; + + assert(pScan); + + /* check kill conditions */ + if (pCon == NULL || !SCisConnected(pCon)) { + return -1; + } + + if ((iEvent == SCANPOINT) || (iEvent == SCANEND)) { + /* send current data */ + iTOF = 0; + iLength = GetScanNP(pScan); + lData = (long *) malloc((iLength + 1) * sizeof(long)); + iData = (int *) malloc((iLength + 1) * sizeof(int)); + if ((!lData) || (!iData)) { + return 0; + } + iData[0] = htonl(iLength); + GetScanCounts(pScan, lData, iLength); + for (i = 0; i < iLength; i++) { + iData[i + 1] = htonl((int) (lData[i])); + } + /* send counts to client */ + SCWriteUUencoded(pCon, "arrow_spinupup", iData, + (iLength + 1) * sizeof(int)); + /* send counts for other detector */ + GetScanMonitor(pScan, 2, lData, iLength); + for (i = 0; i < iLength; i++) { + iData[i + 1] = htonl((int) (lData[i])); + } + SCWriteUUencoded(pCon, "arrow_spinuplo", iData, + (iLength + 1) * sizeof(int)); + /* to do: check for polarization and send spinlo */ + free(iData); + free(lData); + } + return 1; +} + +/*------------------------------------------------------------------------*/ +static int SendLoadedData(pAmorStat self, SConnection * pCon) +{ + int i, iRet, *iData = NULL; + char pBueffel[80]; + UserData ud; + + SCWrite(pCon, "loaded_CLEAR", eValue); + iRet = LLDnodePtr2First(self->iUserList); + while (iRet != 0) { + LLDnodeDataTo(self->iUserList, &ud); + iData = (int *) malloc((ud.iNP * 2 + 1) * sizeof(int)); + if (!iData) { + return 0; + } + iData[0] = htonl(ud.iNP); + for (i = 0; i < ud.iNP; i++) { + iData[i + 1] = htonl((int) (ud.fX[i] * 65536)); + iData[i + 1 + ud.iNP] = htonl((int) (ud.fY[i] * 65536)); + } + sprintf(pBueffel, "loaded_%s", ud.name); + SCWriteUUencoded(pCon, pBueffel, iData, + (ud.iNP * 2 + 1) * sizeof(int)); + iRet = LLDnodePtr2Next(self->iUserList); + } + return 0; +} + +/*------------------------------------------------------------------------*/ +static int LoadCallback(int iEvent, void *pEvent, void *pUser) +{ + pAmorStat pAS = NULL; + SConnection *pCon = NULL; + + pCon = (SConnection *) pUser; + + /* check kill conditions */ + if (pCon == NULL || !SCisConnected(pCon)) { + return -1; + } + + if (iEvent == FILELOADED) { + pAS = (pAmorStat) pEvent; + assert(pAS); + assert(pCon); + SendLoadedData(pAS, pCon); + } + return 1; +} + +/*-------------------------------------------------------------------------*/ +static void ClearUserData(pAmorStat self) +{ + int iRet; + UserData ud; + + iRet = LLDnodePtr2First(self->iUserList); + while (iRet != 0) { + LLDnodeDataTo(self->iUserList, &ud); + if (ud.fX != NULL) + free(ud.fX); + if (ud.fY != NULL) + free(ud.fY); + if (ud.name != NULL) + free(ud.name); + iRet = LLDnodePtr2Next(self->iUserList); + } + LLDdelete(self->iUserList); + self->iUserList = LLDcreate(sizeof(UserData)); +} - iRet = LLDnodePtr2First(self->iUserList); - while(iRet != 0) - { - LLDnodeDataTo(self->iUserList,&ud); - if(ud.fX != NULL) - free(ud.fX); - if(ud.fY != NULL) - free(ud.fY); - if(ud.name != NULL) - free(ud.name); - iRet = LLDnodePtr2Next(self->iUserList); - } - LLDdelete(self->iUserList); - self->iUserList = LLDcreate(sizeof(UserData)); - } /*----------------------------------------------------------------------*/ - void KillAmorStatus(void *pData) - { - pAmorStat self = (pAmorStat)pData; +void KillAmorStatus(void *pData) +{ + pAmorStat self = (pAmorStat) pData; - if(!self) - return; + if (!self) + return; - if(self->iUserList >= 0) - { - ClearUserData(self); - LLDdelete(self->iUserList); - } - if(self->pDes) - DeleteDescriptor(self->pDes); - if(self->pCall) - DeleteCallBackInterface(self->pCall); - free(self); - } -/*------------------------------------------------------------------*/ - int AmorStatusFactory(SConnection *pCon, SicsInterp *pSics, - void *pData, int argc, char *argv[]) - { - pAmorStat pNew = NULL; - CommandList *pCom = NULL; - char pBueffel[256]; - int iRet; + if (self->iUserList >= 0) { + ClearUserData(self); + LLDdelete(self->iUserList); + } + if (self->pDes) + DeleteDescriptor(self->pDes); + if (self->pCall) + DeleteCallBackInterface(self->pCall); + free(self); +} - /* check number of arguments */ - if(argc < 4) - { - sprintf(pBueffel,"ERROR: insufficient number of arguments to %s", - argv[0]); - SCWrite(pCon,pBueffel,eError); - return 0; - } +/*------------------------------------------------------------------*/ +int AmorStatusFactory(SConnection * pCon, SicsInterp * pSics, + void *pData, int argc, char *argv[]) +{ + pAmorStat pNew = NULL; + CommandList *pCom = NULL; + char pBueffel[256]; + int iRet; - /* allocate a new data structure */ - pNew = (pAmorStat)malloc(sizeof(AmorStat)); - if(!pNew) - { - sprintf(pBueffel,"ERROR: out of memory in %s",argv[0]); - SCWrite(pCon,pBueffel,eError); - return 0; - } - memset(pNew,0,sizeof(AmorStat)); - pNew->pDes = CreateDescriptor("AmorStatus"); - pNew->iUserList = LLDcreate(sizeof(UserData)); - pNew->pCall = CreateCallBackInterface(); - if( (!pNew->pDes) || (pNew->iUserList < 0) || (!pNew->pCall) ) - { - sprintf(pBueffel,"ERROR: out of memory in %s",argv[0]); - SCWrite(pCon,pBueffel,eError); + /* check number of arguments */ + if (argc < 4) { + sprintf(pBueffel, "ERROR: insufficient number of arguments to %s", + argv[0]); + SCWrite(pCon, pBueffel, eError); + return 0; + } + + /* allocate a new data structure */ + pNew = (pAmorStat) malloc(sizeof(AmorStat)); + if (!pNew) { + sprintf(pBueffel, "ERROR: out of memory in %s", argv[0]); + SCWrite(pCon, pBueffel, eError); + return 0; + } + memset(pNew, 0, sizeof(AmorStat)); + pNew->pDes = CreateDescriptor("AmorStatus"); + pNew->iUserList = LLDcreate(sizeof(UserData)); + pNew->pCall = CreateCallBackInterface(); + if ((!pNew->pDes) || (pNew->iUserList < 0) || (!pNew->pCall)) { + sprintf(pBueffel, "ERROR: out of memory in %s", argv[0]); + SCWrite(pCon, pBueffel, eError); + KillAmorStatus(pNew); + return 0; + } + + /* to locate the HM and the scan object */ + pCom = FindCommand(pSics, argv[2]); + if (pCom) { + if (pCom->pData) { + if (!iHasType(pCom->pData, "ScanObject")) { + sprintf(pBueffel, "ERROR: %s is NO scan object", argv[2]); + SCWrite(pCon, pBueffel, eError); KillAmorStatus(pNew); return 0; } - - /* to locate the HM and the scan object */ - pCom = FindCommand(pSics,argv[2]); - if(pCom) - { - if(pCom->pData) - { - if(!iHasType(pCom->pData,"ScanObject")) - { - sprintf(pBueffel,"ERROR: %s is NO scan object",argv[2]); - SCWrite(pCon,pBueffel,eError); - KillAmorStatus(pNew); - return 0; - } - } - else - { - sprintf(pBueffel,"ERROR: %s is NO scan object",argv[2]); - SCWrite(pCon,pBueffel,eError); - KillAmorStatus(pNew); - return 0; - } - } - else - { - sprintf(pBueffel,"ERROR: %s NOT found",argv[2]); - SCWrite(pCon,pBueffel,eError); - KillAmorStatus(pNew); - return 0; - } - pNew->pScan = (pScanData)pCom->pData; - pCom = FindCommand(pSics,argv[3]); - if(pCom) - { - if(pCom->pData) - { - if(!iHasType(pCom->pData,"HistMem")) - { - sprintf(pBueffel,"ERROR: %s is NO histogram memory object", - argv[3]); - SCWrite(pCon,pBueffel,eError); - KillAmorStatus(pNew); - return 0; - } - } - else - { - sprintf(pBueffel,"ERROR: %s is NO histogram memory object", - argv[3]); - SCWrite(pCon,pBueffel,eError); - KillAmorStatus(pNew); - return 0; - } - } - else - { - sprintf(pBueffel,"ERROR: %s NOT found",argv[3]); - SCWrite(pCon,pBueffel,eError); - KillAmorStatus(pNew); - return 0; - } - pNew->pHM = (pHistMem)pCom->pData; - pHMHM = (pHistMem)pCom->pData; - - /* install command */ - iRet = AddCommand(pSics,argv[1], - AmorStatusAction,KillAmorStatus,pNew); - if(!iRet) - { - sprintf(pBueffel,"ERROR: duplicate command %s NOT created", - argv[1]); - SCWrite(pCon,pBueffel,eError); - KillAmorStatus(pNew); - return 0; - } - - - return 1; - } -/*------------------------------------------------------------------*/ - static int RegisterInterest(pAmorStat self, SConnection *pCon) - { - long lID; - pDummy pDum = NULL; - pICallBack pCall = NULL; - - assert(self); - assert(pCon); - - /* Register all the callbacks. Dependent on the state of - iTOF invoke the apropriate callbacks in order to force - an initial update. - */ - /* file load callback */ - lID = RegisterCallback(self->pCall,FILELOADED, LoadCallback, - SCCopyConnection(pCon), SCDeleteConnection); - SendLoadedData(self,pCon); - - /* scan object */ - pDum = (pDummy)self->pScan; - pCall = pDum->pDescriptor->GetInterface(pDum,CALLBACKINTERFACE); - if(pCall) - { - lID = RegisterCallback(pCall,SCANSTART,ScanStartCallback, - SCCopyConnection(pCon), SCDeleteConnection); - lID = RegisterCallback(pCall,SCANPOINT,ScanPointCallback, - SCCopyConnection(pCon), SCDeleteConnection); - lID = RegisterCallback(pCall,SCANEND,ScanPointCallback, - SCCopyConnection(pCon), SCDeleteConnection); - if(iTOF == 0) - { - ScanStartCallback(SCANSTART,pDum,pCon); - ScanPointCallback(SCANPOINT,pDum,pCon); - } - } - /* - * histmem - */ - pDum = (pDummy)self->pHM; - pCall = pDum->pDescriptor->GetInterface(pDum,CALLBACKINTERFACE); - if(pCall) - { - lID = RegisterCallback(pCall,COUNTSTART,HMCountStartCallback, - SCCopyConnection(pCon), SCDeleteConnection); - if(iTOF == 1) - { - HMCountStartCallback(COUNTSTART,pDum,pCon); - } - } - return 1; - } -/*-----------------------------------------------------------------*/ - static int FileLoad(pAmorStat self, SConnection *pCon, - char *name, double dScale) - { - char pBueffel[256], pDummy[50]; - FILE *fd = NULL; - UserData ud; - int iNP, i; - float fDummy; - - /* open the file */ - fd = fopen(name,"r"); - if(!fd) - { - sprintf(pBueffel,"ERROR: cannot open %s for reading",name); - SCWrite(pCon,pBueffel,eError); + } else { + sprintf(pBueffel, "ERROR: %s is NO scan object", argv[2]); + SCWrite(pCon, pBueffel, eError); + KillAmorStatus(pNew); + return 0; + } + } else { + sprintf(pBueffel, "ERROR: %s NOT found", argv[2]); + SCWrite(pCon, pBueffel, eError); + KillAmorStatus(pNew); + return 0; + } + pNew->pScan = (pScanData) pCom->pData; + pCom = FindCommand(pSics, argv[3]); + if (pCom) { + if (pCom->pData) { + if (!iHasType(pCom->pData, "HistMem")) { + sprintf(pBueffel, "ERROR: %s is NO histogram memory object", + argv[3]); + SCWrite(pCon, pBueffel, eError); + KillAmorStatus(pNew); return 0; } - - /* skip first line */ - if(fgets(pBueffel,255,fd) == NULL) - { - SCWrite(pCon,"ERROR: premature end of file",eError); - fclose(fd); - return 0; - } + } else { + sprintf(pBueffel, "ERROR: %s is NO histogram memory object", + argv[3]); + SCWrite(pCon, pBueffel, eError); + KillAmorStatus(pNew); + return 0; + } + } else { + sprintf(pBueffel, "ERROR: %s NOT found", argv[3]); + SCWrite(pCon, pBueffel, eError); + KillAmorStatus(pNew); + return 0; + } + pNew->pHM = (pHistMem) pCom->pData; + pHMHM = (pHistMem) pCom->pData; - /* read number of points in second line */ - if(fgets(pBueffel,255,fd) == NULL) - { - SCWrite(pCon,"ERROR: premature end of file",eError); - fclose(fd); - return 0; - } - sscanf(pBueffel,"%s %d",pDummy, &iNP); - /* allocate data */ - ud.iNP = iNP; - ud.fX = (float *)malloc(iNP*sizeof(float)); - ud.fY = (float *)malloc(iNP*sizeof(float)); - ud.name = strdup(name); + /* install command */ + iRet = AddCommand(pSics, argv[1], + AmorStatusAction, KillAmorStatus, pNew); + if (!iRet) { + sprintf(pBueffel, "ERROR: duplicate command %s NOT created", argv[1]); + SCWrite(pCon, pBueffel, eError); + KillAmorStatus(pNew); + return 0; + } - /* skip two lines */ - if(fgets(pBueffel,255,fd) == NULL) - { - SCWrite(pCon,"ERROR: premature end of file",eError); - fclose(fd); - return 0; - } - if(fgets(pBueffel,255,fd) == NULL) - { - SCWrite(pCon,"ERROR: premature end of file",eError); - fclose(fd); - return 0; - } - /* loop reading data */ - for(i = 0; i < iNP; i++) - { - if(fgets(pBueffel,255,fd) == NULL) - { - SCWrite(pCon,"WARNING: premature end of file",eError); - break; - } - sscanf(pBueffel," %f %f %f",&ud.fX[i],&fDummy, &ud.fY[i]); - ud.fY[i] *= dScale; - } - fclose(fd); + return 1; +} - /* enter ud into list */ - LLDnodeInsertFrom(self->iUserList,&ud); +/*------------------------------------------------------------------*/ +static int RegisterInterest(pAmorStat self, SConnection * pCon) +{ + long lID; + pDummy pDum = NULL; + pICallBack pCall = NULL; + + assert(self); + assert(pCon); + + /* Register all the callbacks. Dependent on the state of + iTOF invoke the apropriate callbacks in order to force + an initial update. + */ + /* file load callback */ + lID = RegisterCallback(self->pCall, FILELOADED, LoadCallback, + SCCopyConnection(pCon), SCDeleteConnection); + SendLoadedData(self, pCon); + + /* scan object */ + pDum = (pDummy) self->pScan; + pCall = pDum->pDescriptor->GetInterface(pDum, CALLBACKINTERFACE); + if (pCall) { + lID = RegisterCallback(pCall, SCANSTART, ScanStartCallback, + SCCopyConnection(pCon), SCDeleteConnection); + lID = RegisterCallback(pCall, SCANPOINT, ScanPointCallback, + SCCopyConnection(pCon), SCDeleteConnection); + lID = RegisterCallback(pCall, SCANEND, ScanPointCallback, + SCCopyConnection(pCon), SCDeleteConnection); + if (iTOF == 0) { + ScanStartCallback(SCANSTART, pDum, pCon); + ScanPointCallback(SCANPOINT, pDum, pCon); + } + } + /* + * histmem + */ + pDum = (pDummy) self->pHM; + pCall = pDum->pDescriptor->GetInterface(pDum, CALLBACKINTERFACE); + if (pCall) { + lID = RegisterCallback(pCall, COUNTSTART, HMCountStartCallback, + SCCopyConnection(pCon), SCDeleteConnection); + if (iTOF == 1) { + HMCountStartCallback(COUNTSTART, pDum, pCon); + } + } + return 1; +} + +/*-----------------------------------------------------------------*/ +static int FileLoad(pAmorStat self, SConnection * pCon, + char *name, double dScale) +{ + char pBueffel[256], pDummy[50]; + FILE *fd = NULL; + UserData ud; + int iNP, i; + float fDummy; + + /* open the file */ + fd = fopen(name, "r"); + if (!fd) { + sprintf(pBueffel, "ERROR: cannot open %s for reading", name); + SCWrite(pCon, pBueffel, eError); + return 0; + } + + /* skip first line */ + if (fgets(pBueffel, 255, fd) == NULL) { + SCWrite(pCon, "ERROR: premature end of file", eError); + fclose(fd); + return 0; + } + + /* read number of points in second line */ + if (fgets(pBueffel, 255, fd) == NULL) { + SCWrite(pCon, "ERROR: premature end of file", eError); + fclose(fd); + return 0; + } + sscanf(pBueffel, "%s %d", pDummy, &iNP); + /* allocate data */ + ud.iNP = iNP; + ud.fX = (float *) malloc(iNP * sizeof(float)); + ud.fY = (float *) malloc(iNP * sizeof(float)); + ud.name = strdup(name); + + /* skip two lines */ + if (fgets(pBueffel, 255, fd) == NULL) { + SCWrite(pCon, "ERROR: premature end of file", eError); + fclose(fd); + return 0; + } + if (fgets(pBueffel, 255, fd) == NULL) { + SCWrite(pCon, "ERROR: premature end of file", eError); + fclose(fd); + return 0; + } + + /* loop reading data */ + for (i = 0; i < iNP; i++) { + if (fgets(pBueffel, 255, fd) == NULL) { + SCWrite(pCon, "WARNING: premature end of file", eError); + break; + } + sscanf(pBueffel, " %f %f %f", &ud.fX[i], &fDummy, &ud.fY[i]); + ud.fY[i] *= dScale; + } + fclose(fd); + + /* enter ud into list */ + LLDnodeInsertFrom(self->iUserList, &ud); + + return 1; +} - return 1; - } /*----------------------------------------------------------------- Collapse creates a 2D image from the detector by summing all time channels together in any given detector. */ - static int Collapse(pAmorStat self, SConnection *pCon) - { - HistInt *lData = NULL; - int i, i2, i3, iDim[MAXDIM], iIdx, iSum, status, length; - int *iImage = NULL, *iPtr; - pSINQHM pHist; - SinqHMDriv *pTata; - int iMax = -999999; - char hmCommand[256]; - HistInt *data = NULL; +static int Collapse(pAmorStat self, SConnection * pCon) +{ + HistInt *lData = NULL; + int i, i2, i3, iDim[MAXDIM], iIdx, iSum, status, length; + int *iImage = NULL, *iPtr; + pSINQHM pHist; + SinqHMDriv *pTata; + int iMax = -999999; + char hmCommand[256]; + HistInt *data = NULL; - /* get size of our problem */ - GetHistDim(self->pHM,iDim,&i3); - /* assert(i3 == 3); */ + /* get size of our problem */ + GetHistDim(self->pHM, iDim, &i3); + /* assert(i3 == 3); */ - /* allocate some data */ - length = 2 + iDim[0]*iDim[1]; - iImage = (int *)malloc(length*sizeof(int)); - if(iImage == NULL) - { - SCWrite(pCon,"ERROR: failed to allocate memory in Collapse",eError); - return 0; - } - memset(iImage,0,(2 + iDim[0]*iDim[1])*sizeof(int)); + /* allocate some data */ + length = 2 + iDim[0] * iDim[1]; + iImage = (int *) malloc(length * sizeof(int)); + if (iImage == NULL) { + SCWrite(pCon, "ERROR: failed to allocate memory in Collapse", eError); + return 0; + } + memset(iImage, 0, (2 + iDim[0] * iDim[1]) * sizeof(int)); - /* first two numbers are the dimension of the image */ - iImage[0] = htonl(iDim[0]); - iImage[1] = htonl(iDim[1]); + /* first two numbers are the dimension of the image */ + iImage[0] = htonl(iDim[0]); + iImage[1] = htonl(iDim[1]); - if(isSINQHMDriv(self->pHM->pDriv)) - { - /* - send a Project request to the histogram memory - */ - pTata = (SinqHMDriv *)self->pHM->pDriv->pPriv; - pHist = (pSINQHM)pTata->pMaster; - /* - The 3 in the following call has to be identical to - PROJECT__COLL in sinqhm_def.h - */ - status = SINQHMProject(pHist, 3, 0, iDim[0], - 0, iDim[1], iImage+2, (length-2)*sizeof(int)); - /* - Byte swapping - */ - for(i = 2; i < length; i++) - { - /* - if(iImage[i] > iMax){ - iMax = iImage[i]; + if (isSINQHMDriv(self->pHM->pDriv)) { + /* + send a Project request to the histogram memory + */ + pTata = (SinqHMDriv *) self->pHM->pDriv->pPriv; + pHist = (pSINQHM) pTata->pMaster; + /* + The 3 in the following call has to be identical to + PROJECT__COLL in sinqhm_def.h + */ + status = SINQHMProject(pHist, 3, 0, iDim[0], + 0, iDim[1], iImage + 2, + (length - 2) * sizeof(int)); + /* + Byte swapping + */ + for (i = 2; i < length; i++) { + /* + if(iImage[i] > iMax){ + iMax = iImage[i]; } - */ - iImage[i] = htonl(iImage[i]); - } - /* + */ + iImage[i] = htonl(iImage[i]); + } + /* printf("Collapsed maximum: %d\n",iMax); - */ - if(status != 1) - { - SCWrite(pCon,"ERROR: histogram memory refused to Collapse",eError); - return 0; - } - } - else if(self->iHTTP == 1) - { - if(i3 > 2){ - snprintf(hmCommand,255,"sum:2:0:%d",iDim[2]); - if(self->pHM->pDriv->SubSample != NULL){ - data = self->pHM->pDriv->SubSample(self->pHM->pDriv,pCon,0,hmCommand); - } else { - data = NULL; - } - if(data == NULL) - { - SCWrite(pCon,"ERROR: failed to retrieve collapsed data from HM", eError); - return 0; - } - for(i = 2; i < length; i++) - { - iImage[i] = htonl(data[i-1]); - } - free(data); - } else { - GetHistogramDirect(self->pHM,pCon,0,0,length-2, - &iImage[2], length*sizeof(HistInt)); - for(i = 2; i < length; i++) - { - iImage[i] = htonl(iImage[i]); - } - } - } - else - { - /* - we are in simulation and just create some random numbers - */ - for(i = 0; i < iDim[0]; i++) - { - for(i2 = 0; i2 < iDim[1]; i2++) - { - iIdx = i*iDim[1] + i2; - iImage[iIdx+2] = htonl(random()); - /* iImage[iIdx+2] = htonl(77);*/ - } - } - } + */ + if (status != 1) { + SCWrite(pCon, "ERROR: histogram memory refused to Collapse", eError); + return 0; + } + } else if (self->iHTTP == 1) { + if (i3 > 2) { + snprintf(hmCommand, 255, "sum:2:0:%d", iDim[2]); + if (self->pHM->pDriv->SubSample != NULL) { + data = + self->pHM->pDriv->SubSample(self->pHM->pDriv, pCon, 0, + hmCommand); + } else { + data = NULL; + } + if (data == NULL) { + SCWrite(pCon, "ERROR: failed to retrieve collapsed data from HM", + eError); + return 0; + } + for (i = 2; i < length; i++) { + iImage[i] = htonl(data[i - 1]); + } + free(data); + } else { + GetHistogramDirect(self->pHM, pCon, 0, 0, length - 2, + &iImage[2], length * sizeof(HistInt)); + for (i = 2; i < length; i++) { + iImage[i] = htonl(iImage[i]); + } + } + } else { + /* + we are in simulation and just create some random numbers + */ + for (i = 0; i < iDim[0]; i++) { + for (i2 = 0; i2 < iDim[1]; i2++) { + iIdx = i * iDim[1] + i2; + iImage[iIdx + 2] = htonl(random()); + /* iImage[iIdx+2] = htonl(77); */ + } + } + } + + /* send image */ + SCWriteUUencoded(pCon, "arrow_image", iImage, + ((iDim[0] * iDim[1]) + 2) * sizeof(int)); + free(iImage); + return 1; +} - /* send image */ - SCWriteUUencoded(pCon,"arrow_image",iImage, - ((iDim[0]*iDim[1])+2)*sizeof(int)); - free(iImage); - return 1; - } /*----------------------------------------------------------------- projectYTOF creates a 2D image from the detector by summing all x channels together onto the y - tof plane */ - static int projectYTOF(pAmorStat self, SConnection *pCon) - { - HistInt *lData = NULL; - int i, i2, i3, iDim[MAXDIM], iIdx, iSum, status, length; - int *iImage = NULL, *iPtr; - pSINQHM pHist; - SinqHMDriv *pTata; - int iMax = -999999; - char hmCommand[256]; - HistInt *data = NULL; +static int projectYTOF(pAmorStat self, SConnection * pCon) +{ + HistInt *lData = NULL; + int i, i2, i3, iDim[MAXDIM], iIdx, iSum, status, length; + int *iImage = NULL, *iPtr; + pSINQHM pHist; + SinqHMDriv *pTata; + int iMax = -999999; + char hmCommand[256]; + HistInt *data = NULL; - /* get size of our problem */ - GetHistDim(self->pHM,iDim,&i3); - if(i3 < 3 || iDim[2] < 2){ - SCWrite(pCon,"ERROR: cannot project on Y - TOF, not in TOF mode", eError); - return 0; - } + /* get size of our problem */ + GetHistDim(self->pHM, iDim, &i3); + if (i3 < 3 || iDim[2] < 2) { + SCWrite(pCon, "ERROR: cannot project on Y - TOF, not in TOF mode", + eError); + return 0; + } - /* allocate some data */ - length = 2 + iDim[1]*iDim[2]; - iImage = (int *)malloc(length*sizeof(int)); - if(iImage == NULL) - { - SCWrite(pCon,"ERROR: failed to allocate memory in projectYTOF",eError); - return 0; - } - memset(iImage,0,(2 + iDim[1]*iDim[2])*sizeof(int)); + /* allocate some data */ + length = 2 + iDim[1] * iDim[2]; + iImage = (int *) malloc(length * sizeof(int)); + if (iImage == NULL) { + SCWrite(pCon, "ERROR: failed to allocate memory in projectYTOF", + eError); + return 0; + } + memset(iImage, 0, (2 + iDim[1] * iDim[2]) * sizeof(int)); - /* first two numbers are the dimensions of the image */ - iImage[0] = htonl(iDim[1]); - iImage[1] = htonl(iDim[2]); + /* first two numbers are the dimensions of the image */ + iImage[0] = htonl(iDim[1]); + iImage[1] = htonl(iDim[2]); - if(isSINQHMDriv(self->pHM->pDriv)) - { - /* - send a Project request to the histogram memory - */ - pTata = (SinqHMDriv *)self->pHM->pDriv->pPriv; - pHist = (pSINQHM)pTata->pMaster; - status = SINQHMProject(pHist, PROJECT__AMOR, 0, 0, - 0, 0, iImage+2, (length-2)*sizeof(int)); + if (isSINQHMDriv(self->pHM->pDriv)) { + /* + send a Project request to the histogram memory + */ + pTata = (SinqHMDriv *) self->pHM->pDriv->pPriv; + pHist = (pSINQHM) pTata->pMaster; + status = SINQHMProject(pHist, PROJECT__AMOR, 0, 0, + 0, 0, iImage + 2, (length - 2) * sizeof(int)); - for(i = 2; i < length; i++) - { - iImage[i] = htonl(iImage[i]); - } - if(status != 1) - { - SCWrite(pCon,"ERROR: histogram memory refused to project",eError); - return 0; - } - } - else if(self->iHTTP == 1) - { - snprintf(hmCommand,255,"sum:0:0:%d", iDim[0]); - data = self->pHM->pDriv->SubSample(self->pHM->pDriv,pCon,0,hmCommand); - if(data == NULL) - { - SCWrite(pCon,"ERROR: failed to retrieve Y-projection from HM", eError); - return 0; - } - for(i = 2; i < length; i++) - { - iImage[i] = htonl(data[i-1]); - } - free(data); - } - else - { - /* - we are in simulation and just create some random numbers - */ - for(i = 0; i < iDim[1]; i++) - { - for(i2 = 0; i2 < iDim[2]; i2++) - { - iIdx = i*iDim[2] + i2; - iImage[iIdx+2] = htonl(random()); - iImage[iIdx+2] = htonl(77); - } - } - } + for (i = 2; i < length; i++) { + iImage[i] = htonl(iImage[i]); + } + if (status != 1) { + SCWrite(pCon, "ERROR: histogram memory refused to project", eError); + return 0; + } + } else if (self->iHTTP == 1) { + snprintf(hmCommand, 255, "sum:0:0:%d", iDim[0]); + data = + self->pHM->pDriv->SubSample(self->pHM->pDriv, pCon, 0, hmCommand); + if (data == NULL) { + SCWrite(pCon, "ERROR: failed to retrieve Y-projection from HM", + eError); + return 0; + } + for (i = 2; i < length; i++) { + iImage[i] = htonl(data[i - 1]); + } + free(data); + } else { + /* + we are in simulation and just create some random numbers + */ + for (i = 0; i < iDim[1]; i++) { + for (i2 = 0; i2 < iDim[2]; i2++) { + iIdx = i * iDim[2] + i2; + iImage[iIdx + 2] = htonl(random()); + iImage[iIdx + 2] = htonl(77); + } + } + } + + /* send image */ + SCWriteUUencoded(pCon, "y_tof_projection", iImage, + ((iDim[1] * iDim[2]) + 2) * sizeof(int)); + free(iImage); + return 1; +} - /* send image */ - SCWriteUUencoded(pCon,"y_tof_projection",iImage, - ((iDim[1]*iDim[2])+2)*sizeof(int)); - free(iImage); - return 1; - } /*----------------------------------------------------------------- SendSingleTOF sends single detector data for TOF mode */ - static int SendSingleTOF(pAmorStat self, SConnection *pCon) - { - HistInt *lData = NULL; - int i, i2, i3, iDim[MAXDIM], iIdx, iSum, status, length, nTime; - pSINQHM pHist; - SinqHMDriv *pTata; - int iMax = -999999; - const float *timebin; - HistInt *iData = NULL; - int iStart; +static int SendSingleTOF(pAmorStat self, SConnection * pCon) +{ + HistInt *lData = NULL; + int i, i2, i3, iDim[MAXDIM], iIdx, iSum, status, length, nTime; + pSINQHM pHist; + SinqHMDriv *pTata; + int iMax = -999999; + const float *timebin; + HistInt *iData = NULL; + int iStart; - /* get size of our problem */ - GetHistDim(self->pHM,iDim,&i3); - - /* allocate some data */ - timebin = GetHistTimeBin(self->pHM, &nTime); - if(nTime < 2) { - return 1; - } + /* get size of our problem */ + GetHistDim(self->pHM, iDim, &i3); - length = 1 + 2*nTime; - iData = (HistInt *)malloc(length*sizeof(HistInt)); - if(iData == NULL){ - SCWrite(pCon,"ERROR: failed to allocate memory in SendSingleTOF", - eError); - return 0; - } - memset(iData,0,length*sizeof(int)); + /* allocate some data */ + timebin = GetHistTimeBin(self->pHM, &nTime); + if (nTime < 2) { + return 1; + } - /* first number is the length of each single histogram */ - iData[0] = htonl(nTime); + length = 1 + 2 * nTime; + iData = (HistInt *) malloc(length * sizeof(HistInt)); + if (iData == NULL) { + SCWrite(pCon, "ERROR: failed to allocate memory in SendSingleTOF", + eError); + return 0; + } + memset(iData, 0, length * sizeof(int)); + + /* first number is the length of each single histogram */ + iData[0] = htonl(nTime); - if(isSINQHMDriv(self->pHM->pDriv)) - { - iStart = iDim[0]*iDim[1]*nTime; - GetHistogramDirect(self->pHM,pCon,0,iStart, - iStart + 2*nTime,&iData[1],2*nTime*sizeof(HistInt)); - for(i = 1; i < length; i++) - { - iData[i] = htonl(iData[i]); - } - } - else if(self->iHTTP == 1) - { - GetHistogramDirect(self->pHM,pCon,1,0,2*nTime,&iData[1],2*nTime*sizeof(HistInt)); - for(i = 1; i < length; i++) - { - iData[i] = htonl(iData[i]); - } - } - else - { - /* - we are in simulation and just create some random numbers - */ - for(i = 1; i < length; i++) - { - iData[i] = htonl(random()); - } - } - - /* - send, with a little trick to do two histograms. + if (isSINQHMDriv(self->pHM->pDriv)) { + iStart = iDim[0] * iDim[1] * nTime; + GetHistogramDirect(self->pHM, pCon, 0, iStart, + iStart + 2 * nTime, &iData[1], + 2 * nTime * sizeof(HistInt)); + for (i = 1; i < length; i++) { + iData[i] = htonl(iData[i]); + } + } else if (self->iHTTP == 1) { + GetHistogramDirect(self->pHM, pCon, 1, 0, 2 * nTime, &iData[1], + 2 * nTime * sizeof(HistInt)); + for (i = 1; i < length; i++) { + iData[i] = htonl(iData[i]); + } + } else { + /* + we are in simulation and just create some random numbers */ - SCWriteUUencoded(pCon,"SING1",iData, - (nTime+1)*sizeof(int)); - iData[nTime] = htonl(nTime); - SCWriteUUencoded(pCon,"SING2",&iData[nTime], - (nTime+1)*sizeof(int)); - free(iData); - return 1; - } + for (i = 1; i < length; i++) { + iData[i] = htonl(random()); + } + } + + /* + send, with a little trick to do two histograms. + */ + SCWriteUUencoded(pCon, "SING1", iData, (nTime + 1) * sizeof(int)); + iData[nTime] = htonl(nTime); + SCWriteUUencoded(pCon, "SING2", &iData[nTime], + (nTime + 1) * sizeof(int)); + free(iData); + return 1; +} + /*------------------------------------------------------------------- SubSample sums histogram data in the area defined by the rectangle x1,y1 x2, y2. Summing is along the time axis. */ - static int SubSample(pAmorStat self, SConnection *pCon, - char *name, int x1, int x2, int y1, int y2) - { - int iDim[MAXDIM], i, i2, i3, *iSum = NULL, iLang, *iPtr; - HistInt *lData = NULL; - int iLimit, status, nTime; - char pBueffel[132]; - pSINQHM pHist; - SinqHMDriv *pTata; - const float *fTime; - char hmCommand[256]; - HistInt *data = NULL; +static int SubSample(pAmorStat self, SConnection * pCon, + char *name, int x1, int x2, int y1, int y2) +{ + int iDim[MAXDIM], i, i2, i3, *iSum = NULL, iLang, *iPtr; + HistInt *lData = NULL; + int iLimit, status, nTime; + char pBueffel[132]; + pSINQHM pHist; + SinqHMDriv *pTata; + const float *fTime; + char hmCommand[256]; + HistInt *data = NULL; - /* get histogram dimensions */ - GetHistDim(self->pHM,iDim,&i3); - fTime = GetHistTimeBin(self->pHM,&nTime); - iDim[i3] = nTime; - i3++; + /* get histogram dimensions */ + GetHistDim(self->pHM, iDim, &i3); + fTime = GetHistTimeBin(self->pHM, &nTime); + iDim[i3] = nTime; + i3++; - /* check limits */ - if(x2 < x1){ - i = x1; - x1 = x2; - x2 = i +1; - } - if(y2 < y1){ - i = y1; - y1 = y2; - y2 = i + 1; - } + /* check limits */ + if (x2 < x1) { + i = x1; + x1 = x2; + x2 = i + 1; + } + if (y2 < y1) { + i = y1; + y1 = y2; + y2 = i + 1; + } - iLimit = 0; - if( x1 > iDim[0]) - { - iLimit = 1; - x1 = iDim[0] - 1; - } - if(x1 < 0) - { - iLimit = 1; - x1 = 0; - } - if( x2 > iDim[0]) - { - iLimit = 2; - x2 = iDim[0] - 1; - } - if(x2 < 0) - { - iLimit = 2; - x2 = 0; - } - if( y1 > iDim[1]) - { - iLimit = 3; - y1 = iDim[1] - 1; - } - if(y1 < 0) - { - iLimit = 3; - y1 = 0; - } - if( y2 > iDim[1]) - { - iLimit = 4; - y2 = iDim[1] - 1; - } - if(y2 < 0) - { - iLimit = 4; - y2 = 0; - } - if(iLimit != 0) - { - switch(iLimit) - { - case 1: - strcpy(pBueffel,"WARNING: limit violation on x1"); - break; - case 2: - strcpy(pBueffel,"WARNING: limit violation on x2"); - break; - case 3: - strcpy(pBueffel,"WARNING: limit violation on y1"); - break; - case 4: - strcpy(pBueffel,"WARNING: limit violation on y2"); - break; - } - SCWrite(pCon,pBueffel,eWarning); - } + iLimit = 0; + if (x1 > iDim[0]) { + iLimit = 1; + x1 = iDim[0] - 1; + } + if (x1 < 0) { + iLimit = 1; + x1 = 0; + } + if (x2 > iDim[0]) { + iLimit = 2; + x2 = iDim[0] - 1; + } + if (x2 < 0) { + iLimit = 2; + x2 = 0; + } + if (y1 > iDim[1]) { + iLimit = 3; + y1 = iDim[1] - 1; + } + if (y1 < 0) { + iLimit = 3; + y1 = 0; + } + if (y2 > iDim[1]) { + iLimit = 4; + y2 = iDim[1] - 1; + } + if (y2 < 0) { + iLimit = 4; + y2 = 0; + } + if (iLimit != 0) { + switch (iLimit) { + case 1: + strcpy(pBueffel, "WARNING: limit violation on x1"); + break; + case 2: + strcpy(pBueffel, "WARNING: limit violation on x2"); + break; + case 3: + strcpy(pBueffel, "WARNING: limit violation on y1"); + break; + case 4: + strcpy(pBueffel, "WARNING: limit violation on y2"); + break; + } + SCWrite(pCon, pBueffel, eWarning); + } - /* allocate space for result */ - iSum = (int *)malloc((iDim[2]+1)*sizeof(int)); - if(!iSum) - { - SCWrite(pCon,"ERROR: out of memory in SubSample",eError); - return 0; - } - memset(iSum,0,(iDim[2]+1)*sizeof(int)); + /* allocate space for result */ + iSum = (int *) malloc((iDim[2] + 1) * sizeof(int)); + if (!iSum) { + SCWrite(pCon, "ERROR: out of memory in SubSample", eError); + return 0; + } + memset(iSum, 0, (iDim[2] + 1) * sizeof(int)); - iSum[0] = htonl(iDim[2]); - if(isSINQHMDriv(self->pHM->pDriv)) - { - /* - send project message to histogram memory - */ - pTata = (SinqHMDriv *)self->pHM->pDriv->pPriv; - pHist = (pSINQHM)pTata->pMaster; - status = SINQHMProject(pHist, 4, x1, x2-x1, - y1, y2-y1, iSum+1, iDim[2]*sizeof(int)); - /* - convert to network byte order - */ - for(i = 1; i < iDim[2]+1; i++) - { - iSum[i] = htonl(iSum[i]); - } - if(status != 1) - { - SCWrite(pCon,"ERROR: histogram memory refused to SubSample",eError); - return 0; - } - } - else if(self->iHTTP == 1) - { - snprintf(hmCommand,255,"sample:%d:%d:%d:%d:0:%d;sum:0:0:%d;sum:0:0:%d", - x1,x2,y1,y2,iDim[2]-1,x2-x1,y2-y1); - data = self->pHM->pDriv->SubSample(self->pHM->pDriv,pCon,0,hmCommand); - if(data == NULL) - { - SCWrite(pCon,"ERROR: failed to retrieve sub sampled data fromHM", eError); - return 0; - } - for(i = 1; i < iDim[2]+1; i++) - { - iSum[i] = htonl(data[i-1]); - } - free(data); - } - else - { - /* do acouple of random numbers! */ - for(i = 1; i < iDim[2]+1; i++) - { - iSum[i] = htonl(random()); - } - } + iSum[0] = htonl(iDim[2]); + if (isSINQHMDriv(self->pHM->pDriv)) { + /* + send project message to histogram memory + */ + pTata = (SinqHMDriv *) self->pHM->pDriv->pPriv; + pHist = (pSINQHM) pTata->pMaster; + status = SINQHMProject(pHist, 4, x1, x2 - x1, + y1, y2 - y1, iSum + 1, iDim[2] * sizeof(int)); + /* + convert to network byte order + */ + for (i = 1; i < iDim[2] + 1; i++) { + iSum[i] = htonl(iSum[i]); + } + if (status != 1) { + SCWrite(pCon, "ERROR: histogram memory refused to SubSample", + eError); + return 0; + } + } else if (self->iHTTP == 1) { + snprintf(hmCommand, 255, + "sample:%d:%d:%d:%d:0:%d;sum:0:0:%d;sum:0:0:%d", x1, x2, y1, + y2, iDim[2] - 1, x2 - x1, y2 - y1); + data = + self->pHM->pDriv->SubSample(self->pHM->pDriv, pCon, 0, hmCommand); + if (data == NULL) { + SCWrite(pCon, "ERROR: failed to retrieve sub sampled data fromHM", + eError); + return 0; + } + for (i = 1; i < iDim[2] + 1; i++) { + iSum[i] = htonl(data[i - 1]); + } + free(data); + } else { + /* do acouple of random numbers! */ + for (i = 1; i < iDim[2] + 1; i++) { + iSum[i] = htonl(random()); + } + } - /* send */ - sprintf(pBueffel,"arrowsum_%s",name); - SCWriteUUencoded(pCon,pBueffel,iSum,(iDim[2]+1)*sizeof(int)); - - free(iSum); - return 1; - } -/*------------------------------------------------------------------*/ - int AmorStatusAction(SConnection *pCon, SicsInterp *pSics, - void *pData, int argc, char *argv[]) - { - pAmorStat self = (pAmorStat)pData; - char pBueffel[512]; - double dScale; - int iRet; - int x1, x2, y1, y2; + /* send */ + sprintf(pBueffel, "arrowsum_%s", name); + SCWriteUUencoded(pCon, pBueffel, iSum, (iDim[2] + 1) * sizeof(int)); - assert(self); + free(iSum); + return 1; +} - if(argc < 2) - { - sprintf(pBueffel,"ERROR: need argument to %s",argv[0]); - SCWrite(pCon,pBueffel,eError); - return 0; - } +/*------------------------------------------------------------------*/ +int AmorStatusAction(SConnection * pCon, SicsInterp * pSics, + void *pData, int argc, char *argv[]) +{ + pAmorStat self = (pAmorStat) pData; + char pBueffel[512]; + double dScale; + int iRet; + int x1, x2, y1, y2; - strtolower(argv[1]); - if(strcmp(argv[1],"interest") == 0) - { - RegisterInterest(self,pCon); - SCSendOK(pCon); - return 1; - } - else if(strcmp(argv[1],"load") == 0) - { - if(argc < 4) - { - sprintf(pBueffel, - "ERROR: need filename and scale argument to %s load", + assert(self); + + if (argc < 2) { + sprintf(pBueffel, "ERROR: need argument to %s", argv[0]); + SCWrite(pCon, pBueffel, eError); + return 0; + } + + strtolower(argv[1]); + if (strcmp(argv[1], "interest") == 0) { + RegisterInterest(self, pCon); + SCSendOK(pCon); + return 1; + } else if (strcmp(argv[1], "load") == 0) { + if (argc < 4) { + sprintf(pBueffel, + "ERROR: need filename and scale argument to %s load", argv[0]); - SCWrite(pCon,pBueffel,eError); - return 0; - } - iRet = Tcl_GetDouble(pSics->pTcl,argv[3],&dScale); - if(iRet != TCL_OK) - { - sprintf(pBueffel,"ERROR: cannot convert %s to scale factor", - argv[3]); - SCWrite(pCon,pBueffel,eError); - return 0; - } - FileLoad(self,pCon,argv[2],dScale); - InvokeCallBack(self->pCall, FILELOADED,self); - SCSendOK(pCon); - } - else if(strcmp(argv[1],"collapse") == 0) - { - iRet = Collapse(self,pCon); - if(iRet) - { - SCSendOK(pCon); - } - return iRet; - } - else if(strcmp(argv[1],"projectytof") == 0) - { - iRet = projectYTOF(self,pCon); - if(iRet) - { - SCSendOK(pCon); - } - return iRet; - } - else if(strcmp(argv[1],"http") == 0) - { - if(argc > 2){ - if(!SCMatchRights(pCon,usMugger)){ - return 0; - } - self->iHTTP = atoi(argv[2]); - SCSendOK(pCon); - return 1; - } else { - snprintf(pBueffel,511,"amorstat.http = %d", self->iHTTP); - SCWrite(pCon,pBueffel,eValue); - return 1; - } - } - else if(strcmp(argv[1],"sample") == 0) - { - if(argc < 7) - { - SCWrite(pCon,"ERROR: insufficent number of arguments to sample", - eError); - return 0; - } - iRet = Tcl_GetInt(pSics->pTcl,argv[3],&x1); - if(iRet != TCL_OK) - { - sprintf(pBueffel,"ERROR: cannot convert %s to int", argv[3]); - SCWrite(pCon,pBueffel,eError); - return 0; - } - iRet = Tcl_GetInt(pSics->pTcl,argv[6],&y2); - if(iRet != TCL_OK) - { - sprintf(pBueffel,"ERROR: cannot convert %s to int", argv[6]); - SCWrite(pCon,pBueffel,eError); - return 0; - } - iRet = Tcl_GetInt(pSics->pTcl,argv[4],&x2); - if(iRet != TCL_OK) - { - sprintf(pBueffel,"ERROR: cannot convert %s to int", argv[4]); - SCWrite(pCon,pBueffel,eError); - return 0; - } - iRet = Tcl_GetInt(pSics->pTcl,argv[5],&y1); - if(iRet != TCL_OK) - { - sprintf(pBueffel,"ERROR: cannot convert %s to int", argv[5]); - SCWrite(pCon,pBueffel,eError); - return 0; - } - iRet = SubSample(self,pCon,argv[2],x1,x2,y1,y2); - if(iRet) - SCSendOK(pCon); - return iRet; - } - else if(strcmp(argv[1],"singletof") == 0) - { - return SendSingleTOF(self,pCon); - } - else if(strcmp(argv[1],"sendloaded") == 0) - { - SendLoadedData(self,pCon); - return 1; - } - else if(strcmp(argv[1],"clear") == 0) - { - ClearUserData(self); - InvokeCallBack(self->pCall, FILELOADED,self); - SCSendOK(pCon); - } - else if(strcmp(argv[1],"tofmode") == 0) - { - HMCountStartCallback(COUNTSTART,NULL,pCon); - return 1; - } - else - { - sprintf(pBueffel,"ERROR: %s nor recognized as subcommand to %s", - argv[1], argv[2]); - SCWrite(pCon,pBueffel,eError); + SCWrite(pCon, pBueffel, eError); + return 0; + } + iRet = Tcl_GetDouble(pSics->pTcl, argv[3], &dScale); + if (iRet != TCL_OK) { + sprintf(pBueffel, "ERROR: cannot convert %s to scale factor", + argv[3]); + SCWrite(pCon, pBueffel, eError); + return 0; + } + FileLoad(self, pCon, argv[2], dScale); + InvokeCallBack(self->pCall, FILELOADED, self); + SCSendOK(pCon); + } else if (strcmp(argv[1], "collapse") == 0) { + iRet = Collapse(self, pCon); + if (iRet) { + SCSendOK(pCon); + } + return iRet; + } else if (strcmp(argv[1], "projectytof") == 0) { + iRet = projectYTOF(self, pCon); + if (iRet) { + SCSendOK(pCon); + } + return iRet; + } else if (strcmp(argv[1], "http") == 0) { + if (argc > 2) { + if (!SCMatchRights(pCon, usMugger)) { return 0; } + self->iHTTP = atoi(argv[2]); + SCSendOK(pCon); return 1; - } - - + } else { + snprintf(pBueffel, 511, "amorstat.http = %d", self->iHTTP); + SCWrite(pCon, pBueffel, eValue); + return 1; + } + } else if (strcmp(argv[1], "sample") == 0) { + if (argc < 7) { + SCWrite(pCon, "ERROR: insufficent number of arguments to sample", + eError); + return 0; + } + iRet = Tcl_GetInt(pSics->pTcl, argv[3], &x1); + if (iRet != TCL_OK) { + sprintf(pBueffel, "ERROR: cannot convert %s to int", argv[3]); + SCWrite(pCon, pBueffel, eError); + return 0; + } + iRet = Tcl_GetInt(pSics->pTcl, argv[6], &y2); + if (iRet != TCL_OK) { + sprintf(pBueffel, "ERROR: cannot convert %s to int", argv[6]); + SCWrite(pCon, pBueffel, eError); + return 0; + } + iRet = Tcl_GetInt(pSics->pTcl, argv[4], &x2); + if (iRet != TCL_OK) { + sprintf(pBueffel, "ERROR: cannot convert %s to int", argv[4]); + SCWrite(pCon, pBueffel, eError); + return 0; + } + iRet = Tcl_GetInt(pSics->pTcl, argv[5], &y1); + if (iRet != TCL_OK) { + sprintf(pBueffel, "ERROR: cannot convert %s to int", argv[5]); + SCWrite(pCon, pBueffel, eError); + return 0; + } + iRet = SubSample(self, pCon, argv[2], x1, x2, y1, y2); + if (iRet) + SCSendOK(pCon); + return iRet; + } else if (strcmp(argv[1], "singletof") == 0) { + return SendSingleTOF(self, pCon); + } else if (strcmp(argv[1], "sendloaded") == 0) { + SendLoadedData(self, pCon); + return 1; + } else if (strcmp(argv[1], "clear") == 0) { + ClearUserData(self); + InvokeCallBack(self->pCall, FILELOADED, self); + SCSendOK(pCon); + } else if (strcmp(argv[1], "tofmode") == 0) { + HMCountStartCallback(COUNTSTART, NULL, pCon); + return 1; + } else { + sprintf(pBueffel, "ERROR: %s nor recognized as subcommand to %s", + argv[1], argv[2]); + SCWrite(pCon, pBueffel, eError); + return 0; + } + return 1; +} diff --git a/amorstat.h b/amorstat.h index 6665cec..1d25a87 100644 --- a/amorstat.h +++ b/amorstat.h @@ -11,11 +11,10 @@ #ifndef AMORSTATUS #define AMORSTATUS - int AmorStatusFactory(SConnection *pCon, SicsInterp *pSics, void *pData, +int AmorStatusFactory(SConnection * pCon, SicsInterp * pSics, void *pData, int argc, char *argv[]); - int AmorStatusAction(SConnection *pCon, SicsInterp *pSics, void *pData, - int argc, char *argv[]); - void KillAmorStatus(void *pData); +int AmorStatusAction(SConnection * pCon, SicsInterp * pSics, void *pData, + int argc, char *argv[]); +void KillAmorStatus(void *pData); #endif - diff --git a/arrobj.c b/arrobj.c index 358bd08..534cc16 100644 --- a/arrobj.c +++ b/arrobj.c @@ -36,8 +36,9 @@ typedef struct WrtObjContext { char filename[PATH_MAX]; } WrtObjContext; -/*-----------------------------------------------------------------------*/ -int WrtObjOpen(WrtObjContext *ctx, char *fileName) { +/*-----------------------------------------------------------------------*/ +int WrtObjOpen(WrtObjContext * ctx, char *fileName) +{ int iret; char *slashpos; @@ -49,17 +50,20 @@ int WrtObjOpen(WrtObjContext *ctx, char *fileName) { } else { ctx->pos = slashpos - fileName + 1; } - iret = snprintf(ctx->filename, sizeof(ctx->filename), "%.*s.%s" - , ctx->pos, fileName, fileName + ctx->pos); + iret = + snprintf(ctx->filename, sizeof(ctx->filename), "%.*s.%s", ctx->pos, + fileName, fileName + ctx->pos); if (iret < 0 || iret >= sizeof(ctx->filename)) { return 0; - } - remove(ctx->filename); /* remove already existing temporary file */ - ctx->file = fopen(ctx->filename,"w"); + } + remove(ctx->filename); /* remove already existing temporary file */ + ctx->file = fopen(ctx->filename, "w"); return ctx->file != NULL; } -/*-----------------------------------------------------------------------*/ -void WrtObj(WrtObjContext *ctx, char *objectName) { + +/*-----------------------------------------------------------------------*/ +void WrtObj(WrtObjContext * ctx, char *objectName) +{ CommandList *pCom = NULL; Dummy *pDum = NULL; @@ -70,26 +74,30 @@ void WrtObj(WrtObjContext *ctx, char *objectName) { } pDum = pCom->pData; if (pDum != NULL) { - pDum->pDescriptor->SaveStatus(pCom->pData,pCom->pName,ctx->file); + pDum->pDescriptor->SaveStatus(pCom->pData, pCom->pName, ctx->file); } } } -/*-----------------------------------------------------------------------*/ -void WrtObjClose(WrtObjContext *ctx) { + +/*-----------------------------------------------------------------------*/ +void WrtObjClose(WrtObjContext * ctx) +{ char finalName[PATH_MAX]; if (ctx) { fclose(ctx->file); - snprintf(finalName, sizeof finalName, "%.*s%s" - , ctx->pos, ctx->filename, ctx->filename + ctx->pos + 1); + snprintf(finalName, sizeof finalName, "%.*s%s", ctx->pos, + ctx->filename, ctx->filename + ctx->pos + 1); rename(ctx->filename, finalName); } } + /*----------------------------------------------------------------------------*/ -static int ArrayExists(void *object, void *arg, int argc, char *argv[]) { +static int ArrayExists(void *object, void *arg, int argc, char *argv[]) +{ ArrayObj *arr = ParCast(&arrayObjClass, object); ArrayItem *item; - + assert(arr); if (argc == 1) { for (item = arr->items; item != NULL; item = item->next) { @@ -102,8 +110,10 @@ static int ArrayExists(void *object, void *arg, int argc, char *argv[]) { ParPrintf(object, eValue, "0"); return 1; } + /*----------------------------------------------------------------------------*/ -static int ArrayItems(void *object, void *arg, int argc, char *argv[]) { +static int ArrayItems(void *object, void *arg, int argc, char *argv[]) +{ ArrayObj *arr = ParCast(&arrayObjClass, object); ArrayItem *item; int l; @@ -112,35 +122,43 @@ static int ArrayItems(void *object, void *arg, int argc, char *argv[]) { assert(arr); l = 1; for (item = arr->items; item != NULL; item = item->next) { - l += strlen(item->name); l++; + l += strlen(item->name); + l++; } result = calloc(l, 1); if (result) { p = result; for (item = arr->items; item != NULL; item = item->next) { - strcpy(p, item->name); p+=strlen(item->name); - *p = ' '; p++; + strcpy(p, item->name); + p += strlen(item->name); + *p = ' '; + p++; } - if (p > result) p--; - *p='\0'; + if (p > result) + p--; + *p = '\0'; ParPrintf(object, eValue, result); free(result); } return 1; } + /*----------------------------------------------------------------------------*/ -static int ArrayMakeItem(void *object, void *delete, int argc, char *argv[]) { +static int ArrayMakeItem(void *object, void *delete, int argc, + char *argv[]) +{ ArrayObj *arr = ParCast(&arrayObjClass, object); ArrayItem *item, **last; int iarg; - + assert(arr); - if (argc < 1) goto Usage; + if (argc < 1) + goto Usage; last = &arr->items; for (item = arr->items; item != NULL; item = item->next) { - if (strcasecmp(argv[0], item->name) == 0) { + if (strcasecmp(argv[0], item->name) == 0) { if (delete) { - *last = item->next; /* remove item from list */ + *last = item->next; /* remove item from list */ item->next = arr->freeItems; arr->freeItems = item; return 1; @@ -150,7 +168,8 @@ static int ArrayMakeItem(void *object, void *delete, int argc, char *argv[]) { last = &item->next; } if (delete) { - ParPrintf(object, eError, "ERROR: %s.%s not found", arr->p.name, argv[0]); + ParPrintf(object, eError, "ERROR: %s.%s not found", arr->p.name, + argv[0]); return 0; } if (item == NULL) { @@ -158,13 +177,15 @@ static int ArrayMakeItem(void *object, void *delete, int argc, char *argv[]) { item = arr->freeItems; arr->freeItems = item->next; if (item->name) { - free(item->name); item->name = NULL; + free(item->name); + item->name = NULL; } item->next = NULL; *last = item; } else { item = calloc(1, sizeof(ArrayItem)); - if (item == NULL) return 0; + if (item == NULL) + return 0; *last = item; item->next = NULL; item->unit = NULL; @@ -172,19 +193,21 @@ static int ArrayMakeItem(void *object, void *delete, int argc, char *argv[]) { } } if (item->unit) { - free(item->unit); item->unit=NULL; + free(item->unit); + item->unit = NULL; } if (item->value) { - free(item->value); item->value=NULL; + free(item->value); + item->value = NULL; } if (item->name != NULL) { - if (0 != strcmp(item->name, argv[0])) { - free(item->name); - item->name = strdup(argv[0]); - } - } else { - item->name = strdup(argv[0]); - } + if (0 != strcmp(item->name, argv[0])) { + free(item->name); + item->name = strdup(argv[0]); + } + } else { + item->name = strdup(argv[0]); + } iarg = 1; if (iarg < argc) { if (argv[iarg] && argv[iarg][0]) { @@ -196,22 +219,27 @@ static int ArrayMakeItem(void *object, void *delete, int argc, char *argv[]) { item->unit = argv[iarg]; } iarg++; - if (iarg < argc) goto Usage; + if (iarg < argc) + goto Usage; } } - if (item->unit) item->unit = strdup(item->unit); - if (item->value) item->value = strdup(item->value); + if (item->unit) + item->unit = strdup(item->unit); + if (item->value) + item->value = strdup(item->value); ParInitPar(object, item->name); SCparChange(arr->p.conn); return 1; - Usage: - ParPrintf(object, eError, "Usage: %s makeitem [value] [unit]" - , arr->p.name); - return 0; +Usage: + ParPrintf(object, eError, "Usage: %s makeitem [value] [unit]", + arr->p.name); + return 0; } + /*----------------------------------------------------------------------------*/ -static void ArrayObjParDef(void *object) { +static void ArrayObjParDef(void *object) +{ ArrayObj *arr = ParCast(&arrayObjClass, object); FILE *saveFile; ArrayItem *item, *next; @@ -233,12 +261,15 @@ static void ArrayObjParDef(void *object) { } else { u = ""; } - fprintf(saveFile, " %s makeitem %s \"%s\" \"%s\"\n", arr->p.name, item->name, item->value, u); + fprintf(saveFile, " %s makeitem %s \"%s\" \"%s\"\n", arr->p.name, + item->name, item->value, u); if (saveObjects) { WrtObj(&context, item->name); } } - ParName(item->name); ParSave(2); ParAccess(usUser); + ParName(item->name); + ParSave(2); + ParAccess(usUser); if (item->unit) { ParTail(item->unit); } else { @@ -252,34 +283,53 @@ static void ArrayObjParDef(void *object) { doNotNest = 0; WrtObjClose(&context); } - ParName("makeitem"); ParAccess(usUser); ParCmd(ArrayMakeItem, NULL); - ParName("deleteitem"); ParAccess(usUser); ParCmd(ArrayMakeItem, "del"); - ParName("exists"); ParAccess(usSpy); ParCmd(ArrayExists, NULL); - ParName("items"); ParAccess(usSpy); ParCmd(ArrayItems, NULL); - ParName("saveFile"); ParAccess(usUser); ParStr(&arr->saveFile, ""); + ParName("makeitem"); + ParAccess(usUser); + ParCmd(ArrayMakeItem, NULL); + ParName("deleteitem"); + ParAccess(usUser); + ParCmd(ArrayMakeItem, "del"); + ParName("exists"); + ParAccess(usSpy); + ParCmd(ArrayExists, NULL); + ParName("items"); + ParAccess(usSpy); + ParCmd(ArrayItems, NULL); + ParName("saveFile"); + ParAccess(usUser); + ParStr(&arr->saveFile, ""); ParStdDef(); if (ParActionIs(PAR_KILL)) { for (item = arr->items; item != NULL; item = next) { next = item->next; - if (item->name) free(item->name); - if (item->unit) free(item->unit); - if (item->value) free(item->value); + if (item->name) + free(item->name); + if (item->unit) + free(item->unit); + if (item->value) + free(item->value); free(item); } for (item = arr->freeItems; item != NULL; item = next) { next = item->next; - if (item->name) free(item->name); - if (item->unit) free(item->unit); - if (item->value) free(item->value); + if (item->name) + free(item->name); + if (item->unit) + free(item->unit); + if (item->value) + free(item->value); free(item); } - } + } } + /*----------------------------------------------------------------------------*/ -static int ArrayObjInit(SConnection *con, int argc, char *argv[], int dynamic) { +static int ArrayObjInit(SConnection * con, int argc, char *argv[], + int dynamic) +{ ArrayObj *arr = NULL; char *creationCmd = NULL; - + if (dynamic) { creationCmd = Arg2Tcl(argc, argv, NULL, 0); } @@ -288,8 +338,10 @@ static int ArrayObjInit(SConnection *con, int argc, char *argv[], int dynamic) { arr->items = NULL; return arr != NULL; } + /*----------------------------------------------------------------------------*/ -void ArrayObjStartup(void) { +void ArrayObjStartup(void) +{ ParMakeClass(&arrayObjClass, NULL); - MakeDriver("array", ArrayObjInit, 0, "String Array Object"); + MakeDriver("array", ArrayObjInit, 0, "String Array Object"); } diff --git a/audineccd.h b/audineccd.h index 09cff8a..c799032 100644 --- a/audineccd.h +++ b/audineccd.h @@ -55,33 +55,33 @@ # endif #else -# define PDEBUG(fmt, args...) /* Nothing ... */ +# define PDEBUG(fmt, args...) /* Nothing ... */ #endif #undef PDEBUGG -#define PDEBUGG(fmt, args...) /* Nothing */ +#define PDEBUGG(fmt, args...) /* Nothing */ #endif struct ccd_capability { - char name[128]; /* Name of CCD chip */ - int width; /* Sensible image width */ - int height; /* Sensible image height */ - int color; /* Has color */ - int minwidth; /* Actual geometry frame width */ - int minheight; /* Actual geometry frame height */ + char name[128]; /* Name of CCD chip */ + int width; /* Sensible image width */ + int height; /* Sensible image height */ + int color; /* Has color */ + int minwidth; /* Actual geometry frame width */ + int minheight; /* Actual geometry frame height */ }; /* IOCTL MACROS */ -#define CCD_MGK 0xEE // Very high ... to register !!!! +#define CCD_MGK 0xEE // Very high ... to register !!!! #define CCD_RD_CHIP _IOR(CCD_MGK, 0x01, struct ccd_capability) #define CCD_RD_CCDL _IOR(CCD_MGK, 0x02, struct ccd_capability) #define CCD_RD_GEOM _IOR(CCD_MGK, 0x03, struct ccd_capability) -#define CCD_RD_IMG _IOR(CCD_MGK, 0x04, unsigned long) /* Read image */ +#define CCD_RD_IMG _IOR(CCD_MGK, 0x04, unsigned long) /* Read image */ -#define CCD_CLR _IOW(CCD_MGK, 0x05, unsigned long) /* chip Clearing */ +#define CCD_CLR _IOW(CCD_MGK, 0x05, unsigned long) /* chip Clearing */ #define CCD_SWTC_AMP _IOW(CCD_MGK, 0x06, unsigned long) #define CCD_SWTC_SHT _IOW(CCD_MGK, 0x07, unsigned long) @@ -93,13 +93,13 @@ struct ccd_capability { #define CCD_SET_AX0 _IOW(CCD_MGK, 0x0c, unsigned long) #define CCD_SET_AX1 _IOW(CCD_MGK, 0x0d, unsigned long) -#define CCD_SET_BNN _IOW(CCD_MGK, 0x0e, struct ccd_capability) // Binning +#define CCD_SET_BNN _IOW(CCD_MGK, 0x0e, struct ccd_capability) // Binning #define CCD_AV_IMG _IOR(CCD_MGK, 0x0f, unsigned long) // ma serve ???? -#define CCD_SET_WND _IOW(CCD_MGK, 0x10, struct ccd_capability) // Window -#define CCD_RST_WND _IOW(CCD_MGK, 0x11, unsigned long) // CCD +#define CCD_SET_WND _IOW(CCD_MGK, 0x10, struct ccd_capability) // Window +#define CCD_RST_WND _IOW(CCD_MGK, 0x11, unsigned long) // CCD #define CCD_SET_PRT _IOW(CCD_MGK, 0x12, unsigned long) -#define CCD_RD_VER _IOW(CCD_MGK, 0x13, struct ccd_capability) // Version +#define CCD_RD_VER _IOW(CCD_MGK, 0x13, struct ccd_capability) // Version diff --git a/audinelib.c b/audinelib.c index b934946..e7ec204 100644 --- a/audinelib.c +++ b/audinelib.c @@ -55,457 +55,473 @@ struct aud_handle_s { }; -AUD_HANDLE aud_open (void) - -{AUD_HANDLE aud = (AUD_HANDLE)calloc (1, sizeof (struct aud_handle_s)); - - if (!aud) return 0; - - aud->fd = open (AUD_DEVICE_FILE, O_RDWR); - if (aud->fd < 0) - { - free (aud); - return 0; - } - - aud->single_read = 1; - - return aud; -} - - -void aud_close (AUD_HANDLE aud) - +AUD_HANDLE aud_open(void) { - if (aud) - { - if (aud->fd >= 0) close (aud->fd); - free (aud); - } + AUD_HANDLE aud = (AUD_HANDLE) calloc(1, sizeof(struct aud_handle_s)); + + if (!aud) + return 0; + + aud->fd = open(AUD_DEVICE_FILE, O_RDWR); + if (aud->fd < 0) { + free(aud); + return 0; + } + + aud->single_read = 1; + + return aud; } -char *aud_version (const AUD_HANDLE aud) - -{static struct ccd_capability Info; - char *version = ""; - int ret; - - if (aud) - { - ret = ioctl (aud->fd, CCD_RD_VER, &Info); - if (ret == 0) version = &(Info.name[0]); - } - return version; -} - - -int aud_clear (const AUD_HANDLE aud, int nclear) - -{int ret = 0; - - if (nclear > 0) ret = ioctl (aud->fd, CCD_CLR, &nclear); - return ret; -} - - -int aud_binning_set (const AUD_HANDLE aud, int vb, int hb) - -{struct ccd_capability Info; - - AUD_HANDLE_CHECK (aud); - if ((vb < 1) || (vb > 4) || (hb < 1) || (hb > 4)) - ERRNORET (EINVAL); - - Info.width = vb; - Info.height = hb; - return ioctl (aud->fd, CCD_SET_BNN, &Info); -} - - -int aud_binning_get (const AUD_HANDLE aud, int *vb, int *hb) - -{struct ccd_capability Info; - int ret; - - AUD_HANDLE_CHECK (aud); - - Info.width = 0; - Info.height = 0; - ret = ioctl (aud->fd, CCD_SET_BNN, &Info); - if (ret != 0) return ret; - if (vb) *vb = Info.width; - if (hb) *hb = Info.height; - return 0; -} - - -int aud_geometry_set (const AUD_HANDLE aud, int x, int y, int width, int height) - -{struct ccd_capability Info; - - AUD_HANDLE_CHECK (aud); - - Info.minwidth = x; - Info.minheight = y; - Info.width = width; - Info.height = height; - return ioctl (aud->fd, CCD_SET_WND, &Info); -} - - -int aud_geometry_reset (const AUD_HANDLE aud) - +void aud_close(AUD_HANDLE aud) { - AUD_HANDLE_CHECK (aud); - - return ioctl (aud->fd, CCD_RST_WND); + if (aud) { + if (aud->fd >= 0) + close(aud->fd); + free(aud); + } } -int aud_geometry_get (const AUD_HANDLE aud, int *xorigin, int *yorigin, - int *winwidth, int *winheight, int *color) - -{struct ccd_capability Info; - int ret; - - AUD_HANDLE_CHECK (aud); - - ret = ioctl(aud->fd, CCD_RD_GEOM, &Info); - if (ret != 0) return ret; - - if (xorigin) *xorigin = Info.minwidth; - if (yorigin) *yorigin = Info.minheight; - if (winwidth) *winwidth = Info.width; - if (winheight) *winheight = Info.height; - if (color) *color = Info.color; - - return 0; -} - - -int aud_port_set (const AUD_HANDLE aud, int base) - +char *aud_version(const AUD_HANDLE aud) { - AUD_HANDLE_CHECK (aud); - if (base <= 0) return -EINVAL; - return ioctl (aud->fd, CCD_SET_PRT, &base); + static struct ccd_capability Info; + char *version = ""; + int ret; + + if (aud) { + ret = ioctl(aud->fd, CCD_RD_VER, &Info); + if (ret == 0) + version = &(Info.name[0]); + } + return version; } -int aud_port_get (const AUD_HANDLE aud, int *base) - +int aud_clear(const AUD_HANDLE aud, int nclear) { - AUD_HANDLE_CHECK (aud); - if (!base) return -1; - *base = 0; - return ioctl (aud->fd, CCD_SET_PRT, base); + int ret = 0; + + if (nclear > 0) + ret = ioctl(aud->fd, CCD_CLR, &nclear); + return ret; } -static int aud_line_ctrl_set (const AUD_HANDLE aud, int cmd, int ctrl) - +int aud_binning_set(const AUD_HANDLE aud, int vb, int hb) { - AUD_HANDLE_CHECK (aud); - if ((ctrl != 1) && (ctrl != 2) && (ctrl != 4) && (ctrl != 8)) - ERRNORET (EINVAL); - return ioctl (aud->fd, cmd, &ctrl); + struct ccd_capability Info; + + AUD_HANDLE_CHECK(aud); + if ((vb < 1) || (vb > 4) || (hb < 1) || (hb > 4)) + ERRNORET(EINVAL); + + Info.width = vb; + Info.height = hb; + return ioctl(aud->fd, CCD_SET_BNN, &Info); } -static int aud_line_set (const AUD_HANDLE aud, int cmd, int on_off) - +int aud_binning_get(const AUD_HANDLE aud, int *vb, int *hb) { - AUD_HANDLE_CHECK (aud); - if (on_off != 0) on_off = 1; - return ioctl (aud->fd, cmd, &on_off); + struct ccd_capability Info; + int ret; + + AUD_HANDLE_CHECK(aud); + + Info.width = 0; + Info.height = 0; + ret = ioctl(aud->fd, CCD_SET_BNN, &Info); + if (ret != 0) + return ret; + if (vb) + *vb = Info.width; + if (hb) + *hb = Info.height; + return 0; } -int aud_amplifier_ctrl_set (const AUD_HANDLE aud, int ctrl) - +int aud_geometry_set(const AUD_HANDLE aud, int x, int y, int width, + int height) { - return aud_line_ctrl_set (aud, CCD_SET_AMP, ctrl); + struct ccd_capability Info; + + AUD_HANDLE_CHECK(aud); + + Info.minwidth = x; + Info.minheight = y; + Info.width = width; + Info.height = height; + return ioctl(aud->fd, CCD_SET_WND, &Info); } -int aud_amplifier_set (const AUD_HANDLE aud, int on_off) - +int aud_geometry_reset(const AUD_HANDLE aud) { - return aud_line_set (aud, CCD_SWTC_AMP, on_off); + AUD_HANDLE_CHECK(aud); + + return ioctl(aud->fd, CCD_RST_WND); } -int aud_shutter_ctrl_set (const AUD_HANDLE aud, int ctrl) - +int aud_geometry_get(const AUD_HANDLE aud, int *xorigin, int *yorigin, + int *winwidth, int *winheight, int *color) { - return aud_line_ctrl_set (aud, CCD_SET_SHT, ctrl); + struct ccd_capability Info; + int ret; + + AUD_HANDLE_CHECK(aud); + + ret = ioctl(aud->fd, CCD_RD_GEOM, &Info); + if (ret != 0) + return ret; + + if (xorigin) + *xorigin = Info.minwidth; + if (yorigin) + *yorigin = Info.minheight; + if (winwidth) + *winwidth = Info.width; + if (winheight) + *winheight = Info.height; + if (color) + *color = Info.color; + + return 0; } -int aud_shutter_set (const AUD_HANDLE aud, int on_off) - +int aud_port_set(const AUD_HANDLE aud, int base) { - return aud_line_set (aud, CCD_SWTC_SHT, on_off); + AUD_HANDLE_CHECK(aud); + if (base <= 0) + return -EINVAL; + return ioctl(aud->fd, CCD_SET_PRT, &base); } -int aud_aux0_ctrl_set (const AUD_HANDLE aud, int ctrl) - +int aud_port_get(const AUD_HANDLE aud, int *base) { - return aud_line_ctrl_set (aud, CCD_SET_AX0, ctrl); + AUD_HANDLE_CHECK(aud); + if (!base) + return -1; + *base = 0; + return ioctl(aud->fd, CCD_SET_PRT, base); } -int aud_aux0_set (const AUD_HANDLE aud, int on_off) - +static int aud_line_ctrl_set(const AUD_HANDLE aud, int cmd, int ctrl) { - return aud_line_set (aud, CCD_SWTC_AX0, on_off); + AUD_HANDLE_CHECK(aud); + if ((ctrl != 1) && (ctrl != 2) && (ctrl != 4) && (ctrl != 8)) + ERRNORET(EINVAL); + return ioctl(aud->fd, cmd, &ctrl); } -int aud_aux1_ctrl_set (const AUD_HANDLE aud, int ctrl) - +static int aud_line_set(const AUD_HANDLE aud, int cmd, int on_off) { - return aud_line_ctrl_set (aud, CCD_SET_AX1, ctrl); + AUD_HANDLE_CHECK(aud); + if (on_off != 0) + on_off = 1; + return ioctl(aud->fd, cmd, &on_off); } -int aud_aux1_set (const AUD_HANDLE aud, int on_off) - +int aud_amplifier_ctrl_set(const AUD_HANDLE aud, int ctrl) { - return aud_line_set (aud, CCD_SWTC_AX1, on_off); + return aud_line_ctrl_set(aud, CCD_SET_AMP, ctrl); } -int aud_ccd_info_get (const AUD_HANDLE aud, char **name, int *width, - int *height, int *color) - -{static struct ccd_capability Info; - int ret; - - AUD_HANDLE_CHECK (aud); - if ((ret = ioctl (aud->fd, CCD_RD_CHIP, &Info)) != 0) return ret; - - if (name) *name = Info.name; - if (width) *width = Info.width; - if (height) *height = Info.height; - if (color) *color = Info.color; - - return 0; -} - - -int aud_ccd_listentry_get (const AUD_HANDLE aud, int entry, char **name, - int *width, int *height, int *color) -{static struct ccd_capability Info; - int ret; - - AUD_HANDLE_CHECK (aud); - Info.color = entry; - if ((ret = ioctl (aud->fd, CCD_RD_CCDL, &Info)) != 0) return ret; - - if (name) *name = Info.name; - if (width) *width = Info.width; - if (height) *height = Info.height; - if (color) *color = Info.color; - - return 0; -} - - -void aud_single_read_set (AUD_HANDLE aud, int single_read) - +int aud_amplifier_set(const AUD_HANDLE aud, int on_off) { - if (aud) aud->single_read = single_read; + return aud_line_set(aud, CCD_SWTC_AMP, on_off); } -int aud_image_read (const AUD_HANDLE aud, char **buf, int *bufsize, - int *width, int *height, int *color) - -{int ret; - int nbytes, nread, len; - char *imgbuf; - - AUD_HANDLE_CHECK (aud); - if ((!buf) || (!bufsize)) ERRNORET (EINVAL); - if ((!width) || (!height) || (!color)) ERRNORET (EINVAL); - - if ((ret = aud_geometry_get (aud, 0, 0, width, height, color)) != 0) - return ret; - - /* We get 2 bytes per pixel */ - nbytes = *width * *height * 2; - - /* Do we have to free the user buffer ? */ - if ((*bufsize < nbytes) && (*buf)) - { - free (*buf); - *buf = 0; - *bufsize = 0; - } - - /* If buffer not supplied, allocate buffer */ - if (!(*buf)) - { - *buf = malloc (nbytes); - if (!*buf) ERRNORET (ENOMEM); - *bufsize = nbytes; - } - - /* Start reading image */ - if ((ret = ioctl(aud->fd, CCD_RD_IMG)) != 0) return ret; - - imgbuf = *buf; - while (nbytes > 0) - { - if (aud->single_read) - { - nread = nbytes; - } - else - { - nread = *width * 2; - if (nread > nbytes) - nread = nbytes; - } - len = read(aud->fd, imgbuf, nread); - if (len <= 0) return -1; - nbytes -= len; - imgbuf += len; - } - return 0; -} - - -static void aud_ccdstruct_log (const char *fct, int ret, - const struct ccd_capability *info) - +int aud_shutter_ctrl_set(const AUD_HANDLE aud, int ctrl) { - printf ("\nFunction %s returned %d\n", fct, ret); - if (ret != 0) return; - printf ("Name : %-32s\n", info->name); - printf ("Width: %-6d Height: %-6d Minwidth: %-6d Minheight: %-6d Color: %d\n", - info->width, info->height, info->minwidth, info->minheight, - info->color); + return aud_line_ctrl_set(aud, CCD_SET_SHT, ctrl); } -void aud_ioctl_test (AUD_HANDLE aud) +int aud_shutter_set(const AUD_HANDLE aud, int on_off) +{ + return aud_line_set(aud, CCD_SWTC_SHT, on_off); +} -{int ret; - struct ccd_capability info; - char *buf = 0, *name; - int bufsize = 0, width, height, color; - int j; - if ((!aud) || (aud->fd < 0)) return; +int aud_aux0_ctrl_set(const AUD_HANDLE aud, int ctrl) +{ + return aud_line_ctrl_set(aud, CCD_SET_AX0, ctrl); +} - /* Read driver version */ - ret = ioctl (aud->fd, CCD_RD_VER, &info); - aud_ccdstruct_log ("CCD_RD_VER", ret, &info); - /* Read chip information */ - ret = ioctl (aud->fd, CCD_RD_CHIP, &info); - aud_ccdstruct_log ("CCD_RD_CHIP", ret, &info); +int aud_aux0_set(const AUD_HANDLE aud, int on_off) +{ + return aud_line_set(aud, CCD_SWTC_AX0, on_off); +} - /* Read geometry */ - ret = ioctl (aud->fd, CCD_RD_GEOM, &info); - aud_ccdstruct_log ("CCD_RD_GEOM", ret, &info); - /* Set Window */ - info.minwidth = 1; - info.minheight = 2; - info.width = 200; - info.height = 100; - ret = ioctl (aud->fd, CCD_SET_WND, &info); - printf ("\nCalled CCD_SET_WND: (1,2) (200,100)\n"); +int aud_aux1_ctrl_set(const AUD_HANDLE aud, int ctrl) +{ + return aud_line_ctrl_set(aud, CCD_SET_AX1, ctrl); +} - /* Read geometry */ - ret = ioctl (aud->fd, CCD_RD_GEOM, &info); - aud_ccdstruct_log ("CCD_RD_GEOM", ret, &info); - /* Set binning */ - info.width = 2; - info.height = 3; - printf ("\nSet binning %dx%d", info.width, info.height); - ret = ioctl (aud->fd, CCD_SET_BNN, &info); - aud_ccdstruct_log ("CCD_SET_BNN", ret, &info); +int aud_aux1_set(const AUD_HANDLE aud, int on_off) +{ + return aud_line_set(aud, CCD_SWTC_AX1, on_off); +} - /* Read geometry */ - ret = ioctl (aud->fd, CCD_RD_GEOM, &info); - aud_ccdstruct_log ("CCD_RD_GEOM", ret, &info); - /* (Re-)Set binning */ - info.width = 1; - info.height = 1; - printf ("\nSet binning %dx%d", info.width, info.height); - ret = ioctl (aud->fd, CCD_SET_BNN, &info); - aud_ccdstruct_log ("CCD_SET_BNN", ret, &info); +int aud_ccd_info_get(const AUD_HANDLE aud, char **name, int *width, + int *height, int *color) +{ + static struct ccd_capability Info; + int ret; - /* Read geometry */ - ret = ioctl (aud->fd, CCD_RD_GEOM, &info); - aud_ccdstruct_log ("CCD_RD_GEOM", ret, &info); + AUD_HANDLE_CHECK(aud); + if ((ret = ioctl(aud->fd, CCD_RD_CHIP, &Info)) != 0) + return ret; - /* Clear two times */ - info.width = 2; - printf ("\nStart clear %d times\n", info.width); fflush (stdout); - ret = ioctl (aud->fd, CCD_CLR, &info.width); - printf ("Clear finished.\n"); + if (name) + *name = Info.name; + if (width) + *width = Info.width; + if (height) + *height = Info.height; + if (color) + *color = Info.color; - /* Reading */ - printf ("Start reading image\n"); - ret = aud_image_read (aud, &buf, &bufsize, &width, &height, &color); - printf ("Finished reading: ret=%d width=%d height=%d color=%d bufsize=%d\n", - ret, width, height, color, bufsize); + return 0; +} - /* Set binning */ - info.width = 2; - info.height = 3; - printf ("\nSet binning %dx%d", info.width, info.height); - ret = ioctl (aud->fd, CCD_SET_BNN, &info); - aud_ccdstruct_log ("CCD_SET_BNN", ret, &info); - /* Reading */ - printf ("Start reading small image\n"); - ret = aud_image_read (aud, &buf, &bufsize, &width, &height, &color); - printf ("Finished reading: ret=%d width=%d height=%d color=%d bufsize=%d\n", - ret, width, height, color, bufsize); +int aud_ccd_listentry_get(const AUD_HANDLE aud, int entry, char **name, + int *width, int *height, int *color) +{ + static struct ccd_capability Info; + int ret; - /* Reset window */ - ret = ioctl (aud->fd, CCD_RST_WND); - printf ("\nReset window\n"); + AUD_HANDLE_CHECK(aud); + Info.color = entry; + if ((ret = ioctl(aud->fd, CCD_RD_CCDL, &Info)) != 0) + return ret; - /* Reset binning */ - info.width = 1; - info.height = 1; - printf ("\nSet binning %dx%d", info.width, info.height); - ret = ioctl (aud->fd, CCD_SET_BNN, &info); - aud_ccdstruct_log ("CCD_SET_BNN", ret, &info); + if (name) + *name = Info.name; + if (width) + *width = Info.width; + if (height) + *height = Info.height; + if (color) + *color = Info.color; - /* Read geometry */ - ret = ioctl (aud->fd, CCD_RD_GEOM, &info); - aud_ccdstruct_log ("CCD_RD_GEOM", ret, &info); + return 0; +} - /* Reading */ - printf ("Start reading large image\n"); - ret = aud_image_read (aud, &buf, &bufsize, &width, &height, &color); - printf ("Finished reading: ret=%d width=%d height=%d color=%d bufsize=%d\n", - ret, width, height, color, bufsize); - /* Read current port */ - ret = aud_port_get (aud, &j); - printf ("\naud_port_get returned with %d. Port=0x%x\n", ret, j); +void aud_single_read_set(AUD_HANDLE aud, int single_read) +{ + if (aud) + aud->single_read = single_read; +} - printf ("\nList of supported CCDs:\n"); - j = 0; - while (aud_ccd_listentry_get (aud, j, &name, &info.width, &info.height, - &info.color) == 0) - { - printf ("%d: %s, %dx%d, %d\n", j, name, info.width, info.height, info.color); - j++; - } + +int aud_image_read(const AUD_HANDLE aud, char **buf, int *bufsize, + int *width, int *height, int *color) +{ + int ret; + int nbytes, nread, len; + char *imgbuf; + + AUD_HANDLE_CHECK(aud); + if ((!buf) || (!bufsize)) + ERRNORET(EINVAL); + if ((!width) || (!height) || (!color)) + ERRNORET(EINVAL); + + if ((ret = aud_geometry_get(aud, 0, 0, width, height, color)) != 0) + return ret; + + /* We get 2 bytes per pixel */ + nbytes = *width * *height * 2; + + /* Do we have to free the user buffer ? */ + if ((*bufsize < nbytes) && (*buf)) { + free(*buf); + *buf = 0; + *bufsize = 0; + } + + /* If buffer not supplied, allocate buffer */ + if (!(*buf)) { + *buf = malloc(nbytes); + if (!*buf) + ERRNORET(ENOMEM); + *bufsize = nbytes; + } + + /* Start reading image */ + if ((ret = ioctl(aud->fd, CCD_RD_IMG)) != 0) + return ret; + + imgbuf = *buf; + while (nbytes > 0) { + if (aud->single_read) { + nread = nbytes; + } else { + nread = *width * 2; + if (nread > nbytes) + nread = nbytes; + } + len = read(aud->fd, imgbuf, nread); + if (len <= 0) + return -1; + nbytes -= len; + imgbuf += len; + } + return 0; +} + + +static void aud_ccdstruct_log(const char *fct, int ret, + const struct ccd_capability *info) +{ + printf("\nFunction %s returned %d\n", fct, ret); + if (ret != 0) + return; + printf("Name : %-32s\n", info->name); + printf + ("Width: %-6d Height: %-6d Minwidth: %-6d Minheight: %-6d Color: %d\n", + info->width, info->height, info->minwidth, info->minheight, + info->color); +} + + +void aud_ioctl_test(AUD_HANDLE aud) +{ + int ret; + struct ccd_capability info; + char *buf = 0, *name; + int bufsize = 0, width, height, color; + int j; + + if ((!aud) || (aud->fd < 0)) + return; + + /* Read driver version */ + ret = ioctl(aud->fd, CCD_RD_VER, &info); + aud_ccdstruct_log("CCD_RD_VER", ret, &info); + + /* Read chip information */ + ret = ioctl(aud->fd, CCD_RD_CHIP, &info); + aud_ccdstruct_log("CCD_RD_CHIP", ret, &info); + + /* Read geometry */ + ret = ioctl(aud->fd, CCD_RD_GEOM, &info); + aud_ccdstruct_log("CCD_RD_GEOM", ret, &info); + + /* Set Window */ + info.minwidth = 1; + info.minheight = 2; + info.width = 200; + info.height = 100; + ret = ioctl(aud->fd, CCD_SET_WND, &info); + printf("\nCalled CCD_SET_WND: (1,2) (200,100)\n"); + + /* Read geometry */ + ret = ioctl(aud->fd, CCD_RD_GEOM, &info); + aud_ccdstruct_log("CCD_RD_GEOM", ret, &info); + + /* Set binning */ + info.width = 2; + info.height = 3; + printf("\nSet binning %dx%d", info.width, info.height); + ret = ioctl(aud->fd, CCD_SET_BNN, &info); + aud_ccdstruct_log("CCD_SET_BNN", ret, &info); + + /* Read geometry */ + ret = ioctl(aud->fd, CCD_RD_GEOM, &info); + aud_ccdstruct_log("CCD_RD_GEOM", ret, &info); + + /* (Re-)Set binning */ + info.width = 1; + info.height = 1; + printf("\nSet binning %dx%d", info.width, info.height); + ret = ioctl(aud->fd, CCD_SET_BNN, &info); + aud_ccdstruct_log("CCD_SET_BNN", ret, &info); + + /* Read geometry */ + ret = ioctl(aud->fd, CCD_RD_GEOM, &info); + aud_ccdstruct_log("CCD_RD_GEOM", ret, &info); + + /* Clear two times */ + info.width = 2; + printf("\nStart clear %d times\n", info.width); + fflush(stdout); + ret = ioctl(aud->fd, CCD_CLR, &info.width); + printf("Clear finished.\n"); + + /* Reading */ + printf("Start reading image\n"); + ret = aud_image_read(aud, &buf, &bufsize, &width, &height, &color); + printf + ("Finished reading: ret=%d width=%d height=%d color=%d bufsize=%d\n", + ret, width, height, color, bufsize); + + /* Set binning */ + info.width = 2; + info.height = 3; + printf("\nSet binning %dx%d", info.width, info.height); + ret = ioctl(aud->fd, CCD_SET_BNN, &info); + aud_ccdstruct_log("CCD_SET_BNN", ret, &info); + + /* Reading */ + printf("Start reading small image\n"); + ret = aud_image_read(aud, &buf, &bufsize, &width, &height, &color); + printf + ("Finished reading: ret=%d width=%d height=%d color=%d bufsize=%d\n", + ret, width, height, color, bufsize); + + /* Reset window */ + ret = ioctl(aud->fd, CCD_RST_WND); + printf("\nReset window\n"); + + /* Reset binning */ + info.width = 1; + info.height = 1; + printf("\nSet binning %dx%d", info.width, info.height); + ret = ioctl(aud->fd, CCD_SET_BNN, &info); + aud_ccdstruct_log("CCD_SET_BNN", ret, &info); + + /* Read geometry */ + ret = ioctl(aud->fd, CCD_RD_GEOM, &info); + aud_ccdstruct_log("CCD_RD_GEOM", ret, &info); + + /* Reading */ + printf("Start reading large image\n"); + ret = aud_image_read(aud, &buf, &bufsize, &width, &height, &color); + printf + ("Finished reading: ret=%d width=%d height=%d color=%d bufsize=%d\n", + ret, width, height, color, bufsize); + + /* Read current port */ + ret = aud_port_get(aud, &j); + printf("\naud_port_get returned with %d. Port=0x%x\n", ret, j); + + printf("\nList of supported CCDs:\n"); + j = 0; + while (aud_ccd_listentry_get(aud, j, &name, &info.width, &info.height, + &info.color) == 0) { + printf("%d: %s, %dx%d, %d\n", j, name, info.width, info.height, + info.color); + j++; + } } @@ -540,71 +556,71 @@ void aud_ioctl_test (AUD_HANDLE aud) sprintf (card, "%-80.80s", value); \ fwrite (card, 1, 80, fp); } -int audine_fits_write (const char *fname, const char *img, - int width, int height) +int audine_fits_write(const char *fname, const char *img, + int width, int height) { - FILE *fp; - char value[50]; - unsigned short *us_img = (unsigned short *) img; - unsigned short *row; - int x, y, high, low; - long pos; - time_t timp; + FILE *fp; + char value[50]; + unsigned short *us_img = (unsigned short *) img; + unsigned short *row; + int x, y, high, low; + long pos; + time_t timp; - fp = fopen(fname, "w"); - if (fp) { - FITS_WRITE_BOOLCARD(fp, "SIMPLE", 1); - FITS_WRITE_LONGCARD(fp, "BITPIX", 16); - FITS_WRITE_LONGCARD(fp, "NAXIS", 2); - FITS_WRITE_LONGCARD(fp, "NAXIS1", width); - FITS_WRITE_LONGCARD(fp, "NAXIS2", height); - FITS_WRITE_DOUBLECARD(fp, "BZERO", 0.0); - FITS_WRITE_DOUBLECARD(fp, "BSCALE", 1.0); - FITS_WRITE_DOUBLECARD(fp, "DATAMIN", 0.0); - FITS_WRITE_DOUBLECARD(fp, "DATAMAX", 32767.0); - FITS_WRITE_CARD(fp, " "); - FITS_WRITE_CARD(fp, "HISTORY THIS FILE WAS GENERATED BY AUDINELIB"); - FITS_WRITE_CARD(fp, " "); + fp = fopen(fname, "w"); + if (fp) { + FITS_WRITE_BOOLCARD(fp, "SIMPLE", 1); + FITS_WRITE_LONGCARD(fp, "BITPIX", 16); + FITS_WRITE_LONGCARD(fp, "NAXIS", 2); + FITS_WRITE_LONGCARD(fp, "NAXIS1", width); + FITS_WRITE_LONGCARD(fp, "NAXIS2", height); + FITS_WRITE_DOUBLECARD(fp, "BZERO", 0.0); + FITS_WRITE_DOUBLECARD(fp, "BSCALE", 1.0); + FITS_WRITE_DOUBLECARD(fp, "DATAMIN", 0.0); + FITS_WRITE_DOUBLECARD(fp, "DATAMAX", 32767.0); + FITS_WRITE_CARD(fp, " "); + FITS_WRITE_CARD(fp, "HISTORY THIS FILE WAS GENERATED BY AUDINELIB"); + FITS_WRITE_CARD(fp, " "); - timp = time(NULL); - strftime(value, sizeof(value), "%d/%m/%Y", gmtime(&timp)); - FITS_WRITE_STRINGCARD(fp, "DATE", value); + timp = time(NULL); + strftime(value, sizeof(value), "%d/%m/%Y", gmtime(&timp)); + FITS_WRITE_STRINGCARD(fp, "DATE", value); - FITS_WRITE_CARD(fp, "END"); + FITS_WRITE_CARD(fp, "END"); - /* Fill up primary HDU to multiple of 2880 bytes */ - fflush(fp); - pos = ftell(fp) % 2880; - if (pos != 0) { - pos = 2880 - pos; - while (pos-- > 0) - putc(' ', fp); - } + /* Fill up primary HDU to multiple of 2880 bytes */ + fflush(fp); + pos = ftell(fp) % 2880; + if (pos != 0) { + pos = 2880 - pos; + while (pos-- > 0) + putc(' ', fp); + } - /* FITS standard requires integer data to be most significant - byte first, */ - /* image origin bottom left. We want to create an astronomical - oriented image (top is bottom, left is right) */ - for (y = 0; y < height; y++) { - row = us_img + y * width; - for (x = width - 1; x >= 0; x--) { - high = (row[x] >> 8) & 0xff; - low = (row[x] & 0xff); - putc(high, fp); - putc(low, fp); - } - } - /* Fill up file to multiple of 2880 bytes */ - fflush(fp); - pos = ftell(fp) % 2880; - if (pos != 0) { - pos = 2880 - pos; - while (pos-- > 0) - putc(0, fp); - } - fclose(fp); - } else { - return -1; - } - return 0; + /* FITS standard requires integer data to be most significant + byte first, */ + /* image origin bottom left. We want to create an astronomical + oriented image (top is bottom, left is right) */ + for (y = 0; y < height; y++) { + row = us_img + y * width; + for (x = width - 1; x >= 0; x--) { + high = (row[x] >> 8) & 0xff; + low = (row[x] & 0xff); + putc(high, fp); + putc(low, fp); + } + } + /* Fill up file to multiple of 2880 bytes */ + fflush(fp); + pos = ftell(fp) % 2880; + if (pos != 0) { + pos = 2880 - pos; + while (pos-- > 0) + putc(0, fp); + } + fclose(fp); + } else { + return -1; + } + return 0; } diff --git a/audinelib.h b/audinelib.h index 7d9816e..f5677fb 100644 --- a/audinelib.h +++ b/audinelib.h @@ -31,48 +31,49 @@ #ifndef _AUDINELIB_H_ #define _AUDINELIB_H_ -typedef struct aud_handle_s * AUD_HANDLE; +typedef struct aud_handle_s *AUD_HANDLE; -AUD_HANDLE aud_open (void); +AUD_HANDLE aud_open(void); -void aud_close (AUD_HANDLE aud); +void aud_close(AUD_HANDLE aud); -char *aud_version (const AUD_HANDLE aud); +char *aud_version(const AUD_HANDLE aud); -int aud_image_read (const AUD_HANDLE aud, char **buf, int *bufsize, - int *width, int *height, int *color); -void aud_single_read_set (AUD_HANDLE aud, int single_read); +int aud_image_read(const AUD_HANDLE aud, char **buf, int *bufsize, + int *width, int *height, int *color); +void aud_single_read_set(AUD_HANDLE aud, int single_read); -int aud_ccd_info_get (const AUD_HANDLE aud, char **name, - int *width, int *height, int *color); +int aud_ccd_info_get(const AUD_HANDLE aud, char **name, + int *width, int *height, int *color); -int aud_ccd_listentry_get (const AUD_HANDLE aud, int entry, char **name, - int *width, int *height, int *color); +int aud_ccd_listentry_get(const AUD_HANDLE aud, int entry, char **name, + int *width, int *height, int *color); -int aud_binning_set (const AUD_HANDLE aud, int vb, int hb); -int aud_binning_get (const AUD_HANDLE aud, int *vb, int *hb); +int aud_binning_set(const AUD_HANDLE aud, int vb, int hb); +int aud_binning_get(const AUD_HANDLE aud, int *vb, int *hb); -int aud_geometry_set (const AUD_HANDLE aud,int x,int y,int width,int height); -int aud_geometry_get (const AUD_HANDLE aud, int *xorigin, int *yorigin, - int *winwidth, int *winheight, int *color); -int aud_geometry_reset (const AUD_HANDLE aud); +int aud_geometry_set(const AUD_HANDLE aud, int x, int y, int width, + int height); +int aud_geometry_get(const AUD_HANDLE aud, int *xorigin, int *yorigin, + int *winwidth, int *winheight, int *color); +int aud_geometry_reset(const AUD_HANDLE aud); -int aud_amplifier_ctrl_set (const AUD_HANDLE aud, int ctrl); -int aud_amplifier_set (const AUD_HANDLE aud, int off_on); +int aud_amplifier_ctrl_set(const AUD_HANDLE aud, int ctrl); +int aud_amplifier_set(const AUD_HANDLE aud, int off_on); -int aud_shutter_ctrl_set (const AUD_HANDLE aud, int ctrl); -int aud_shutter_set (const AUD_HANDLE aud, int off_on); +int aud_shutter_ctrl_set(const AUD_HANDLE aud, int ctrl); +int aud_shutter_set(const AUD_HANDLE aud, int off_on); -int aud_aux0_ctrl_set (const AUD_HANDLE aud, int ctrl); -int aud_aux0_set (const AUD_HANDLE aud, int off_on); +int aud_aux0_ctrl_set(const AUD_HANDLE aud, int ctrl); +int aud_aux0_set(const AUD_HANDLE aud, int off_on); -int aud_aux1_ctrl_set (const AUD_HANDLE aud, int ctrl); -int aud_aux1_set (const AUD_HANDLE aud, int off_on); +int aud_aux1_ctrl_set(const AUD_HANDLE aud, int ctrl); +int aud_aux1_set(const AUD_HANDLE aud, int off_on); -int aud_clear (const AUD_HANDLE, int nclear); +int aud_clear(const AUD_HANDLE, int nclear); -void aud_ioctl_test (AUD_HANDLE aud); +void aud_ioctl_test(AUD_HANDLE aud); -int audine_fits_write (const char *fname, const char *img, - int width, int height); +int audine_fits_write(const char *fname, const char *img, + int width, int height); #endif diff --git a/bruker.c b/bruker.c index f240770..a9c8dcd 100644 --- a/bruker.c +++ b/bruker.c @@ -22,7 +22,7 @@ #include #include #include -#include +#include #include "hardsup/serialsinq.h" #include "hardsup/el734_errcodes.h" #include "hardsup/el734fix.h" @@ -33,15 +33,15 @@ */ /*----------------------------------------------------------------------- The Bruker Data Structure -*/ - typedef struct { - void *pData; - char *pHost; - int iPort; - int iChannel; - int iMode; - int iLastError; - } BrukerDriv, *pBrukerDriv; +*/ +typedef struct { + void *pData; + char *pHost; + int iPort; + int iChannel; + int iMode; + int iLastError; +} BrukerDriv, *pBrukerDriv; /*----------------------------------------------------------------------- A couple of defines for Bruker modes and special error conditions */ @@ -56,7 +56,7 @@ #define ERRPENDING -1605 #define NOPOWER -1606 #define NOTFIELD -1607 -#define BADINTERN -1608 +#define BADINTERN -1608 #define NOCONN -1609 #define BTIMEOUT -1610 #define NOPOLUNIT -1620 @@ -81,673 +81,619 @@ extern char *rmtrail(char *p); are processed through this special function which takes care of the error handling. */ - static int BrukerCommand(pBrukerDriv self, char *pCommand, - char *pReplyBuffer, int iReplyLen) - { - int iTest, iCode; - char *pPtr; - - assert(self); - assert(iReplyLen > 20); /* so small a buffer will hide errors */ - - if(self->pData == NULL) - { - self->iLastError = NOCONN; - return 0; - } - - /* send the command to the Bruker */ - rmtrail(pCommand); - iTest = SerialWriteRead(&(self->pData), pCommand,pReplyBuffer, iReplyLen); +static int BrukerCommand(pBrukerDriv self, char *pCommand, + char *pReplyBuffer, int iReplyLen) +{ + int iTest, iCode; + char *pPtr; + + assert(self); + assert(iReplyLen > 20); /* so small a buffer will hide errors */ + + if (self->pData == NULL) { + self->iLastError = NOCONN; + return 0; + } + + /* send the command to the Bruker */ + rmtrail(pCommand); + iTest = + SerialWriteRead(&(self->pData), pCommand, pReplyBuffer, iReplyLen); #ifdef debug - printf("Comm: %s , Reply %s\n",pCommand,pReplyBuffer); -#endif - if(iTest != 1) /* communication error */ - { - self->iLastError = iTest; - return 0; - } - - /* identify timeout */ - if(strstr(pReplyBuffer,"?TMO") != NULL) - { - self->iLastError = BTIMEOUT; - return 0; - } - - /* try to find a E0 response indicating a Bruker error */ - if( (pPtr = strstr(pReplyBuffer,"E0")) == NULL) - { - return 1; - } - - /* decode the error */ - sscanf(pPtr+1,"%x",&iCode); - switch(iCode) - { - case 1: - self->iLastError = NOFUNC; - break; - case 2: - self->iLastError = BADARG; - break; - case 4: - self->iLastError = NOACCESS; - break; - case 5: - self->iLastError = BADRANGE; - break; - case 7: - self->iLastError = ERRPENDING; - break; - case 9: - self->iLastError = NOPOWER; - break; - case 10: - self->iLastError = NOTFIELD; - break; - default: - self->iLastError = BADINTERN; - break; - } - return 0; - } -/*-------------------------------------------------------------------------*/ - int BrukerReadField(pEVControl pEva, float *fField) - { - pBrukerDriv self = NULL; - int iRet; - char pBueffel[80]; - char pCommand[6]; - char *pPtr,*pSign; - int iSign = 1; - float fVal; - - self = (pBrukerDriv)pEva->pDriv->pPrivate; - assert(self); - - if(self->pData == NULL) - { - self->iLastError = NOCONN; - return 0; - } - - strcpy(pCommand,"FIE/"); - iRet = BrukerCommand(self,pCommand,pBueffel,79); - if(!iRet) - { - *fField = -99; - return 0; - } - - pPtr = pBueffel+4; /* skip over echo */ - /* deal with obstructing sign */ - if( (pSign = strchr(pPtr,'+')) != NULL) - { - *pSign = ' '; - iSign = 1; - } - if( (pSign = strchr(pPtr,'-')) != NULL) - { - *pSign = ' '; - iSign = -1; - } - sscanf(pPtr,"%f",&fVal); - *fField = iSign * fVal; - return 1; - } -/*-------------------------------------------------------------------------*/ - int BrukerReadCurrent(pEVControl pEva, float *fField) - { - pBrukerDriv self = NULL; - int iRet, iSign = 1; - char pBueffel[80]; - char pCommand[6]; - char *pPtr, *pSign = NULL; - float fVal; - - self = (pBrukerDriv)pEva->pDriv->pPrivate; - assert(self); - - if(self->pData == NULL) - { - self->iLastError = NOCONN; - return 0; - } - - strcpy(pCommand,"CHN/"); - iRet = BrukerCommand(self,pCommand,pBueffel,79); - if(!iRet) - { - *fField = -99; - return 0; - } - - pPtr = pBueffel+4; /* skip over echo */ - /* deal with obstructing sign */ - if( (pSign = strchr(pPtr,'+')) != NULL) - { - *pSign = ' '; - iSign = 1; - } - if( (pSign = strchr(pPtr,'-')) != NULL) - { - *pSign = ' '; - iSign = -1; - } - sscanf(pPtr,"%f",&fVal); - *fField = iSign * fVal; - return 1; - } -/*-------------------------------------------------------------------------*/ - static int BrukerGet(pEVDriver pEva, float *fValue) - { - pBrukerDriv self = NULL; - int iRet, iSign = 1; - char pBueffel[80]; - char pCommand[6]; - char *pPtr, *pSign = NULL; - float fVal; - - self = (pBrukerDriv)pEva->pPrivate; - assert(self); - - if(self->pData == NULL) - { - self->iLastError = NOCONN; - return 0; - } - - if(self->iMode == FIELD) - { - strcpy(pCommand,"CUF/"); - iRet = BrukerCommand(self,pCommand,pBueffel,79); - } - else if(self->iMode == CURRENT) - { - strcpy(pCommand,"CUR/"); - iRet = BrukerCommand(self,pCommand,pBueffel,79); - } - else - { - /* programming error */ - assert(1); - } - - if(!iRet) - { - *fValue = -99; - return 0; - } - - pPtr = pBueffel+4; /* skip over echo */ - /* deal with obstructing sign */ - if( (pSign = strchr(pPtr,'+')) != NULL) - { - *pSign = ' '; - iSign = 1; - } - if( (pSign = strchr(pPtr,'-')) != NULL) - { - *pSign = ' '; - iSign = -1; - } - sscanf(pPtr,"%f",&fVal); - *fValue = iSign * fVal; - return 1; + printf("Comm: %s , Reply %s\n", pCommand, pReplyBuffer); +#endif + if (iTest != 1) { /* communication error */ + self->iLastError = iTest; + return 0; } -/*-------------------------------------------------------------------------*/ - static int BrukerRun(pEVDriver pEva, float fVal) - { - pBrukerDriv self = NULL; - int iRet; - char pBueffel[80]; - char pCommand[40]; - char *pPtr; - - self = (pBrukerDriv)pEva->pPrivate; - assert(self); - - if(self->pData == NULL) - { - self->iLastError = NOCONN; - return 0; - } - if(self->iMode == FIELD) - { - sprintf(pCommand,"PTF=%-6.2f",fVal); - iRet = BrukerCommand(self,pCommand,pBueffel,79); - } - else if(self->iMode == CURRENT) - { - sprintf(pCommand,"PNT=%-6.2f",fVal); - iRet = BrukerCommand(self,pCommand,pBueffel,79); - } - else - { - /* programming error */ - assert(1); - } - - if(!iRet) - { - return 0; - } - return 1; + /* identify timeout */ + if (strstr(pReplyBuffer, "?TMO") != NULL) { + self->iLastError = BTIMEOUT; + return 0; } + + /* try to find a E0 response indicating a Bruker error */ + if ((pPtr = strstr(pReplyBuffer, "E0")) == NULL) { + return 1; + } + + /* decode the error */ + sscanf(pPtr + 1, "%x", &iCode); + switch (iCode) { + case 1: + self->iLastError = NOFUNC; + break; + case 2: + self->iLastError = BADARG; + break; + case 4: + self->iLastError = NOACCESS; + break; + case 5: + self->iLastError = BADRANGE; + break; + case 7: + self->iLastError = ERRPENDING; + break; + case 9: + self->iLastError = NOPOWER; + break; + case 10: + self->iLastError = NOTFIELD; + break; + default: + self->iLastError = BADINTERN; + break; + } + return 0; +} + +/*-------------------------------------------------------------------------*/ +int BrukerReadField(pEVControl pEva, float *fField) +{ + pBrukerDriv self = NULL; + int iRet; + char pBueffel[80]; + char pCommand[6]; + char *pPtr, *pSign; + int iSign = 1; + float fVal; + + self = (pBrukerDriv) pEva->pDriv->pPrivate; + assert(self); + + if (self->pData == NULL) { + self->iLastError = NOCONN; + return 0; + } + + strcpy(pCommand, "FIE/"); + iRet = BrukerCommand(self, pCommand, pBueffel, 79); + if (!iRet) { + *fField = -99; + return 0; + } + + pPtr = pBueffel + 4; /* skip over echo */ + /* deal with obstructing sign */ + if ((pSign = strchr(pPtr, '+')) != NULL) { + *pSign = ' '; + iSign = 1; + } + if ((pSign = strchr(pPtr, '-')) != NULL) { + *pSign = ' '; + iSign = -1; + } + sscanf(pPtr, "%f", &fVal); + *fField = iSign * fVal; + return 1; +} + +/*-------------------------------------------------------------------------*/ +int BrukerReadCurrent(pEVControl pEva, float *fField) +{ + pBrukerDriv self = NULL; + int iRet, iSign = 1; + char pBueffel[80]; + char pCommand[6]; + char *pPtr, *pSign = NULL; + float fVal; + + self = (pBrukerDriv) pEva->pDriv->pPrivate; + assert(self); + + if (self->pData == NULL) { + self->iLastError = NOCONN; + return 0; + } + + strcpy(pCommand, "CHN/"); + iRet = BrukerCommand(self, pCommand, pBueffel, 79); + if (!iRet) { + *fField = -99; + return 0; + } + + pPtr = pBueffel + 4; /* skip over echo */ + /* deal with obstructing sign */ + if ((pSign = strchr(pPtr, '+')) != NULL) { + *pSign = ' '; + iSign = 1; + } + if ((pSign = strchr(pPtr, '-')) != NULL) { + *pSign = ' '; + iSign = -1; + } + sscanf(pPtr, "%f", &fVal); + *fField = iSign * fVal; + return 1; +} + +/*-------------------------------------------------------------------------*/ +static int BrukerGet(pEVDriver pEva, float *fValue) +{ + pBrukerDriv self = NULL; + int iRet, iSign = 1; + char pBueffel[80]; + char pCommand[6]; + char *pPtr, *pSign = NULL; + float fVal; + + self = (pBrukerDriv) pEva->pPrivate; + assert(self); + + if (self->pData == NULL) { + self->iLastError = NOCONN; + return 0; + } + + if (self->iMode == FIELD) { + strcpy(pCommand, "CUF/"); + iRet = BrukerCommand(self, pCommand, pBueffel, 79); + } else if (self->iMode == CURRENT) { + strcpy(pCommand, "CUR/"); + iRet = BrukerCommand(self, pCommand, pBueffel, 79); + } else { + /* programming error */ + assert(1); + } + + if (!iRet) { + *fValue = -99; + return 0; + } + + pPtr = pBueffel + 4; /* skip over echo */ + /* deal with obstructing sign */ + if ((pSign = strchr(pPtr, '+')) != NULL) { + *pSign = ' '; + iSign = 1; + } + if ((pSign = strchr(pPtr, '-')) != NULL) { + *pSign = ' '; + iSign = -1; + } + sscanf(pPtr, "%f", &fVal); + *fValue = iSign * fVal; + return 1; +} + +/*-------------------------------------------------------------------------*/ +static int BrukerRun(pEVDriver pEva, float fVal) +{ + pBrukerDriv self = NULL; + int iRet; + char pBueffel[80]; + char pCommand[40]; + char *pPtr; + + self = (pBrukerDriv) pEva->pPrivate; + assert(self); + + if (self->pData == NULL) { + self->iLastError = NOCONN; + return 0; + } + + if (self->iMode == FIELD) { + sprintf(pCommand, "PTF=%-6.2f", fVal); + iRet = BrukerCommand(self, pCommand, pBueffel, 79); + } else if (self->iMode == CURRENT) { + sprintf(pCommand, "PNT=%-6.2f", fVal); + iRet = BrukerCommand(self, pCommand, pBueffel, 79); + } else { + /* programming error */ + assert(1); + } + + if (!iRet) { + return 0; + } + return 1; +} + /*------------------------------------------------------------------------*/ - static int BrukerError(pEVDriver pEva, int *iCode, char *pError, - int iErrLen) - { - pBrukerDriv self = NULL; +static int BrukerError(pEVDriver pEva, int *iCode, char *pError, + int iErrLen) +{ + pBrukerDriv self = NULL; - self = (pBrukerDriv)pEva->pPrivate; - assert(self); + self = (pBrukerDriv) pEva->pPrivate; + assert(self); + + *iCode = self->iLastError; + switch (*iCode) { + case NOFUNC: + strncpy(pError, "Function not supported", iErrLen); + break; + case BADINTERN: + case BADARG: + strncpy(pError, + "Programming problem, reset Controller & contact Programmer", + iErrLen); + break; + case NOTFIELD: + strncpy(pError, "Bruker not switched to field mode", iErrLen); + break; + case BADRANGE: + strncpy(pError, "Requested value out of range", iErrLen); + break; + case NOACCESS: + strncpy(pError, "No Access, check key position at Controller", + iErrLen); + break; + case ERRPENDING: + strncpy(pError, "Error condition pending in Bruker Controller", + iErrLen); + break; + case NOPOWER: + strncpy(pError, + "Power OFF as consequence of some error in Bruker Controller", + iErrLen); + break; + case NOCONN: + strncpy(pError, "No Connection to Bruker Controller", iErrLen); + break; + case BTIMEOUT: + strncpy(pError, "Timeout at serial port", iErrLen); + break; + case NOPOLUNIT: + strncpy(pError, + "No polarity switching unit, try setting negative current", + iErrLen); + break; + default: + SerialError(*iCode, pError, iErrLen); + break; + } + return 1; +} - *iCode = self->iLastError; - switch(*iCode) - { - case NOFUNC: - strncpy(pError, - "Function not supported", - iErrLen); - break; - case BADINTERN: - case BADARG: - strncpy(pError, - "Programming problem, reset Controller & contact Programmer", - iErrLen); - break; - case NOTFIELD: - strncpy(pError,"Bruker not switched to field mode",iErrLen); - break; - case BADRANGE: - strncpy(pError,"Requested value out of range",iErrLen); - break; - case NOACCESS: - strncpy(pError,"No Access, check key position at Controller", - iErrLen); - break; - case ERRPENDING: - strncpy(pError,"Error condition pending in Bruker Controller", - iErrLen); - break; - case NOPOWER: - strncpy(pError, - "Power OFF as consequence of some error in Bruker Controller", - iErrLen); - break; - case NOCONN: - strncpy(pError,"No Connection to Bruker Controller",iErrLen); - break; - case BTIMEOUT: - strncpy(pError,"Timeout at serial port",iErrLen); - break; - case NOPOLUNIT: - strncpy(pError,"No polarity switching unit, try setting negative current", - iErrLen); - break; - default: - SerialError(*iCode,pError,iErrLen); - break; - } - return 1; - } /*---------------------------------------------------------------------------*/ - static int BrukerSend(pEVDriver pEva, char *pCommand, char *pReply, - int iReplyLen) - { - pBrukerDriv self = NULL; - int iRet; +static int BrukerSend(pEVDriver pEva, char *pCommand, char *pReply, + int iReplyLen) +{ + pBrukerDriv self = NULL; + int iRet; - self = (pBrukerDriv)pEva->pPrivate; - assert(self); + self = (pBrukerDriv) pEva->pPrivate; + assert(self); - if(self->pData == NULL) - { - self->iLastError = NOCONN; - return 0; - } + if (self->pData == NULL) { + self->iLastError = NOCONN; + return 0; + } - iRet = SerialWriteRead(&(self->pData),pCommand, pReply, iReplyLen); - if(iRet != 1) - { - self->iLastError = iRet; - return 0; - } - return 1; - } + iRet = SerialWriteRead(&(self->pData), pCommand, pReply, iReplyLen); + if (iRet != 1) { + self->iLastError = iRet; + return 0; + } + return 1; +} + /*--------------------------------------------------------------------------*/ - static int BrukerInit(pEVDriver pEva) - { - pBrukerDriv self = NULL; - int iRet; - char pBueffel[80], pCommand[20]; +static int BrukerInit(pEVDriver pEva) +{ + pBrukerDriv self = NULL; + int iRet; + char pBueffel[80], pCommand[20]; - self = (pBrukerDriv)pEva->pPrivate; - assert(self); + self = (pBrukerDriv) pEva->pPrivate; + assert(self); - /* open port connection */ - self->pData = NULL; - iRet = SerialOpen(&(self->pData),self->pHost, self->iPort, self->iChannel); - if(iRet != 1) - { - self->iLastError = iRet; - return 0; - } - /* configure serial port terminators */ - SerialSendTerm(&(self->pData),"\r"); - SerialATerm(&(self->pData),"1\r\n"); - - /* set power on */ - strcpy(pCommand,"DCP=1"); - iRet = SerialWriteRead(&(self->pData),pCommand,pBueffel,80); - if(iRet != 1) - { - self->iLastError = iRet; - return 0; - } - - /* switch to current mode as default init mode */ - self->iMode = CURRENT; - strcpy(pCommand,"EXT=0"); - iRet = SerialWriteRead(&(self->pData),pCommand,pBueffel,80); - if(iRet != 1) - { - self->iLastError = iRet; - return 0; - } - return 1; + /* open port connection */ + self->pData = NULL; + iRet = + SerialOpen(&(self->pData), self->pHost, self->iPort, self->iChannel); + if (iRet != 1) { + self->iLastError = iRet; + return 0; } + /* configure serial port terminators */ + SerialSendTerm(&(self->pData), "\r"); + SerialATerm(&(self->pData), "1\r\n"); + + /* set power on */ + strcpy(pCommand, "DCP=1"); + iRet = SerialWriteRead(&(self->pData), pCommand, pBueffel, 80); + if (iRet != 1) { + self->iLastError = iRet; + return 0; + } + + /* switch to current mode as default init mode */ + self->iMode = CURRENT; + strcpy(pCommand, "EXT=0"); + iRet = SerialWriteRead(&(self->pData), pCommand, pBueffel, 80); + if (iRet != 1) { + self->iLastError = iRet; + return 0; + } + return 1; +} + /*-------------------------------------------------------------------------*/ - static int BrukerClose(pEVDriver pEva) - { - pBrukerDriv self = NULL; +static int BrukerClose(pEVDriver pEva) +{ + pBrukerDriv self = NULL; - self = (pBrukerDriv)pEva->pPrivate; - assert(self); + self = (pBrukerDriv) pEva->pPrivate; + assert(self); + + SerialClose(&(self->pData)); + self->pData = 0; + + return 1; +} - SerialClose(&(self->pData)); - self->pData = 0; - - return 1; - } /*---------------------------------------------------------------------------*/ - static int BrukerFix(pEVDriver self, int iError) - { - pBrukerDriv pMe = NULL; - int iRet; - char pCommand[20], pBueffel[80]; - - assert(self); - pMe = (pBrukerDriv )self->pPrivate; - assert(pMe); +static int BrukerFix(pEVDriver self, int iError) +{ + pBrukerDriv pMe = NULL; + int iRet; + char pCommand[20], pBueffel[80]; - switch(iError) - { - /* network errors */ - case EL734__BAD_FLUSH: - case EL734__BAD_RECV: - case EL734__BAD_RECV_NET: - case EL734__BAD_RECV_UNKN: - case EL734__BAD_RECVLEN: - case EL734__BAD_RECV1: - case EL734__BAD_RECV1_PIPE: - case EL734__BAD_RNG: - case EL734__BAD_SEND: - case EL734__BAD_SEND_PIPE: - case EL734__BAD_SEND_NET: - case EL734__BAD_SEND_UNKN: - case EL734__BAD_SENDLEN: - BrukerClose(self); - iRet = BrukerInit(self); - if(iRet) - { - return DEVREDO; - } - else - { - return DEVFAULT; - } - break; - case EL734__FORCED_CLOSED: - case NOCONN: - iRet = BrukerInit(self); - if(iRet) - { - return DEVREDO; - } - else - { - return DEVFAULT; - } - break; - /* fixable Bruker Errors */ - case ERRPENDING: - strcpy(pCommand,"RST=0"); - iRet = BrukerCommand(pMe,pCommand, pBueffel,79); - if(iRet) - { - return DEVREDO; - } - else - { - return DEVFAULT; - } - break; - case NOPOWER: - strcpy(pCommand,"RST=0"); - iRet = BrukerCommand(pMe,pCommand, pBueffel,79); - strcpy(pCommand,"DCP=1"); - iRet = BrukerCommand(pMe,pCommand, pBueffel,79); - if(iRet) - { - return DEVREDO; - } - else - { - return DEVFAULT; - } - break; - case NOTFIELD: - strcpy(pCommand,"EXT=2"); - iRet = BrukerCommand(pMe,pCommand, pBueffel,79); - if(iRet) - { - return DEVREDO; - } - else - { - return DEVFAULT; - } - break; - /* handable protocoll errors */ - case EL734__BAD_TMO: - case BTIMEOUT: - case NOFUNC: - return DEVREDO; - break; - default: - return DEVFAULT; - break; - } - return DEVFAULT; + assert(self); + pMe = (pBrukerDriv) self->pPrivate; + assert(pMe); + + switch (iError) { + /* network errors */ + case EL734__BAD_FLUSH: + case EL734__BAD_RECV: + case EL734__BAD_RECV_NET: + case EL734__BAD_RECV_UNKN: + case EL734__BAD_RECVLEN: + case EL734__BAD_RECV1: + case EL734__BAD_RECV1_PIPE: + case EL734__BAD_RNG: + case EL734__BAD_SEND: + case EL734__BAD_SEND_PIPE: + case EL734__BAD_SEND_NET: + case EL734__BAD_SEND_UNKN: + case EL734__BAD_SENDLEN: + BrukerClose(self); + iRet = BrukerInit(self); + if (iRet) { + return DEVREDO; + } else { + return DEVFAULT; + } + break; + case EL734__FORCED_CLOSED: + case NOCONN: + iRet = BrukerInit(self); + if (iRet) { + return DEVREDO; + } else { + return DEVFAULT; + } + break; + /* fixable Bruker Errors */ + case ERRPENDING: + strcpy(pCommand, "RST=0"); + iRet = BrukerCommand(pMe, pCommand, pBueffel, 79); + if (iRet) { + return DEVREDO; + } else { + return DEVFAULT; + } + break; + case NOPOWER: + strcpy(pCommand, "RST=0"); + iRet = BrukerCommand(pMe, pCommand, pBueffel, 79); + strcpy(pCommand, "DCP=1"); + iRet = BrukerCommand(pMe, pCommand, pBueffel, 79); + if (iRet) { + return DEVREDO; + } else { + return DEVFAULT; + } + break; + case NOTFIELD: + strcpy(pCommand, "EXT=2"); + iRet = BrukerCommand(pMe, pCommand, pBueffel, 79); + if (iRet) { + return DEVREDO; + } else { + return DEVFAULT; + } + break; + /* handable protocoll errors */ + case EL734__BAD_TMO: + case BTIMEOUT: + case NOFUNC: + return DEVREDO; + break; + default: + return DEVFAULT; + break; } + return DEVFAULT; +} + /*------------------------------------------------------------------------*/ - void KillBruker(void *pData) - { - pBrukerDriv pMe = NULL; - - pMe = (pBrukerDriv)pData; - assert(pMe); - - if(pMe->pHost) - { - free(pMe->pHost); - } - free(pMe); - } +void KillBruker(void *pData) +{ + pBrukerDriv pMe = NULL; + + pMe = (pBrukerDriv) pData; + assert(pMe); + + if (pMe->pHost) { + free(pMe->pHost); + } + free(pMe); +} + /*------------------------------------------------------------------------*/ - pEVDriver CreateBrukerDriver(int argc, char *argv[]) - { - pEVDriver pNew = NULL; - pBrukerDriv pSim = NULL; - - /* check for arguments */ - if(argc < 3) - { - return NULL; - } - - pNew = CreateEVDriver(argc,argv); - pSim = (pBrukerDriv)malloc(sizeof(BrukerDriv)); - memset(pSim,0,sizeof(BrukerDriv)); - if(!pNew || !pSim) - { - return NULL; - } - pNew->pPrivate = pSim; - pNew->KillPrivate = KillBruker; - - /* initalise pBrukerDriver */ - pSim->iLastError = 0; - pSim->pHost = strdup(argv[0]); - pSim->iPort = atoi(argv[1]); - pSim->iChannel = atoi(argv[2]); - - - /* initialise function pointers */ - pNew->SetValue = BrukerRun; - pNew->GetValue = BrukerGet; - pNew->Send = BrukerSend; - pNew->GetError = BrukerError; - pNew->TryFixIt = BrukerFix; - pNew->Init = BrukerInit; - pNew->Close = BrukerClose; - - return pNew; - } +pEVDriver CreateBrukerDriver(int argc, char *argv[]) +{ + pEVDriver pNew = NULL; + pBrukerDriv pSim = NULL; + + /* check for arguments */ + if (argc < 3) { + return NULL; + } + + pNew = CreateEVDriver(argc, argv); + pSim = (pBrukerDriv) malloc(sizeof(BrukerDriv)); + memset(pSim, 0, sizeof(BrukerDriv)); + if (!pNew || !pSim) { + return NULL; + } + pNew->pPrivate = pSim; + pNew->KillPrivate = KillBruker; + + /* initalise pBrukerDriver */ + pSim->iLastError = 0; + pSim->pHost = strdup(argv[0]); + pSim->iPort = atoi(argv[1]); + pSim->iChannel = atoi(argv[2]); + + + /* initialise function pointers */ + pNew->SetValue = BrukerRun; + pNew->GetValue = BrukerGet; + pNew->Send = BrukerSend; + pNew->GetError = BrukerError; + pNew->TryFixIt = BrukerFix; + pNew->Init = BrukerInit; + pNew->Close = BrukerClose; + + return pNew; +} + /*-------------------------------------------------------------------------*/ - int BrukerSetMode(pEVControl pEva, SConnection *pCon, int iMode) - { - pBrukerDriv self = NULL; - int iRet; - char pBueffel[80]; - char pCommand[6]; - char *pPtr; - - self = (pBrukerDriv)pEva->pDriv->pPrivate; - assert(self); +int BrukerSetMode(pEVControl pEva, SConnection * pCon, int iMode) +{ + pBrukerDriv self = NULL; + int iRet; + char pBueffel[80]; + char pCommand[6]; + char *pPtr; + + self = (pBrukerDriv) pEva->pDriv->pPrivate; + assert(self); + + if (self->pData == NULL) { + self->iLastError = NOCONN; + return 0; + } + + if (iMode == CURRENT) { + strcpy(pCommand, "EXT=0"); + } else if (iMode == FIELD) { + strcpy(pCommand, "EXT=2"); + } else { + SCWrite(pCon, "ERROR: Internal: invalid mode for Bruker given", + eError); + return 0; + } + iRet = BrukerCommand(self, pCommand, pBueffel, 79); + if (!iRet) { + strcpy(pBueffel, "ERROR:"); + BrukerError(pEva->pDriv, &iRet, (pBueffel + 7), 70); + SCWrite(pCon, pBueffel, eError); + return 0; + } + self->iMode = iMode; + return 1; +} - if(self->pData == NULL) - { - self->iLastError = NOCONN; - return 0; - } - - if(iMode == CURRENT) - { - strcpy(pCommand,"EXT=0"); - } - else if(iMode == FIELD) - { - strcpy(pCommand,"EXT=2"); - } - else - { - SCWrite(pCon,"ERROR: Internal: invalid mode for Bruker given",eError); - return 0; - } - iRet = BrukerCommand(self,pCommand,pBueffel,79); - if(!iRet) - { - strcpy(pBueffel,"ERROR:"); - BrukerError(pEva->pDriv,&iRet,(pBueffel+7),70); - SCWrite(pCon,pBueffel,eError); - return 0; - } - self->iMode = iMode; - return 1; - } /*-------------------------------------------------------------------------*/ - int BrukerGetPolarity(pEVControl pEva, SConnection *pCon, int *iMode) - { - pBrukerDriv self = NULL; - int iRet; - char pBueffel[80]; - char pCommand[6]; - char *pPtr; - - self = (pBrukerDriv)pEva->pDriv->pPrivate; - assert(self); +int BrukerGetPolarity(pEVControl pEva, SConnection * pCon, int *iMode) +{ + pBrukerDriv self = NULL; + int iRet; + char pBueffel[80]; + char pCommand[6]; + char *pPtr; + + self = (pBrukerDriv) pEva->pDriv->pPrivate; + assert(self); + + if (self->pData == NULL) { + self->iLastError = NOCONN; + return 0; + } + strcpy(pCommand, "POL/"); + iRet = BrukerCommand(self, pCommand, pBueffel, 79); + if (!iRet) { + strcpy(pBueffel, "ERROR:"); + BrukerError(pEva->pDriv, &iRet, (pBueffel + 7), 70); + SCWrite(pCon, pBueffel, eError); + return 0; + } + pPtr = pBueffel + 4; + sscanf(pPtr, "%d", iMode); + return 1; +} - if(self->pData == NULL) - { - self->iLastError = NOCONN; - return 0; - } - strcpy(pCommand,"POL/"); - iRet = BrukerCommand(self,pCommand,pBueffel,79); - if(!iRet) - { - strcpy(pBueffel,"ERROR:"); - BrukerError(pEva->pDriv,&iRet,(pBueffel+7),70); - SCWrite(pCon,pBueffel,eError); - return 0; - } - pPtr = pBueffel+4; - sscanf(pPtr,"%d",iMode); - return 1; - } /*------------------------------------------------------------------------*/ - int BrukerSetPolarity(pEVControl pEva, SConnection *pCon, int iMode) - { - pBrukerDriv self = NULL; - int iRet; - char pBueffel[80]; - char pCommand[6]; - char *pPtr; - - self = (pBrukerDriv)pEva->pDriv->pPrivate; - assert(self); +int BrukerSetPolarity(pEVControl pEva, SConnection * pCon, int iMode) +{ + pBrukerDriv self = NULL; + int iRet; + char pBueffel[80]; + char pCommand[6]; + char *pPtr; - if(self->pData == NULL) - { - self->iLastError = NOCONN; - return 0; - } - - if(iMode == PPLUS) - { - strcpy(pCommand,"POL=0"); - } - else if(iMode == PMINUS) - { - strcpy(pCommand,"POL=1"); - } - else - { - assert(1); /* programming error */ - } + self = (pBrukerDriv) pEva->pDriv->pPrivate; + assert(self); + + if (self->pData == NULL) { + self->iLastError = NOCONN; + return 0; + } + + if (iMode == PPLUS) { + strcpy(pCommand, "POL=0"); + } else if (iMode == PMINUS) { + strcpy(pCommand, "POL=1"); + } else { + assert(1); /* programming error */ + } + + iRet = BrukerCommand(self, pCommand, pBueffel, 79); + if ((strstr(pBueffel, "POL=0E01") != NULL) || + (strstr(pBueffel, "POL=1E01") != NULL)) { + self->iLastError = NOPOLUNIT; + iRet = 0; + } + if (!iRet) { + strcpy(pBueffel, "ERROR:"); + BrukerError(pEva->pDriv, &iRet, (pBueffel + 6), 70); + SCWrite(pCon, pBueffel, eError); + return 0; + } + return 1; +} - iRet = BrukerCommand(self,pCommand,pBueffel,79); - if( (strstr(pBueffel,"POL=0E01") != NULL) || - (strstr(pBueffel,"POL=1E01") != NULL) ) - { - self->iLastError = NOPOLUNIT; - iRet = 0; - } - if(!iRet) - { - strcpy(pBueffel,"ERROR:"); - BrukerError(pEva->pDriv,&iRet,(pBueffel+6),70); - SCWrite(pCon,pBueffel,eError); - return 0; - } - return 1; - } /*-------------------------------------------------------------------------- handle Bruker specific commands: - polarity for switching polarity @@ -757,243 +703,180 @@ extern char *rmtrail(char *p); - list append our own stuff to the rest in all other cases fall back and call EVControllerWrapper to handle it or eventually throw an error. -*/ - int BrukerAction(SConnection *pCon, SicsInterp *pSics, void *pData, - int argc, char *argv[]) - { - - pEVControl self = NULL; - int iRet, iMode; - char pBueffel[256]; - pBrukerDriv pMe = NULL; - float fVal; - - self = (pEVControl)pData; - assert(self); - pMe = (pBrukerDriv)self->pDriv->pPrivate; - assert(pMe); +*/ +int BrukerAction(SConnection * pCon, SicsInterp * pSics, void *pData, + int argc, char *argv[]) +{ - if(argc > 1) - { - strtolower(argv[1]); -/*------ polarity */ - if(strcmp(argv[1],"polarity") == 0) - { - if(argc > 2) /* set case */ - { - strtolower(argv[2]); - if(strcmp(argv[2],"plus") == 0) - { - iMode = PPLUS; - } - else if(strcmp(argv[2],"minus") == 0) - { - iMode = PMINUS; - } - else - { - sprintf(pBueffel,"ERROR: %s is no knwon polarity mode", argv[2]); - SCWrite(pCon,pBueffel,eError); - return 0; - } - /* check permission */ - if(!SCMatchRights(pCon,usUser)) - { - return 0; - } - /* do it */ - iRet = BrukerSetPolarity(self,pCon,iMode); - if(iRet) - { - SCSendOK(pCon); - return 1; - } - else - { - return 0; - } - } - else /* get case */ - { - iRet = BrukerGetPolarity(self,pCon,&iMode); - if(iRet) - { - if(iMode == PPLUS) - { - sprintf(pBueffel,"%s.polarity = plus",argv[0]); - } - else if (iMode == PMINUS) - { - sprintf(pBueffel,"%s.polarity = minus",argv[0]); - } - else - { - assert(1); /* programming problem */ - } - SCWrite(pCon,pBueffel,eValue); - return 1; - } - } + pEVControl self = NULL; + int iRet, iMode; + char pBueffel[256]; + pBrukerDriv pMe = NULL; + float fVal; + + self = (pEVControl) pData; + assert(self); + pMe = (pBrukerDriv) self->pDriv->pPrivate; + assert(pMe); + + if (argc > 1) { + strtolower(argv[1]); +/*------ polarity */ + if (strcmp(argv[1], "polarity") == 0) { + if (argc > 2) { /* set case */ + strtolower(argv[2]); + if (strcmp(argv[2], "plus") == 0) { + iMode = PPLUS; + } else if (strcmp(argv[2], "minus") == 0) { + iMode = PMINUS; + } else { + sprintf(pBueffel, "ERROR: %s is no knwon polarity mode", + argv[2]); + SCWrite(pCon, pBueffel, eError); + return 0; } -/*-------- control mode */ - else if(strcmp(argv[1],"mode") == 0) - { - if(argc > 2) /* set case */ - { - strtolower(argv[2]); - if(strcmp(argv[2],"field") == 0) - { - iMode = FIELD; - } - else if(strcmp(argv[2],"current") == 0) - { - iMode = CURRENT; - } - else - { - sprintf(pBueffel,"ERROR: %s is no known control mode", argv[2]); - SCWrite(pCon,pBueffel,eError); - return 0; - } - /* check permission */ - if(!SCMatchRights(pCon,usUser)) - { - return 0; - } - /* do it */ - iRet = BrukerSetMode(self,pCon,iMode); - if(iRet) - { - SCSendOK(pCon); - return 1; - } - else - { - return 0; - } - } - else /* get case */ - { - if(pMe->iMode == FIELD) - { - sprintf(pBueffel,"%s.mode = field",argv[0]); - } - else if (pMe->iMode == CURRENT) - { - sprintf(pBueffel,"%s.mode = current",argv[0]); - } - else - { - assert(1); /* programming problem */ - } - SCWrite(pCon,pBueffel,eValue); - return 1; - } + /* check permission */ + if (!SCMatchRights(pCon, usUser)) { + return 0; } + /* do it */ + iRet = BrukerSetPolarity(self, pCon, iMode); + if (iRet) { + SCSendOK(pCon); + return 1; + } else { + return 0; + } + } else { /* get case */ + + iRet = BrukerGetPolarity(self, pCon, &iMode); + if (iRet) { + if (iMode == PPLUS) { + sprintf(pBueffel, "%s.polarity = plus", argv[0]); + } else if (iMode == PMINUS) { + sprintf(pBueffel, "%s.polarity = minus", argv[0]); + } else { + assert(1); /* programming problem */ + } + SCWrite(pCon, pBueffel, eValue); + return 1; + } + } + } +/*-------- control mode */ + else if (strcmp(argv[1], "mode") == 0) { + if (argc > 2) { /* set case */ + strtolower(argv[2]); + if (strcmp(argv[2], "field") == 0) { + iMode = FIELD; + } else if (strcmp(argv[2], "current") == 0) { + iMode = CURRENT; + } else { + sprintf(pBueffel, "ERROR: %s is no known control mode", argv[2]); + SCWrite(pCon, pBueffel, eError); + return 0; + } + /* check permission */ + if (!SCMatchRights(pCon, usUser)) { + return 0; + } + /* do it */ + iRet = BrukerSetMode(self, pCon, iMode); + if (iRet) { + SCSendOK(pCon); + return 1; + } else { + return 0; + } + } else { /* get case */ + + if (pMe->iMode == FIELD) { + sprintf(pBueffel, "%s.mode = field", argv[0]); + } else if (pMe->iMode == CURRENT) { + sprintf(pBueffel, "%s.mode = current", argv[0]); + } else { + assert(1); /* programming problem */ + } + SCWrite(pCon, pBueffel, eValue); + return 1; + } + } /*-----------field */ - else if(strcmp(argv[1],"field") == 0) - { - iRet = BrukerReadField(self,&fVal); - if(!iRet) - { - strcpy(pBueffel,"ERROR: "); - self->pDriv->GetError(self->pDriv,&iMode,pBueffel+7,240); - SCWrite(pCon,pBueffel,eError); - return 0; - } - sprintf(pBueffel,"%s.field = %f Tesla",argv[0],fVal); - SCWrite(pCon,pBueffel,eValue); - return 1; - } + else if (strcmp(argv[1], "field") == 0) { + iRet = BrukerReadField(self, &fVal); + if (!iRet) { + strcpy(pBueffel, "ERROR: "); + self->pDriv->GetError(self->pDriv, &iMode, pBueffel + 7, 240); + SCWrite(pCon, pBueffel, eError); + return 0; + } + sprintf(pBueffel, "%s.field = %f Tesla", argv[0], fVal); + SCWrite(pCon, pBueffel, eValue); + return 1; + } /*----------- current */ - else if(strcmp(argv[1],"current") == 0) - { - iRet = BrukerReadCurrent(self,&fVal); - if(!iRet) - { - strcpy(pBueffel,"ERROR: "); - self->pDriv->GetError(self->pDriv,&iMode,pBueffel+7,240); - SCWrite(pCon,pBueffel,eError); - return 0; - } - sprintf(pBueffel,"%s.current = %f A",argv[0],fVal); - SCWrite(pCon,pBueffel,eValue); - return 1; - } + else if (strcmp(argv[1], "current") == 0) { + iRet = BrukerReadCurrent(self, &fVal); + if (!iRet) { + strcpy(pBueffel, "ERROR: "); + self->pDriv->GetError(self->pDriv, &iMode, pBueffel + 7, 240); + SCWrite(pCon, pBueffel, eError); + return 0; + } + sprintf(pBueffel, "%s.current = %f A", argv[0], fVal); + SCWrite(pCon, pBueffel, eValue); + return 1; + } /*--------- list */ - else if(strcmp(argv[1],"list") == 0) - { - /* print generals first */ - EVControlWrapper(pCon,pSics,pData,argc,argv); - /* print our add on stuff */ - iRet = BrukerReadCurrent(self,&fVal); - if(!iRet) - { - strcpy(pBueffel,"ERROR: "); - self->pDriv->GetError(self->pDriv,&iMode,pBueffel+7,240); - SCWrite(pCon,pBueffel,eError); - } - else - { - sprintf(pBueffel,"%s.current = %f A",argv[0],fVal); - SCWrite(pCon,pBueffel,eValue); - } - iRet = BrukerReadField(self,&fVal); - if(!iRet) - { - strcpy(pBueffel,"ERROR: "); - self->pDriv->GetError(self->pDriv,&iMode,pBueffel+7,240); - SCWrite(pCon,pBueffel,eError); - } - else - { - sprintf(pBueffel,"%s.field = %f Tesla",argv[0],fVal); - SCWrite(pCon,pBueffel,eValue); - } - if(pMe->iMode == FIELD) - { - sprintf(pBueffel,"%s.mode = field",argv[0]); - } - else if (pMe->iMode == CURRENT) - { - sprintf(pBueffel,"%s.mode = current",argv[0]); - } - else - { - sprintf(pBueffel,"ERROR: Programming error"); - } - SCWrite(pCon,pBueffel,eValue); - iRet = BrukerGetPolarity(self,pCon,&iMode); - if(iRet) - { - if(iMode == PPLUS) - { - sprintf(pBueffel,"%s.polarity = plus",argv[0]); - } - else if (iMode == PMINUS) - { - sprintf(pBueffel,"%s.polarity = minus",argv[0]); - } - else if(iMode == PBUSY) - { - sprintf(pBueffel,"%s.polarity = busy",argv[0]); - } - else - { - sprintf(pBueffel,"ERROR: Programming problem"); - } - SCWrite(pCon,pBueffel,eValue); - } - else - { - SCWrite(pCon,"ERROR: cannot read polarity",eError); - } - return 1; - } - else - { - return EVControlWrapper(pCon,pSics,pData,argc,argv); - } - } - return EVControlWrapper(pCon,pSics,pData,argc,argv); + else if (strcmp(argv[1], "list") == 0) { + /* print generals first */ + EVControlWrapper(pCon, pSics, pData, argc, argv); + /* print our add on stuff */ + iRet = BrukerReadCurrent(self, &fVal); + if (!iRet) { + strcpy(pBueffel, "ERROR: "); + self->pDriv->GetError(self->pDriv, &iMode, pBueffel + 7, 240); + SCWrite(pCon, pBueffel, eError); + } else { + sprintf(pBueffel, "%s.current = %f A", argv[0], fVal); + SCWrite(pCon, pBueffel, eValue); + } + iRet = BrukerReadField(self, &fVal); + if (!iRet) { + strcpy(pBueffel, "ERROR: "); + self->pDriv->GetError(self->pDriv, &iMode, pBueffel + 7, 240); + SCWrite(pCon, pBueffel, eError); + } else { + sprintf(pBueffel, "%s.field = %f Tesla", argv[0], fVal); + SCWrite(pCon, pBueffel, eValue); + } + if (pMe->iMode == FIELD) { + sprintf(pBueffel, "%s.mode = field", argv[0]); + } else if (pMe->iMode == CURRENT) { + sprintf(pBueffel, "%s.mode = current", argv[0]); + } else { + sprintf(pBueffel, "ERROR: Programming error"); + } + SCWrite(pCon, pBueffel, eValue); + iRet = BrukerGetPolarity(self, pCon, &iMode); + if (iRet) { + if (iMode == PPLUS) { + sprintf(pBueffel, "%s.polarity = plus", argv[0]); + } else if (iMode == PMINUS) { + sprintf(pBueffel, "%s.polarity = minus", argv[0]); + } else if (iMode == PBUSY) { + sprintf(pBueffel, "%s.polarity = busy", argv[0]); + } else { + sprintf(pBueffel, "ERROR: Programming problem"); + } + SCWrite(pCon, pBueffel, eValue); + } else { + SCWrite(pCon, "ERROR: cannot read polarity", eError); + } + return 1; + } else { + return EVControlWrapper(pCon, pSics, pData, argc, argv); + } } + return EVControlWrapper(pCon, pSics, pData, argc, argv); +} diff --git a/bruker.h b/bruker.h index bfa26a2..8b80f7f 100644 --- a/bruker.h +++ b/bruker.h @@ -14,12 +14,12 @@ #ifndef BRUKERMAGNET #define BRUKERMAGNET - pEVDriver CreateBrukerDriver(int argc, char *argv[]); - - int BrukerReadField(pEVControl self, float *fField); - int BrukerReadCurrent(pEVControl self, float *fCurrent); - - int BrukerAction(SConnection *pCon, SicsInterp *pSics, void *pData, - int argc, char *argv[]); - -#endif +pEVDriver CreateBrukerDriver(int argc, char *argv[]); + +int BrukerReadField(pEVControl self, float *fField); +int BrukerReadCurrent(pEVControl self, float *fCurrent); + +int BrukerAction(SConnection * pCon, SicsInterp * pSics, void *pData, + int argc, char *argv[]); + +#endif diff --git a/buffer.c b/buffer.c index 5b3771a..a71e533 100644 --- a/buffer.c +++ b/buffer.c @@ -49,538 +49,507 @@ #include #include "ruli.h" /*-------------------------------------------------------------------------*/ - static int SaveBuffer(void *pData, char *name, FILE *fd) - { - pRuenBuffer self = NULL; - int iRet; - char *pPtr = NULL; - - assert(fd); - assert(pData); - - self = (pRuenBuffer)pData; - fprintf(fd,"# RuenBuffer %s\n",name); - fprintf(fd,"Buf new %s\n",name); - iRet = LLDnodePtr2First(self->iLineList); - while(iRet != 0) - { - pPtr = (char *)LLDnodePtr(self->iLineList); - fprintf(fd,"%s append %s\n",name,pPtr); - iRet = LLDnodePtr2Next(self->iLineList); - } - return 1; +static int SaveBuffer(void *pData, char *name, FILE * fd) +{ + pRuenBuffer self = NULL; + int iRet; + char *pPtr = NULL; + + assert(fd); + assert(pData); + + self = (pRuenBuffer) pData; + fprintf(fd, "# RuenBuffer %s\n", name); + fprintf(fd, "Buf new %s\n", name); + iRet = LLDnodePtr2First(self->iLineList); + while (iRet != 0) { + pPtr = (char *) LLDnodePtr(self->iLineList); + fprintf(fd, "%s append %s\n", name, pPtr); + iRet = LLDnodePtr2Next(self->iLineList); } + return 1; +} /*--------------------------------------------------------------------------*/ - pRuenBuffer CreateRuenBuffer(char *name) - { - pRuenBuffer pNew = NULL; - - pNew = (pRuenBuffer)malloc(sizeof(RuenBuffer)); - if(!pNew) - { - return NULL; - } - pNew->pDes = CreateDescriptor("SicsRuenBuffer"); - if(!pNew->pDes) - { - free(pNew); - return NULL; - } - - pNew->name = strdup(name); - Fortify_CheckAllMemory(); - pNew->iLineList = LLDblobCreate(); - if(pNew->iLineList == -1) - { - DeleteDescriptor(pNew->pDes); - free(pNew->name); - free(pNew); - return NULL; - } - pNew->pDes->SaveStatus = SaveBuffer; - return pNew; - } -/*--------------------------------------------------------------------------*/ - static void DeleteLineBuffer(int iList) - { - int iRet; - char *pPtr; - - iRet = LLDnodePtr2First(iList); - while(iRet != 0) - { - pPtr = (char *)LLDnodePtr(iList); - free(pPtr); - iRet = LLDnodePtr2Next(iList); - } - LLDdelete(iList); - } -/*-------------------------------------------------------------------------*/ - void DeleteRuenBuffer(void *self) - { - int iRet; - pRuenBuffer pOld = (pRuenBuffer)self; - - assert(pOld); - /* delete line buffer */ - DeleteLineBuffer(pOld->iLineList); - if(pOld->name) - { - free(pOld->name); - } - if(pOld->pDes) - { - DeleteDescriptor(pOld->pDes); - } - free(pOld); - } -/*--------------------------------------------------------------------------*/ - pRuenBuffer CopyRuenBuffer(pRuenBuffer pOld, char *name) - { - pRuenBuffer pNew = NULL; - int iRet; - char *pPtr; - - pNew = CreateRuenBuffer(name); - if(!pNew) - { - return NULL; - } +pRuenBuffer CreateRuenBuffer(char *name) +{ + pRuenBuffer pNew = NULL; + + pNew = (pRuenBuffer) malloc(sizeof(RuenBuffer)); + if (!pNew) { + return NULL; + } + pNew->pDes = CreateDescriptor("SicsRuenBuffer"); + if (!pNew->pDes) { + free(pNew); + return NULL; + } + + pNew->name = strdup(name); + Fortify_CheckAllMemory(); + pNew->iLineList = LLDblobCreate(); + if (pNew->iLineList == -1) { + DeleteDescriptor(pNew->pDes); + free(pNew->name); + free(pNew); + return NULL; + } + pNew->pDes->SaveStatus = SaveBuffer; + return pNew; +} + +/*--------------------------------------------------------------------------*/ +static void DeleteLineBuffer(int iList) +{ + int iRet; + char *pPtr; + + iRet = LLDnodePtr2First(iList); + while (iRet != 0) { + pPtr = (char *) LLDnodePtr(iList); + free(pPtr); + iRet = LLDnodePtr2Next(iList); + } + LLDdelete(iList); +} - /* copy list*/ - iRet = LLDnodePtr2First(pOld->iLineList); - while(iRet != 0) - { - pPtr = (char *)LLDnodePtr(pOld->iLineList); - LLDstringAdd(pNew->iLineList,pPtr); - iRet = LLDnodePtr2Next(pOld->iLineList); - } - return pNew; - } /*-------------------------------------------------------------------------*/ - int BufferAppendLine(pRuenBuffer self, char *line) - { - assert(self); - - return LLDstringAppend(self->iLineList,line); - } -/*------------------------------------------------------------------------*/ - int BufferDel(pRuenBuffer self, int i) - { - int iNum; - int iRet; - - assert(self); - - iRet = LLDnodePtr2First(self->iLineList); - iNum = 0; - while(iRet != 0) - { - if(iNum == i) - { - LLDstringDelete(self->iLineList); - return 1; - } - iNum++; - iRet = LLDnodePtr2Next(self->iLineList); - } - return 0; - } -/*------------------------------------------------------------------------*/ - int BufferInsertAfter(pRuenBuffer self, int i, char *line) - { - int iNum; - int iRet; - - assert(self); - - iRet = LLDnodePtr2First(self->iLineList); - iNum = 0; - while(iRet != 0) - { - if(iNum == i) - { - LLDstringInsert(self->iLineList, line); - return 1; - } - iNum++; - iRet = LLDnodePtr2Next(self->iLineList); - } - return 0; - } -/*------------------------------------------------------------------------*/ - int BufferPrint(pRuenBuffer self, SConnection *pCon) - { - int iRet; - char *pPtr = NULL; - char pBueffel[512]; - int iCount = 1; +void DeleteRuenBuffer(void *self) +{ + int iRet; + pRuenBuffer pOld = (pRuenBuffer) self; - iRet = LLDnodePtr2First(self->iLineList); - sprintf(pBueffel,"Listing for Bueffer %s",self->name); - SCWrite(pCon,pBueffel,eValue); - while(iRet != 0) - { - pPtr = (char *)LLDnodePtr(self->iLineList); - sprintf(pBueffel,"[%d] %s",iCount,pPtr); - SCWrite(pCon,pBueffel,eValue); - iRet = LLDnodePtr2Next(self->iLineList); - iCount++; - } - return 1; - } + assert(pOld); + /* delete line buffer */ + DeleteLineBuffer(pOld->iLineList); + if (pOld->name) { + free(pOld->name); + } + if (pOld->pDes) { + DeleteDescriptor(pOld->pDes); + } + free(pOld); +} + +/*--------------------------------------------------------------------------*/ +pRuenBuffer CopyRuenBuffer(pRuenBuffer pOld, char *name) +{ + pRuenBuffer pNew = NULL; + int iRet; + char *pPtr; + + pNew = CreateRuenBuffer(name); + if (!pNew) { + return NULL; + } + + /* copy list */ + iRet = LLDnodePtr2First(pOld->iLineList); + while (iRet != 0) { + pPtr = (char *) LLDnodePtr(pOld->iLineList); + LLDstringAdd(pNew->iLineList, pPtr); + iRet = LLDnodePtr2Next(pOld->iLineList); + } + return pNew; +} + +/*-------------------------------------------------------------------------*/ +int BufferAppendLine(pRuenBuffer self, char *line) +{ + assert(self); + + return LLDstringAppend(self->iLineList, line); +} /*------------------------------------------------------------------------*/ - extern char *StrReplace(char *str, char *old, char *pNew); +int BufferDel(pRuenBuffer self, int i) +{ + int iNum; + int iRet; + + assert(self); + + iRet = LLDnodePtr2First(self->iLineList); + iNum = 0; + while (iRet != 0) { + if (iNum == i) { + LLDstringDelete(self->iLineList); + return 1; + } + iNum++; + iRet = LLDnodePtr2Next(self->iLineList); + } + return 0; +} + +/*------------------------------------------------------------------------*/ +int BufferInsertAfter(pRuenBuffer self, int i, char *line) +{ + int iNum; + int iRet; + + assert(self); + + iRet = LLDnodePtr2First(self->iLineList); + iNum = 0; + while (iRet != 0) { + if (iNum == i) { + LLDstringInsert(self->iLineList, line); + return 1; + } + iNum++; + iRet = LLDnodePtr2Next(self->iLineList); + } + return 0; +} + +/*------------------------------------------------------------------------*/ +int BufferPrint(pRuenBuffer self, SConnection * pCon) +{ + int iRet; + char *pPtr = NULL; + char pBueffel[512]; + int iCount = 1; + + iRet = LLDnodePtr2First(self->iLineList); + sprintf(pBueffel, "Listing for Bueffer %s", self->name); + SCWrite(pCon, pBueffel, eValue); + while (iRet != 0) { + pPtr = (char *) LLDnodePtr(self->iLineList); + sprintf(pBueffel, "[%d] %s", iCount, pPtr); + SCWrite(pCon, pBueffel, eValue); + iRet = LLDnodePtr2Next(self->iLineList); + iCount++; + } + return 1; +} + +/*------------------------------------------------------------------------*/ +extern char *StrReplace(char *str, char *old, char *pNew); /* realised in Strrepl.c - */ - - int BufferReplace(pRuenBuffer self, char *pattern, char *pReplace) - { - int iRet; - char *pPtr = NULL; - char pBueffel[1024]; - char *pRet; + */ - iRet = LLDnodePtr2First(self->iLineList); - while(iRet != 0) - { - pPtr = (char *)LLDnodePtr(self->iLineList); - strcpy(pBueffel,pPtr); - pRet = NULL; - pRet = StrReplace(pBueffel,pattern,pReplace); - if(pRet) - { - LLDstringDelete(self->iLineList); - iRet = LLDnodePtr2Next(self->iLineList); - LLDnodePtr2Prev(self->iLineList); - if(iRet) - { - LLDstringInsert(self->iLineList,pBueffel); - } - else - { - LLDstringAppend(self->iLineList,pBueffel); - } +int BufferReplace(pRuenBuffer self, char *pattern, char *pReplace) +{ + int iRet; + char *pPtr = NULL; + char pBueffel[1024]; + char *pRet; + + iRet = LLDnodePtr2First(self->iLineList); + while (iRet != 0) { + pPtr = (char *) LLDnodePtr(self->iLineList); + strcpy(pBueffel, pPtr); + pRet = NULL; + pRet = StrReplace(pBueffel, pattern, pReplace); + if (pRet) { + LLDstringDelete(self->iLineList); + iRet = LLDnodePtr2Next(self->iLineList); + LLDnodePtr2Prev(self->iLineList); + if (iRet) { + LLDstringInsert(self->iLineList, pBueffel); + } else { + LLDstringAppend(self->iLineList, pBueffel); } - iRet = LLDnodePtr2Next(self->iLineList); - } - return 1; - } + } + iRet = LLDnodePtr2Next(self->iLineList); + } + return 1; +} + /*-----------------------------------------------------------------------*/ - int BufferRun(pRuenBuffer self, SConnection *pCon, SicsInterp *pSics) - { - int iRet; - char *pPtr = NULL; - int iInt, iRes; - - iRes = 1; - iRet = LLDnodePtr2First(self->iLineList); - while(iRet != 0) - { - pPtr = (char *)LLDnodePtr(self->iLineList); - iInt = InterpExecute(pSics,pCon,pPtr); - if(!iInt) - { - if(SCGetInterrupt(pCon) > eAbortBatch) { - iRes = 0; - break; - } - } - iRet = LLDnodePtr2Next(self->iLineList); - } - return iRes; - } -/*------------------------------------------------------------------------*/ - int BufferSave(pRuenBuffer self, char *file) - { - int iRet; - char *pPtr = NULL; - FILE *fd = NULL; +int BufferRun(pRuenBuffer self, SConnection * pCon, SicsInterp * pSics) +{ + int iRet; + char *pPtr = NULL; + int iInt, iRes; - fd = fopen(file,"w"); - if(fd == NULL) - { - return 0; - } - iRet = LLDnodePtr2First(self->iLineList); - while(iRet != 0) - { - pPtr = (char *)LLDnodePtr(self->iLineList); - fprintf(fd,"%s\n",pPtr); - iRet = LLDnodePtr2Next(self->iLineList); - } - fclose(fd); - return 1; - } -/*------------------------------------------------------------------------*/ - int BufferLoad(pRuenBuffer self, char *file) - { - int iRet; - char *pPtr = NULL; - FILE *fd = NULL; - char pBueffel[256]; + iRes = 1; + iRet = LLDnodePtr2First(self->iLineList); + while (iRet != 0) { + pPtr = (char *) LLDnodePtr(self->iLineList); + iInt = InterpExecute(pSics, pCon, pPtr); + if (!iInt) { + if (SCGetInterrupt(pCon) > eAbortBatch) { + iRes = 0; + break; + } + } + iRet = LLDnodePtr2Next(self->iLineList); + } + return iRes; +} - fd = fopen(file,"r"); - if(fd == NULL) - { - return 0; - } - - pPtr = fgets(pBueffel,255,fd); - while(pPtr != NULL) - { - LLDstringAppend(self->iLineList,pBueffel); - pPtr = fgets(pBueffel,255,fd); - } - - fclose(fd); - return 1; - } - /*------------------------------------------------------------------------*/ - pRuenBuffer FindRuenBuffer(SicsInterp *pSics, char *name) - { - pRuenBuffer pBuf = NULL; - CommandList *pCom = NULL; - - pCom = FindCommand(pSics,name); - if(!pCom) - { - return NULL; - } - pBuf = (pRuenBuffer)pCom->pData; - if(!pBuf) - { - return NULL; - } - if(!pBuf->pDes) - { - return NULL; - } - if(strcmp(pBuf->pDes->name,"SicsRuenBuffer") != 0) - { - return NULL; - } - return pBuf; - } +int BufferSave(pRuenBuffer self, char *file) +{ + int iRet; + char *pPtr = NULL; + FILE *fd = NULL; + + fd = fopen(file, "w"); + if (fd == NULL) { + return 0; + } + iRet = LLDnodePtr2First(self->iLineList); + while (iRet != 0) { + pPtr = (char *) LLDnodePtr(self->iLineList); + fprintf(fd, "%s\n", pPtr); + iRet = LLDnodePtr2Next(self->iLineList); + } + fclose(fd); + return 1; +} + +/*------------------------------------------------------------------------*/ +int BufferLoad(pRuenBuffer self, char *file) +{ + int iRet; + char *pPtr = NULL; + FILE *fd = NULL; + char pBueffel[256]; + + fd = fopen(file, "r"); + if (fd == NULL) { + return 0; + } + + pPtr = fgets(pBueffel, 255, fd); + while (pPtr != NULL) { + LLDstringAppend(self->iLineList, pBueffel); + pPtr = fgets(pBueffel, 255, fd); + } + + fclose(fd); + return 1; +} + +/*------------------------------------------------------------------------*/ +pRuenBuffer FindRuenBuffer(SicsInterp * pSics, char *name) +{ + pRuenBuffer pBuf = NULL; + CommandList *pCom = NULL; + + pCom = FindCommand(pSics, name); + if (!pCom) { + return NULL; + } + pBuf = (pRuenBuffer) pCom->pData; + if (!pBuf) { + return NULL; + } + if (!pBuf->pDes) { + return NULL; + } + if (strcmp(pBuf->pDes->name, "SicsRuenBuffer") != 0) { + return NULL; + } + return pBuf; +} + /*-------------------------------------------------------------------------*/ - int InitBufferSys(SConnection *pCon, SicsInterp *pSics, void *pData, - int argc, char *argv[]) - { - pRuenStack pStack = NULL; +int InitBufferSys(SConnection * pCon, SicsInterp * pSics, void *pData, + int argc, char *argv[]) +{ + pRuenStack pStack = NULL; + + pStack = CreateRuenStack(); + if (!pStack) { + SCWrite(pCon, "ERROR: No memory to create Ruen-Stack", eError); + return 0; + } + AddCommand(pSics, "Buf", BufferCommand, NULL, NULL); + AddCommand(pSics, "Stack", RuenStackAction, DeleteRuenStack, pStack); + return 1; +} - pStack = CreateRuenStack(); - if(!pStack) - { - SCWrite(pCon,"ERROR: No memory to create Ruen-Stack",eError); - return 0; - } - AddCommand(pSics,"Buf",BufferCommand,NULL,NULL); - AddCommand(pSics,"Stack",RuenStackAction,DeleteRuenStack,pStack); - return 1; - } /*------------------------------------------------------------------------*/ - int BufferCommand(SConnection *pCon, SicsInterp *pSics, void *pData, - int argc, char *argv[]) - { - int iRet, iRet2; - char pBueffel[512]; - char **argx; - FuPaResult PaRes; - pRuenBuffer pBuf = NULL; - FuncTemplate BufferTemplate[] = { - {"new",1,{FUPATEXT} }, - {"del",1,{FUPATEXT} }, - {"copy",2,{FUPATEXT, FUPATEXT}}, - }; +int BufferCommand(SConnection * pCon, SicsInterp * pSics, void *pData, + int argc, char *argv[]) +{ + int iRet, iRet2; + char pBueffel[512]; + char **argx; + FuPaResult PaRes; + pRuenBuffer pBuf = NULL; + FuncTemplate BufferTemplate[] = { + {"new", 1, {FUPATEXT}}, + {"del", 1, {FUPATEXT}}, + {"copy", 2, {FUPATEXT, FUPATEXT}}, + }; - assert(pCon); - assert(pSics); - - /* minimum user to use this */ - if(!SCMatchRights(pCon,usUser)) - { - return 0; - } - /* parse function args */ - argtolower(argc,argv); - argx = &argv[1]; - iRet = EvaluateFuPa((pFuncTemplate)&BufferTemplate,3,argc-1,argx,&PaRes); - if(iRet < 0) - { - sprintf(pBueffel,"%s",PaRes.pError); - SCWrite(pCon,pBueffel,eError); + assert(pCon); + assert(pSics); + + /* minimum user to use this */ + if (!SCMatchRights(pCon, usUser)) { + return 0; + } + /* parse function args */ + argtolower(argc, argv); + argx = &argv[1]; + iRet = + EvaluateFuPa((pFuncTemplate) & BufferTemplate, 3, argc - 1, argx, + &PaRes); + if (iRet < 0) { + sprintf(pBueffel, "%s", PaRes.pError); + SCWrite(pCon, pBueffel, eError); + return 0; + } + + switch (iRet) { + case 0: /* new */ + pBuf = CreateRuenBuffer(PaRes.Arg[0].text); + if (!pBuf) { + SCWrite(pCon, "ERROR: Out of memory allocating buffer", eError); return 0; - } - - switch(iRet) - { - case 0: /* new */ - pBuf = CreateRuenBuffer(PaRes.Arg[0].text); - if(!pBuf) - { - SCWrite(pCon, "ERROR: Out of memory allocating buffer",eError); - return 0; - } - iRet2 = AddCommand(pSics,pBuf->name,BufferAction,DeleteRuenBuffer, - (void *)pBuf); - if(!iRet2) - { - sprintf(pBueffel,"ERROR: duplicate command %s not created",pBuf->name); - SCWrite(pCon,pBueffel,eError); - DeleteRuenBuffer((void *)pBuf); - return 0; - } - return 1; - break; - case 1: /* del */ - return RemoveCommand(pSics,PaRes.Arg[0].text); - break; - case 2: /* copy */ - pBuf = FindRuenBuffer(pSics,PaRes.Arg[0].text); - if(!pBuf) - { - sprintf(pBueffel,"ERROR: Buffer %s not found", - PaRes.Arg[0].text); - SCWrite(pCon,pBueffel,eError); - return 0; - } - pBuf = CopyRuenBuffer(pBuf,PaRes.Arg[1].text); - if(!pBuf) - { - sprintf(pBueffel,"ERROR: creating buffer %s ", - PaRes.Arg[1].text); - SCWrite(pCon,pBueffel,eError); - return 0; - } - iRet2 = AddCommand(pSics,pBuf->name,BufferAction,DeleteRuenBuffer, - (void *)pBuf); - if(!iRet2) - { - sprintf(pBueffel,"ERROR: duplicate command %s not created",pBuf->name); - SCWrite(pCon,pBueffel,eError); - DeleteRuenBuffer((void *)pBuf); - return 0; - } + } + iRet2 = AddCommand(pSics, pBuf->name, BufferAction, DeleteRuenBuffer, + (void *) pBuf); + if (!iRet2) { + sprintf(pBueffel, "ERROR: duplicate command %s not created", + pBuf->name); + SCWrite(pCon, pBueffel, eError); + DeleteRuenBuffer((void *) pBuf); + return 0; + } + return 1; + break; + case 1: /* del */ + return RemoveCommand(pSics, PaRes.Arg[0].text); + break; + case 2: /* copy */ + pBuf = FindRuenBuffer(pSics, PaRes.Arg[0].text); + if (!pBuf) { + sprintf(pBueffel, "ERROR: Buffer %s not found", PaRes.Arg[0].text); + SCWrite(pCon, pBueffel, eError); + return 0; + } + pBuf = CopyRuenBuffer(pBuf, PaRes.Arg[1].text); + if (!pBuf) { + sprintf(pBueffel, "ERROR: creating buffer %s ", PaRes.Arg[1].text); + SCWrite(pCon, pBueffel, eError); + return 0; + } + iRet2 = AddCommand(pSics, pBuf->name, BufferAction, DeleteRuenBuffer, + (void *) pBuf); + if (!iRet2) { + sprintf(pBueffel, "ERROR: duplicate command %s not created", + pBuf->name); + SCWrite(pCon, pBueffel, eError); + DeleteRuenBuffer((void *) pBuf); + return 0; + } + + return 1; + break; + default: + assert(0); + break; + + } + assert(0); +} - return 1; - break; - default: - assert(0); - break; - - } - assert(0); - } /*-------------------------------------------------------------------------*/ - int BufferAction(SConnection *pCon, SicsInterp *pSics, void *pData, - int argc, char *argv[]) - { - int iRet, iRet2; - char pBueffel[512]; - char **argx; - FuPaResult PaRes; - pRuenBuffer pBuf = NULL; - FuncTemplate BufferTemplate[] = { - {"append",0,{FUPATEXT} }, - {"del",1,{FUPAINT} }, - {"ins",1,{FUPAINT}}, - {"save",1,{FUPATEXT}}, - {"load",1,{FUPATEXT}}, - {"subst",2,{FUPATEXT,FUPATEXT}}, - {"print",0,{0,0}}, - {"run",0,{0,0}} - }; +int BufferAction(SConnection * pCon, SicsInterp * pSics, void *pData, + int argc, char *argv[]) +{ + int iRet, iRet2; + char pBueffel[512]; + char **argx; + FuPaResult PaRes; + pRuenBuffer pBuf = NULL; + FuncTemplate BufferTemplate[] = { + {"append", 0, {FUPATEXT}}, + {"del", 1, {FUPAINT}}, + {"ins", 1, {FUPAINT}}, + {"save", 1, {FUPATEXT}}, + {"load", 1, {FUPATEXT}}, + {"subst", 2, {FUPATEXT, FUPATEXT}}, + {"print", 0, {0, 0}}, + {"run", 0, {0, 0}} + }; - assert(pCon); - assert(pSics); - pBuf = (pRuenBuffer)pData; - assert(pBuf); - - - /* You need to be user in order to do this */ - if(!SCMatchRights(pCon,usUser)) - { - return 0; - } - /* parse function args */ - argx = &argv[1]; - strtolower(argx[0]); - iRet = EvaluateFuPa((pFuncTemplate)&BufferTemplate,8,argc-1,argx,&PaRes); - if(iRet < 0) - { - sprintf(pBueffel,"%s",PaRes.pError); - SCWrite(pCon,pBueffel,eError); + assert(pCon); + assert(pSics); + pBuf = (pRuenBuffer) pData; + assert(pBuf); + + + /* You need to be user in order to do this */ + if (!SCMatchRights(pCon, usUser)) { + return 0; + } + /* parse function args */ + argx = &argv[1]; + strtolower(argx[0]); + iRet = + EvaluateFuPa((pFuncTemplate) & BufferTemplate, 8, argc - 1, argx, + &PaRes); + if (iRet < 0) { + sprintf(pBueffel, "%s", PaRes.pError); + SCWrite(pCon, pBueffel, eError); + return 0; + } + + switch (iRet) { + case 0: /* append */ + argx = &argv[2]; + Arg2Text(argc - 2, argx, pBueffel, 511); + BufferAppendLine(pBuf, pBueffel); + SCSendOK(pCon); + return 1; + break; + case 1: /* del */ + iRet2 = BufferDel(pBuf, PaRes.Arg[0].iVal); + if (iRet2) + SCSendOK(pCon); + break; + case 2: /* ins */ + argx = &argv[3]; + Arg2Text(argc - 3, argx, pBueffel, 511); + iRet2 = BufferInsertAfter(pBuf, PaRes.Arg[0].iVal, pBueffel); + if (iRet2) + SCSendOK(pCon); + return iRet2; + break; + case 3: /* save */ + iRet2 = BufferSave(pBuf, PaRes.Arg[0].text); + if (!iRet2) { + sprintf(pBueffel, "ERROR: cannot open %s for writing", + PaRes.Arg[0].text); + SCWrite(pCon, pBueffel, eError); return 0; - } - - switch(iRet) - { - case 0: /* append */ - argx = &argv[2]; - Arg2Text(argc-2,argx,pBueffel,511); - BufferAppendLine(pBuf,pBueffel); - SCSendOK(pCon); - return 1; - break; - case 1: /* del */ - iRet2 = BufferDel(pBuf,PaRes.Arg[0].iVal); - if(iRet2) - SCSendOK(pCon); - break; - case 2: /* ins */ - argx = &argv[3]; - Arg2Text(argc-3,argx,pBueffel,511); - iRet2 = BufferInsertAfter(pBuf,PaRes.Arg[0].iVal,pBueffel); - if(iRet2) - SCSendOK(pCon); - return iRet2; - break; - case 3: /* save */ - iRet2 = BufferSave(pBuf,PaRes.Arg[0].text); - if(!iRet2) - { - sprintf(pBueffel,"ERROR: cannot open %s for writing", - PaRes.Arg[0].text); - SCWrite(pCon,pBueffel,eError); - return 0; - } - else - { - SCSendOK(pCon); - return 1; - } - break; - case 4: /* load */ - iRet2 = BufferLoad(pBuf,PaRes.Arg[0].text); - if(!iRet2) - { - sprintf(pBueffel,"ERROR: cannot open %s for reading ", - PaRes.Arg[0].text); - SCWrite(pCon,pBueffel,eError); - return 0; - } - else - { - SCSendOK(pCon); - return 1; - } - break; - case 5: /* subst */ - iRet2 = BufferReplace(pBuf,PaRes.Arg[0].text,PaRes.Arg[1].text); - if(iRet2) - SCSendOK(pCon); - break; - case 6: /* print */ - return BufferPrint(pBuf,pCon); - break; - case 7: /* run */ - return BufferRun(pBuf,pCon,pSics); - default: - assert(0); - } - return 1; - } - + } else { + SCSendOK(pCon); + return 1; + } + break; + case 4: /* load */ + iRet2 = BufferLoad(pBuf, PaRes.Arg[0].text); + if (!iRet2) { + sprintf(pBueffel, "ERROR: cannot open %s for reading ", + PaRes.Arg[0].text); + SCWrite(pCon, pBueffel, eError); + return 0; + } else { + SCSendOK(pCon); + return 1; + } + break; + case 5: /* subst */ + iRet2 = BufferReplace(pBuf, PaRes.Arg[0].text, PaRes.Arg[1].text); + if (iRet2) + SCSendOK(pCon); + break; + case 6: /* print */ + return BufferPrint(pBuf, pCon); + break; + case 7: /* run */ + return BufferRun(pBuf, pCon, pSics); + default: + assert(0); + } + return 1; +} diff --git a/buffer.h b/buffer.h index d83d4fc..c421200 100644 --- a/buffer.h +++ b/buffer.h @@ -28,69 +28,69 @@ #include - typedef struct { - pObjectDescriptor pDes; /* needed */ - char *name; /* BufferName */ - int iLineList; /* Handle to the Line List */ - } RuenBuffer, *pRuenBuffer; - -/*--------------------- live & death ----------------------------------- */ - pRuenBuffer CreateRuenBuffer(char *name); - void DeleteRuenBuffer(void *pSelf); - pRuenBuffer CopyRuenBuffer(pRuenBuffer pOld, char *NewName); - +typedef struct { + pObjectDescriptor pDes; /* needed */ + char *name; /* BufferName */ + int iLineList; /* Handle to the Line List */ +} RuenBuffer, *pRuenBuffer; + +/*--------------------- live & death ----------------------------------- */ +pRuenBuffer CreateRuenBuffer(char *name); +void DeleteRuenBuffer(void *pSelf); +pRuenBuffer CopyRuenBuffer(pRuenBuffer pOld, char *NewName); + /*--------------------- operations --------------------------------------*/ - int BufferAppendLine(pRuenBuffer self, char *line); - int BufferDel(pRuenBuffer self, int iLine); +int BufferAppendLine(pRuenBuffer self, char *line); +int BufferDel(pRuenBuffer self, int iLine); /* deletes line iLine from the RuenBuffer self - --------------------------------------------------------------------------*/ - int BufferInsertAfter(pRuenBuffer self, int iLine, char *line); + + ------------------------------------------------------------------------- */ +int BufferInsertAfter(pRuenBuffer self, int iLine, char *line); /* inserts line line AFTER line number iLine in the RuenBuffer self -------------------------------------------------------------------------- */ - int BufferPrint(pRuenBuffer self, SConnection *pCon); + ------------------------------------------------------------------------- */ +int BufferPrint(pRuenBuffer self, SConnection * pCon); /* - lists the contents of the RuenBuffer on the Connection pCon ------------------------------------------------------------------------- */ - int BufferReplace(pRuenBuffer self, char *pattern, char *pReplace); + lists the contents of the RuenBuffer on the Connection pCon + ------------------------------------------------------------------------ */ +int BufferReplace(pRuenBuffer self, char *pattern, char *pReplace); /* - replaces all occurences of the string pattern in the whole RuenBuffer - by the replacement string pReplace. -------------------------------------------------------------------------- */ - int BufferRun(pRuenBuffer self, SConnection *pCon, SicsInterp *pSics); + replaces all occurences of the string pattern in the whole RuenBuffer + by the replacement string pReplace. + ------------------------------------------------------------------------- */ +int BufferRun(pRuenBuffer self, SConnection * pCon, SicsInterp * pSics); /* executes the lines of the Ruenbuffer one by one. Returns 1 on success, 0 on error. -------------------------------------------------------------------------- */ - int BufferSave(pRuenBuffer self, char *file); + ------------------------------------------------------------------------- */ +int BufferSave(pRuenBuffer self, char *file); /* - writes the contents of Ruenbuffer self to the file specified by - file. + writes the contents of Ruenbuffer self to the file specified by + file. Returns 1 on success, 0 on error. ---------------------------------------------------------------------------*/ - int BufferLoad(pRuenBuffer self, char *file); + -------------------------------------------------------------------------- */ +int BufferLoad(pRuenBuffer self, char *file); /* - reads the contents of file into the RuenBuffer self. + reads the contents of file into the RuenBuffer self. Returns 1 on success, 0 on error. - */ + */ /* ------------------------ object functions ----------------------------*/ - int InitBufferSys(SConnection *pCon, SicsInterp *pSics, void *pData, - int argc, char *argv[]); - int BufferCommand(SConnection *pCon, SicsInterp *pSics, void *pData, - int argc, char *argv[]); - int BufferAction(SConnection *pCon, SicsInterp *pSics, void *pData, - int argc, char *argv[]); - +int InitBufferSys(SConnection * pCon, SicsInterp * pSics, void *pData, + int argc, char *argv[]); +int BufferCommand(SConnection * pCon, SicsInterp * pSics, void *pData, + int argc, char *argv[]); +int BufferAction(SConnection * pCon, SicsInterp * pSics, void *pData, + int argc, char *argv[]); + /* ----------------------- utility --------------------------------------*/ - pRuenBuffer FindRuenBuffer(SicsInterp *pSics, char *name); +pRuenBuffer FindRuenBuffer(SicsInterp * pSics, char *name); /* similar to FindCommand in SCinter.h. But checks the object found if it is a RuenBuffer. Returns NULL if no RuenBuffer with this name could be found. Returns a pointer to the RuenBuffer, when a RuenBuffer of this name could be found in the interpreter pSics -----------------------------------------------------------------------------*/ -#endif + ---------------------------------------------------------------------------- */ +#endif diff --git a/delcam.c b/delcam.c index fae3550..5b5f6c3 100644 --- a/delcam.c +++ b/delcam.c @@ -40,17 +40,17 @@ /* Time in ms to activate shutter before/after exposure */ #define SHUTTER_DELAY 200 /*=================== DaDa Structure =========================*/ -typedef struct { - AUD_HANDLE aud_handle; - int amplictrl; - int shutterctrl; - int nClear; - int running; - int error; - int schnarch; - int width, height; - pCounter count; - }Delcam, *pDelcam; +typedef struct { + AUD_HANDLE aud_handle; + int amplictrl; + int shutterctrl; + int nClear; + int running; + int error; + int schnarch; + int width, height; + pCounter count; +} Delcam, *pDelcam; /*====================== codes =============================================*/ #define NOBEAM -120 #define FAULT -121 @@ -58,444 +58,475 @@ typedef struct { Configures the HM from the options in pOpt and the HM data structure Returns 1 on success, 0 on failure ---------------------------------------------------------------------*/ -static int DelcamConfigure(pHistDriver self, SConnection *pCon, - pStringDict pOpt, SicsInterp *pSics){ - pDelcam pPriv = NULL; - char buffer[80]; - int status, w, h; - - pPriv =(pDelcam)self->pPriv; +static int DelcamConfigure(pHistDriver self, SConnection * pCon, + pStringDict pOpt, SicsInterp * pSics) +{ + pDelcam pPriv = NULL; + char buffer[80]; + int status, w, h; - if(StringDictGet(pOpt,"amplictrl",buffer, 79) == 1){ - pPriv->amplictrl = atoi(buffer); - } else { - pPriv->amplictrl = 0; - } - if(pPriv->amplictrl < 0 || pPriv->amplictrl > 8){ - SCWrite(pCon,"ERROR: invalid amplictrl value, range 0 - 8",eError); - pPriv->amplictrl = 0; - } - if(StringDictGet(pOpt,"shutterctrl",buffer, 79) == 1){ - pPriv->shutterctrl = atoi(buffer); - } else { - pPriv->shutterctrl = 0; - } - if(StringDictGet(pOpt,"clear",buffer, 79) == 1){ - pPriv->nClear = atoi(buffer); - } else { - pPriv->nClear = 1; - } - if(StringDictGet(pOpt,"schnarch",buffer, 79) == 1){ - pPriv->schnarch = atoi(buffer); - } else { - pPriv->schnarch = 1; - } - if(StringDictGet(pOpt,"counter",buffer, 79) == 1){ - pPriv->count = (pCounter)FindCommandData(pServ->pSics, - buffer, "SingleCounter"); - } - if(pPriv->count == NULL){ - SCWrite(pCon,"ERROR: no slave counter configured: need it desperatly!", + pPriv = (pDelcam) self->pPriv; + + if (StringDictGet(pOpt, "amplictrl", buffer, 79) == 1) { + pPriv->amplictrl = atoi(buffer); + } else { + pPriv->amplictrl = 0; + } + if (pPriv->amplictrl < 0 || pPriv->amplictrl > 8) { + SCWrite(pCon, "ERROR: invalid amplictrl value, range 0 - 8", eError); + pPriv->amplictrl = 0; + } + if (StringDictGet(pOpt, "shutterctrl", buffer, 79) == 1) { + pPriv->shutterctrl = atoi(buffer); + } else { + pPriv->shutterctrl = 0; + } + if (StringDictGet(pOpt, "clear", buffer, 79) == 1) { + pPriv->nClear = atoi(buffer); + } else { + pPriv->nClear = 1; + } + if (StringDictGet(pOpt, "schnarch", buffer, 79) == 1) { + pPriv->schnarch = atoi(buffer); + } else { + pPriv->schnarch = 1; + } + if (StringDictGet(pOpt, "counter", buffer, 79) == 1) { + pPriv->count = (pCounter) FindCommandData(pServ->pSics, + buffer, "SingleCounter"); + } + if (pPriv->count == NULL) { + SCWrite(pCon, + "ERROR: no slave counter configured: need it desperatly!", eError); - return 0; + return 0; + } + pPriv->running = 0; + if (pPriv->aud_handle == NULL) { + pPriv->aud_handle = aud_open(); + if (pPriv->aud_handle == NULL) { + SCWrite(pCon, "ERROR: failed to open DELCam", eError); + return 0; } - pPriv->running = 0; - if(pPriv->aud_handle == NULL){ - pPriv->aud_handle = aud_open(); - if(pPriv->aud_handle == NULL){ - SCWrite(pCon,"ERROR: failed to open DELCam", eError); - return 0; - } - } - status = aud_geometry_get(pPriv->aud_handle, 0, 0, &w, &h,0); - if(status != 0) { - snprintf(buffer,80,"ERROR: errno %d while trying to read geometry", - errno); - SCWrite(pCon,buffer,eError); - return 0; - } - sprintf(buffer,"%d",w); - StringDictUpdate(self->pOption,"dim0",buffer); - sprintf(buffer,"%d",h); - StringDictUpdate(self->pOption,"dim1",buffer); - configureHMdata(self->data,self->pOption,pCon); - if(!resizeBuffer(self->data)) { - SCWrite(pCon,"ERROR: out of memory allocating HMData for DELCam",eError); - return 0; - } - pPriv->width = w; - pPriv->height = h; - - return 1; + } + status = aud_geometry_get(pPriv->aud_handle, 0, 0, &w, &h, 0); + if (status != 0) { + snprintf(buffer, 80, "ERROR: errno %d while trying to read geometry", + errno); + SCWrite(pCon, buffer, eError); + return 0; + } + sprintf(buffer, "%d", w); + StringDictUpdate(self->pOption, "dim0", buffer); + sprintf(buffer, "%d", h); + StringDictUpdate(self->pOption, "dim1", buffer); + configureHMdata(self->data, self->pOption, pCon); + if (!resizeBuffer(self->data)) { + SCWrite(pCon, "ERROR: out of memory allocating HMData for DELCam", + eError); + return 0; + } + pPriv->width = w; + pPriv->height = h; + + return 1; } + /*-------------------------------------------------------------------- Start histogramming, Returns HWFault on failure, 1 on success ----------------------------------------------------------------------*/ -static int DelcamStart(pHistDriver self,SConnection *pCon){ - pDelcam pPriv = NULL; - int status, i; - char buffer[80]; +static int DelcamStart(pHistDriver self, SConnection * pCon) +{ + pDelcam pPriv = NULL; + int status, i; + char buffer[80]; - pPriv =(pDelcam)self->pPriv; - - /* - * configure counter - */ - if(self->eCount != eTimer){ - SCWrite(pCon,"WARNING: bad count mode switched to preset time", + pPriv = (pDelcam) self->pPriv; + + /* + * configure counter + */ + if (self->eCount != eTimer) { + SCWrite(pCon, "WARNING: bad count mode switched to preset time", eWarning); - } - SetCounterMode(pPriv->count, eTimer); - SetCounterPreset(pPriv->count,self->fCountPreset); - - /* - * deal with amplifier - */ - if(pPriv->amplictrl |= 0){ - status = aud_amplifier_ctrl_set (pPriv->aud_handle, pPriv->amplictrl); - if(status != 0){ - snprintf(buffer,80,"ERROR: failed to set amplifier, errno = %d", - errno); - SCWrite(pCon,buffer,eError); - pPriv->error = FAULT; - return HWFault; - } - } - status = aud_amplifier_set(pPriv->aud_handle, 0); - if(status != 0){ - snprintf(buffer,80,"ERROR: failed to start amplifier, errno = %d", - errno); - SCWrite(pCon,buffer,eError); - pPriv->error = FAULT; - return HWFault; - } - usleep(AMPLIFIER_DELAY*1000); + } + SetCounterMode(pPriv->count, eTimer); + SetCounterPreset(pPriv->count, self->fCountPreset); - /* - * deal with shutter - */ - if(pPriv->shutterctrl |= 0){ - status = aud_shutter_ctrl_set (pPriv->aud_handle, pPriv->shutterctrl); - if(status != 0){ - snprintf(buffer,80,"ERROR: failed to set shutterctrl, errno = %d", - errno); - SCWrite(pCon,buffer,eError); - pPriv->error = FAULT; - return HWFault; - } - status = aud_shutter_set(pPriv->aud_handle, 1); - if(status != 0){ - snprintf(buffer,80,"ERROR: failed to start shutter, errno = %d", - errno); - SCWrite(pCon,buffer,eError); - pPriv->error = FAULT; - return HWFault; - } - usleep(SHUTTER_DELAY*1000); + /* + * deal with amplifier + */ + if (pPriv->amplictrl |= 0) { + status = aud_amplifier_ctrl_set(pPriv->aud_handle, pPriv->amplictrl); + if (status != 0) { + snprintf(buffer, 80, "ERROR: failed to set amplifier, errno = %d", + errno); + SCWrite(pCon, buffer, eError); + pPriv->error = FAULT; + return HWFault; } - - /* - * clear - */ - status = aud_clear(pPriv->aud_handle, pPriv->nClear); - if(status != 0){ - snprintf(buffer,80,"ERROR: failed to clear CCD, errno = %d", - errno); - SCWrite(pCon,buffer,eError); - pPriv->error = FAULT; - return HWFault; + } + status = aud_amplifier_set(pPriv->aud_handle, 0); + if (status != 0) { + snprintf(buffer, 80, "ERROR: failed to start amplifier, errno = %d", + errno); + SCWrite(pCon, buffer, eError); + pPriv->error = FAULT; + return HWFault; + } + usleep(AMPLIFIER_DELAY * 1000); + + /* + * deal with shutter + */ + if (pPriv->shutterctrl |= 0) { + status = aud_shutter_ctrl_set(pPriv->aud_handle, pPriv->shutterctrl); + if (status != 0) { + snprintf(buffer, 80, "ERROR: failed to set shutterctrl, errno = %d", + errno); + SCWrite(pCon, buffer, eError); + pPriv->error = FAULT; + return HWFault; } - - pPriv->running = 1; - clearHMData(self->data); - return pPriv->count->pDriv->Start(pPriv->count->pDriv); + status = aud_shutter_set(pPriv->aud_handle, 1); + if (status != 0) { + snprintf(buffer, 80, "ERROR: failed to start shutter, errno = %d", + errno); + SCWrite(pCon, buffer, eError); + pPriv->error = FAULT; + return HWFault; + } + usleep(SHUTTER_DELAY * 1000); + } + + /* + * clear + */ + status = aud_clear(pPriv->aud_handle, pPriv->nClear); + if (status != 0) { + snprintf(buffer, 80, "ERROR: failed to clear CCD, errno = %d", errno); + SCWrite(pCon, buffer, eError); + pPriv->error = FAULT; + return HWFault; + } + + pPriv->running = 1; + clearHMData(self->data); + return pPriv->count->pDriv->Start(pPriv->count->pDriv); } + /*-------------------------------------------------------------------- Stops histogramming, Returns HWFault on failure, 1 on success ----------------------------------------------------------------------*/ -static int DelcamHalt(pHistDriver self){ - pDelcam pPriv = NULL; - - pPriv =(pDelcam)self->pPriv; - return pPriv->count->pDriv->Halt(pPriv->count->pDriv); +static int DelcamHalt(pHistDriver self) +{ + pDelcam pPriv = NULL; + + pPriv = (pDelcam) self->pPriv; + return pPriv->count->pDriv->Halt(pPriv->count->pDriv); } + /*-------------------------------------------------------------------- Checks histogramming status, Returns HWFault on failure, HWIdle when finished, HWBusy when counting ----------------------------------------------------------------------*/ -static int DelcamCountStatus(pHistDriver self,SConnection *pCon){ - pDelcam pPriv = NULL; - int status, color, imSize = 0, i; - float val; - char buffer[80]; - unsigned short *imData = NULL; - char *shittyCompiler = NULL; - - pPriv =(pDelcam)self->pPriv; - - status = pPriv->count->pDriv->GetStatus(pPriv->count->pDriv,&val); - if(status == HWNoBeam) { - /* - SCWrite(pCon,"WARNING: NO BEAM, during CCD measurement",eWarning); - DelcamHalt(self); - pPriv->error = NOBEAM; +static int DelcamCountStatus(pHistDriver self, SConnection * pCon) +{ + pDelcam pPriv = NULL; + int status, color, imSize = 0, i; + float val; + char buffer[80]; + unsigned short *imData = NULL; + char *shittyCompiler = NULL; + + pPriv = (pDelcam) self->pPriv; + + status = pPriv->count->pDriv->GetStatus(pPriv->count->pDriv, &val); + if (status == HWNoBeam) { + /* + SCWrite(pCon,"WARNING: NO BEAM, during CCD measurement",eWarning); + DelcamHalt(self); + pPriv->error = NOBEAM; + status = HWFault; + */ + return HWBusy; + } + if (status != HWBusy && pPriv->running == 1) { + pPriv->running = 0; + /* + * stop the CCD and transfer data + */ + if (pPriv->shutterctrl |= 0) { + status = aud_shutter_set(pPriv->aud_handle, 0); + if (status != 0) { + snprintf(buffer, 80, "ERROR: failed to close shutter, errno = %d", + errno); + SCWrite(pCon, buffer, eError); + pPriv->error = FAULT; status = HWFault; - */ - return HWBusy; + } + usleep(SHUTTER_DELAY * 1000); } - if(status != HWBusy && pPriv->running == 1) { - pPriv->running = 0; - /* - * stop the CCD and transfer data - */ - if(pPriv->shutterctrl |= 0){ - status = aud_shutter_set(pPriv->aud_handle, 0); - if(status != 0){ - snprintf(buffer,80,"ERROR: failed to close shutter, errno = %d", - errno); - SCWrite(pCon,buffer,eError); - pPriv->error = FAULT; - status = HWFault; - } - usleep(SHUTTER_DELAY*1000); - } - status = aud_amplifier_set(pPriv->aud_handle, 1); - if(status != 0){ - snprintf(buffer,80,"ERROR: failed to stop amplifier, errno = %d", - errno); - SCWrite(pCon,buffer,eError); - pPriv->error = FAULT; - status = HWFault; - } - /* usleep(AMPLIFIER_DELAY*1000); */ + status = aud_amplifier_set(pPriv->aud_handle, 1); + if (status != 0) { + snprintf(buffer, 80, "ERROR: failed to stop amplifier, errno = %d", + errno); + SCWrite(pCon, buffer, eError); + pPriv->error = FAULT; + status = HWFault; + } + /* usleep(AMPLIFIER_DELAY*1000); */ - usleep(pPriv->schnarch*1000); + usleep(pPriv->schnarch * 1000); - SCWrite(pCon, + SCWrite(pCon, "WARNING: computer freeze for ~15 sec is normal during readout", - eWarning); - - status = aud_image_read(pPriv->aud_handle, &shittyCompiler, - &imSize, &pPriv->width, - &pPriv->height, &color); - imData = (unsigned short *)shittyCompiler; - if(status != 0){ - snprintf(buffer,80,"ERROR: failed to read DELCam with errno = %d", - errno); - SCWrite(pCon,buffer,eError); - pPriv->error = FAULT; - status = HWFault; - } - if(imData != NULL){ - for(i = 0; i < pPriv->width*pPriv->height; i++){ - self->data->localBuffer[i] = (int) imData[i]; - } - free(imData); - } + eWarning); + + status = aud_image_read(pPriv->aud_handle, &shittyCompiler, + &imSize, &pPriv->width, + &pPriv->height, &color); + imData = (unsigned short *) shittyCompiler; + if (status != 0) { + snprintf(buffer, 80, "ERROR: failed to read DELCam with errno = %d", + errno); + SCWrite(pCon, buffer, eError); + pPriv->error = FAULT; + status = HWFault; } - return status; + if (imData != NULL) { + for (i = 0; i < pPriv->width * pPriv->height; i++) { + self->data->localBuffer[i] = (int) imData[i]; + } + free(imData); + } + } + return status; } + /*-------------------------------------------------------------------- Get info on error after last HWFault, returns 1 always. Puts an int error code into *code and errLen chars of error description into error ----------------------------------------------------------------------*/ -static int DelcamGetError(pHistDriver self,int *code, - char *error, int errLen){ - pDelcam pPriv = NULL; - - pPriv =(pDelcam)self->pPriv; - switch(pPriv->error){ - case FAULT: - snprintf(error,errLen,"ERROR: DELcam fault"); - *code = FAULT; - break; - case NOBEAM: - snprintf(error,errLen,"ERROR: ABORT for beam interruption"); - *code = FAULT; - break; - default: - return pPriv->count->pDriv->GetError(pPriv->count->pDriv, - code, error, errLen); - } - return 0; +static int DelcamGetError(pHistDriver self, int *code, + char *error, int errLen) +{ + pDelcam pPriv = NULL; + + pPriv = (pDelcam) self->pPriv; + switch (pPriv->error) { + case FAULT: + snprintf(error, errLen, "ERROR: DELcam fault"); + *code = FAULT; + break; + case NOBEAM: + snprintf(error, errLen, "ERROR: ABORT for beam interruption"); + *code = FAULT; + break; + default: + return pPriv->count->pDriv->GetError(pPriv->count->pDriv, + code, error, errLen); + } + return 0; } + /*-------------------------------------------------------------------- Try to fix the HM error in code. Returns COREDO when the last operation needs to be redone, COTERM when the error cannot be fixed. ----------------------------------------------------------------------*/ -static int DelcamFixIt(pHistDriver self,int code){ - pDelcam pPriv = NULL; - - pPriv =(pDelcam)self->pPriv; - switch(code){ - case FAULT: - case NOBEAM: - return COTERM; - break; - default: - return - pPriv->count->pDriv->TryAndFixIt(pPriv->count->pDriv,code); - break; - } +static int DelcamFixIt(pHistDriver self, int code) +{ + pDelcam pPriv = NULL; + + pPriv = (pDelcam) self->pPriv; + switch (code) { + case FAULT: + case NOBEAM: return COTERM; + break; + default: + return pPriv->count->pDriv->TryAndFixIt(pPriv->count->pDriv, code); + break; + } + return COTERM; } + /*-------------------------------------------------------------------- GetData reads updates the internal cache of monitor values from the hardware, Returns 1 or HWFault ----------------------------------------------------------------------*/ -static int DelcamGetData(pHistDriver self,SConnection *pCon){ - pDelcam pPriv = NULL; - - pPriv =(pDelcam)self->pPriv; - return 1; +static int DelcamGetData(pHistDriver self, SConnection * pCon) +{ + pDelcam pPriv = NULL; + + pPriv = (pDelcam) self->pPriv; + return 1; } + /*-------------------------------------------------------------------- GetMonitor reads the monitor value i. Returns either the monitor value or -9999 if no such monitor exists or an error occurred ----------------------------------------------------------------------*/ -static long DelcamGetMonitor(pHistDriver self,int i, SConnection *pCon){ - pDelcam pPriv = NULL; - - pPriv =(pDelcam)self->pPriv; - return GetMonitor(pPriv->count,i,pCon); +static long DelcamGetMonitor(pHistDriver self, int i, SConnection * pCon) +{ + pDelcam pPriv = NULL; + + pPriv = (pDelcam) self->pPriv; + return GetMonitor(pPriv->count, i, pCon); } + /*-------------------------------------------------------------------- GetTime reads the total counting time. Returns either the value or -9999.99 if no such value exists or an error occurred ----------------------------------------------------------------------*/ -static float DelcamGetTime(pHistDriver self,SConnection *pCon){ - pDelcam pPriv = NULL; - - pPriv =(pDelcam)self->pPriv; - return GetCountTime(pPriv->count,pCon); +static float DelcamGetTime(pHistDriver self, SConnection * pCon) +{ + pDelcam pPriv = NULL; + + pPriv = (pDelcam) self->pPriv; + return GetCountTime(pPriv->count, pCon); } + /*-------------------------------------------------------------------- Pause histogramming, Returns HWFault on failure, 1 on success ----------------------------------------------------------------------*/ -static int DelcamPause(pHistDriver self,SConnection *pCon){ - pDelcam pPriv = NULL; - - pPriv =(pDelcam)self->pPriv; - SCWrite(pCon,"WARNING: pausing pointless for CCD, IGNORED!",eWarning); - return 1; +static int DelcamPause(pHistDriver self, SConnection * pCon) +{ + pDelcam pPriv = NULL; + + pPriv = (pDelcam) self->pPriv; + SCWrite(pCon, "WARNING: pausing pointless for CCD, IGNORED!", eWarning); + return 1; } + /*-------------------------------------------------------------------- Continue histogramming, Returns HWFault on failure, 1 on success ----------------------------------------------------------------------*/ -static int DelcamContinue(pHistDriver self,SConnection *pCon){ - pDelcam pPriv = NULL; - - pPriv =(pDelcam)self->pPriv; - SCWrite(pCon,"WARNING: pausing pointless for CCD, IGNORED!",eWarning); - return 1; +static int DelcamContinue(pHistDriver self, SConnection * pCon) +{ + pDelcam pPriv = NULL; + + pPriv = (pDelcam) self->pPriv; + SCWrite(pCon, "WARNING: pausing pointless for CCD, IGNORED!", eWarning); + return 1; } + /*-------------------------------------------------------------------- Free the data associated with the private data structure of the driver ----------------------------------------------------------------------*/ -static int DelcamFree(pHistDriver self){ - pDelcam pPriv = NULL; - - pPriv =(pDelcam)self->pPriv; - aud_close(pPriv->aud_handle); - free(pPriv); - return 1; +static int DelcamFree(pHistDriver self) +{ + pDelcam pPriv = NULL; + + pPriv = (pDelcam) self->pPriv; + aud_close(pPriv->aud_handle); + free(pPriv); + return 1; } + /*-------------------------------------------------------------------- Set The HM data or a subset of it. Returns HWFault or 1 ----------------------------------------------------------------------*/ static int DelcamSetHistogram(pHistDriver self, - SConnection *pCon, - int i, int iStart, int iEnd, HistInt *pData){ - pDelcam pPriv = NULL; - int j; - - pPriv =(pDelcam)self->pPriv; - SCWrite(pCon,"WARNING: driver does not support setting HM",eWarning); - return 1; + SConnection * pCon, + int i, int iStart, int iEnd, HistInt * pData) +{ + pDelcam pPriv = NULL; + int j; + + pPriv = (pDelcam) self->pPriv; + SCWrite(pCon, "WARNING: driver does not support setting HM", eWarning); + return 1; } + /*-------------------------------------------------------------------- Set HM to a preset value, Returns HWFault on failure, 1 on success ----------------------------------------------------------------------*/ -static int DelcamPreset(pHistDriver self,SConnection *pCon, - HistInt value){ - pDelcam pPriv = NULL; - int j; - - pPriv =(pDelcam)self->pPriv; - for(j = 0; j < pPriv->width*pPriv->height; j++){ - self->data->localBuffer[j] = value; - } - return 1; +static int DelcamPreset(pHistDriver self, SConnection * pCon, + HistInt value) +{ + pDelcam pPriv = NULL; + int j; + + pPriv = (pDelcam) self->pPriv; + for (j = 0; j < pPriv->width * pPriv->height; j++) { + self->data->localBuffer[j] = value; + } + return 1; } + /*-------------------------------------------------------------------- get The HM data or a subset of it. Returns HWFault or 1 ----------------------------------------------------------------------*/ static int DelcamGetHistogram(pHistDriver self, - SConnection *pCon, - int i, int iStart, int iEnd, HistInt *pData){ - pDelcam pPriv = NULL; - HistInt *data = NULL; - pPriv =(pDelcam)self->pPriv; - - data = self->data->localBuffer + iStart; - if(iEnd > getHMDataLength(self->data) || iStart < 0){ - SCWrite(pCon,"ERROR: data length out of range",eError); - return 0; - } - memcpy(pData,data,(iEnd - iStart)*sizeof(HistInt)); - return 1; + SConnection * pCon, + int i, int iStart, int iEnd, HistInt * pData) +{ + pDelcam pPriv = NULL; + HistInt *data = NULL; + pPriv = (pDelcam) self->pPriv; + + data = self->data->localBuffer + iStart; + if (iEnd > getHMDataLength(self->data) || iStart < 0) { + SCWrite(pCon, "ERROR: data length out of range", eError); + return 0; + } + memcpy(pData, data, (iEnd - iStart) * sizeof(HistInt)); + return 1; } + /*-------------------------------------------------------------------- Make the HMDriver, returns a driver or NULL on failure ----------------------------------------------------------------------*/ -pHistDriver MakeDelcamHM(pStringDict pOption){ - pHistDriver pNew = NULL; - pDelcam pPriv = NULL; +pHistDriver MakeDelcamHM(pStringDict pOption) +{ + pHistDriver pNew = NULL; + pDelcam pPriv = NULL; - /* create the general driver */ - pNew = CreateHistDriver(pOption); - if(!pNew){ - return NULL; - } + /* create the general driver */ + pNew = CreateHistDriver(pOption); + if (!pNew) { + return NULL; + } - /*Create private data structure*/ - pPriv = NULL; - pPriv = (pDelcam)malloc(sizeof(Delcam)); - if(pPriv == NULL){ - return NULL; - } - memset(pPriv,0,sizeof(Delcam)); - pPriv->width = 768; - pPriv->height = 512; - pNew->pPriv = pPriv; - - - /* add our options */ - StringDictAddPair(pOption,"amplictrl","0"); - StringDictAddPair(pOption,"shutterctrl","0"); - StringDictAddPair(pOption,"clear","1"); - StringDictAddPair(pOption,"schnarch","1"); - StringDictAddPair(pOption,"counter","unkown"); + /*Create private data structure */ + pPriv = NULL; + pPriv = (pDelcam) malloc(sizeof(Delcam)); + if (pPriv == NULL) { + return NULL; + } + memset(pPriv, 0, sizeof(Delcam)); + pPriv->width = 768; + pPriv->height = 512; + pNew->pPriv = pPriv; - /* configure all those functions */ - pNew->Configure = DelcamConfigure; - pNew->Start = DelcamStart; - pNew->Halt = DelcamHalt; - pNew->GetCountStatus = DelcamCountStatus; - pNew->GetError = DelcamGetError; - pNew->TryAndFixIt = DelcamFixIt; - pNew->GetData = DelcamGetData; - pNew->GetHistogram = DelcamGetHistogram; - pNew->SetHistogram = DelcamSetHistogram; - pNew->GetMonitor = DelcamGetMonitor; - pNew->GetTime = DelcamGetTime; - pNew->Preset = DelcamPreset; - pNew->FreePrivate = DelcamFree; - pNew->Pause = DelcamPause; - pNew->Continue = DelcamContinue; - return pNew; + /* add our options */ + StringDictAddPair(pOption, "amplictrl", "0"); + StringDictAddPair(pOption, "shutterctrl", "0"); + StringDictAddPair(pOption, "clear", "1"); + StringDictAddPair(pOption, "schnarch", "1"); + StringDictAddPair(pOption, "counter", "unkown"); + + /* configure all those functions */ + pNew->Configure = DelcamConfigure; + pNew->Start = DelcamStart; + pNew->Halt = DelcamHalt; + pNew->GetCountStatus = DelcamCountStatus; + pNew->GetError = DelcamGetError; + pNew->TryAndFixIt = DelcamFixIt; + pNew->GetData = DelcamGetData; + pNew->GetHistogram = DelcamGetHistogram; + pNew->SetHistogram = DelcamSetHistogram; + pNew->GetMonitor = DelcamGetMonitor; + pNew->GetTime = DelcamGetTime; + pNew->Preset = DelcamPreset; + pNew->FreePrivate = DelcamFree; + pNew->Pause = DelcamPause; + pNew->Continue = DelcamContinue; + + return pNew; } diff --git a/dgrambroadcast.c b/dgrambroadcast.c index c1dbf7b..3a79723 100644 --- a/dgrambroadcast.c +++ b/dgrambroadcast.c @@ -9,9 +9,9 @@ /* broadcast address for our network */ /* unsigned int brAddr = 0x818197ff; - only our network */ unsigned int brAddr[] = { - 0x818197ff, /* 129.129.151.255 */ - 0x818196ff, /* 129.129.150.255 - same router as our subnet */ - 0x81818aff, /* 129.129.138.255 - same router as our subnet */ + 0x818197ff, /* 129.129.151.255 */ + 0x818196ff, /* 129.129.150.255 - same router as our subnet */ + 0x81818aff, /* 129.129.138.255 - same router as our subnet */ }; int nrBrAddr = sizeof(brAddr) / sizeof(unsigned int); #endif @@ -50,15 +50,15 @@ int nrBrAddr = sizeof(brAddr) / sizeof(unsigned int); #ifdef TESTING #define PERROR(x) perror(x) #else -#define PERROR(x) +#define PERROR(x) #endif #include "dgrambroadcast.h" -int McastSocket; /* multicast socket */ -struct sockaddr_in McastDestination; /* multicast destination address */ +int McastSocket; /* multicast socket */ +struct sockaddr_in McastDestination; /* multicast destination address */ /*********************************************************************/ @@ -66,49 +66,51 @@ struct sockaddr_in McastDestination; /* multicast destination address */ // -DDESTINATION_MCAST="\"226.129.151.57\"" // which is acs-gateway with first byte replaced to 226 -static char DESTINATION_MCAST[128] = {0}; // place to hold x.y.z.w IPv4 address +static char DESTINATION_MCAST[128] = { 0 }; // place to hold x.y.z.w IPv4 address void initDestMcastAddr() { - struct hostent *hp; + struct hostent *hp; - if (memcmp(DESTINATION_MCAST, "226.", 4) == 0) { - return; // already initialized - } + if (memcmp(DESTINATION_MCAST, "226.", 4) == 0) { + return; // already initialized + } - hp = gethostbyname(SERVER_HOST); - if (hp == (struct hostent *) 0) { - printf("%s: unknown host", SERVER_HOST); - exit(99); - } + hp = gethostbyname(SERVER_HOST); + if (hp == (struct hostent *) 0) { + printf("%s: unknown host", SERVER_HOST); + exit(99); + } - sprintf(DESTINATION_MCAST, "226.%d.%d.%d", hp->h_addr[1]&0xFF, hp->h_addr[2]&0xFF, hp->h_addr[3]&0xFF); - //printf("Got DESTINATION_MCAST = '%s'\n", DESTINATION_MCAST); + sprintf(DESTINATION_MCAST, "226.%d.%d.%d", hp->h_addr[1] & 0xFF, + hp->h_addr[2] & 0xFF, hp->h_addr[3] & 0xFF); + //printf("Got DESTINATION_MCAST = '%s'\n", DESTINATION_MCAST); } /*********************************************************************/ void closeBroadcastSocket(sendSocket) -int sendSocket; +int sendSocket; { #ifdef TESTING printf("closeBroadcastSocket()\n"); #endif close(sendSocket); - - if (McastSocket >= 0) close(McastSocket); - + + if (McastSocket >= 0) + close(McastSocket); + } /*********************************************************************/ int openBroadcastSocket() { - //unsigned char ttl; - int ttl; - int sendSocket; - int enableBroadcast; + //unsigned char ttl; + int ttl; + int sendSocket; + int enableBroadcast; - int status; + int status; initDestMcastAddr(); @@ -124,7 +126,9 @@ int openBroadcastSocket() } enableBroadcast = 1; - status = setsockopt(sendSocket, SOL_SOCKET, SO_BROADCAST, (char *) &enableBroadcast, sizeof(enableBroadcast)); + status = + setsockopt(sendSocket, SOL_SOCKET, SO_BROADCAST, + (char *) &enableBroadcast, sizeof(enableBroadcast)); if (status < 0) { PERROR("setsockopt"); return status; @@ -138,9 +142,11 @@ int openBroadcastSocket() } //else { printf("Multicast socket opened\n");} - ttl = 4; // with less then 2 it does not work - if(setsockopt(McastSocket, IPPROTO_IP, IP_MULTICAST_TTL, (char *) &ttl, sizeof(ttl)) < 0) { - perror("setsockopt() failed setting IP_MULTICAST_TTL"); + ttl = 4; // with less then 2 it does not work + if (setsockopt + (McastSocket, IPPROTO_IP, IP_MULTICAST_TTL, (char *) &ttl, + sizeof(ttl)) < 0) { + perror("setsockopt() failed setting IP_MULTICAST_TTL"); } //else {printf("Multicast socket configured\n");} @@ -158,7 +164,7 @@ int openReceiveSocket(port) unsigned short port; { struct sockaddr_in name; - int recvSocket; + int recvSocket; initDestMcastAddr(); @@ -172,50 +178,54 @@ unsigned short port; return recvSocket; } - { - int sopt = 1; + { + int sopt = 1; - if (setsockopt(recvSocket, SOL_SOCKET, SO_REUSEADDR, (char *) &sopt, sizeof(int)) != 0) { - perror("SO_REUSEADDR"); - printf("not fatal, continuing\n"); - } + if (setsockopt + (recvSocket, SOL_SOCKET, SO_REUSEADDR, (char *) &sopt, + sizeof(int)) != 0) { + perror("SO_REUSEADDR"); + printf("not fatal, continuing\n"); } + } - /* Create name with wildcards. */ - name.sin_family = AF_INET; - name.sin_addr.s_addr = INADDR_ANY; - name.sin_port = htons(port); - if (bind(recvSocket, (struct sockaddr *) &name, sizeof(name))) { - PERROR("bind"); - recvSocket = -1; - return recvSocket; - } - + /* Create name with wildcards. */ + name.sin_family = AF_INET; + name.sin_addr.s_addr = INADDR_ANY; + name.sin_port = htons(port); + if (bind(recvSocket, (struct sockaddr *) &name, sizeof(name))) { + PERROR("bind"); + recvSocket = -1; + return recvSocket; + } #ifdef USE_MULTICAST - { - char group[100]; // group address string - struct ip_mreq McastReq; // multicast group request + { + char group[100]; // group address string + struct ip_mreq McastReq; // multicast group request - printf("Receive on port 0x%04X=%d, use multicast group=\"%s\" addr=INADDR_ANY\n", - port & 0xFFFF, port, DESTINATION_MCAST); + printf + ("Receive on port 0x%04X=%d, use multicast group=\"%s\" addr=INADDR_ANY\n", + port & 0xFFFF, port, DESTINATION_MCAST); - // Join the multicast group from we want to receive datagrams. - // Initialize the multicast request structure and then pass - // it as an option to setsockopt(). The imr_multiaddr element - // is initialized to the desired multicast group. The - // imr_interface element is initilized to IPADDR_ANY which - // causes the multcast receives to come from the default - // interface. + // Join the multicast group from we want to receive datagrams. + // Initialize the multicast request structure and then pass + // it as an option to setsockopt(). The imr_multiaddr element + // is initialized to the desired multicast group. The + // imr_interface element is initilized to IPADDR_ANY which + // causes the multcast receives to come from the default + // interface. - // Set defaults and get group address and port number if - // specified in command line. - strcpy(group, DESTINATION_MCAST ); + // Set defaults and get group address and port number if + // specified in command line. + strcpy(group, DESTINATION_MCAST); - McastReq.imr_multiaddr.s_addr = inet_addr(group); - McastReq.imr_interface.s_addr = INADDR_ANY; + McastReq.imr_multiaddr.s_addr = inet_addr(group); + McastReq.imr_interface.s_addr = INADDR_ANY; - if(setsockopt(recvSocket, IPPROTO_IP, IP_ADD_MEMBERSHIP, (char *) &McastReq, sizeof(McastReq)) < 0) - perror("setsockopt failed for IP_ADD_MEMBERSHIP"); + if (setsockopt + (recvSocket, IPPROTO_IP, IP_ADD_MEMBERSHIP, (char *) &McastReq, + sizeof(McastReq)) < 0) + perror("setsockopt failed for IP_ADD_MEMBERSHIP"); } #endif @@ -227,20 +237,22 @@ unsigned short port; void receiveJoinMCast(recvSocket) int recvSocket; { - struct ip_mreq McastReq; // multicast group request - char *group; + struct ip_mreq McastReq; // multicast group request + char *group; - initDestMcastAddr(); + initDestMcastAddr(); - group = DESTINATION_MCAST; + group = DESTINATION_MCAST; - - McastReq.imr_multiaddr.s_addr = inet_addr(group); - McastReq.imr_interface.s_addr = INADDR_ANY; - if(setsockopt(recvSocket, IPPROTO_IP, IP_ADD_MEMBERSHIP, (char *) &McastReq, sizeof(McastReq)) < 0) - perror("setsockopt failed for IP_ADD_MEMBERSHIP"); + McastReq.imr_multiaddr.s_addr = inet_addr(group); + McastReq.imr_interface.s_addr = INADDR_ANY; + + if (setsockopt + (recvSocket, IPPROTO_IP, IP_ADD_MEMBERSHIP, (char *) &McastReq, + sizeof(McastReq)) < 0) + perror("setsockopt failed for IP_ADD_MEMBERSHIP"); } @@ -250,8 +262,8 @@ int recvSocket; int usec; { struct timeval tv; - int nfds, rm, wm, em; - int status; + int nfds, rm, wm, em; + int status; #ifdef TESTING printf("selectReceiveSocket()\n"); @@ -265,20 +277,21 @@ int usec; tv.tv_usec = usec; #ifndef vaxc - status = select(nfds, (fd_set *) &rm, (fd_set *) &wm, (fd_set *) &em, &tv); + status = + select(nfds, (fd_set *) & rm, (fd_set *) & wm, (fd_set *) & em, &tv); #else status = select(nfds, &rm, &wm, &em, &tv); #endif - return status; /* 0 = nothing to read, 1 = ready for read, -1 = error */ + return status; /* 0 = nothing to read, 1 = ready for read, -1 = error */ } int readReceiveSocket(recvSocket, buff, len) -int recvSocket; +int recvSocket; unsigned char *buff; -int len; +int len; { - int status; + int status; #ifdef TESTING printf("readReceiveSocket()\n"); @@ -286,32 +299,37 @@ int len; memset(buff, '\0', len); status = read(recvSocket, buff, len); - if (status < 0) PERROR("read"); + if (status < 0) + PERROR("read"); return status; } /*********************************************************************/ int sendBroadcastMessage(sendSocket, sendPort, sndMsg, sndMsgLen) -int sendSocket; +int sendSocket; unsigned short sendPort; unsigned char *sndMsg; -int sndMsgLen; +int sndMsgLen; { - int status; + int status; #ifdef SEND_BCASTS_TOO - int i; - int flags; - struct sockaddr_in sendName; + int i; + int flags; + struct sockaddr_in sendName; #endif #ifdef TESTING - printf("sendBroadcastMessage(s=%d, 0x%04X, msg, len=%d)\n", sendSocket, sendPort, sndMsgLen); + printf("sendBroadcastMessage(s=%d, 0x%04X, msg, len=%d)\n", sendSocket, + sendPort, sndMsgLen); #endif - /* send multicast message */ - status = sendto(McastSocket, (char *) sndMsg, sndMsgLen, 0, (struct sockaddr *) &McastDestination, sizeof(McastDestination)); - return status; + /* send multicast message */ + status = + sendto(McastSocket, (char *) sndMsg, sndMsgLen, 0, + (struct sockaddr *) &McastDestination, + sizeof(McastDestination)); + return status; #ifdef SEND_BCASTS_TOO @@ -324,8 +342,8 @@ int sndMsgLen; flags = 0; status = sendto(sendSocket, (char *) sndMsg, sndMsgLen, - flags, (struct sockaddr *) &sendName, - sizeof(sendName)); + flags, (struct sockaddr *) &sendName, + sizeof(sendName)); if (status != sndMsgLen) { /*printf("sendBroadcastMessage(s=%d, 0x%04X, msg, len=%d - FAILED)\n", brAddr[i], sendPort, sndMsgLen);*/ @@ -339,4 +357,3 @@ int sndMsgLen; return status; } - diff --git a/dgrambroadcast.h b/dgrambroadcast.h index 456f723..f09619b 100644 --- a/dgrambroadcast.h +++ b/dgrambroadcast.h @@ -1,11 +1,10 @@ #define MAX_BROADCAST_MSG_LEN 1472 -int openBroadcastSocket ( /* void */ ); +int openBroadcastSocket( /* void */ ); void closeBroadcastSocket( /* sendSocket */ ); -int sendBroadcastMessage( /* sendSocket, sendPort, sndMsg, sndMsgLen */ ); - -int openReceiveSocket ( /* port */ ); -int readReceiveSocket ( /* recvSocket, buff, len */ ); -int selectReceiveSocket ( /* recvSocket, usec */ ); +int sendBroadcastMessage( /* sendSocket, sendPort, sndMsg, sndMsgLen */ ); +int openReceiveSocket( /* port */ ); +int readReceiveSocket( /* recvSocket, buff, len */ ); +int selectReceiveSocket( /* recvSocket, usec */ ); diff --git a/dilludriv.c b/dilludriv.c index cda811b..21fc4a1 100644 --- a/dilludriv.c +++ b/dilludriv.c @@ -20,251 +20,246 @@ #include #include -#include "evdriver.h" +#include "evdriver.h" #include "hardsup/dillutil.h" #include "hardsup/el734_def.h" #include "hardsup/el734fix.h" -#include "dilludriv.h" - +#include "dilludriv.h" + /*-----------------------------------------------------------------------*/ - typedef struct { - pDILLU pData; - char *pHost; - int iPort; - int iChannel; - int iLastError; - char *pTranslationFile; - } DILLUDriv, *pDILLUDriv; +typedef struct { + pDILLU pData; + char *pHost; + int iPort; + int iChannel; + int iLastError; + char *pTranslationFile; +} DILLUDriv, *pDILLUDriv; /*----------------------------------------------------------------------------*/ - static int GetDILLUPos(pEVDriver self, float *fPos) - { - pDILLUDriv pMe = NULL; - int iRet; - - assert(self); - pMe = (pDILLUDriv)self->pPrivate; - assert(pMe); - - iRet = DILLU_Read(&pMe->pData,fPos); - if(iRet != 1 ) - { - pMe->iLastError = iRet; - return 0; - } - if( (*fPos < 0) || (*fPos > 1000) ) - { - *fPos = -999.; - return 0; - } - return 1; - } -/*----------------------------------------------------------------------------*/ - static int DILLURun(pEVDriver self, float fVal) - { - pDILLUDriv pMe = NULL; - int iRet; - - assert(self); - pMe = (pDILLUDriv )self->pPrivate; - assert(pMe); +static int GetDILLUPos(pEVDriver self, float *fPos) +{ + pDILLUDriv pMe = NULL; + int iRet; - iRet = DILLU_Set(&pMe->pData,fVal); - if(iRet != 1) - { - pMe->iLastError = iRet; - return 0; - } - return 1; - } -/*--------------------------------------------------------------------------*/ - static int DILLUError(pEVDriver self, int *iCode, char *error, int iErrLen) - { - pDILLUDriv pMe = NULL; - - assert(self); - pMe = (pDILLUDriv)self->pPrivate; - assert(pMe); + assert(self); + pMe = (pDILLUDriv) self->pPrivate; + assert(pMe); - *iCode = pMe->iLastError; - DILLU_Error2Text(&pMe->pData,pMe->iLastError,error,iErrLen); - - return 1; + iRet = DILLU_Read(&pMe->pData, fPos); + if (iRet != 1) { + pMe->iLastError = iRet; + return 0; } + if ((*fPos < 0) || (*fPos > 1000)) { + *fPos = -999.; + return 0; + } + return 1; +} + +/*----------------------------------------------------------------------------*/ +static int DILLURun(pEVDriver self, float fVal) +{ + pDILLUDriv pMe = NULL; + int iRet; + + assert(self); + pMe = (pDILLUDriv) self->pPrivate; + assert(pMe); + + iRet = DILLU_Set(&pMe->pData, fVal); + if (iRet != 1) { + pMe->iLastError = iRet; + return 0; + } + return 1; +} + /*--------------------------------------------------------------------------*/ - static int DILLUSend(pEVDriver self, char *pCommand, char *pReply, int iLen) - { - pDILLUDriv pMe = NULL; - int iRet; - - assert(self); - pMe = (pDILLUDriv )self->pPrivate; - assert(pMe); +static int DILLUError(pEVDriver self, int *iCode, char *error, int iErrLen) +{ + pDILLUDriv pMe = NULL; - iRet = DILLU_Send(&pMe->pData,pCommand, pReply,iLen); - if(iRet != 1) - { - pMe->iLastError = iRet; - return 0; - } - return 1; + assert(self); + pMe = (pDILLUDriv) self->pPrivate; + assert(pMe); + + *iCode = pMe->iLastError; + DILLU_Error2Text(&pMe->pData, pMe->iLastError, error, iErrLen); + + return 1; +} - } /*--------------------------------------------------------------------------*/ - static int DILLUInit(pEVDriver self) - { - pDILLUDriv pMe = NULL; - int iRet; - - assert(self); - pMe = (pDILLUDriv )self->pPrivate; - assert(pMe); +static int DILLUSend(pEVDriver self, char *pCommand, char *pReply, + int iLen) +{ + pDILLUDriv pMe = NULL; + int iRet; + + assert(self); + pMe = (pDILLUDriv) self->pPrivate; + assert(pMe); + + iRet = DILLU_Send(&pMe->pData, pCommand, pReply, iLen); + if (iRet != 1) { + pMe->iLastError = iRet; + return 0; + } + return 1; + +} - pMe->pData = NULL; - iRet = DILLU_Open(&pMe->pData, pMe->pHost, pMe->iPort, pMe->iChannel, - 0,pMe->pTranslationFile); - if(iRet != 1) - { - pMe->iLastError = iRet; - return 0; - } - DILLU_Config(&pMe->pData, 1000); - return 1; - } /*--------------------------------------------------------------------------*/ - static int DILLUClose(pEVDriver self) - { - pDILLUDriv pMe = NULL; - int iRet; - - assert(self); - pMe = (pDILLUDriv )self->pPrivate; - assert(pMe); +static int DILLUInit(pEVDriver self) +{ + pDILLUDriv pMe = NULL; + int iRet; + + assert(self); + pMe = (pDILLUDriv) self->pPrivate; + assert(pMe); + + pMe->pData = NULL; + iRet = DILLU_Open(&pMe->pData, pMe->pHost, pMe->iPort, pMe->iChannel, + 0, pMe->pTranslationFile); + if (iRet != 1) { + pMe->iLastError = iRet; + return 0; + } + DILLU_Config(&pMe->pData, 1000); + return 1; +} + +/*--------------------------------------------------------------------------*/ +static int DILLUClose(pEVDriver self) +{ + pDILLUDriv pMe = NULL; + int iRet; + + assert(self); + pMe = (pDILLUDriv) self->pPrivate; + assert(pMe); + + DILLU_Close(&pMe->pData); + return 1; +} - DILLU_Close(&pMe->pData); - return 1; - } /*---------------------------------------------------------------------------*/ - static int DILLUFix(pEVDriver self, int iError) - { - pDILLUDriv pMe = NULL; - int iRet; - - assert(self); - pMe = (pDILLUDriv )self->pPrivate; - assert(pMe); +static int DILLUFix(pEVDriver self, int iError) +{ + pDILLUDriv pMe = NULL; + int iRet; - switch(iError) - { - /* network errors */ - case EL734__BAD_FLUSH: - case EL734__BAD_RECV: - case EL734__BAD_RECV_NET: - case EL734__BAD_RECV_UNKN: - case EL734__BAD_RECVLEN: - case EL734__BAD_RECV1: - case EL734__BAD_RECV1_PIPE: - case EL734__BAD_RNG: - case EL734__BAD_SEND: - case EL734__BAD_SEND_PIPE: - case EL734__BAD_SEND_NET: - case EL734__BAD_SEND_UNKN: - case EL734__BAD_SENDLEN: - DILLUClose(self); - iRet = DILLUInit(self); - if(iRet) - { - return DEVREDO; - } - else - { - return DEVFAULT; - } - break; - /* handable protocoll errors */ - case EL734__BAD_TMO: - return DEVREDO; - break; - case DILLU__NODILLFILE: - case DILLU__ERRORTABLE: - case DILLU__READONLY: - case DILLU__OUTOFRANGE: - case DILLU__BADMALLOC: - case DILLU__FILENOTFOUND: - return DEVFAULT; - case DILLU__BADREAD: - case DILLU__SILLYANSWER: - return DEVREDO; - default: - return DEVFAULT; - break; - } - return DEVFAULT; + assert(self); + pMe = (pDILLUDriv) self->pPrivate; + assert(pMe); + + switch (iError) { + /* network errors */ + case EL734__BAD_FLUSH: + case EL734__BAD_RECV: + case EL734__BAD_RECV_NET: + case EL734__BAD_RECV_UNKN: + case EL734__BAD_RECVLEN: + case EL734__BAD_RECV1: + case EL734__BAD_RECV1_PIPE: + case EL734__BAD_RNG: + case EL734__BAD_SEND: + case EL734__BAD_SEND_PIPE: + case EL734__BAD_SEND_NET: + case EL734__BAD_SEND_UNKN: + case EL734__BAD_SENDLEN: + DILLUClose(self); + iRet = DILLUInit(self); + if (iRet) { + return DEVREDO; + } else { + return DEVFAULT; + } + break; + /* handable protocoll errors */ + case EL734__BAD_TMO: + return DEVREDO; + break; + case DILLU__NODILLFILE: + case DILLU__ERRORTABLE: + case DILLU__READONLY: + case DILLU__OUTOFRANGE: + case DILLU__BADMALLOC: + case DILLU__FILENOTFOUND: + return DEVFAULT; + case DILLU__BADREAD: + case DILLU__SILLYANSWER: + return DEVREDO; + default: + return DEVFAULT; + break; } - + return DEVFAULT; +} + /*--------------------------------------------------------------------------*/ - static int DILLUHalt(pEVDriver *self) - { - assert(self); - - return 1; +static int DILLUHalt(pEVDriver * self) +{ + assert(self); + + return 1; +} + +/*------------------------------------------------------------------------*/ +void KillDILLU(void *pData) +{ + pDILLUDriv pMe = NULL; + + pMe = (pDILLUDriv) pData; + assert(pMe); + + if (pMe->pHost) { + free(pMe->pHost); } + if (pMe->pTranslationFile) { + free(pMe->pTranslationFile); + } + free(pMe); +} + /*------------------------------------------------------------------------*/ - void KillDILLU(void *pData) - { - pDILLUDriv pMe = NULL; - - pMe = (pDILLUDriv)pData; - assert(pMe); - - if(pMe->pHost) - { - free(pMe->pHost); - } - if(pMe->pTranslationFile) - { - free(pMe->pTranslationFile); - } - free(pMe); - } -/*------------------------------------------------------------------------*/ - pEVDriver CreateDILLUDriv(int argc, char *argv[]) - { - pEVDriver pNew = NULL; - pDILLUDriv pSim = NULL; - - /* check for arguments */ - if(argc < 3) - { - return NULL; - } - - pNew = CreateEVDriver(argc,argv); - pSim = (pDILLUDriv)malloc(sizeof(DILLUDriv)); - memset(pSim,0,sizeof(DILLUDriv)); - if(!pNew || !pSim) - { - return NULL; - } - pNew->pPrivate = pSim; - pNew->KillPrivate = KillDILLU; - - /* initalise pDILLUDriver */ - pSim->iLastError = 0; - pSim->pHost = strdup(argv[0]); - pSim->iPort = atoi(argv[1]); - pSim->iChannel = atoi(argv[2]); - pSim->pTranslationFile = strdup(argv[3]); - - - /* initialise function pointers */ - pNew->SetValue = DILLURun; - pNew->GetValue = GetDILLUPos; - pNew->Send = DILLUSend; - pNew->GetError = DILLUError; - pNew->TryFixIt = DILLUFix; - pNew->Init = DILLUInit; - pNew->Close = DILLUClose; - - return pNew; - } - +pEVDriver CreateDILLUDriv(int argc, char *argv[]) +{ + pEVDriver pNew = NULL; + pDILLUDriv pSim = NULL; + + /* check for arguments */ + if (argc < 3) { + return NULL; + } + + pNew = CreateEVDriver(argc, argv); + pSim = (pDILLUDriv) malloc(sizeof(DILLUDriv)); + memset(pSim, 0, sizeof(DILLUDriv)); + if (!pNew || !pSim) { + return NULL; + } + pNew->pPrivate = pSim; + pNew->KillPrivate = KillDILLU; + + /* initalise pDILLUDriver */ + pSim->iLastError = 0; + pSim->pHost = strdup(argv[0]); + pSim->iPort = atoi(argv[1]); + pSim->iChannel = atoi(argv[2]); + pSim->pTranslationFile = strdup(argv[3]); + + + /* initialise function pointers */ + pNew->SetValue = DILLURun; + pNew->GetValue = GetDILLUPos; + pNew->Send = DILLUSend; + pNew->GetError = DILLUError; + pNew->TryFixIt = DILLUFix; + pNew->Init = DILLUInit; + pNew->Close = DILLUClose; + + return pNew; +} diff --git a/dilludriv.h b/dilludriv.h index f2a0907..3a9c6ea 100644 --- a/dilludriv.h +++ b/dilludriv.h @@ -10,6 +10,6 @@ ---------------------------------------------------------------------------*/ #ifndef DILLUDRIV #define DILLUDRIV - pEVDriver CreateDILLUDriv(int argc, char *argv[]); - +pEVDriver CreateDILLUDriv(int argc, char *argv[]); + #endif diff --git a/dmc.c b/dmc.c index 31614cf..f759205 100644 --- a/dmc.c +++ b/dmc.c @@ -46,9 +46,9 @@ #include "nxdata.h" #include "dmc.h" - int InitDmc(SConnection *pCon, SicsInterp *pSics, void *pData, - int argc, char *argv[]) - { - AddCommand(pSics,"StoreData",SNStoreDMC,NULL,NULL); - return 1; - } +int InitDmc(SConnection * pCon, SicsInterp * pSics, void *pData, + int argc, char *argv[]) +{ + AddCommand(pSics, "StoreData", SNStoreDMC, NULL, NULL); + return 1; +} diff --git a/dmc.h b/dmc.h index aee4fb3..3f44154 100644 --- a/dmc.h +++ b/dmc.h @@ -13,7 +13,7 @@ #ifndef SICSDMC #define SICSDMC - int InitDmc(SConnection *pCon, SicsInterp *pSics, void *pData, - int argc, char *argv[]); +int InitDmc(SConnection * pCon, SicsInterp * pSics, void *pData, + int argc, char *argv[]); #endif diff --git a/docho.c b/docho.c index 3321dd1..c07da43 100644 --- a/docho.c +++ b/docho.c @@ -32,22 +32,22 @@ /*----------------------------------------------------------------------- A private data structure for this Dornier chopper -------------------------------------------------------------------------*/ - typedef struct { - char *pHost; - int iPort; - int iChannel; - void *pData; - int iRefreshIntervall; - pStringDict pPar; - time_t tRefresh; - int iStop; - long lTask; - int iError; - int iBusy; - float fRatio; - int iSingle; - char pError[80]; - } DoCho, *pDoCho; +typedef struct { + char *pHost; + int iPort; + int iChannel; + void *pData; + int iRefreshIntervall; + pStringDict pPar; + time_t tRefresh; + int iStop; + long lTask; + int iError; + int iBusy; + float fRatio; + int iSingle; + char pError[80]; +} DoCho, *pDoCho; /* pHost, iPort and iChannel combined are the adress of the chopper controller at the Macintosh terminal server. pData is the serial @@ -83,7 +83,7 @@ ERROR CODES: */ #define UNDRIVABLE -8002 -#define UNKNOWNPAR -8003 +#define UNKNOWNPAR -8003 #define PARERROR -8004 #define BADSYNC -8005 #define BADSTOP -8006 @@ -94,52 +94,44 @@ extern char *trim(char *pTrim); /* trim.c */ /*----------------------------------------------------------------------*/ static void SplitChopperReply(pCodri self, char *prefix, char *pBueffel) { - char pToken[30], pValue[20], pEntry[80]; - char *pPtr, *pTok, *pVal; - int iCount, iRet; - pDoCho pPriv = NULL; + char pToken[30], pValue[20], pEntry[80]; + char *pPtr, *pTok, *pVal; + int iCount, iRet; + pDoCho pPriv = NULL; - pPriv = (pDoCho)self->pPrivate; + pPriv = (pDoCho) self->pPrivate; - /* decompose pBueffel and store into string dictionary */ - pPtr = strtok(pBueffel,";"); - while(pPtr != NULL) - { - iCount = sscanf(pPtr,"%s %s",pToken,pValue); - if(iCount == 2) - { - pTok = trim(pToken); - pVal = trim(pValue); - pEntry[0] = '\0'; - sprintf(pEntry,"%s.%s",prefix,pTok); - iRet = StringDictUpdate(pPriv->pPar,pEntry,pVal); - if(!iRet) - { - StringDictAddPair(pPriv->pPar,pEntry,pVal); - strcat(self->pParList,pEntry); - strcat(self->pParList,","); - } - } - else - { - /* this fixes a bug with oversized messages in dphas */ - if(strstr(pPtr,"dphas") != NULL) - { - sprintf(pEntry,"%s.dphas",prefix); - iRet = StringDictUpdate(pPriv->pPar, - pEntry,pPtr+5); - if(!iRet) - { - StringDictAddPair(pPriv->pPar,pEntry, - pPtr+5); - strcat(self->pParList,pEntry); - strcat(self->pParList,","); - } - } - } - pPtr = strtok(NULL,";"); + /* decompose pBueffel and store into string dictionary */ + pPtr = strtok(pBueffel, ";"); + while (pPtr != NULL) { + iCount = sscanf(pPtr, "%s %s", pToken, pValue); + if (iCount == 2) { + pTok = trim(pToken); + pVal = trim(pValue); + pEntry[0] = '\0'; + sprintf(pEntry, "%s.%s", prefix, pTok); + iRet = StringDictUpdate(pPriv->pPar, pEntry, pVal); + if (!iRet) { + StringDictAddPair(pPriv->pPar, pEntry, pVal); + strcat(self->pParList, pEntry); + strcat(self->pParList, ","); } + } else { + /* this fixes a bug with oversized messages in dphas */ + if (strstr(pPtr, "dphas") != NULL) { + sprintf(pEntry, "%s.dphas", prefix); + iRet = StringDictUpdate(pPriv->pPar, pEntry, pPtr + 5); + if (!iRet) { + StringDictAddPair(pPriv->pPar, pEntry, pPtr + 5); + strcat(self->pParList, pEntry); + strcat(self->pParList, ","); + } + } + } + pPtr = strtok(NULL, ";"); + } } + /*------------------------------------------------------------------------- Well, DoChoStatus sends a status request to the Dornier chopper control system. There is a gotcha, you need three reads to get the full information. @@ -147,620 +139,551 @@ static void SplitChopperReply(pCodri self, char *prefix, char *pBueffel) string dictionary. The single status components are separated by ;. -------------------------------------------------------------------------*/ - static int DoChoStatus(pCodri self) - { - int iRet, iCount, iCode; - char pBueffel[1024], pToken[30], pValue[20]; - char *pPtr, *pTok, *pVal; - pDoCho pPriv = NULL; +static int DoChoStatus(pCodri self) +{ + int iRet, iCount, iCode; + char pBueffel[1024], pToken[30], pValue[20]; + char *pPtr, *pTok, *pVal; + pDoCho pPriv = NULL; - assert(self); - pPriv = (pDoCho)self->pPrivate; - assert(pPriv); - pPriv->iBusy = 0; - pPriv->iError = 0; + assert(self); + pPriv = (pDoCho) self->pPrivate; + assert(pPriv); + pPriv->iBusy = 0; + pPriv->iError = 0; - /* first send, command, returns the echo */ - iRet = SerialWriteRead(&(pPriv->pData),"asyst 1",pBueffel,1023); - if(iRet < 0) - { - pPriv->iError = iRet; - return 0; - } - - /* next send: reads first chopper line */ - iRet = SerialWriteRead(&(pPriv->pData),"",pBueffel,1023); - if(iRet < 0) - { - pPriv->iError = iRet; - return 0; - } - SplitChopperReply(self,"chopper1",pBueffel); - - if(!pPriv->iSingle) - { - /* second send: get next second chopper line */ - iRet = SerialWriteRead(&(pPriv->pData),"",pBueffel,1023); - if(iRet < 0) - { - pPriv->iError = iRet; - return 0; - } - SplitChopperReply(self,"chopper2",pBueffel); - } - - - return 1; + /* first send, command, returns the echo */ + iRet = SerialWriteRead(&(pPriv->pData), "asyst 1", pBueffel, 1023); + if (iRet < 0) { + pPriv->iError = iRet; + return 0; } -/*-------------------------------------------------------------------------*/ - static int DoChoTask(void *pData) - { - pCodri self = NULL; - pDoCho pPriv = NULL; - int iCode, iRet; - char pDummy[60]; - self = (pCodri)pData; - assert(self); - pPriv = (pDoCho)self->pPrivate; - assert(pPriv); + /* next send: reads first chopper line */ + iRet = SerialWriteRead(&(pPriv->pData), "", pBueffel, 1023); + if (iRet < 0) { + pPriv->iError = iRet; + return 0; + } + SplitChopperReply(self, "chopper1", pBueffel); - /* check for stop */ - if(pPriv->iStop) - return 0; - - - /* check if it is time to run a status request */ - if(time(NULL) > pPriv->tRefresh) - { - /* try, fix error */ - if(pPriv->iError != 0) - { - self->GetError(self,&iCode,pDummy,59); - iRet = self->TryFixIt(self,iCode); - if(iRet == CHFAIL) - { - pPriv->tRefresh = time(NULL) + pPriv->iRefreshIntervall; - return 1; - } - } - /* do it */ - DoChoStatus(self); - pPriv->tRefresh = time(NULL) + pPriv->iRefreshIntervall; - } - return 1; - } -/*------------------------------------------------------------------------*/ - static void DoChoKill(void *pData) - { - pCodri self = NULL; - pDoCho pPriv = NULL; - - self = (pCodri)pData; - if(!self) - return; - pPriv = (pDoCho)self->pPrivate; - if(!pPriv) - return; - - - if(pPriv->pData) - { - SerialClose(&(pPriv->pData)); - pPriv->pData = NULL; + if (!pPriv->iSingle) { + /* second send: get next second chopper line */ + iRet = SerialWriteRead(&(pPriv->pData), "", pBueffel, 1023); + if (iRet < 0) { + pPriv->iError = iRet; + return 0; } + SplitChopperReply(self, "chopper2", pBueffel); + } - if(pPriv->pHost) - free(pPriv->pHost); - if(pPriv->pPar) - DeleteStringDict(pPriv->pPar); - free(pPriv); - } + return 1; +} + /*-------------------------------------------------------------------------*/ - static int DoChoInit(pCodri self) - { - pDoCho pPriv = NULL; - int iRet; +static int DoChoTask(void *pData) +{ + pCodri self = NULL; + pDoCho pPriv = NULL; + int iCode, iRet; + char pDummy[60]; - assert(self); - pPriv = (pDoCho)self->pPrivate; - assert(pPriv); - pPriv->iError = 0; + self = (pCodri) pData; + assert(self); + pPriv = (pDoCho) self->pPrivate; + assert(pPriv); - /* first open the connection to the serial port server and channel */ - iRet = SerialOpen(&(pPriv->pData),pPriv->pHost,pPriv->iPort, - pPriv->iChannel); - if(iRet <= 0) - { - pPriv->iError = iRet; - return 0; - } - /* configure the connection */ - SerialConfig(&(pPriv->pData),10000); - SerialATerm(&(pPriv->pData),"1\r\n"); - SerialSendTerm(&(pPriv->pData),"\r"); + /* check for stop */ + if (pPriv->iStop) + return 0; - pPriv->iStop = 0; - pPriv->tRefresh = 0; /* force a status request when first run */ - - /* start the update task */ - if(pPriv->lTask == 0) - { - pPriv->lTask = TaskRegister(pServ->pTasker, - DoChoTask, - NULL, - NULL, - self, - 1); - } - return 1; - } -/*------------------------------------------------------------------------*/ - static int DoChoClose(pCodri self) - { - pDoCho pPriv = NULL; - int iRet; - long lVal; - assert(self); - pPriv = (pDoCho)self->pPrivate; - assert(pPriv); - - if(pPriv->pData) - { - SerialClose(&(pPriv->pData)); - pPriv->pData = NULL; - } - return 1; + /* check if it is time to run a status request */ + if (time(NULL) > pPriv->tRefresh) { + /* try, fix error */ + if (pPriv->iError != 0) { + self->GetError(self, &iCode, pDummy, 59); + iRet = self->TryFixIt(self, iCode); + if (iRet == CHFAIL) { + pPriv->tRefresh = time(NULL) + pPriv->iRefreshIntervall; + return 1; + } + } + /* do it */ + DoChoStatus(self); + pPriv->tRefresh = time(NULL) + pPriv->iRefreshIntervall; } + return 1; +} + /*------------------------------------------------------------------------*/ - static int DoChoDelete(pCodri self) - { - pDoCho pPriv = NULL; +static void DoChoKill(void *pData) +{ + pCodri self = NULL; + pDoCho pPriv = NULL; - assert(self); - pPriv = (pDoCho)self->pPrivate; - assert(pPriv); + self = (pCodri) pData; + if (!self) + return; + pPriv = (pDoCho) self->pPrivate; + if (!pPriv) + return; - if(pPriv->pData) - { - SerialClose(&(pPriv->pData)); - pPriv->pData = NULL; - } - if(pPriv->pHost) - free(pPriv->pHost); - if(pPriv->pPar) - DeleteStringDict(pPriv->pPar); - - free(pPriv); - - return 1; + if (pPriv->pData) { + SerialClose(&(pPriv->pData)); + pPriv->pData = NULL; } + + if (pPriv->pHost) + free(pPriv->pHost); + if (pPriv->pPar) + DeleteStringDict(pPriv->pPar); + + free(pPriv); +} + +/*-------------------------------------------------------------------------*/ +static int DoChoInit(pCodri self) +{ + pDoCho pPriv = NULL; + int iRet; + + assert(self); + pPriv = (pDoCho) self->pPrivate; + assert(pPriv); + pPriv->iError = 0; + + /* first open the connection to the serial port server and channel */ + iRet = SerialOpen(&(pPriv->pData), pPriv->pHost, pPriv->iPort, + pPriv->iChannel); + if (iRet <= 0) { + pPriv->iError = iRet; + return 0; + } + /* configure the connection */ + SerialConfig(&(pPriv->pData), 10000); + SerialATerm(&(pPriv->pData), "1\r\n"); + SerialSendTerm(&(pPriv->pData), "\r"); + + pPriv->iStop = 0; + pPriv->tRefresh = 0; /* force a status request when first run */ + + /* start the update task */ + if (pPriv->lTask == 0) { + pPriv->lTask = TaskRegister(pServ->pTasker, + DoChoTask, NULL, NULL, self, 1); + } + return 1; +} + +/*------------------------------------------------------------------------*/ +static int DoChoClose(pCodri self) +{ + pDoCho pPriv = NULL; + int iRet; + long lVal; + + assert(self); + pPriv = (pDoCho) self->pPrivate; + assert(pPriv); + + if (pPriv->pData) { + SerialClose(&(pPriv->pData)); + pPriv->pData = NULL; + } + return 1; +} + +/*------------------------------------------------------------------------*/ +static int DoChoDelete(pCodri self) +{ + pDoCho pPriv = NULL; + + assert(self); + pPriv = (pDoCho) self->pPrivate; + assert(pPriv); + + if (pPriv->pData) { + SerialClose(&(pPriv->pData)); + pPriv->pData = NULL; + } + + if (pPriv->pHost) + free(pPriv->pHost); + if (pPriv->pPar) + DeleteStringDict(pPriv->pPar); + + free(pPriv); + + return 1; +} + /*--------------------------------------------------------------------------*/ - static int DoChoSetPar2(pCodri self, char *parname, char *pValue) - { - pDoCho pPriv = NULL; - char pCommand[80], pReply[132]; - char pState[20]; - int iRet; +static int DoChoSetPar2(pCodri self, char *parname, char *pValue) +{ + pDoCho pPriv = NULL; + char pCommand[80], pReply[132]; + char pState[20]; + int iRet; - assert(self); - pPriv = (pDoCho)self->pPrivate; - assert(pPriv); + assert(self); + pPriv = (pDoCho) self->pPrivate; + assert(pPriv); - /* deal with our four parameters */ - if(strcmp(parname,"chopper1.nspee") == 0) - { - sprintf(pCommand,"nspee 1 %s",pValue); - } - else if(strcmp(parname,"chopper2.nspee") == 0) - { - iRet = StringDictGet(pPriv->pPar,"chopper2.state",pState,19); - if(iRet && strstr(pState,"async") != NULL ) - { - sprintf(pCommand,"nspee 2 %s",pValue); - } - else - { - pPriv->iError = BADSYNC; - return 0; - } - } - else if(strcmp(parname,"chopper2.nphas") == 0) - { - sprintf(pCommand,"nphas 2 %s",pValue); - } - else if(strcmp(parname,"chopper1.nphas") == 0) - { - sprintf(pCommand,"nphas 1 %s",pValue); - } - else if(strcmp(parname,"chopper2.ratio") == 0) - { - sprintf(pCommand,"ratio 2 %s",pValue); - } - else - { - pPriv->iError = UNDRIVABLE; - return 0; - } - - iRet = SerialWriteRead(&(pPriv->pData),pCommand,pReply,131); - if(iRet != 1) - { - pPriv->iError = iRet; - return 0; - } - if(strstr(pReply,"error") != NULL) - { - pPriv->iError = CHOPERROR; - strncpy(pPriv->pError,pReply,79); - return 0; - } - else - { - pPriv->iError = 0; - } - pPriv->iBusy = 1; - return 1; + /* deal with our four parameters */ + if (strcmp(parname, "chopper1.nspee") == 0) { + sprintf(pCommand, "nspee 1 %s", pValue); + } else if (strcmp(parname, "chopper2.nspee") == 0) { + iRet = StringDictGet(pPriv->pPar, "chopper2.state", pState, 19); + if (iRet && strstr(pState, "async") != NULL) { + sprintf(pCommand, "nspee 2 %s", pValue); + } else { + pPriv->iError = BADSYNC; + return 0; + } + } else if (strcmp(parname, "chopper2.nphas") == 0) { + sprintf(pCommand, "nphas 2 %s", pValue); + } else if (strcmp(parname, "chopper1.nphas") == 0) { + sprintf(pCommand, "nphas 1 %s", pValue); + } else if (strcmp(parname, "chopper2.ratio") == 0) { + sprintf(pCommand, "ratio 2 %s", pValue); + } else { + pPriv->iError = UNDRIVABLE; + return 0; } + + iRet = SerialWriteRead(&(pPriv->pData), pCommand, pReply, 131); + if (iRet != 1) { + pPriv->iError = iRet; + return 0; + } + if (strstr(pReply, "error") != NULL) { + pPriv->iError = CHOPERROR; + strncpy(pPriv->pError, pReply, 79); + return 0; + } else { + pPriv->iError = 0; + } + pPriv->iBusy = 1; + return 1; +} + /*-------------------------------------------------------------------------*/ - static int DoChoHalt(pCodri self) - { - pDoCho pPriv = NULL; +static int DoChoHalt(pCodri self) +{ + pDoCho pPriv = NULL; - assert(self); - pPriv = (pDoCho)self->pPrivate; - assert(pPriv); + assert(self); + pPriv = (pDoCho) self->pPrivate; + assert(pPriv); + + /* + there is no documented way to stop the Dornier chopper + system. This at least makes SICS happy. + */ + pPriv->iError = BADSTOP; + pPriv->iBusy = 0; + return 1; +} - /* - there is no documented way to stop the Dornier chopper - system. This at least makes SICS happy. - */ - pPriv->iError = BADSTOP; - pPriv->iBusy = 0; - return 1; - } /*---------------------------------------------------------------------------*/ - static int DoChoSetPar(pCodri self, char *parname, float fValue) - { - char pValue[50]; - pDoCho pPriv = NULL; +static int DoChoSetPar(pCodri self, char *parname, float fValue) +{ + char pValue[50]; + pDoCho pPriv = NULL; - assert(self); - pPriv = (pDoCho)self->pPrivate; - assert(pPriv); + assert(self); + pPriv = (pDoCho) self->pPrivate; + assert(pPriv); - if(strstr(parname,"nspee") != NULL) - { - sprintf(pValue,"%d",(int)fValue); - } - else if(strstr(parname,"ratio") != NULL) - { - sprintf(pValue,"%d",(int)fValue); - pPriv->fRatio = (int)fValue; - } - else if(strcmp(parname,"updateintervall") == 0) - { - sprintf(pValue,"%d",(int)fValue); - StringDictUpdate(pPriv->pPar,"updateintervall",pValue); - pPriv->iRefreshIntervall = (int)fValue; - return 1; - } - else - { - sprintf(pValue,"%f",fValue); - } - return DoChoSetPar2(self,parname, pValue); + if (strstr(parname, "nspee") != NULL) { + sprintf(pValue, "%d", (int) fValue); + } else if (strstr(parname, "ratio") != NULL) { + sprintf(pValue, "%d", (int) fValue); + pPriv->fRatio = (int) fValue; + } else if (strcmp(parname, "updateintervall") == 0) { + sprintf(pValue, "%d", (int) fValue); + StringDictUpdate(pPriv->pPar, "updateintervall", pValue); + pPriv->iRefreshIntervall = (int) fValue; + return 1; + } else { + sprintf(pValue, "%f", fValue); } + return DoChoSetPar2(self, parname, pValue); +} + /*----------------------------------------------------------------------*/ - static int DoChoGetPar(pCodri self, char *parname, - char *pBuffer, int iBufLen) - { - pDoCho pPriv = NULL; - int iRet; +static int DoChoGetPar(pCodri self, char *parname, + char *pBuffer, int iBufLen) +{ + pDoCho pPriv = NULL; + int iRet; - assert(self); - pPriv = (pDoCho)self->pPrivate; - assert(pPriv); + assert(self); + pPriv = (pDoCho) self->pPrivate; + assert(pPriv); - if(pPriv->iError != 0) - { - self->GetError(self,&iRet,pBuffer,iBufLen); - return 0; - } - - iRet = StringDictGet(pPriv->pPar,parname,pBuffer,iBufLen); - if(!iRet) - { - pPriv->iError = UNKNOWNPAR; - return 0; - } - return 1; + if (pPriv->iError != 0) { + self->GetError(self, &iRet, pBuffer, iBufLen); + return 0; } + + iRet = StringDictGet(pPriv->pPar, parname, pBuffer, iBufLen); + if (!iRet) { + pPriv->iError = UNKNOWNPAR; + return 0; + } + return 1; +} + /*-----------------------------------------------------------------------*/ - static int DoChoCheckPar(pCodri self, char *parname) - { - pDoCho pPriv = NULL; - char pVal1[20], pVal2[20]; - float fTarget, fIst, fDelta; - int iRet; +static int DoChoCheckPar(pCodri self, char *parname) +{ + pDoCho pPriv = NULL; + char pVal1[20], pVal2[20]; + float fTarget, fIst, fDelta; + int iRet; - assert(self); - pPriv = (pDoCho)self->pPrivate; - assert(pPriv); + assert(self); + pPriv = (pDoCho) self->pPrivate; + assert(pPriv); - /* check the busy flag first */ - if(pPriv->iBusy) - return HWBusy; + /* check the busy flag first */ + if (pPriv->iBusy) + return HWBusy; - /* was there an error in the status show? */ - if(pPriv->iError != 0) - { - return HWFault; - } - - /* updateintervall is always HWIdle */ - if(strcmp(parname,"updateintervall") == 0) - { - return HWIdle; - } - - /* OK, got a new status let us check the parameter */ - /* chopper 1 speed */ - if(strcmp(parname,"chopper1.nspee") == 0) - { - iRet = StringDictGet(pPriv->pPar,"chopper1.nspee",pVal1,19); - iRet += StringDictGet(pPriv->pPar,"chopper1.aspee",pVal2,19); - if(iRet != 2) - { - pPriv->iError = PARERROR; - return HWFault; - } - sscanf(pVal1,"%f",&fTarget); - sscanf(pVal2,"%f",&fIst); - fDelta = fTarget - fIst; - if(fDelta < 0.0) - fDelta = -fDelta; - if(fDelta > 50) - { - return HWBusy; - } - else - { - return HWIdle; - } - } - /* chopper 2 speed */ - if(strcmp(parname,"chopper2.nspee") == 0) - { - iRet = StringDictGet(pPriv->pPar,"chopper2.nspee",pVal1,19); - iRet += StringDictGet(pPriv->pPar,"chopper2.aspee",pVal2,19); - if(iRet != 2) - { - pPriv->iError = PARERROR; - return HWFault; - } - sscanf(pVal1,"%f",&fTarget); - sscanf(pVal2,"%f",&fIst); - fDelta = fTarget - fIst; - if(fDelta < 0.0) - fDelta = -fDelta; - if(fDelta > 5.) - { - return HWBusy; - } - else - { - return HWIdle; - } - } - - /* phase */ - if(strcmp(parname,"chopper2.nphas") == 0) - { - iRet = StringDictGet(pPriv->pPar,"chopper2.dphas",pVal1,19); - sscanf(pVal1,"%f",&fDelta); - if(fDelta < 0.) - fDelta = - fDelta; - if(fDelta > 0.3) - { - return HWBusy; - } - else - { - return HWIdle; - } - } - if(strcmp(parname,"chopper1.nphas") == 0) - { - iRet = StringDictGet(pPriv->pPar,"chopper1.dphas",pVal1,19); - sscanf(pVal1,"%f",&fDelta); - if(fDelta < 0.) - fDelta = - fDelta; - if(fDelta > 0.3) - { - return HWBusy; - } - else - { - return HWIdle; - } - } - - /* ratio */ - if(strcmp(parname,"chopper2.ratio") == 0) - { - iRet = StringDictGet(pPriv->pPar,"chopper2.ratio",pVal1,19); - sscanf(pVal1,"%f",&fIst); - fDelta = fIst - pPriv->fRatio; - if(fDelta < 0.) - fDelta = - fDelta; - if(fDelta > 0.3) - { - return HWBusy; - } - else - { - return HWIdle; - } - } - pPriv->iError = UNKNOWNPAR; - return HWFault; - } -/*-------------------------------------------------------------------------*/ - static int DoChoError(pCodri self, int *iCode, char *pError, int iLen) - { - pDoCho pPriv = NULL; - - assert(self); - pPriv = (pDoCho)self->pPrivate; - assert(pPriv); - - *iCode = pPriv->iError; - switch(pPriv->iError) - { - case UNDRIVABLE: - strncpy(pError,"Parameter is not drivable",iLen); - break; - case UNKNOWNPAR: - strncpy(pError,"Parameter is unknown",iLen); - break; - case PARERROR: - strncpy(pError,"Internal parameter error",iLen); - break; - case BADSYNC: - strncpy(pError,"Cannot drive slave chopper",iLen); - break; - case CHOPERROR: - strncpy(pError,pPriv->pError,iLen); - break; - case BADSTOP: - strncpy(pError, - "User called STOP. WARNING: chopper is still untamed!", - iLen); - break; - default: - SerialError(pPriv->iError,pError,iLen); - break; - } - pPriv->iError = 0; - return 1; + /* was there an error in the status show? */ + if (pPriv->iError != 0) { + return HWFault; } -/*------------------------------------------------------------------------*/ - static int DoChoFix(pCodri self, int iCode) - { - pDoCho pPriv = NULL; - int iRet; - assert(self); - pPriv = (pDoCho)self->pPrivate; - assert(pPriv); + /* updateintervall is always HWIdle */ + if (strcmp(parname, "updateintervall") == 0) { + return HWIdle; + } + + /* OK, got a new status let us check the parameter */ + /* chopper 1 speed */ + if (strcmp(parname, "chopper1.nspee") == 0) { + iRet = StringDictGet(pPriv->pPar, "chopper1.nspee", pVal1, 19); + iRet += StringDictGet(pPriv->pPar, "chopper1.aspee", pVal2, 19); + if (iRet != 2) { + pPriv->iError = PARERROR; + return HWFault; + } + sscanf(pVal1, "%f", &fTarget); + sscanf(pVal2, "%f", &fIst); + fDelta = fTarget - fIst; + if (fDelta < 0.0) + fDelta = -fDelta; + if (fDelta > 50) { + return HWBusy; + } else { + return HWIdle; + } + } + /* chopper 2 speed */ + if (strcmp(parname, "chopper2.nspee") == 0) { + iRet = StringDictGet(pPriv->pPar, "chopper2.nspee", pVal1, 19); + iRet += StringDictGet(pPriv->pPar, "chopper2.aspee", pVal2, 19); + if (iRet != 2) { + pPriv->iError = PARERROR; + return HWFault; + } + sscanf(pVal1, "%f", &fTarget); + sscanf(pVal2, "%f", &fIst); + fDelta = fTarget - fIst; + if (fDelta < 0.0) + fDelta = -fDelta; + if (fDelta > 5.) { + return HWBusy; + } else { + return HWIdle; + } + } + + /* phase */ + if (strcmp(parname, "chopper2.nphas") == 0) { + iRet = StringDictGet(pPriv->pPar, "chopper2.dphas", pVal1, 19); + sscanf(pVal1, "%f", &fDelta); + if (fDelta < 0.) + fDelta = -fDelta; + if (fDelta > 0.3) { + return HWBusy; + } else { + return HWIdle; + } + } + if (strcmp(parname, "chopper1.nphas") == 0) { + iRet = StringDictGet(pPriv->pPar, "chopper1.dphas", pVal1, 19); + sscanf(pVal1, "%f", &fDelta); + if (fDelta < 0.) + fDelta = -fDelta; + if (fDelta > 0.3) { + return HWBusy; + } else { + return HWIdle; + } + } + + /* ratio */ + if (strcmp(parname, "chopper2.ratio") == 0) { + iRet = StringDictGet(pPriv->pPar, "chopper2.ratio", pVal1, 19); + sscanf(pVal1, "%f", &fIst); + fDelta = fIst - pPriv->fRatio; + if (fDelta < 0.) + fDelta = -fDelta; + if (fDelta > 0.3) { + return HWBusy; + } else { + return HWIdle; + } + } + pPriv->iError = UNKNOWNPAR; + return HWFault; +} - switch(iCode) - { - /* network errors */ - case EL734__BAD_FLUSH: - case EL734__BAD_RECV: - case EL734__BAD_RECV_NET: - case EL734__BAD_RECV_UNKN: - case EL734__BAD_RECVLEN: - case EL734__BAD_RECV1: - case EL734__BAD_RECV1_PIPE: - case EL734__BAD_RNG: - case EL734__BAD_SEND: - case EL734__BAD_SEND_PIPE: - case EL734__BAD_SEND_NET: - case EL734__BAD_SEND_UNKN: - case EL734__BAD_SENDLEN: - case NOCONNECTION: - SerialForceClose(&(pPriv->pData)); - pPriv->pData = NULL; - iRet = SerialOpen(&(pPriv->pData),pPriv->pHost, - pPriv->iPort,pPriv->iChannel); - if(iRet == 1 ) - { - return CHREDO; - } - else - { - return CHFAIL; - } - break; - case EL734__FORCED_CLOSED: - iRet = DoChoInit(self); - if(iRet) - { - return CHREDO; - } - else - { - return CHFAIL; - } - break; - default: - return CHFAIL; - break; - } - return CHFAIL; - } /*-------------------------------------------------------------------------*/ - pCodri MakeDoChoDriver(char *pHost, int iPort, int iChannel, int iSingle) - { - pCodri pNew = NULL; - pDoCho pPriv = NULL; - char *pText; +static int DoChoError(pCodri self, int *iCode, char *pError, int iLen) +{ + pDoCho pPriv = NULL; - /* allocate memory */ - pText = (char *)malloc(4096*sizeof(char)); - pNew = (pCodri)malloc(sizeof(Codri)); - pPriv = (pDoCho)malloc(sizeof(DoCho)); - if( !pText || !pNew || !pPriv) - { - return NULL; - } - memset(pText,0,4096); - memset(pNew,0,sizeof(Codri)); - memset(pPriv,0,sizeof(DoCho)); + assert(self); + pPriv = (pDoCho) self->pPrivate; + assert(pPriv); - /* initialize private data structure */ - pPriv->pHost = strdup(pHost); - pPriv->iPort = iPort; - pPriv->iChannel = iChannel; - pPriv->pData = NULL; - pPriv->iRefreshIntervall = 60; - pPriv->pPar = CreateStringDict(); - pPriv->tRefresh = time(NULL); - pPriv->iSingle = iSingle; - if(!pPriv->pPar) - { - free(pText); - free(pNew); - free(pPriv); - return NULL; - } + *iCode = pPriv->iError; + switch (pPriv->iError) { + case UNDRIVABLE: + strncpy(pError, "Parameter is not drivable", iLen); + break; + case UNKNOWNPAR: + strncpy(pError, "Parameter is unknown", iLen); + break; + case PARERROR: + strncpy(pError, "Internal parameter error", iLen); + break; + case BADSYNC: + strncpy(pError, "Cannot drive slave chopper", iLen); + break; + case CHOPERROR: + strncpy(pError, pPriv->pError, iLen); + break; + case BADSTOP: + strncpy(pError, + "User called STOP. WARNING: chopper is still untamed!", iLen); + break; + default: + SerialError(pPriv->iError, pError, iLen); + break; + } + pPriv->iError = 0; + return 1; +} - /* install codri */ - pNew->Init = DoChoInit; - pNew->Close = DoChoClose; - pNew->Delete = DoChoDelete; - pNew->SetPar = DoChoSetPar; - pNew->SetPar2 = DoChoSetPar2; - pNew->GetPar = DoChoGetPar; - pNew->CheckPar = DoChoCheckPar; - pNew->GetError = DoChoError; - pNew->TryFixIt = DoChoFix; - pNew->Halt = DoChoHalt; - pNew->pParList = pText; - strcpy(pNew->pParList,"updateintervall,"); - StringDictAddPair(pPriv->pPar,"updateintervall","60"); - pNew->pPrivate = pPriv; +/*------------------------------------------------------------------------*/ +static int DoChoFix(pCodri self, int iCode) +{ + pDoCho pPriv = NULL; + int iRet; - return pNew; - } + assert(self); + pPriv = (pDoCho) self->pPrivate; + assert(pPriv); + switch (iCode) { + /* network errors */ + case EL734__BAD_FLUSH: + case EL734__BAD_RECV: + case EL734__BAD_RECV_NET: + case EL734__BAD_RECV_UNKN: + case EL734__BAD_RECVLEN: + case EL734__BAD_RECV1: + case EL734__BAD_RECV1_PIPE: + case EL734__BAD_RNG: + case EL734__BAD_SEND: + case EL734__BAD_SEND_PIPE: + case EL734__BAD_SEND_NET: + case EL734__BAD_SEND_UNKN: + case EL734__BAD_SENDLEN: + case NOCONNECTION: + SerialForceClose(&(pPriv->pData)); + pPriv->pData = NULL; + iRet = SerialOpen(&(pPriv->pData), pPriv->pHost, + pPriv->iPort, pPriv->iChannel); + if (iRet == 1) { + return CHREDO; + } else { + return CHFAIL; + } + break; + case EL734__FORCED_CLOSED: + iRet = DoChoInit(self); + if (iRet) { + return CHREDO; + } else { + return CHFAIL; + } + break; + default: + return CHFAIL; + break; + } + return CHFAIL; +} +/*-------------------------------------------------------------------------*/ +pCodri MakeDoChoDriver(char *pHost, int iPort, int iChannel, int iSingle) +{ + pCodri pNew = NULL; + pDoCho pPriv = NULL; + char *pText; + /* allocate memory */ + pText = (char *) malloc(4096 * sizeof(char)); + pNew = (pCodri) malloc(sizeof(Codri)); + pPriv = (pDoCho) malloc(sizeof(DoCho)); + if (!pText || !pNew || !pPriv) { + return NULL; + } + memset(pText, 0, 4096); + memset(pNew, 0, sizeof(Codri)); + memset(pPriv, 0, sizeof(DoCho)); + /* initialize private data structure */ + pPriv->pHost = strdup(pHost); + pPriv->iPort = iPort; + pPriv->iChannel = iChannel; + pPriv->pData = NULL; + pPriv->iRefreshIntervall = 60; + pPriv->pPar = CreateStringDict(); + pPriv->tRefresh = time(NULL); + pPriv->iSingle = iSingle; + if (!pPriv->pPar) { + free(pText); + free(pNew); + free(pPriv); + return NULL; + } + + /* install codri */ + pNew->Init = DoChoInit; + pNew->Close = DoChoClose; + pNew->Delete = DoChoDelete; + pNew->SetPar = DoChoSetPar; + pNew->SetPar2 = DoChoSetPar2; + pNew->GetPar = DoChoGetPar; + pNew->CheckPar = DoChoCheckPar; + pNew->GetError = DoChoError; + pNew->TryFixIt = DoChoFix; + pNew->Halt = DoChoHalt; + pNew->pParList = pText; + strcpy(pNew->pParList, "updateintervall,"); + StringDictAddPair(pPriv->pPar, "updateintervall", "60"); + pNew->pPrivate = pPriv; + + return pNew; +} diff --git a/dornier2.c b/dornier2.c index 60d7a9b..815486b 100644 --- a/dornier2.c +++ b/dornier2.c @@ -53,337 +53,350 @@ typedef struct __VelSelDriv *pVelSelDriv; #define STATSEND 1 #define STATREAD 2 /*----------------------------- The private data structure ---------------*/ - typedef struct{ - prs232 controller; - int iTimeOut; - int iLastError; - time_t t_End; - time_t t_timeout; - float fTarget; - float fLastRPM; - int statusMode; - DornierStatus lastStatus; - int minRPM; /* the minimum control speed of the thing*/ - int haltCount; - int rejectCount; - int noStatus; /* flag which indicates that no valid status - has yet been read. Solves a starting - problem - */ - int firstStatus; /* at times the nvs does not send - the reply to the first status - request after starting. This flag - helps to suppress an error message - which may be confusing to loosers - */ - } Dornier, *pDornier; +typedef struct { + prs232 controller; + int iTimeOut; + int iLastError; + time_t t_End; + time_t t_timeout; + float fTarget; + float fLastRPM; + int statusMode; + DornierStatus lastStatus; + int minRPM; /* the minimum control speed of the thing */ + int haltCount; + int rejectCount; + int noStatus; /* flag which indicates that no valid status + has yet been read. Solves a starting + problem + */ + int firstStatus; /* at times the nvs does not send + the reply to the first status + request after starting. This flag + helps to suppress an error message + which may be confusing to loosers + */ +} Dornier, *pDornier; /*------------------------------------------------------------------*/ -static int requestDornierStatus(pDornier pDorn){ +static int requestDornierStatus(pDornier pDorn) +{ int status; - status = writeRS232(pDorn->controller,"???\n",4); - if(status < 0){ + status = writeRS232(pDorn->controller, "???\n", 4); + if (status < 0) { pDorn->iLastError = status; return 0; } return 1; } + /*------------------------------------------------------------------*/ -static int readAndInterpretStatus(pDornier pDorn, DornierStatus *DStatus){ +static int readAndInterpretStatus(pDornier pDorn, DornierStatus * DStatus) +{ int status, datalen; char reply[512]; datalen = 512; - status = readRS232TillTerm(pDorn->controller,reply,&datalen); - if(status < 0){ + status = readRS232TillTerm(pDorn->controller, reply, &datalen); + if (status < 0) { pDorn->iLastError = status; return 0; } - if(strlen(reply) < 80){ + if (strlen(reply) < 80) { pDorn->iLastError = INVALIDSTATUS; pDorn->statusMode = STATSEND; return 0; } - DecodeNewDornierStatus(reply,DStatus); - if(pDorn->noStatus == 1){ + DecodeNewDornierStatus(reply, DStatus); + if (pDorn->noStatus == 1) { pDorn->noStatus = 0; } return 1; } + /*-----------------------------------------------------------------*/ -static int takeControl(pDornier pDorn){ +static int takeControl(pDornier pDorn) +{ int iRet; char pError[80]; - setRS232ReplyTerminator(pDorn->controller,"\\"); - iRet = transactRS232(pDorn->controller,"REM\n",4,pError,79); - setRS232ReplyTerminator(pDorn->controller,"\n"); + setRS232ReplyTerminator(pDorn->controller, "\\"); + iRet = transactRS232(pDorn->controller, "REM\n", 4, pError, 79); + setRS232ReplyTerminator(pDorn->controller, "\n"); return iRet; } + /*--------------------------------------------------------------------*/ - static int GetDornierPos(pVelSelDriv self, float *fPos) - { - pDornier pDorn = NULL; - DornierStatus DStatus; - int status; - - assert(self); - pDorn = (pDornier)self->pPrivate; - - if(pDorn->statusMode == STATSEND){ - if(!requestDornierStatus(pDorn)){ - *fPos = -9999.; - return 0; - } - if(!readAndInterpretStatus(pDorn,&DStatus)){ - *fPos = -9999.; - return 0; - } - pDorn->lastStatus = DStatus; - } - - *fPos = pDorn->lastStatus.cur_rpm; - pDorn->fLastRPM = pDorn->lastStatus.cur_rpm; - return 1; - } -/*--------------------------------------------------------------------------*/ - static int DornierHalt(pVelSelDriv self) - { - pDornier pDorn = NULL; - int iRet; - char pCom[50]; - char pAnswer[80]; - - assert(self); - pDorn = (pDornier)self->pPrivate; - - snprintf(pCom,49,"SDR %d\n",pDorn->minRPM); - iRet = transactRS232(pDorn->controller,pCom,strlen(pCom), - pAnswer,79); - if(iRet < 1) - { - pDorn->iLastError = iRet; - return 0; - } - return 1; - } -/*----------------------------------------------------------------------*/ - static int DornierText(pVelSelDriv self, char *pText, int iTextLen) - { - pDornier pDorn = NULL; - int iRet, iErrStat; - DornierStatus sStatus; - char pBueffel[1024]; - char pHelp[80]; - - assert(self); - pDorn = (pDornier)self->pPrivate; - - /* - use cached status while waiting for reply during drive - */ - if(pDorn->statusMode == STATSEND){ - if(!requestDornierStatus(pDorn)){ - return 0; - } - if(!readAndInterpretStatus(pDorn,&sStatus)){ - return 0; - } - pDorn->lastStatus = sStatus; - } else { - sStatus = pDorn->lastStatus; - } - - /* format it to a string */ - sprintf(pHelp,"RPM: %d , should %d\n",sStatus.cur_rpm,sStatus.nom_rpm); - strcpy(pBueffel,pHelp); - sprintf(pHelp,"State: %s\n",sStatus.rm); - strcat(pBueffel,pHelp); - sprintf(pHelp,"Current: %d\n",sStatus.pwr); - strcat(pBueffel,pHelp); - sprintf(pHelp,"Rotor T: %d, Housing T: %d\n",sStatus.rot_temp, - sStatus.cont_temp); - strcat(pBueffel,pHelp); - sprintf(pHelp,"Cooling: In-T: %d, Out-T: %d, Flow: %f\n", - sStatus.inl_temp,sStatus.outl_temp,sStatus.cool_wat); - strcat(pBueffel,pHelp); - sprintf(pHelp,"Vaccum: %f, Accel: %f",sStatus.vacuum, sStatus.accel); - strcat(pBueffel,pHelp); - - strncpy(pText,pBueffel, iTextLen); - return 1; - } -/*-------------------------------------------------------------------------*/ - static int DornierRun(pVelSelDriv self, float fVal) - { - int iRet; - char pCommand[50], pAnswer[50], pText[132]; - pDornier pDorn = NULL; - int startFlag = 0; - int i; - DornierStatus sStatus; - - assert(self); - pDorn = (pDornier)self->pPrivate; - - /* - make sure that a status was read before we do anything here, - otherwise we may be in deep trouble - */ - if(pDorn->statusMode == STATSEND){ - iRet = requestDornierStatus(pDorn); - if(iRet == 0){ - return 0; - } - } - iRet = readAndInterpretStatus(pDorn,&sStatus); - if(iRet == 0){ - return 0; - } - pDorn->lastStatus = sStatus; - - /* - less then STARTSPEED, means halt in this case. - Accept this only after three times, see code in GetError as well. - */ - if(fVal < 0){ - fVal = - fVal; - } - memset(pCommand,0,50); - pDorn->rejectCount = 0; - - if(fVal < STARTSPEED - 3*self->fTolerance) - { - if(pDorn->haltCount < 3){ - pDorn->iLastError = HALTREQ; - return 0; - } - strcpy(pCommand,"HAL\n"); - setRS232ReplyTerminator(pDorn->controller,"\r"); - pDorn->haltCount = 0; - pDorn->fTarget = fVal; - } else { - if(pDorn->lastStatus.cur_rpm < STARTSPEED - 3 * self->fTolerance){ - strcpy(pCommand,"SST\n"); - startFlag = 1; - pDorn->fTarget = STARTSPEED; - setRS232ReplyTerminator(pDorn->controller,"\r"); - } else { - setRS232ReplyTerminator(pDorn->controller,"\r"); - sprintf(pCommand,"SDR %d\n",(int)fVal); - pDorn->fTarget = fVal; - } - } - - iRet = transactRS232(pDorn->controller,pCommand,strlen(pCommand), - pAnswer,49); - setRS232ReplyTerminator(pDorn->controller,"\n"); - pDorn->firstStatus = 1; - if(iRet < 1) - { - if(iRet != INCOMPLETE){ - - pDorn->iLastError = iRet; - return 0; - } - } - pDorn->statusMode = STATSEND; - if(startFlag){ - pDorn->iLastError = STARTED; - return 0; - } - return 1; - } -/*---------------------------------------------------------------------*/ -static int DornierError(pVelSelDriv self, int *iCode, - char *error, int iErrLen){ - pDornier pDorn = NULL; - - assert(self); - pDorn = (pDornier)self->pPrivate; - - *iCode = pDorn->iLastError; - - switch(pDorn->iLastError){ - case HALTREQ: - strncpy(error,"Repeat command if you really want to HALT selector", - iErrLen); - pDorn->haltCount++; - break; - case STARTED: - strncpy(error, - "Started selector, standby and check manually when ready", - iErrLen); - break; - case INVALIDSTATUS: - strncpy(error,"Received invalid status reply",iErrLen); - break; - case TARGETREJECTED: - strncpy(error,"VS in local mode or target out of range", iErrLen); - break; - case NOSTATUS: - strncpy(error,"No successfull status request after 3 tries", - iErrLen); - break; - default: - getRS232Error(pDorn->iLastError,error,iErrLen); - break; - } - return 1; -} -/*-------------------------------------------------------------------*/ -static int DornierFixIt(pVelSelDriv self, int iCode){ - pDornier pDorn = NULL; - int status, oldReject; - - assert(self); - pDorn = (pDornier)self->pPrivate; - - switch(iCode){ - case NOTCONNECTED: - status = initRS232(pDorn->controller); - if(status){ - return VELOREDO; - } else { - return VELOFAIL; - } - break; - case TIMEOUT: - case INCOMPLETE: - case INVALIDSTATUS: - return VELOREDO; - break; - case TARGETREJECTED: - if(pDorn->rejectCount >= 3){ - pDorn->rejectCount = 0; - return VELOFAIL; - } - oldReject = pDorn->rejectCount; - status = takeControl(pDorn); - if(status >= 1){ - DornierRun(self,pDorn->fTarget); - pDorn->rejectCount = oldReject + 1; - return VELOREDO; - } - return VELOFAIL; - break; - default: - return VELOFAIL; - } -} -/*---------------------------------------------------------------------*/ -static int statusSendHandler(pDornier pDorn){ +static int GetDornierPos(pVelSelDriv self, float *fPos) +{ + pDornier pDorn = NULL; + DornierStatus DStatus; int status; - if(!requestDornierStatus(pDorn)){ + assert(self); + pDorn = (pDornier) self->pPrivate; + + if (pDorn->statusMode == STATSEND) { + if (!requestDornierStatus(pDorn)) { + *fPos = -9999.; + return 0; + } + if (!readAndInterpretStatus(pDorn, &DStatus)) { + *fPos = -9999.; + return 0; + } + pDorn->lastStatus = DStatus; + } + + *fPos = pDorn->lastStatus.cur_rpm; + pDorn->fLastRPM = pDorn->lastStatus.cur_rpm; + return 1; +} + +/*--------------------------------------------------------------------------*/ +static int DornierHalt(pVelSelDriv self) +{ + pDornier pDorn = NULL; + int iRet; + char pCom[50]; + char pAnswer[80]; + + assert(self); + pDorn = (pDornier) self->pPrivate; + + snprintf(pCom, 49, "SDR %d\n", pDorn->minRPM); + iRet = transactRS232(pDorn->controller, pCom, strlen(pCom), pAnswer, 79); + if (iRet < 1) { + pDorn->iLastError = iRet; + return 0; + } + return 1; +} + +/*----------------------------------------------------------------------*/ +static int DornierText(pVelSelDriv self, char *pText, int iTextLen) +{ + pDornier pDorn = NULL; + int iRet, iErrStat; + DornierStatus sStatus; + char pBueffel[1024]; + char pHelp[80]; + + assert(self); + pDorn = (pDornier) self->pPrivate; + + /* + use cached status while waiting for reply during drive + */ + if (pDorn->statusMode == STATSEND) { + if (!requestDornierStatus(pDorn)) { + return 0; + } + if (!readAndInterpretStatus(pDorn, &sStatus)) { + return 0; + } + pDorn->lastStatus = sStatus; + } else { + sStatus = pDorn->lastStatus; + } + + /* format it to a string */ + sprintf(pHelp, "RPM: %d , should %d\n", sStatus.cur_rpm, + sStatus.nom_rpm); + strcpy(pBueffel, pHelp); + sprintf(pHelp, "State: %s\n", sStatus.rm); + strcat(pBueffel, pHelp); + sprintf(pHelp, "Current: %d\n", sStatus.pwr); + strcat(pBueffel, pHelp); + sprintf(pHelp, "Rotor T: %d, Housing T: %d\n", sStatus.rot_temp, + sStatus.cont_temp); + strcat(pBueffel, pHelp); + sprintf(pHelp, "Cooling: In-T: %d, Out-T: %d, Flow: %f\n", + sStatus.inl_temp, sStatus.outl_temp, sStatus.cool_wat); + strcat(pBueffel, pHelp); + sprintf(pHelp, "Vaccum: %f, Accel: %f", sStatus.vacuum, sStatus.accel); + strcat(pBueffel, pHelp); + + strncpy(pText, pBueffel, iTextLen); + return 1; +} + +/*-------------------------------------------------------------------------*/ +static int DornierRun(pVelSelDriv self, float fVal) +{ + int iRet; + char pCommand[50], pAnswer[50], pText[132]; + pDornier pDorn = NULL; + int startFlag = 0; + int i; + DornierStatus sStatus; + + assert(self); + pDorn = (pDornier) self->pPrivate; + + /* + make sure that a status was read before we do anything here, + otherwise we may be in deep trouble + */ + if (pDorn->statusMode == STATSEND) { + iRet = requestDornierStatus(pDorn); + if (iRet == 0) { + return 0; + } + } + iRet = readAndInterpretStatus(pDorn, &sStatus); + if (iRet == 0) { + return 0; + } + pDorn->lastStatus = sStatus; + + /* + less then STARTSPEED, means halt in this case. + Accept this only after three times, see code in GetError as well. + */ + if (fVal < 0) { + fVal = -fVal; + } + memset(pCommand, 0, 50); + pDorn->rejectCount = 0; + + if (fVal < STARTSPEED - 3 * self->fTolerance) { + if (pDorn->haltCount < 3) { + pDorn->iLastError = HALTREQ; + return 0; + } + strcpy(pCommand, "HAL\n"); + setRS232ReplyTerminator(pDorn->controller, "\r"); + pDorn->haltCount = 0; + pDorn->fTarget = fVal; + } else { + if (pDorn->lastStatus.cur_rpm < STARTSPEED - 3 * self->fTolerance) { + strcpy(pCommand, "SST\n"); + startFlag = 1; + pDorn->fTarget = STARTSPEED; + setRS232ReplyTerminator(pDorn->controller, "\r"); + } else { + setRS232ReplyTerminator(pDorn->controller, "\r"); + sprintf(pCommand, "SDR %d\n", (int) fVal); + pDorn->fTarget = fVal; + } + } + + iRet = transactRS232(pDorn->controller, pCommand, strlen(pCommand), + pAnswer, 49); + setRS232ReplyTerminator(pDorn->controller, "\n"); + pDorn->firstStatus = 1; + if (iRet < 1) { + if (iRet != INCOMPLETE) { + + pDorn->iLastError = iRet; + return 0; + } + } + pDorn->statusMode = STATSEND; + if (startFlag) { + pDorn->iLastError = STARTED; + return 0; + } + return 1; +} + +/*---------------------------------------------------------------------*/ +static int DornierError(pVelSelDriv self, int *iCode, + char *error, int iErrLen) +{ + pDornier pDorn = NULL; + + assert(self); + pDorn = (pDornier) self->pPrivate; + + *iCode = pDorn->iLastError; + + switch (pDorn->iLastError) { + case HALTREQ: + strncpy(error, "Repeat command if you really want to HALT selector", + iErrLen); + pDorn->haltCount++; + break; + case STARTED: + strncpy(error, + "Started selector, standby and check manually when ready", + iErrLen); + break; + case INVALIDSTATUS: + strncpy(error, "Received invalid status reply", iErrLen); + break; + case TARGETREJECTED: + strncpy(error, "VS in local mode or target out of range", iErrLen); + break; + case NOSTATUS: + strncpy(error, "No successfull status request after 3 tries", iErrLen); + break; + default: + getRS232Error(pDorn->iLastError, error, iErrLen); + break; + } + return 1; +} + +/*-------------------------------------------------------------------*/ +static int DornierFixIt(pVelSelDriv self, int iCode) +{ + pDornier pDorn = NULL; + int status, oldReject; + + assert(self); + pDorn = (pDornier) self->pPrivate; + + switch (iCode) { + case NOTCONNECTED: + status = initRS232(pDorn->controller); + if (status) { + return VELOREDO; + } else { + return VELOFAIL; + } + break; + case TIMEOUT: + case INCOMPLETE: + case INVALIDSTATUS: + return VELOREDO; + break; + case TARGETREJECTED: + if (pDorn->rejectCount >= 3) { + pDorn->rejectCount = 0; + return VELOFAIL; + } + oldReject = pDorn->rejectCount; + status = takeControl(pDorn); + if (status >= 1) { + DornierRun(self, pDorn->fTarget); + pDorn->rejectCount = oldReject + 1; + return VELOREDO; + } + return VELOFAIL; + break; + default: + return VELOFAIL; + } +} + +/*---------------------------------------------------------------------*/ +static int statusSendHandler(pDornier pDorn) +{ + int status; + + if (!requestDornierStatus(pDorn)) { return VSFAIL; } - pDorn->t_timeout = time(NULL) + pDorn->iTimeOut/1000; + pDorn->t_timeout = time(NULL) + pDorn->iTimeOut / 1000; pDorn->statusMode = STATREAD; return VSACCEL; } + /*------------------------------------------------------------------*/ -static int evaluateStatus(pVelSelDriv self, int *iCode){ +static int evaluateStatus(pVelSelDriv self, int *iCode) +{ int status; DornierStatus sStatus; char pCommand[80]; @@ -392,12 +405,12 @@ static int evaluateStatus(pVelSelDriv self, int *iCode){ static int iCount = 0; pDornier pDorn = NULL; - pDorn = (pDornier)self->pPrivate; + pDorn = (pDornier) self->pPrivate; pDorn->statusMode = STATSEND; - status = readAndInterpretStatus(pDorn,&sStatus); - if(!status){ - if(pDorn->firstStatus == 1){ + status = readAndInterpretStatus(pDorn, &sStatus); + if (!status) { + if (pDorn->firstStatus == 1) { pDorn->firstStatus = 0; return VSACCEL; } @@ -407,51 +420,53 @@ static int evaluateStatus(pVelSelDriv self, int *iCode){ *iCode = ROTMOVE; /* - sometimes the velocity selector does not accept a new target: - Two reasons: a) it is local, b) out of range - Check for this here as it is the only place appropriate. - */ + sometimes the velocity selector does not accept a new target: + Two reasons: a) it is local, b) out of range + Check for this here as it is the only place appropriate. + */ fDelta = sStatus.nom_rpm - pDorn->fTarget; - if(fDelta < 0){ - fDelta = - fDelta; + if (fDelta < 0) { + fDelta = -fDelta; } - if(fDelta > self->fTolerance){ + if (fDelta > self->fTolerance) { pDorn->iLastError = TARGETREJECTED; return VSFAIL; } /* - This code considers the velocity selector arrived if it reads - four times a difference between requested speed and actual speed - below difference - */ + This code considers the velocity selector arrived if it reads + four times a difference between requested speed and actual speed + below difference + */ pDorn->fLastRPM = sStatus.cur_rpm; fDelta = sStatus.cur_rpm - sStatus.nom_rpm; - if(fDelta < 0){ - fDelta = - fDelta; + if (fDelta < 0) { + fDelta = -fDelta; } - if(fDelta > self->fTolerance){ + if (fDelta > self->fTolerance) { iCount = 0; return VSACCEL; } else { iCount++; - if(iCount > 4){ + if (iCount > 4) { return VSOK; } else { return VSACCEL; - } + } } } + /*---------------------------------------------------------------------*/ -static int statusReceiveHandler(pVelSelDriv self, int *iCode){ +static int statusReceiveHandler(pVelSelDriv self, int *iCode) +{ int status; pDornier pDorn = NULL; - pDorn = (pDornier)self->pPrivate; + pDorn = (pDornier) self->pPrivate; status = availableRS232(pDorn->controller); - if(!status){ - if(time(NULL) > pDorn->t_timeout){ + if (!status) { + if (time(NULL) > pDorn->t_timeout) { pDorn->iLastError = TIMEOUT; pDorn->statusMode = STATSEND; return VELOFAIL; @@ -459,257 +474,235 @@ static int statusReceiveHandler(pVelSelDriv self, int *iCode){ return VSACCEL; } } - + return evaluateStatus(self, iCode); } + /*-------------------------------------------------------------------------- The Dornier takes a long time to answer a status message. In order to keep SICS responsive the following state machine is implemented: - a status request is sent. - next data availability will be checked, if available: process! ---------------------------------------------------------------------------*/ -static int DornierStatNew(pVelSelDriv self, int *iCode, float *fCur){ +static int DornierStatNew(pVelSelDriv self, int *iCode, float *fCur) +{ pDornier pDorn = NULL; int status; - - assert(self); - pDorn = (pDornier)self->pPrivate; - if(pDorn->statusMode == STATSEND){ + assert(self); + pDorn = (pDornier) self->pPrivate; + + if (pDorn->statusMode == STATSEND) { return statusSendHandler(pDorn); } else { - status = statusReceiveHandler(self,iCode); + status = statusReceiveHandler(self, iCode); *fCur = pDorn->fLastRPM; return status; } } + /*------------------------------------------------------------------------*/ - static int DornierLoss(pVelSelDriv self, float *fLoss) - { - pDornier pDorn = NULL; - int iRet, iErrStat, iDelta; - DornierStatus DStatus; - char pCommand[] = {"BRE\n"}; - char pAnswer[80]; - static int iCount; - static int iError; - int i; - - assert(self); - pDorn = (pDornier)self->pPrivate; +static int DornierLoss(pVelSelDriv self, float *fLoss) +{ + pDornier pDorn = NULL; + int iRet, iErrStat, iDelta; + DornierStatus DStatus; + char pCommand[] = { "BRE\n" }; + char pAnswer[80]; + static int iCount; + static int iError; + int i; - /* send a command */ - iRet = transactRS232(pDorn->controller,pCommand,strlen(pCommand), - pAnswer,79); - if(iRet < 1) - { - pDorn->iLastError = iRet; - return 0; - } - - /* wait 10 seconds before doing anything */ - SicsWait(10); + assert(self); + pDorn = (pDornier) self->pPrivate; - /* loop until back to speed again */ - for(i = 0; i < 100; i++ ) - { - if(!requestDornierStatus(pDorn)){ - return 0; - } - if(!readAndInterpretStatus(pDorn,&DStatus)){ - return 0; - } - iError = 0; - iDelta = DStatus.cur_rpm - DStatus.nom_rpm; - if(iDelta < 0) - { - iDelta = -iDelta; - } - if(iDelta < 15) - { - iCount++; - if(iCount > 4) - { - break; - } - } - else - { - iCount = 0; - } - } - *fLoss = DStatus.pwr; - return 1; + /* send a command */ + iRet = transactRS232(pDorn->controller, pCommand, strlen(pCommand), + pAnswer, 79); + if (iRet < 1) { + pDorn->iLastError = iRet; + return 0; } + + /* wait 10 seconds before doing anything */ + SicsWait(10); + + /* loop until back to speed again */ + for (i = 0; i < 100; i++) { + if (!requestDornierStatus(pDorn)) { + return 0; + } + if (!readAndInterpretStatus(pDorn, &DStatus)) { + return 0; + } + iError = 0; + iDelta = DStatus.cur_rpm - DStatus.nom_rpm; + if (iDelta < 0) { + iDelta = -iDelta; + } + if (iDelta < 15) { + iCount++; + if (iCount > 4) { + break; + } + } else { + iCount = 0; + } + } + *fLoss = DStatus.pwr; + return 1; +} + /*-------------------------------------------------------------------------*/ - static void DornierKill(void *pData) - { - pDornier pDorn = NULL; - - pDorn = (pDornier)pData; - assert(pDorn); - - writeRS232(pDorn->controller,"TTY\n",4); - KillRS232(pDorn->controller); - free(pDorn); - } +static void DornierKill(void *pData) +{ + pDornier pDorn = NULL; + + pDorn = (pDornier) pData; + assert(pDorn); + + writeRS232(pDorn->controller, "TTY\n", 4); + KillRS232(pDorn->controller); + free(pDorn); +} + /*------------------------------------------------------------------------*/ - static int DornierInit(pVelSelDriv self, SConnection *pCon) - { - pDornier pDorn = NULL; - int iRet, iError; - float fRot; - char pError[80], pBueffel[256]; - - assert(self); - pDorn = (pDornier)self->pPrivate; - assert(pDorn); - - iRet = initRS232(pDorn->controller); - if(iRet < 0){ - return 1; - } - setRS232SendTerminator(pDorn->controller,"\n"); - setRS232Timeout(pDorn->controller,pDorn->iTimeOut); - setRS232Debug(pDorn->controller,0); +static int DornierInit(pVelSelDriv self, SConnection * pCon) +{ + pDornier pDorn = NULL; + int iRet, iError; + float fRot; + char pError[80], pBueffel[256]; + + assert(self); + pDorn = (pDornier) self->pPrivate; + assert(pDorn); + + iRet = initRS232(pDorn->controller); + if (iRet < 0) { + return 1; + } + setRS232SendTerminator(pDorn->controller, "\n"); + setRS232Timeout(pDorn->controller, pDorn->iTimeOut); + setRS232Debug(pDorn->controller, 0); + + /* + tell him that we want control. + Funny enough no or is sent in the reply to this. + */ + iRet = takeControl(pDorn); + if (iRet <= 1) { + sprintf(pBueffel, + "ERROR: %s while switching velocity selector to remote", + pError); + SCWrite(pCon, pBueffel, eError); + } + /* + check which status the velo is in + */ + pDorn->statusMode = STATSEND; + return 1; +} - /* - tell him that we want control. - Funny enough no or is sent in the reply to this. - */ - iRet = takeControl(pDorn); - if(iRet <= 1) - { - sprintf(pBueffel, - "ERROR: %s while switching velocity selector to remote", - pError); - SCWrite(pCon,pBueffel,eError); - } - /* - check which status the velo is in - */ - pDorn->statusMode = STATSEND; - return 1; - } /*-------------------------------------------------------------------------*/ - pVelSelDriv VSCreateDornier2003(char *name, Tcl_Interp *pTcl) - { - pVelSelDriv pNew = NULL; - pDornier pDorn = NULL; - char *pPtr = NULL; - int iVal, iRet, iPort; - char pHost[132]; +pVelSelDriv VSCreateDornier2003(char *name, Tcl_Interp * pTcl) +{ + pVelSelDriv pNew = NULL; + pDornier pDorn = NULL; + char *pPtr = NULL; + int iVal, iRet, iPort; + char pHost[132]; - /* the most likely error is the parameters specified are wrong! - So check this first. We''ll use Tcl's result for error reporting. - name is the name of an Tcl array which should hold the info - necessary - */ - - /* allocate a Dornier structure */ - pDorn = (pDornier)malloc(sizeof(Dornier)); - if(!pDorn) - { - return NULL; - } - memset(pDorn,0,sizeof(Dornier)); - - /* host name */ - pPtr = (char *)Tcl_GetVar2(pTcl,name,"Host",TCL_GLOBAL_ONLY); - if(!pPtr) - { - Tcl_AppendResult(pTcl,"ERROR: no hostname found in",name,NULL); - free(pDorn); - return NULL; - } - strncpy(pHost,pPtr,131); - - /* port number */ - pPtr = (char *)Tcl_GetVar2(pTcl,name,"Port",TCL_GLOBAL_ONLY); - if(!pPtr) - { - Tcl_AppendResult(pTcl,"ERROR: no port number found in",name,NULL); - free(pDorn); - return NULL; - } - iRet = Tcl_GetInt(pTcl,pPtr,&iPort); - if(iRet != TCL_OK) - { - free(pDorn); - return NULL; - } - - /* time out. This one gets defaulted when not specified */ - pPtr = (char *)Tcl_GetVar2(pTcl,name,"Timeout",TCL_GLOBAL_ONLY); - if(!pPtr) - { - pDorn->iTimeOut = 1000; - } - else - { - iRet = Tcl_GetInt(pTcl,pPtr,&iVal); - if(iRet != TCL_OK) - { - pDorn->iTimeOut = 1000; - } - pDorn->iTimeOut = iVal; - } + /* the most likely error is the parameters specified are wrong! + So check this first. We''ll use Tcl's result for error reporting. + name is the name of an Tcl array which should hold the info + necessary + */ - /* minimum control speed */ - pPtr = (char *)Tcl_GetVar2(pTcl,name,"MinControl",TCL_GLOBAL_ONLY); - if(!pPtr) - { - pDorn->minRPM = 3100; - } - else - { - iRet = Tcl_GetInt(pTcl,pPtr,&iVal); - if(iRet != TCL_OK) - { - pDorn->minRPM = 3100; - } - pDorn->minRPM = iVal; - } - - - /* business as usual: allocate memory */ - pNew = (pVelSelDriv)malloc(sizeof(VelSelDriv)); - if(!pNew) - { - return NULL; - } - - /* zero the world */ - memset(pNew,0,sizeof(VelSelDriv)); - pNew->pPrivate = pDorn; - pDorn->controller = createRS232(pHost,iPort); - if(!pDorn->controller){ - DornierKill(pNew->pPrivate); - free(pNew); - return NULL; - } - pDorn->noStatus = 1; - - /* initialise function pointers */ - pNew->DeletePrivate = DornierKill; - pNew->Halt = DornierHalt; - pNew->GetError = DornierError; - pNew->TryAndFixIt = DornierFixIt; - pNew->GetRotation = GetDornierPos; - pNew->SetRotation = DornierRun; - pNew->GetStatus = DornierStatNew; - pNew->GetDriverText = DornierText; - pNew->GetLossCurrent = DornierLoss; - pNew->Init = DornierInit; - - /* done it */ - return pNew; - } + /* allocate a Dornier structure */ + pDorn = (pDornier) malloc(sizeof(Dornier)); + if (!pDorn) { + return NULL; + } + memset(pDorn, 0, sizeof(Dornier)); + /* host name */ + pPtr = (char *) Tcl_GetVar2(pTcl, name, "Host", TCL_GLOBAL_ONLY); + if (!pPtr) { + Tcl_AppendResult(pTcl, "ERROR: no hostname found in", name, NULL); + free(pDorn); + return NULL; + } + strncpy(pHost, pPtr, 131); + /* port number */ + pPtr = (char *) Tcl_GetVar2(pTcl, name, "Port", TCL_GLOBAL_ONLY); + if (!pPtr) { + Tcl_AppendResult(pTcl, "ERROR: no port number found in", name, NULL); + free(pDorn); + return NULL; + } + iRet = Tcl_GetInt(pTcl, pPtr, &iPort); + if (iRet != TCL_OK) { + free(pDorn); + return NULL; + } + + /* time out. This one gets defaulted when not specified */ + pPtr = (char *) Tcl_GetVar2(pTcl, name, "Timeout", TCL_GLOBAL_ONLY); + if (!pPtr) { + pDorn->iTimeOut = 1000; + } else { + iRet = Tcl_GetInt(pTcl, pPtr, &iVal); + if (iRet != TCL_OK) { + pDorn->iTimeOut = 1000; + } + pDorn->iTimeOut = iVal; + } + + /* minimum control speed */ + pPtr = (char *) Tcl_GetVar2(pTcl, name, "MinControl", TCL_GLOBAL_ONLY); + if (!pPtr) { + pDorn->minRPM = 3100; + } else { + iRet = Tcl_GetInt(pTcl, pPtr, &iVal); + if (iRet != TCL_OK) { + pDorn->minRPM = 3100; + } + pDorn->minRPM = iVal; + } + /* business as usual: allocate memory */ + pNew = (pVelSelDriv) malloc(sizeof(VelSelDriv)); + if (!pNew) { + return NULL; + } + /* zero the world */ + memset(pNew, 0, sizeof(VelSelDriv)); + pNew->pPrivate = pDorn; + pDorn->controller = createRS232(pHost, iPort); + if (!pDorn->controller) { + DornierKill(pNew->pPrivate); + free(pNew); + return NULL; + } + pDorn->noStatus = 1; + /* initialise function pointers */ + pNew->DeletePrivate = DornierKill; + pNew->Halt = DornierHalt; + pNew->GetError = DornierError; + pNew->TryAndFixIt = DornierFixIt; + pNew->GetRotation = GetDornierPos; + pNew->SetRotation = DornierRun; + pNew->GetStatus = DornierStatNew; + pNew->GetDriverText = DornierText; + pNew->GetLossCurrent = DornierLoss; + pNew->Init = DornierInit; + /* done it */ + return pNew; +} diff --git a/dspcode.c b/dspcode.c index 8b9293b..80ecf32 100644 --- a/dspcode.c +++ b/dspcode.c @@ -1,418 +1,419 @@ -void slsdspCodeToText(int code, char *text, int textlen){ - switch(code){ - case 0x0: - strncpy(text,"NO",textlen); - break; - case 0x1: - strncpy(text,"DEVICE_STATE_ERROR",textlen); - break; - case 0x2: - strncpy(text,"DEVICE_SUPERVISOR_DISABLED",textlen); - break; - case 0x3: - strncpy(text,"COMMAND_ABORT",textlen); - break; - case 0x4: - strncpy(text,"DATA_NOT_STORED",textlen); - break; - case 0x5: - strncpy(text,"ERROR_ERASING_FLASH",textlen); - break; - case 0x6: - strncpy(text,"COMMUNICATION_BREAK",textlen); - break; - case 0x7: - strncpy(text,"INTERNAL_COMMUNICATION_ERROR",textlen); - break; - case 0x8: - strncpy(text,"MASTER_CARD_ERROR",textlen); - break; - case 0x9: - strncpy(text,"INTERNAL_BUFFER_FULL",textlen); - break; - case 0xa: - strncpy(text,"WRONG_SECTOR",textlen); - break; - case 0xb: - strncpy(text,"DATA_NOT_COPIED",textlen); - break; - case 0xc: - strncpy(text,"WRONG_DOWNLOAD_PARAMETERS",textlen); - break; - case 0xd: - strncpy(text,"DEVICE_PARAMETRIZATION_ERROR",textlen); - break; - case 0x10: - strncpy(text,"TIMEOUT_DC_LINK_VOLTAGE",textlen); - break; - case 0x11: - strncpy(text,"TIMEOUT_AUXILIARY_RELAY_ON",textlen); - break; - case 0x12: - strncpy(text,"TIMEOUT_AUXILIARY_RELAY_OFF",textlen); - break; - case 0x13: - strncpy(text,"TIMEOUT_MAIN_RELAY_ON",textlen); - break; - case 0x14: - strncpy(text,"TIMEOUT_MAIN_RELAY_OFF",textlen); - break; - case 0x15: - strncpy(text,"TIMEOUT_DATA_DOWNLOAD",textlen); - break; - case 0x20: - strncpy(text,"INTERLOCK",textlen); - break; - case 0x21: - strncpy(text,"MASTER_SWITCH",textlen); - break; - case 0x22: - strncpy(text,"MAGNET_INTERLOCK",textlen); - break; - case 0x23: - strncpy(text,"TEMPERATURE_TRANSFORMER",textlen); - break; - case 0x24: - strncpy(text,"TEMPERATURE_RECTIFIER",textlen); - break; - case 0x25: - strncpy(text,"TEMPERATURE_CONVERTER",textlen); - break; - case 0x26: - strncpy(text,"CURRENT_TRANSDUCER",textlen); - break; - case 0x27: - strncpy(text,"TEMPERATURE_POLARITY_SWITCH",textlen); - break; - case 0x28: - strncpy(text,"POWER_SEMICONDUCTOR",textlen); - break; - case 0x29: - strncpy(text,"MAIN_RELAY",textlen); - break; - case 0x2a: - strncpy(text,"AD_CONVERTER_CARD",textlen); - break; - case 0x2b: - strncpy(text,"POLARITY_SWITCH",textlen); - break; - case 0x2c: - strncpy(text,"AUXILIARY_RELAY",textlen); - break; - case 0x2d: - strncpy(text,"MASTER_SWITCH_T1",textlen); - break; - case 0x2e: - strncpy(text,"MASTER_SWITCH_T2",textlen); - break; - case 0x2f: - strncpy(text,"TEMPERATURE_MAGNET",textlen); - break; - case 0x30: - strncpy(text,"WATER_MAGNET",textlen); - break; - case 0x31: - strncpy(text,"WATER_RACK",textlen); - break; - case 0x40: - strncpy(text,"LOAD_CURRENT_TOO_HIGH",textlen); - break; - case 0x41: - strncpy(text,"DC_LINK_VOLTAGE_TOO_LOW",textlen); - break; - case 0x42: - strncpy(text,"DC_LINK_VOLTAGE_TOO_HIGH",textlen); - break; - case 0x43: - strncpy(text,"LOAD_VOLTAGE_TOO_HIGH",textlen); - break; - case 0x44: - strncpy(text,"LOAD_CURRENT_RIPPLE_TOO_HIGH",textlen); - break; - case 0x45: - strncpy(text,"DC_LINK_ISOLATION_NOT_OK",textlen); - break; - case 0x46: - strncpy(text,"LOAD_ISOLATION_NOT_OK",textlen); - break; - case 0x47: - strncpy(text,"LOAD_IMPEDANCE_OUT_OF_RANGE",textlen); - break; - case 0x48: - strncpy(text,"SHUT_OFF_CURRENT_TOO_HIGH",textlen); - break; - case 0x49: - strncpy(text,"LOAD_DC_CURRENT_TOO_HIGH",textlen); - break; - case 0x4a: - strncpy(text,"CURRENT_I1A1_TOO_HIGH",textlen); - break; - case 0x4b: - strncpy(text,"CURRENT_I1B1_TOO_HIGH",textlen); - break; - case 0x4c: - strncpy(text,"CURRENT_I1A2_TOO_HIGH",textlen); - break; - case 0x4d: - strncpy(text,"CURRENT_I1B2_TOO_HIGH",textlen); - break; - case 0x4e: - strncpy(text,"CURRENT_I2A1_TOO_HIGH",textlen); - break; - case 0x4f: - strncpy(text,"CURRENT_I2B1_TOO_HIGH",textlen); - break; - case 0x50: - strncpy(text,"CURRENT_I2A2_TOO_HIGH",textlen); - break; - case 0x51: - strncpy(text,"CURRENT_I2B2_TOO_HIGH",textlen); - break; - case 0x52: - strncpy(text,"CURRENT_I3P_TOO_HIGH",textlen); - break; - case 0x53: - strncpy(text,"CURRENT_I3N_TOO_HIGH",textlen); - break; - case 0x54: - strncpy(text,"CURRENT_IE_TOO_HIGH",textlen); - break; - case 0x55: - strncpy(text,"VOLTAGE_U1A_TOO_LOW",textlen); - break; - case 0x56: - strncpy(text,"VOLTAGE_U1B_TOO_LOW",textlen); - break; - case 0x57: - strncpy(text,"DIFF_CURRENT_I1A1_I1A2_TOO_HIGH",textlen); - break; - case 0x58: - strncpy(text,"DIFF_CURRENT_I1B1_I1B2_TOO_HIGH",textlen); - break; - case 0x59: - strncpy(text,"DIFF_CURRENT_I2A1_I2A2_TOO_HIGH",textlen); - break; - case 0x5a: - strncpy(text,"DIFF_CURRENT_I2B1_I2B2_TOO_HIGH",textlen); - break; - case 0x5b: - strncpy(text,"DIFF_CURRENT_I3P_I3N_TOO_HIGH",textlen); - break; - case 0x5c: - strncpy(text,"CURRENT_I1A_TOO_HIGH",textlen); - break; - case 0x5d: - strncpy(text,"CURRENT_I1B_TOO_HIGH",textlen); - break; - case 0x5e: - strncpy(text,"CURRENT_I3A1_TOO_HIGH",textlen); - break; - case 0x5f: - strncpy(text,"CURRENT_I3B1_TOO_HIGH",textlen); - break; - case 0x60: - strncpy(text,"CURRENT_I3A2_TOO_HIGH",textlen); - break; - case 0x61: - strncpy(text,"CURRENT_I3B2_TOO_HIGH",textlen); - break; - case 0x62: - strncpy(text,"CURRENT_I4_TOO_HIGH",textlen); - break; - case 0x63: - strncpy(text,"CURRENT_I5_TOO_HIGH",textlen); - break; - case 0x64: - strncpy(text,"DIFF_CURRENT_I3A1_I3A2_TOO_HIGH",textlen); - break; - case 0x65: - strncpy(text,"DIFF_CURRENT_I3B1_I3B2_TOO_HIGH",textlen); - break; - case 0x66: - strncpy(text,"DIFF_CURRENT_I4_I5_TOO_HIGH",textlen); - break; - case 0x67: - strncpy(text,"VOLTAGE_U3A_TOO_LOW",textlen); - break; - case 0x68: - strncpy(text,"VOLTAGE_U3B_TOO_LOW",textlen); - break; - case 0x69: - strncpy(text,"VOLTAGE_U1_TOO_LOW",textlen); - break; - case 0x6a: - strncpy(text,"VOLTAGE_U3A_TOO_HIGH",textlen); - break; - case 0x6b: - strncpy(text,"VOLTAGE_U3B_TOO_HIGH",textlen); - break; - case 0x6c: - strncpy(text,"SPEED_ERROR_TOO_HIGH",textlen); - break; - case 0x70: - strncpy(text,"MAIN_RELAY_A",textlen); - break; - case 0x71: - strncpy(text,"MAIN_RELAY_B",textlen); - break; - case 0x72: - strncpy(text,"POWER_SWITCH_A",textlen); - break; - case 0x73: - strncpy(text,"POWER_SWITCH_B",textlen); - break; - case 0x74: - strncpy(text,"MONITOR_TRAFO_A",textlen); - break; - case 0x75: - strncpy(text,"MONITOR_TRAFO_B",textlen); - break; - case 0x76: - strncpy(text,"TEMPERATURE_RECTIFIER_A",textlen); - break; - case 0x77: - strncpy(text,"TEMPERATURE_RECTIFIER_B",textlen); - break; - case 0x78: - strncpy(text,"TEMPERATURE_CONVERTER_A",textlen); - break; - case 0x79: - strncpy(text,"TEMPERATURE_CONVERTER_B",textlen); - break; - case 0x7a: - strncpy(text,"TEMPERATURE_CONVERTER_A1",textlen); - break; - case 0x7b: - strncpy(text,"TEMPERATURE_CONVERTER_B1",textlen); - break; - case 0x7c: - strncpy(text,"TEMPERATURE_CONVERTER_A2",textlen); - break; - case 0x7d: - strncpy(text,"TEMPERATURE_CONVERTER_B2",textlen); - break; - case 0x7e: - strncpy(text,"TEMPERATURE_TRANSFORMER_A",textlen); - break; - case 0x7f: - strncpy(text,"TEMPERATURE_TRANSFORMER_B",textlen); - break; - case 0x80: - strncpy(text,"WATER_RECTIFIER_A",textlen); - break; - case 0x81: - strncpy(text,"WATER_RECTIFIER_B",textlen); - break; - case 0x82: - strncpy(text,"WATER_CONVERTER_A",textlen); - break; - case 0x83: - strncpy(text,"WATER_CONVERTER_B",textlen); - break; - case 0x84: - strncpy(text,"WATER_CONVERTER_A1",textlen); - break; - case 0x85: - strncpy(text,"WATER_CONVERTER_B1",textlen); - break; - case 0x86: - strncpy(text,"WATER_CONVERTER_A2",textlen); - break; - case 0x87: - strncpy(text,"WATER_CONVERTER_B2",textlen); - break; - case 0x88: - strncpy(text,"WATER_TRANSFORMER_A",textlen); - break; - case 0x89: - strncpy(text,"WATER_TRANSFORMER_B",textlen); - break; - case 0x8a: - strncpy(text,"DOOR_A",textlen); - break; - case 0x8b: - strncpy(text,"DOOR_B",textlen); - break; - case 0x8c: - strncpy(text,"DOOR_C",textlen); - break; - case 0x8d: - strncpy(text,"POWER_SEMICONDUCTOR_CONVERTER_A",textlen); - break; - case 0x8e: - strncpy(text,"POWER_SEMICONDUCTOR_CONVERTER_B",textlen); - break; - case 0x8f: - strncpy(text,"POWER_SEMICONDUCTOR_CONVERTER_A1",textlen); - break; - case 0x90: - strncpy(text,"POWER_SEMICONDUCTOR_CONVERTER_B1",textlen); - break; - case 0x91: - strncpy(text,"POWER_SEMICONDUCTOR_CONVERTER_A2",textlen); - break; - case 0x92: - strncpy(text,"POWER_SEMICONDUCTOR_CONVERTER_B2",textlen); - break; - case 0x93: - strncpy(text,"CURRENT_TRANSDUCER_I3P",textlen); - break; - case 0x94: - strncpy(text,"CURRENT_TRANSDUCER_I3N",textlen); - break; - case 0x95: - strncpy(text,"MAGNET_INTERLOCK_1",textlen); - break; - case 0x96: - strncpy(text,"MAGNET_INTERLOCK_2",textlen); - break; - case 0x97: - strncpy(text,"VENTILATOR",textlen); - break; - case 0x98: - strncpy(text,"EMERGENCY_SWITCH",textlen); - break; - case 0x99: - strncpy(text,"CAPACITOR_DISCHARGE_A_ON",textlen); - break; - case 0x9a: - strncpy(text,"CAPACITOR_DISCHARGE_B_ON",textlen); - break; - case 0x9b: - strncpy(text,"CURRENT_TRANSDUCER_I4",textlen); - break; - case 0x9c: - strncpy(text,"CURRENT_TRANSDUCER_I5",textlen); - break; - case 0xb0: - strncpy(text,"TIMEOUT_DC_LINK_VOLTAGE_PART_A",textlen); - break; - case 0xb1: - strncpy(text,"TIMEOUT_DC_LINK_VOLTAGE_PART_B",textlen); - break; - case 0xb2: - strncpy(text,"TIMEOUT_AUXILIARY_RELAY_A_ON",textlen); - break; - case 0xb3: - strncpy(text,"TIMEOUT_AUXILIARY_RELAY_B_ON",textlen); - break; - case 0xb4: - strncpy(text,"TIMEOUT_AUXILIARY_RELAY_A_OFF",textlen); - break; - case 0xb5: - strncpy(text,"TIMEOUT_AUXILIARY_RELAY_B_OFF",textlen); - break; - case 0xb6: - strncpy(text,"TIMEOUT_MAIN_RELAY_A_ON",textlen); - break; - case 0xb7: - strncpy(text,"TIMEOUT_MAIN_RELAY_B_ON",textlen); - break; - case 0xb8: - strncpy(text,"TIMEOUT_MAIN_RELAY_A_OFF",textlen); - break; - case 0xb9: - strncpy(text,"TIMEOUT_MAIN_RELAY_B_OFF",textlen); - break; +void slsdspCodeToText(int code, char *text, int textlen) +{ + switch (code) { + case 0x0: + strncpy(text, "NO", textlen); + break; + case 0x1: + strncpy(text, "DEVICE_STATE_ERROR", textlen); + break; + case 0x2: + strncpy(text, "DEVICE_SUPERVISOR_DISABLED", textlen); + break; + case 0x3: + strncpy(text, "COMMAND_ABORT", textlen); + break; + case 0x4: + strncpy(text, "DATA_NOT_STORED", textlen); + break; + case 0x5: + strncpy(text, "ERROR_ERASING_FLASH", textlen); + break; + case 0x6: + strncpy(text, "COMMUNICATION_BREAK", textlen); + break; + case 0x7: + strncpy(text, "INTERNAL_COMMUNICATION_ERROR", textlen); + break; + case 0x8: + strncpy(text, "MASTER_CARD_ERROR", textlen); + break; + case 0x9: + strncpy(text, "INTERNAL_BUFFER_FULL", textlen); + break; + case 0xa: + strncpy(text, "WRONG_SECTOR", textlen); + break; + case 0xb: + strncpy(text, "DATA_NOT_COPIED", textlen); + break; + case 0xc: + strncpy(text, "WRONG_DOWNLOAD_PARAMETERS", textlen); + break; + case 0xd: + strncpy(text, "DEVICE_PARAMETRIZATION_ERROR", textlen); + break; + case 0x10: + strncpy(text, "TIMEOUT_DC_LINK_VOLTAGE", textlen); + break; + case 0x11: + strncpy(text, "TIMEOUT_AUXILIARY_RELAY_ON", textlen); + break; + case 0x12: + strncpy(text, "TIMEOUT_AUXILIARY_RELAY_OFF", textlen); + break; + case 0x13: + strncpy(text, "TIMEOUT_MAIN_RELAY_ON", textlen); + break; + case 0x14: + strncpy(text, "TIMEOUT_MAIN_RELAY_OFF", textlen); + break; + case 0x15: + strncpy(text, "TIMEOUT_DATA_DOWNLOAD", textlen); + break; + case 0x20: + strncpy(text, "INTERLOCK", textlen); + break; + case 0x21: + strncpy(text, "MASTER_SWITCH", textlen); + break; + case 0x22: + strncpy(text, "MAGNET_INTERLOCK", textlen); + break; + case 0x23: + strncpy(text, "TEMPERATURE_TRANSFORMER", textlen); + break; + case 0x24: + strncpy(text, "TEMPERATURE_RECTIFIER", textlen); + break; + case 0x25: + strncpy(text, "TEMPERATURE_CONVERTER", textlen); + break; + case 0x26: + strncpy(text, "CURRENT_TRANSDUCER", textlen); + break; + case 0x27: + strncpy(text, "TEMPERATURE_POLARITY_SWITCH", textlen); + break; + case 0x28: + strncpy(text, "POWER_SEMICONDUCTOR", textlen); + break; + case 0x29: + strncpy(text, "MAIN_RELAY", textlen); + break; + case 0x2a: + strncpy(text, "AD_CONVERTER_CARD", textlen); + break; + case 0x2b: + strncpy(text, "POLARITY_SWITCH", textlen); + break; + case 0x2c: + strncpy(text, "AUXILIARY_RELAY", textlen); + break; + case 0x2d: + strncpy(text, "MASTER_SWITCH_T1", textlen); + break; + case 0x2e: + strncpy(text, "MASTER_SWITCH_T2", textlen); + break; + case 0x2f: + strncpy(text, "TEMPERATURE_MAGNET", textlen); + break; + case 0x30: + strncpy(text, "WATER_MAGNET", textlen); + break; + case 0x31: + strncpy(text, "WATER_RACK", textlen); + break; + case 0x40: + strncpy(text, "LOAD_CURRENT_TOO_HIGH", textlen); + break; + case 0x41: + strncpy(text, "DC_LINK_VOLTAGE_TOO_LOW", textlen); + break; + case 0x42: + strncpy(text, "DC_LINK_VOLTAGE_TOO_HIGH", textlen); + break; + case 0x43: + strncpy(text, "LOAD_VOLTAGE_TOO_HIGH", textlen); + break; + case 0x44: + strncpy(text, "LOAD_CURRENT_RIPPLE_TOO_HIGH", textlen); + break; + case 0x45: + strncpy(text, "DC_LINK_ISOLATION_NOT_OK", textlen); + break; + case 0x46: + strncpy(text, "LOAD_ISOLATION_NOT_OK", textlen); + break; + case 0x47: + strncpy(text, "LOAD_IMPEDANCE_OUT_OF_RANGE", textlen); + break; + case 0x48: + strncpy(text, "SHUT_OFF_CURRENT_TOO_HIGH", textlen); + break; + case 0x49: + strncpy(text, "LOAD_DC_CURRENT_TOO_HIGH", textlen); + break; + case 0x4a: + strncpy(text, "CURRENT_I1A1_TOO_HIGH", textlen); + break; + case 0x4b: + strncpy(text, "CURRENT_I1B1_TOO_HIGH", textlen); + break; + case 0x4c: + strncpy(text, "CURRENT_I1A2_TOO_HIGH", textlen); + break; + case 0x4d: + strncpy(text, "CURRENT_I1B2_TOO_HIGH", textlen); + break; + case 0x4e: + strncpy(text, "CURRENT_I2A1_TOO_HIGH", textlen); + break; + case 0x4f: + strncpy(text, "CURRENT_I2B1_TOO_HIGH", textlen); + break; + case 0x50: + strncpy(text, "CURRENT_I2A2_TOO_HIGH", textlen); + break; + case 0x51: + strncpy(text, "CURRENT_I2B2_TOO_HIGH", textlen); + break; + case 0x52: + strncpy(text, "CURRENT_I3P_TOO_HIGH", textlen); + break; + case 0x53: + strncpy(text, "CURRENT_I3N_TOO_HIGH", textlen); + break; + case 0x54: + strncpy(text, "CURRENT_IE_TOO_HIGH", textlen); + break; + case 0x55: + strncpy(text, "VOLTAGE_U1A_TOO_LOW", textlen); + break; + case 0x56: + strncpy(text, "VOLTAGE_U1B_TOO_LOW", textlen); + break; + case 0x57: + strncpy(text, "DIFF_CURRENT_I1A1_I1A2_TOO_HIGH", textlen); + break; + case 0x58: + strncpy(text, "DIFF_CURRENT_I1B1_I1B2_TOO_HIGH", textlen); + break; + case 0x59: + strncpy(text, "DIFF_CURRENT_I2A1_I2A2_TOO_HIGH", textlen); + break; + case 0x5a: + strncpy(text, "DIFF_CURRENT_I2B1_I2B2_TOO_HIGH", textlen); + break; + case 0x5b: + strncpy(text, "DIFF_CURRENT_I3P_I3N_TOO_HIGH", textlen); + break; + case 0x5c: + strncpy(text, "CURRENT_I1A_TOO_HIGH", textlen); + break; + case 0x5d: + strncpy(text, "CURRENT_I1B_TOO_HIGH", textlen); + break; + case 0x5e: + strncpy(text, "CURRENT_I3A1_TOO_HIGH", textlen); + break; + case 0x5f: + strncpy(text, "CURRENT_I3B1_TOO_HIGH", textlen); + break; + case 0x60: + strncpy(text, "CURRENT_I3A2_TOO_HIGH", textlen); + break; + case 0x61: + strncpy(text, "CURRENT_I3B2_TOO_HIGH", textlen); + break; + case 0x62: + strncpy(text, "CURRENT_I4_TOO_HIGH", textlen); + break; + case 0x63: + strncpy(text, "CURRENT_I5_TOO_HIGH", textlen); + break; + case 0x64: + strncpy(text, "DIFF_CURRENT_I3A1_I3A2_TOO_HIGH", textlen); + break; + case 0x65: + strncpy(text, "DIFF_CURRENT_I3B1_I3B2_TOO_HIGH", textlen); + break; + case 0x66: + strncpy(text, "DIFF_CURRENT_I4_I5_TOO_HIGH", textlen); + break; + case 0x67: + strncpy(text, "VOLTAGE_U3A_TOO_LOW", textlen); + break; + case 0x68: + strncpy(text, "VOLTAGE_U3B_TOO_LOW", textlen); + break; + case 0x69: + strncpy(text, "VOLTAGE_U1_TOO_LOW", textlen); + break; + case 0x6a: + strncpy(text, "VOLTAGE_U3A_TOO_HIGH", textlen); + break; + case 0x6b: + strncpy(text, "VOLTAGE_U3B_TOO_HIGH", textlen); + break; + case 0x6c: + strncpy(text, "SPEED_ERROR_TOO_HIGH", textlen); + break; + case 0x70: + strncpy(text, "MAIN_RELAY_A", textlen); + break; + case 0x71: + strncpy(text, "MAIN_RELAY_B", textlen); + break; + case 0x72: + strncpy(text, "POWER_SWITCH_A", textlen); + break; + case 0x73: + strncpy(text, "POWER_SWITCH_B", textlen); + break; + case 0x74: + strncpy(text, "MONITOR_TRAFO_A", textlen); + break; + case 0x75: + strncpy(text, "MONITOR_TRAFO_B", textlen); + break; + case 0x76: + strncpy(text, "TEMPERATURE_RECTIFIER_A", textlen); + break; + case 0x77: + strncpy(text, "TEMPERATURE_RECTIFIER_B", textlen); + break; + case 0x78: + strncpy(text, "TEMPERATURE_CONVERTER_A", textlen); + break; + case 0x79: + strncpy(text, "TEMPERATURE_CONVERTER_B", textlen); + break; + case 0x7a: + strncpy(text, "TEMPERATURE_CONVERTER_A1", textlen); + break; + case 0x7b: + strncpy(text, "TEMPERATURE_CONVERTER_B1", textlen); + break; + case 0x7c: + strncpy(text, "TEMPERATURE_CONVERTER_A2", textlen); + break; + case 0x7d: + strncpy(text, "TEMPERATURE_CONVERTER_B2", textlen); + break; + case 0x7e: + strncpy(text, "TEMPERATURE_TRANSFORMER_A", textlen); + break; + case 0x7f: + strncpy(text, "TEMPERATURE_TRANSFORMER_B", textlen); + break; + case 0x80: + strncpy(text, "WATER_RECTIFIER_A", textlen); + break; + case 0x81: + strncpy(text, "WATER_RECTIFIER_B", textlen); + break; + case 0x82: + strncpy(text, "WATER_CONVERTER_A", textlen); + break; + case 0x83: + strncpy(text, "WATER_CONVERTER_B", textlen); + break; + case 0x84: + strncpy(text, "WATER_CONVERTER_A1", textlen); + break; + case 0x85: + strncpy(text, "WATER_CONVERTER_B1", textlen); + break; + case 0x86: + strncpy(text, "WATER_CONVERTER_A2", textlen); + break; + case 0x87: + strncpy(text, "WATER_CONVERTER_B2", textlen); + break; + case 0x88: + strncpy(text, "WATER_TRANSFORMER_A", textlen); + break; + case 0x89: + strncpy(text, "WATER_TRANSFORMER_B", textlen); + break; + case 0x8a: + strncpy(text, "DOOR_A", textlen); + break; + case 0x8b: + strncpy(text, "DOOR_B", textlen); + break; + case 0x8c: + strncpy(text, "DOOR_C", textlen); + break; + case 0x8d: + strncpy(text, "POWER_SEMICONDUCTOR_CONVERTER_A", textlen); + break; + case 0x8e: + strncpy(text, "POWER_SEMICONDUCTOR_CONVERTER_B", textlen); + break; + case 0x8f: + strncpy(text, "POWER_SEMICONDUCTOR_CONVERTER_A1", textlen); + break; + case 0x90: + strncpy(text, "POWER_SEMICONDUCTOR_CONVERTER_B1", textlen); + break; + case 0x91: + strncpy(text, "POWER_SEMICONDUCTOR_CONVERTER_A2", textlen); + break; + case 0x92: + strncpy(text, "POWER_SEMICONDUCTOR_CONVERTER_B2", textlen); + break; + case 0x93: + strncpy(text, "CURRENT_TRANSDUCER_I3P", textlen); + break; + case 0x94: + strncpy(text, "CURRENT_TRANSDUCER_I3N", textlen); + break; + case 0x95: + strncpy(text, "MAGNET_INTERLOCK_1", textlen); + break; + case 0x96: + strncpy(text, "MAGNET_INTERLOCK_2", textlen); + break; + case 0x97: + strncpy(text, "VENTILATOR", textlen); + break; + case 0x98: + strncpy(text, "EMERGENCY_SWITCH", textlen); + break; + case 0x99: + strncpy(text, "CAPACITOR_DISCHARGE_A_ON", textlen); + break; + case 0x9a: + strncpy(text, "CAPACITOR_DISCHARGE_B_ON", textlen); + break; + case 0x9b: + strncpy(text, "CURRENT_TRANSDUCER_I4", textlen); + break; + case 0x9c: + strncpy(text, "CURRENT_TRANSDUCER_I5", textlen); + break; + case 0xb0: + strncpy(text, "TIMEOUT_DC_LINK_VOLTAGE_PART_A", textlen); + break; + case 0xb1: + strncpy(text, "TIMEOUT_DC_LINK_VOLTAGE_PART_B", textlen); + break; + case 0xb2: + strncpy(text, "TIMEOUT_AUXILIARY_RELAY_A_ON", textlen); + break; + case 0xb3: + strncpy(text, "TIMEOUT_AUXILIARY_RELAY_B_ON", textlen); + break; + case 0xb4: + strncpy(text, "TIMEOUT_AUXILIARY_RELAY_A_OFF", textlen); + break; + case 0xb5: + strncpy(text, "TIMEOUT_AUXILIARY_RELAY_B_OFF", textlen); + break; + case 0xb6: + strncpy(text, "TIMEOUT_MAIN_RELAY_A_ON", textlen); + break; + case 0xb7: + strncpy(text, "TIMEOUT_MAIN_RELAY_B_ON", textlen); + break; + case 0xb8: + strncpy(text, "TIMEOUT_MAIN_RELAY_A_OFF", textlen); + break; + case 0xb9: + strncpy(text, "TIMEOUT_MAIN_RELAY_B_OFF", textlen); + break; } } diff --git a/ease.c b/ease.c index 367adfd..db7fdad 100644 --- a/ease.c +++ b/ease.c @@ -26,37 +26,50 @@ static ParClass easeDrivClass = { "EaseDriv", sizeof(EaseDriv) }; static int parameterChange = 0; /*----------------------------------------------------------------------------*/ -ParClass *EaseBaseClass(void) { +ParClass *EaseBaseClass(void) +{ return ParMakeClass(&easeBaseClass, NULL); } + /*----------------------------------------------------------------------------*/ -ParClass *EaseDrivClass(void) { +ParClass *EaseDrivClass(void) +{ return ParMakeClass(&easeDrivClass, EaseBaseClass()); } + /*----------------------------------------------------------------------------*/ -EaseBase *EaseBaseCast(void *object) { +EaseBase *EaseBaseCast(void *object) +{ return ParCast(&easeBaseClass, object); } + /*----------------------------------------------------------------------------*/ -EaseDriv *EaseDrivCast(void *object) { +EaseDriv *EaseDrivCast(void *object) +{ return ParCast(&easeDrivClass, object); } + /*----------------------------------------------------------------------------*/ -void EaseStop(EaseBase *eab) { +void EaseStop(EaseBase * eab) +{ FsmStop(eab->task, eab->idle); closeRS232(eab->ser); eab->state = EASE_notconnected; } + /*----------------------------------------------------------------------------*/ -void EaseWriteError(EaseBase *eab) { +void EaseWriteError(EaseBase * eab) +{ int l; switch (eab->errCode) { case NOTCONNECTED: - ParPrintf(eab, eError, "ERROR: unconnected socket for %s", eab->p.name); + ParPrintf(eab, eError, "ERROR: unconnected socket for %s", + eab->p.name); break; case FAILEDCONNECT: - ParPrintf(eab, eError, "ERROR: can not connect to %s:%d (terminalserver off or no ethernet connection)", - eab->ser->pHost, eab->ser->iPort); + ParPrintf(eab, eError, + "ERROR: can not connect to %s:%d (terminalserver off or no ethernet connection)", + eab->ser->pHost, eab->ser->iPort); break; case TIMEOUT: ParPrintf(eab, eError, "ERROR: timeout on %s\ncmd: %s\nans: %s", @@ -64,51 +77,59 @@ void EaseWriteError(EaseBase *eab) { break; case INCOMPLETE: ParPrintf(eab, eError, "ERROR: incomplete answer %s from %s", eab->ans, - eab->p.name); + eab->p.name); break; case EASE_ILL_ANS: - if (eab->p.verbose < 1) break; + if (eab->p.verbose < 1) + break; l = strlen(eab->cmd); - if (l > 0 && eab->cmd[l-1] < ' ') { + if (l > 0 && eab->cmd[l - 1] < ' ') { l--; } ParPrintf(eab, eError, "ERROR: illegal answer %s from %s (cmd: %*s)", - eab->ans, eab->p.name, l, eab->cmd); + eab->ans, eab->p.name, l, eab->cmd); break; case EASE_DEV_CHANGED: - ParPrintf(eab, eError, "ERROR: controller was exchanged on %s", eab->p.name); + ParPrintf(eab, eError, "ERROR: controller was exchanged on %s", + eab->p.name); EaseStop(eab); break; case EASE_FAULT: ParPrintf(eab, eError, "ERROR: error on %s", eab->p.name); break; default: - ParPrintf(eab, eError, "ERROR: error code %d on %s", eab->errCode, eab->p.name); + ParPrintf(eab, eError, "ERROR: error code %d on %s", eab->errCode, + eab->p.name); break; } } + /*----------------------------------------------------------------------------*/ -void EaseWrite(EaseBase *eab, char *cmd) { +void EaseWrite(EaseBase * eab, char *cmd) +{ /* cmd==NULL: repeat the same command */ int iRet; char trash[64]; int l; - - if (eab->errCode || eab->state == EASE_expect) return; + + if (eab->errCode || eab->state == EASE_expect) + return; while (availableRS232(eab->ser) == 1) { - l=sizeof(trash); + l = sizeof(trash); iRet = readRS232TillTerm(eab->ser, trash, &l); - if (iRet < 0) break; + if (iRet < 0) + break; ParPrintf(eab, -2, "trash: %s\n", trash); } if (cmd) { - snprintf(eab->cmd, sizeof(eab->cmd), "%s%s", cmd, eab->ser->sendTerminator); + snprintf(eab->cmd, sizeof(eab->cmd), "%s%s", cmd, + eab->ser->sendTerminator); } iRet = writeRS232(eab->ser, eab->cmd, strlen(eab->cmd)); if (iRet < 0) { FsmStop(eab->task, eab->idle); snprintf(eab->msg, sizeof eab->msg, - "connection to %s:%d lost", eab->ser->pHost, eab->ser->iPort); + "connection to %s:%d lost", eab->ser->pHost, eab->ser->iPort); ParPrintf(eab, eError, "ERROR: %s", eab->msg); closeRS232(eab->ser); eab->state = EASE_notconnected; @@ -123,9 +144,11 @@ void EaseWrite(EaseBase *eab, char *cmd) { eab->state = EASE_expect; eab->cmdtime = time(NULL); } + /*----------------------------------------------------------------------------*/ -int EaseWaitRead(EaseBase *eab) { - int cnt=0; +int EaseWaitRead(EaseBase * eab) +{ + int cnt = 0; time_t start; if (eab->state < EASE_idle) { @@ -137,8 +160,8 @@ int EaseWaitRead(EaseBase *eab) { /* TaskYield(pServ->pTasker); does not work (pardef is not recursive) */ FsmTaskHandler(eab->task); cnt++; - if (time(NULL) > start+5) { - eab->ans[0]='\0'; + if (time(NULL) > start + 5) { + eab->ans[0] = '\0'; eab->state = EASE_read; return TIMEOUT; } @@ -147,12 +170,16 @@ int EaseWaitRead(EaseBase *eab) { /* if (cnt>1) ParPrintf(eab, eError, "TaskYield %d\n", cnt); */ return 1; } + /*----------------------------------------------------------------------------*/ -void EaseParHasChanged(void) { +void EaseParHasChanged(void) +{ parameterChange = 1; } + /*----------------------------------------------------------------------------*/ -void EaseSavePars(void) { +void EaseSavePars(void) +{ char *pFile = NULL; if (parameterChange) { @@ -160,16 +187,18 @@ void EaseSavePars(void) { assert(pServ->pSics); - pFile = IFindOption(pSICSOptions,"statusfile"); + pFile = IFindOption(pSICSOptions, "statusfile"); if (pFile) { - WriteSicsStatus(pServ->pSics,pFile,0); + WriteSicsStatus(pServ->pSics, pFile, 0); } } } + /*----------------------------------------------------------------------------*/ -static int EaseRestart(EaseBase *eab) { +static int EaseRestart(EaseBase * eab) +{ int iRet; - + eab->errCode = 0; if (eab->task) { FsmStop(eab->task, eab->idle); @@ -185,14 +214,16 @@ static int EaseRestart(EaseBase *eab) { return -1; } snprintf(eab->msg, sizeof eab->msg, - "connecting to %s:%d", eab->ser->pHost, eab->ser->iPort); + "connecting to %s:%d", eab->ser->pHost, eab->ser->iPort); return 0; } + /*----------------------------------------------------------------------------*/ -int EaseHandler(EaseBase *eab) { +int EaseHandler(EaseBase * eab) +{ EaseDriv *ead = EaseDrivCast(eab);; int iret; - + EaseSavePars(); if (ead && ead->stopped && ead->hwstate == HWBusy) { ead->stopped = 0; @@ -204,9 +235,9 @@ int EaseHandler(EaseBase *eab) { } if (eab->state == EASE_expect) { - if (eab->cmdtime !=0 && time(NULL) > eab->cmdtime + eab->p.period*2) { + if (eab->cmdtime != 0 && time(NULL) > eab->cmdtime + eab->p.period * 2) { snprintf(eab->msg, sizeof eab->msg, "no response since %d sec", - (int)(time(NULL) - eab->cmdtime)); + (int) (time(NULL) - eab->cmdtime)); } return 0; } @@ -218,10 +249,11 @@ int EaseHandler(EaseBase *eab) { } if (eab->state == EASE_connecting) { iret = initRS232Finished(eab->ser); - if (iret == 0) return 0; /* waiting for connection */ + if (iret == 0) + return 0; /* waiting for connection */ if (iret < 0) { snprintf(eab->msg, sizeof eab->msg, - "connection for %s failed", eab->p.name); + "connection for %s failed", eab->p.name); ParPrintf(eab, eError, "%s", eab->msg); closeRS232(eab->ser); eab->state = EASE_notconnected; @@ -229,7 +261,7 @@ int EaseHandler(EaseBase *eab) { } else { eab->tmo = 20; snprintf(eab->msg, sizeof eab->msg, - "get a first answer from %s", eab->p.name); + "get a first answer from %s", eab->p.name); eab->state = EASE_idle; } } @@ -260,10 +292,12 @@ int EaseHandler(EaseBase *eab) { } return 1; } + /*----------------------------------------------------------------------------*/ -int EaseNextFullRead(EaseBase *eab) { +int EaseNextFullRead(EaseBase * eab) +{ time_t thisPeriod; - + thisPeriod = time(NULL) / eab->p.period; if (thisPeriod != eab->readPeriod) { eab->readPeriod = thisPeriod; @@ -271,29 +305,36 @@ int EaseNextFullRead(EaseBase *eab) { } return 0; } + /*----------------------------------------------------------------------------*/ -static long EaseSendIt(long pc, void *object) { +static long EaseSendIt(long pc, void *object) +{ EaseBase *eab = EaseBaseCast(object); - - switch (pc) { default: /* FSM BEGIN *******************************/ + + switch (pc) { + default: /* FSM BEGIN ****************************** */ EaseWrite(eab, eab->sendCmd); ParPrintf(eab, eWarning, "send cmd> %s", eab->sendCmd); eab->sendCmd = NULL; - return __LINE__; case __LINE__: /**********************************/ + return __LINE__; + case __LINE__: /**********************************/ ParPrintf(eab, eWarning, "response> %s", eab->ans); - return 0; } /* FSM END ********************************************/ + return 0; + } /* FSM END ******************************************* */ } + /*----------------------------------------------------------------------------*/ -int EaseCheckDoit(EaseBase *eab) { +int EaseCheckDoit(EaseBase * eab) +{ int i, n; - + if (eab->todo == NULL) { if (eab->sendCmd != NULL) { eab->todo = EaseSendIt; return 1; } n = eab->maxflag / EASE_FLAGBITS; - for (i=0; i<=n; i++) { + for (i = 0; i <= n; i++) { if (eab->updateFlags[i]) { eab->todo = eab->doit; return 1; @@ -302,80 +343,97 @@ int EaseCheckDoit(EaseBase *eab) { } return eab->todo != NULL; } + /*----------------------------------------------------------------------------*/ -static long EaseIdle(long pc, void *object) { +static long EaseIdle(long pc, void *object) +{ EaseBase *eab = EaseBaseCast(object); EaseDriv *ead = EaseDrivCast(object); struct timeval tm; FsmFunc todo; - - switch (pc) { default: /* FSM BEGIN *******************************/ - + + switch (pc) { + default: /* FSM BEGIN ****************************** */ + idle: - if (! EaseCheckDoit(eab)) goto rd; + if (!EaseCheckDoit(eab)) + goto rd; doit: todo = eab->todo; eab->todo = NULL; FsmCall(todo); - return __LINE__; case __LINE__: /**********************************/ + return __LINE__; + case __LINE__: /**********************************/ eab->startOk = 1; rd: /* - if (eab->state == EASE_lost) { - snprintf(eab->msg, sizeof eab->msg, "no response from %s", - eab->p.type->name); - } - */ + if (eab->state == EASE_lost) { + snprintf(eab->msg, sizeof eab->msg, "no response from %s", + eab->p.type->name); + } + */ FsmCall(eab->read); - return __LINE__; case __LINE__: /**********************************/ + return __LINE__; + case __LINE__: /**********************************/ - if (EaseCheckDoit(eab)) goto doit; + if (EaseCheckDoit(eab)) + goto doit; /* - gettimeofday(&tm, NULL); - printf("stop %s %f\n", eab->evc->pName, tm.tv_usec / 1e6); - */ + gettimeofday(&tm, NULL); + printf("stop %s %f\n", eab->evc->pName, tm.tv_usec / 1e6); + */ FsmWait(1); - return __LINE__; case __LINE__: /**********************************/ + return __LINE__; + case __LINE__: /**********************************/ /* - gettimeofday(&tm, NULL); - printf("start %s %f\n", eab->evc->pName, tm.tv_usec / 1e6); - */ + gettimeofday(&tm, NULL); + printf("start %s %f\n", eab->evc->pName, tm.tv_usec / 1e6); + */ goto idle; - - /* never return */ - return 0; } /* FSM END ********************************************/ + + /* never return */ + return 0; + } /* FSM END ******************************************* */ } + /*----------------------------------------------------------------------------*/ -static float EaseGetValue(void *obj, SConnection *pCon) { +static float EaseGetValue(void *obj, SConnection * pCon) +{ float val; EaseBase *eab; - + assert(eab = EaseBaseCast(obj)); ParGetFloat(pCon, eab, "", &val); return val; } + /*----------------------------------------------------------------------------*/ -int EaseUpdate(int flag) { +int EaseUpdate(int flag) +{ EaseBase *eab = EaseBaseCast(ParObject()); - - ParAccess(usUser); ParSave(0); + + ParAccess(usUser); + ParSave(0); if (ParActionIs(PAR_SET) > 0) { assert(flag >= 0); assert(flag <= eab->maxflag); eab->updateFlags[flag / EASE_FLAGBITS] |= 1 << (flag % EASE_FLAGBITS); - if (eab->task) FsmSpeed(eab->task); + if (eab->task) + FsmSpeed(eab->task); return 1; } return 0; } + /*----------------------------------------------------------------------------*/ -int EaseNextUpdate(void *object) { +int EaseNextUpdate(void *object) +{ EaseBase *eab = EaseBaseCast(object); unsigned long mask, p; int i, n, flag; - + n = eab->maxflag / EASE_FLAGBITS; for (i = 0; i <= n; i++) { mask = eab->updateFlags[i]; @@ -384,7 +442,7 @@ int EaseNextUpdate(void *object) { /* find first */ while (flag < 32) { if (mask & p) { - eab->updateFlags[i] &= ~ p; + eab->updateFlags[i] &= ~p; return flag + i * EASE_FLAGBITS; } p <<= 1; @@ -393,11 +451,13 @@ int EaseNextUpdate(void *object) { } return -1; } + /*----------------------------------------------------------------------------*/ -int EaseGetUpdate(void *object, int flag) { +int EaseGetUpdate(void *object, int flag) +{ EaseBase *eab = EaseBaseCast(object); int i; - + assert(flag >= 0); assert(flag <= eab->maxflag); i = flag / EASE_FLAGBITS; @@ -406,21 +466,26 @@ int EaseGetUpdate(void *object, int flag) { } return 0; } + /*----------------------------------------------------------------------------*/ -void EaseSetUpdate(void *object, int flag, int state) { +void EaseSetUpdate(void *object, int flag, int state) +{ EaseBase *eab = EaseBaseCast(object); - + assert(flag >= 0); assert(flag <= eab->maxflag); - + if (state) { eab->updateFlags[flag / EASE_FLAGBITS] |= 1 << (flag % EASE_FLAGBITS); } else { - eab->updateFlags[flag / EASE_FLAGBITS] &= ~ (1 << (flag % EASE_FLAGBITS)); + eab->updateFlags[flag / EASE_FLAGBITS] &= + ~(1 << (flag % EASE_FLAGBITS)); } } + /*----------------------------------------------------------------------------*/ -static long EaseRun(void *obj, SConnection *pCon, float fVal) { +static long EaseRun(void *obj, SConnection * pCon, float fVal) +{ EaseBase *eab = EaseBaseCast(obj); EaseDriv *ead = EaseDrivCast(obj); int canc; @@ -428,7 +493,7 @@ static long EaseRun(void *obj, SConnection *pCon, float fVal) { assert(ead); ParSaveConn(eab, pCon); - if (! eab->doit) { + if (!eab->doit) { ParPrintf(ead, eError, "ERROR: missing run function %s", eab->p.name); return 0; } @@ -447,7 +512,7 @@ static long EaseRun(void *obj, SConnection *pCon, float fVal) { return 0; } ead->targetValue = fVal; - EaseParHasChanged(); /* assume that targetValue has to be saved */ + EaseParHasChanged(); /* assume that targetValue has to be saved */ ead->stopped = 0; /* eab->todo = eab->doit; */ EaseSetUpdate(eab, EASE_RUN, 1); @@ -456,7 +521,7 @@ static long EaseRun(void *obj, SConnection *pCon, float fVal) { ead->timeout = time(NULL) + ead->maxwait; } else { ead->maxwait = -1; - ead->timeout = time(NULL) + 9999999; /* approx. infinite */ + ead->timeout = time(NULL) + 9999999; /* approx. infinite */ } ead->finish = 0; ead->usedSettle = 0; @@ -466,19 +531,23 @@ static long EaseRun(void *obj, SConnection *pCon, float fVal) { } return 1; } + /*----------------------------------------------------------------------------*/ -static int EaseHalt(void *obj) { +static int EaseHalt(void *obj) +{ EaseDriv *ead; - + assert(ead = EaseDrivCast(obj)); ead->stopped = 1; return 1; } + /*----------------------------------------------------------------------------*/ -static int EaseIsInTol(void *obj) { - EaseDriv *ead = EaseDrivCast(obj); +static int EaseIsInTol(void *obj) +{ + EaseDriv *ead = EaseDrivCast(obj); float f; - + f = EaseGetValue(ead, NULL) - ead->targetValue; if (ead->tolState == EASE_outOfTolerance) { if (fabsf(f) < ead->tolerance) { @@ -491,7 +560,7 @@ static int EaseIsInTol(void *obj) { if (fabsf(f) > ead->tolerance * 1.11) { if (ead->tolState == EASE_inTolerance) { ParPrintf(obj, eWarning, "%s is out of tolerance by %f", - ead->b.p.name, f); + ead->b.p.name, f); } ead->tolState = EASE_outOfTolerance; return 0; @@ -499,16 +568,20 @@ static int EaseIsInTol(void *obj) { return 1; } } + /*----------------------------------------------------------------------------*/ -static int EaseErrHandler(void *obj) { +static int EaseErrHandler(void *obj) +{ /* to be implemented */ return 1; } + /*----------------------------------------------------------------------------*/ -static int EaseCheckStatus(void *obj, SConnection *pCon) { +static int EaseCheckStatus(void *obj, SConnection * pCon) +{ EaseDriv *ead = EaseDrivCast(obj); time_t now, t; - + assert(ead); ParSaveConn(ead, pCon); if (ead->stopped) { @@ -516,14 +589,15 @@ static int EaseCheckStatus(void *obj, SConnection *pCon) { } now = time(NULL); if (now > ead->timeout) { - ParPrintf(obj, eWarning, "maxwait expired when driving %s", ead->b.p.name); + ParPrintf(obj, eWarning, "maxwait expired when driving %s", + ead->b.p.name); ead->hwstate = HWIdle; } else if (EaseIsInTol(obj)) { if (ead->finish == 0) { ead->finish = now - ead->usedSettle; - if (now < ead->finish + ead->settle) { + if (now < ead->finish + ead->settle) { ParPrintf(obj, eWarning, "settle %s for %ld sec", - ead->b.p.name, (long)(ead->finish + ead->settle - now)); + ead->b.p.name, (long) (ead->finish + ead->settle - now)); } } if (now > ead->finish + ead->settle && ead->hwstate != HWIdle) { @@ -536,12 +610,14 @@ static int EaseCheckStatus(void *obj, SConnection *pCon) { } return ead->hwstate; } + /*----------------------------------------------------------------------------*/ -static EVMode EaseGetMode(void *obj) { - EaseDriv *ead = EaseDrivCast(obj); - +static EVMode EaseGetMode(void *obj) +{ + EaseDriv *ead = EaseDrivCast(obj); + assert(ead); - + if (ead->hwstate == HWBusy) { return EVDrive; } @@ -550,32 +626,39 @@ static EVMode EaseGetMode(void *obj) { } return EVMonitor; } + /*----------------------------------------------------------------------------*/ -static int EaseCheckLimits(void *obj, float fVal, char *error, int errLen) { +static int EaseCheckLimits(void *obj, float fVal, char *error, int errLen) +{ EaseDriv *ead; - + assert(ead = EaseDrivCast(obj)); - + /* lower limit */ if (fVal < ead->lowerLimit) { - snprintf(error, errLen, "ERROR: %g violates lower limit of device",fVal); + snprintf(error, errLen, "ERROR: %g violates lower limit of device", + fVal); return 0; } /* upper limit */ if (fVal > ead->upperLimit) { - snprintf(error, errLen, "ERROR: %g violates upper limit of device",fVal); + snprintf(error, errLen, "ERROR: %g violates upper limit of device", + fVal); return 0; } return 1; } + /*----------------------------------------------------------------------------*/ -static int EaseStdHandler(void *object) { +static int EaseStdHandler(void *object) +{ int iret, l; EaseBase *eab = EaseBaseCast(object); char *corr; - + assert(eab); - if (eab->state < EASE_idle) goto quit; + if (eab->state < EASE_idle) + goto quit; if (availableNetRS232(eab->ser) || availableRS232(eab->ser)) { eab->msg[0] = '\0'; l = sizeof(eab->ans); @@ -612,28 +695,29 @@ error: quit: return EaseHandler(eab); } + /*----------------------------------------------------------------------------*/ -static int EaseInit(SConnection *pCon, EaseBase *eab, int argc, char *argv[], - int maxflag, - FsmHandler handler, - FsmFunc start, - FsmFunc idle, - FsmFunc read) { +static int EaseInit(SConnection * pCon, EaseBase * eab, int argc, + char *argv[], int maxflag, FsmHandler handler, + FsmFunc start, FsmFunc idle, FsmFunc read) +{ /* args (starting from argv[0]): : - */ + */ int port, iRet, i; rs232 *ser; char *colon, *host; char buf[64]; - + if (handler == NULL) { handler = EaseStdHandler; } - assert(eab); assert(start); assert(read || idle); + assert(eab); + assert(start); + assert(read || idle); eab->handler = handler; eab->start = start; eab->read = read; @@ -642,35 +726,35 @@ static int EaseInit(SConnection *pCon, EaseBase *eab, int argc, char *argv[], } else { eab->idle = EaseIdle; } - + if (argc < 1 || argc > 2) { SCWrite(pCon, "illegal number of arguments", eError); return 0; } colon = strchr(argv[0], ':'); - if (!colon && argc == 1) { /* use a rs232 object */ + if (!colon && argc == 1) { /* use a rs232 object */ ser = FindCommandData(pServ->pSics, argv[0], "RS232 Controller"); if (ser == NULL) { SCWrite(pCon, "ERROR: rs232 not found", eError); return 0; } } else { - if (argc == 1) { /* host:port syntax */ - port=atoi(colon+1); - i = colon-argv[0]; + if (argc == 1) { /* host:port syntax */ + port = atoi(colon + 1); + i = colon - argv[0]; if (i >= sizeof buf) { SCWrite(pCon, "ERROR: host name too long", eError); return 0; } strncpy(buf, argv[0], i); - buf[i]='\0'; + buf[i] = '\0'; host = buf; - } else if (argc == 2) { /* host port syntax */ + } else if (argc == 2) { /* host port syntax */ host = argv[0]; - port=atoi(argv[1]); + port = atoi(argv[1]); } - if (port==0) { + if (port == 0) { SCWrite(pCon, "ERROR: illegal port number", eError); return 0; } @@ -689,31 +773,35 @@ static int EaseInit(SConnection *pCon, EaseBase *eab, int argc, char *argv[], eab->maxflag = maxflag; eab->sendCmd = NULL; eab->tmo = 20; - eab->updateFlags = calloc(maxflag / EASE_FLAGBITS + 1, sizeof (*eab->updateFlags)); + eab->updateFlags = + calloc(maxflag / EASE_FLAGBITS + 1, sizeof(*eab->updateFlags)); if (eab->updateFlags == NULL) { SCWrite(pCon, "out of memory", eError); return 0; } - - setRS232ReplyTerminator(eab->ser,"\r"); - setRS232SendTerminator(eab->ser,"\r"); - setRS232Timeout(eab->ser,5000); /* milliseconds */ - setRS232Debug(eab->ser,0); + + setRS232ReplyTerminator(eab->ser, "\r"); + setRS232SendTerminator(eab->ser, "\r"); + setRS232Timeout(eab->ser, 5000); /* milliseconds */ + setRS232Debug(eab->ser, 0); eab->task = NULL; - if (EaseRestart(eab) < 0) return -1; + if (EaseRestart(eab) < 0) + return -1; eab->task = FsmStartTask(eab, eab->handler, eab->idle, eab->p.name); - - TaskRegister(pServ->pTasker, (TaskFunc)FsmTaskHandler, NULL, FsmKill, - eab->task, 0); + + TaskRegister(pServ->pTasker, (TaskFunc) FsmTaskHandler, NULL, FsmKill, + eab->task, 0); return 1; } + /*----------------------------------------------------------------------------*/ -static void *EaseGetInterface(void *obj, int iCode) { +static void *EaseGetInterface(void *obj, int iCode) +{ EaseBase *eab = EaseBaseCast(obj); EaseDriv *ead = EaseDrivCast(obj); - - assert(eab); + + assert(eab); if (iCode == DRIVEID) { if (ead) { return ead->drivInt; @@ -725,65 +813,66 @@ static void *EaseGetInterface(void *obj, int iCode) { } return NULL; } + /*----------------------------------------------------------------------------*/ -void *EaseMakeBase(SConnection *con, void *class, int argc, char *argv[], +void *EaseMakeBase(SConnection * con, void *class, int argc, char *argv[], int dynamic, int maxflag, ParDef pardef, FsmHandler handler, - FsmFunc start, - FsmFunc idle, - FsmFunc read) { + FsmFunc start, FsmFunc idle, FsmFunc read) +{ /* args (starting from argv[0]): - MakeObject objectname - - */ + MakeObject objectname + + */ EaseBase *eab; char *creationCmd = NULL; - + if (dynamic) { creationCmd = Arg2Tcl(argc, argv, NULL, 0); } eab = ParMake(con, argv[1], class, pardef, creationCmd); - if (!eab) return NULL; + if (!eab) + return NULL; ParCheck(&easeBaseClass, eab); - if (! EaseInit(con, eab, argc-3, argv+3, maxflag, - handler, start, idle, read)) { + if (!EaseInit(con, eab, argc - 3, argv + 3, maxflag, + handler, start, idle, read)) { RemoveCommand(pServ->pSics, argv[1]); return NULL; } return eab; } + /*----------------------------------------------------------------------------*/ -void *EaseMakeDriv(SConnection *con, void *class, int argc, char *argv[], +void *EaseMakeDriv(SConnection * con, void *class, int argc, char *argv[], int dynamic, int maxflag, ParDef pardef, FsmHandler handler, - FsmFunc start, - FsmFunc idle, - FsmFunc read, - FsmFunc run) { - + FsmFunc start, FsmFunc idle, FsmFunc read, FsmFunc run) +{ + int iret; EaseDriv *ead; char *creationCmd = NULL; - + assert(run); if (dynamic) { creationCmd = Arg2Tcl(argc, argv, NULL, 0); } ead = ParMake(con, argv[1], class, pardef, creationCmd); - if (!ead) return NULL; + if (!ead) + return NULL; ParCheck(&easeDrivClass, ead); ead->b.doit = run; - - ead->evInt = CreateEVInterface(); + + ead->evInt = CreateEVInterface(); ead->drivInt = CreateDrivableInterface(); ead->b.p.desc->GetInterface = EaseGetInterface; - - if (! ead->evInt || ! ead->drivInt || - ! EaseInit(con, (EaseBase *)ead, argc-3, argv+3, maxflag, - handler, start, idle, read)) { + + if (!ead->evInt || !ead->drivInt || + !EaseInit(con, (EaseBase *) ead, argc - 3, argv + 3, maxflag, + handler, start, idle, read)) { RemoveCommand(pServ->pSics, argv[1]); return NULL; } @@ -798,48 +887,56 @@ void *EaseMakeDriv(SConnection *con, void *class, int argc, char *argv[], ead->drivInt->SetValue = EaseRun; ead->drivInt->CheckStatus = EaseCheckStatus; ead->drivInt->GetValue = EaseGetValue; - + ead->maxwait = -1; ead->lowerLimit = 0; ead->upperLimit = 1000; ead->settle = 0; ead->tolerance = 1; ead->targetValue = 0; - + /* EMon interface to be implemented */ return ead; } + /*----------------------------------------------------------------------------*/ -void EaseMsgPar(void *object) { +void EaseMsgPar(void *object) +{ EaseBase *eab = EaseBaseCast(object); - + assert(eab); ParName("status"); ParLogAs(NULL); if (eab->msg[0] == '\0') { - ParList(""); /* do not list when empty */ + ParList(""); /* do not list when empty */ } else { ParList(NULL); } ParFixedStr(eab->msg, sizeof eab->msg, NULL); return; } + /*----------------------------------------------------------------------------*/ -int EaseRestartWrapper(void *object, void *userarg, int argc, char *argv[]) { +int EaseRestartWrapper(void *object, void *userarg, int argc, char *argv[]) +{ EaseBase *eab = EaseBaseCast(object); - + EaseRestart(eab); return 0; } + /*----------------------------------------------------------------------------*/ -void EaseBasePar(void *object) { +void EaseBasePar(void *object) +{ EaseBase *eab = EaseBaseCast(object); - + assert(eab); - ParName("restart"); ParAccess(usUser); ParCmd(EaseRestartWrapper, NULL); - + ParName("restart"); + ParAccess(usUser); + ParCmd(EaseRestartWrapper, NULL); + if (ParActionIs(PAR_KILL)) { if (eab->ser) { KillRS232(eab->ser); @@ -854,17 +951,19 @@ void EaseBasePar(void *object) { eab->updateFlags = NULL; } } - + return; } + /*----------------------------------------------------------------------------*/ -int EaseSend(void *object, void *userarg, int argc, char *argv[]) { +int EaseSend(void *object, void *userarg, int argc, char *argv[]) +{ EaseBase *eab = EaseBaseCast(object); int iret; char cmd[32]; char ans[64]; char *term; - + iret = EaseWaitRead(eab); if (iret >= 0) { eab->sendCmd = ParArg2Str(argc, argv, NULL, 0); @@ -879,13 +978,19 @@ int EaseSend(void *object, void *userarg, int argc, char *argv[]) { } return 0; } + /*----------------------------------------------------------------------------*/ -void EaseSendPar(void *object) { - ParName("send"); ParAccess(usUser); ParCmd(EaseSend, NULL); +void EaseSendPar(void *object) +{ + ParName("send"); + ParAccess(usUser); + ParCmd(EaseSend, NULL); return; } + /*----------------------------------------------------------------------------*/ -void EaseKillDriv(EaseDriv *ead) { +void EaseKillDriv(EaseDriv * ead) +{ if (ead->drivInt) { free(ead->drivInt); } @@ -893,44 +998,58 @@ void EaseKillDriv(EaseDriv *ead) { free(ead->evInt); } } + /*----------------------------------------------------------------------------*/ -void EaseDrivPar(void *object, char *fmt, char *unit) { +void EaseDrivPar(void *object, char *fmt, char *unit) +{ EaseDriv *ead; - + assert(ead = EaseDrivCast(object)); - + ParName("upperLimit"); - ParFmt(fmt); ParTail(unit); ParAccess(usUser); ParSave(1); + ParFmt(fmt); + ParTail(unit); + ParAccess(usUser); + ParSave(1); ParFloat(&ead->upperLimit, 310.); - + ParName("lowerLimit"); if (ead->lowerLimit != 0) { - ParFmt(fmt); ParTail(unit); + ParFmt(fmt); + ParTail(unit); }; - ParAccess(usUser); ParSave(1); + ParAccess(usUser); + ParSave(1); ParFloat(&ead->lowerLimit, 0.0); - + ParName("tolerance"); - ParFmt(fmt); ParTail(unit); ParAccess(usUser); ParSave(1); + ParFmt(fmt); + ParTail(unit); + ParAccess(usUser); + ParSave(1); ParFloat(&ead->tolerance, 1.0); - + ParName("maxwait"); if (ead->maxwait < 0) { ParTail("disabled"); } else { ParTail("sec"); } - ParAccess(usUser); ParSave(1); + ParAccess(usUser); + ParSave(1); ParInt(&ead->maxwait, 7200); - + ParName("settle"); - ParTail("sec"); ParAccess(usUser); ParSave(1); + ParTail("sec"); + ParAccess(usUser); + ParSave(1); ParInt(&ead->settle, 0); - + ParName("targetValue"); - ParFmt(fmt); ParTail(unit); + ParFmt(fmt); + ParTail(unit); ParFloat(&ead->targetValue, PAR_NAN); - + if (ParActionIs(PAR_KILL)) { EaseKillDriv(ead); } diff --git a/ease.h b/ease.h index 888c353..695398e 100644 --- a/ease.h +++ b/ease.h @@ -23,8 +23,10 @@ Markus Zolliker, March 2005 #define EASE_RUN 0 typedef enum { EASE_connecting, EASE_notconnected, - EASE_idle, EASE_read, EASE_expect, EASE_lost } EaseState; -typedef enum { EASE_notMonitored, EASE_inTolerance, EASE_outOfTolerance } EaseTolState; + EASE_idle, EASE_read, EASE_expect, EASE_lost +} EaseState; +typedef enum { EASE_notMonitored, EASE_inTolerance, + EASE_outOfTolerance } EaseTolState; typedef struct { ParData p; @@ -35,11 +37,11 @@ typedef struct { FsmFunc doit; FsmFunc todo; rs232 *ser; - Fsm *task; /* a pointer to the task */ - int errCode; /* error code of last operation. not changed on success */ + Fsm *task; /* a pointer to the task */ + int errCode; /* error code of last operation. not changed on success */ EaseState state; time_t cmdtime; - int syntax; /* not used in ease, may be used by the driver. used by oxinst.c */ + int syntax; /* not used in ease, may be used by the driver. used by oxinst.c */ char cmd[64]; char ans[64]; char version[64]; @@ -58,7 +60,7 @@ typedef struct { EVInterface *evInt; EVMode eMode; int stopped; - int hwstate; /* SICS driver state */ + int hwstate; /* SICS driver state */ EaseTolState tolState; float upperLimit; float lowerLimit; @@ -76,28 +78,28 @@ ParClass *EaseDrivClass(void); EaseBase *EaseBaseCast(void *object); EaseDriv *EaseDrivCast(void *object); -void EaseWriteError(EaseBase *eab); -void EaseWrite(EaseBase *eab, char *cmd); -int EaseWaitRead(EaseBase *eab); -int EaseHandler(EaseBase *eab); +void EaseWriteError(EaseBase * eab); +void EaseWrite(EaseBase * eab, char *cmd); +int EaseWaitRead(EaseBase * eab); +int EaseHandler(EaseBase * eab); void EaseBasePar(void *object); void EaseSendPar(void *object); void EaseMsgPar(void *object); -void EaseKillDriv(EaseDriv *ead); +void EaseKillDriv(EaseDriv * ead); void EaseDrivPar(void *object, char *fmt, char *unit); void EaseParHasChanged(void); -void EaseStop(EaseBase *eab); -int EaseCheckDoit(EaseBase *eab); -int EaseNextFullRead(EaseBase *eab); +void EaseStop(EaseBase * eab); +int EaseCheckDoit(EaseBase * eab); +int EaseNextFullRead(EaseBase * eab); -int EaseUpdate(int flag); /* used inside pardef, after ParName and before - the parameter definition. - The specified flag is updated - when the parameter was changed. - returns 1 when changed, 0 when not changed - calls ParAccess(usUser) and ParSave(1), as - this seems to be useful for parameters - that reflect a state of the device. */ +int EaseUpdate(int flag); /* used inside pardef, after ParName and before + the parameter definition. + The specified flag is updated + when the parameter was changed. + returns 1 when changed, 0 when not changed + calls ParAccess(usUser) and ParSave(1), as + this seems to be useful for parameters + that reflect a state of the device. */ int EaseNextUpdate(void *object); /* get next update flag and clear it. return the next set update flag or -1 when no @@ -108,20 +110,15 @@ int EaseGetUpdate(void *object, int flag); void EaseSetUpdate(void *object, int flag, int state); /* set an update flag */ -void *EaseMakeBase(SConnection *con, void *class, int argc, char *argv[], +void *EaseMakeBase(SConnection * con, void *class, int argc, char *argv[], int dynamic, int maxflag, ParDef pardef, FsmHandler handler, - FsmFunc start, - FsmFunc idle, - FsmFunc read); -void *EaseMakeDriv(SConnection *con, void *class, int argc, char *argv[], + FsmFunc start, FsmFunc idle, FsmFunc read); +void *EaseMakeDriv(SConnection * con, void *class, int argc, char *argv[], int dynamic, int maxflag, ParDef pardef, FsmHandler handler, - FsmFunc start, - FsmFunc idle, - FsmFunc read, - FsmFunc run); + FsmFunc start, FsmFunc idle, FsmFunc read, FsmFunc run); #endif diff --git a/ecb.c b/ecb.c index ec190b4..454e01f 100644 --- a/ecb.c +++ b/ecb.c @@ -20,57 +20,58 @@ #include "ecb.h" #include "ecb.i" /*------------- private defines and error codes ------------------------*/ -#define ACKN ('\6') /* Acknowledge character */ +#define ACKN ('\6') /* Acknowledge character */ #define READ_BYTES 3 #define WRITE_BYTES 4 #define DMAREAD 5 #define ECB_BYTES 65535 -typedef union /* Used to swap bytes in 'address' and 'byte_count' */ - { - unsigned short word; - struct - { - unsigned char msb; /* Most significant byte */ - unsigned char lsb; /* Least significant byte */ - }b; - }Swap; +typedef union { /* Used to swap bytes in 'address' and 'byte_count' */ + unsigned short word; + struct { + unsigned char msb; /* Most significant byte */ + unsigned char lsb; /* Least significant byte */ + } b; +} Swap; /* ------- error codes */ #define ECBILLEGALFUNC -100 #define ECBOVERFLOW -101 /*----------------------------------------------------------------------*/ -static int ecbSendFunc(pECB self, int func){ +static int ecbSendFunc(pECB self, int func) +{ unsigned char function, response; int count, status; /* - send function code - */ - function = (unsigned char)func; + send function code + */ + function = (unsigned char) func; count = 1; - status = GPIBsend(self->gpib,self->ecbDeviceID,&function,count); - if(status < 0){ + status = GPIBsend(self->gpib, self->ecbDeviceID, &function, count); + if (status < 0) { self->lastError = status; return 0; } /* - read acknowledge byte - */ - status = GPIBread(self->gpib,self->ecbDeviceID,&response,count); - if(status < 0){ + read acknowledge byte + */ + status = GPIBread(self->gpib, self->ecbDeviceID, &response, count); + if (status < 0) { self->lastError = status; return 0; } - if(response != ACKN){ + if (response != ACKN) { self->lastError = ECBILLEGALFUNC; return 0; } return 1; } + /*-----------------------------------------------------------------------*/ -int ecbExecute(pECB self, int func, Z80_reg in, Z80_reg *out){ +int ecbExecute(pECB self, int func, Z80_reg in, Z80_reg * out) +{ int count, status; assert(self != NULL); @@ -78,85 +79,88 @@ int ecbExecute(pECB self, int func, Z80_reg in, Z80_reg *out){ self->lastError = 0; /* - send function code - */ - status = ecbSendFunc(self,func); - if(status <= 0){ + send function code + */ + status = ecbSendFunc(self, func); + if (status <= 0) { return status; } /* - send input register - */ + send input register + */ count = 4; - status = GPIBsend(self->gpib,self->ecbDeviceID, &in, count); - if(status < 0){ + status = GPIBsend(self->gpib, self->ecbDeviceID, &in, count); + if (status < 0) { self->lastError = status; return 0; } /* - read result register - */ - status = GPIBread(self->gpib,self->ecbDeviceID, out, count); - if(status < 0){ + read result register + */ + status = GPIBread(self->gpib, self->ecbDeviceID, out, count); + if (status < 0) { self->lastError = status; return 0; } - return 1; + return 1; } + /*----------------------------------------------------------------------*/ static int ecbPrepareIO(pECB self, int func, unsigned short address, - unsigned short byteCount){ + unsigned short byteCount) +{ Swap save, adr, count; int status, bytes; - if(byteCount >= ECB_BYTES){ + if (byteCount >= ECB_BYTES) { self->lastError = ECBOVERFLOW; return 0; } /* - Swap address and byteCount?? This may be a portability issue! - This may not be necessary on some platforms - */ - save.word = address; /* Swap address bytes */ + Swap address and byteCount?? This may be a portability issue! + This may not be necessary on some platforms + */ + save.word = address; /* Swap address bytes */ adr.b.lsb = save.b.msb; adr.b.msb = save.b.lsb; - save.word = byteCount; /* Swap byte count bytes */ + save.word = byteCount; /* Swap byte count bytes */ count.b.lsb = save.b.msb; count.b.msb = save.b.lsb; - status = ecbSendFunc(self,func); - if(status <= 0){ + status = ecbSendFunc(self, func); + if (status <= 0) { return status; } /* - send address - */ + send address + */ bytes = 2; - status = GPIBsend(self->gpib,self->ecbDeviceID,&adr,bytes); - if(status < 0){ + status = GPIBsend(self->gpib, self->ecbDeviceID, &adr, bytes); + if (status < 0) { self->lastError = status; return 0; } /* - send byte count - */ - status = GPIBsend(self->gpib,self->ecbDeviceID,&count,bytes); - if(status < 0){ + send byte count + */ + status = GPIBsend(self->gpib, self->ecbDeviceID, &count, bytes); + if (status < 0) { self->lastError = status; return 0; } return 1; } + /*-----------------------------------------------------------------------*/ -int ecbRead(pECB self, unsigned short address, - void *buffer, int byteCount){ +int ecbRead(pECB self, unsigned short address, void *buffer, int byteCount) +{ int status, count; @@ -164,52 +168,58 @@ int ecbRead(pECB self, unsigned short address, assert(self->gpib != NULL); self->lastError = 0; - status = ecbPrepareIO(self,READ_BYTES,address,(unsigned short)byteCount); - if(status <= 0){ + status = + ecbPrepareIO(self, READ_BYTES, address, (unsigned short) byteCount); + if (status <= 0) { return 0; } /* - actual read - */ - status = GPIBread(self->gpib,self->ecbDeviceID, buffer, byteCount); - if(status < 0){ + actual read + */ + status = GPIBread(self->gpib, self->ecbDeviceID, buffer, byteCount); + if (status < 0) { self->lastError = status; return 0; } return 1; } + /*----------------------------------------------------------------------*/ -int ecbDMARead(pECB self, unsigned short address, void *buffer, - unsigned short byteCount){ +int ecbDMARead(pECB self, unsigned short address, void *buffer, + unsigned short byteCount) +{ int status, count; assert(self != NULL); assert(self->gpib != NULL); self->lastError = 0; - status = ecbPrepareIO(self,DMAREAD,address,(unsigned short)byteCount); - if(status <= 0){ + status = + ecbPrepareIO(self, DMAREAD, address, (unsigned short) byteCount); + if (status <= 0) { return 0; } - usleep(20*1000); + usleep(20 * 1000); /* - actual read - */ - status = GPIBread(self->gpib,self->ecbDeviceID, buffer, byteCount); - if(status < 0){ + actual read + */ + status = GPIBread(self->gpib, self->ecbDeviceID, buffer, byteCount); + if (status < 0) { self->lastError = status; return 0; } return 1; } + /*----------------------------------------------------------------------*/ -int ecbWrite(pECB self, unsigned short address, - void *buffer, int byteCount){ +int ecbWrite(pECB self, unsigned short address, + void *buffer, int byteCount) +{ int status, count; @@ -217,71 +227,80 @@ int ecbWrite(pECB self, unsigned short address, assert(self->gpib != NULL); self->lastError = 0; - status = ecbPrepareIO(self,WRITE_BYTES,address,(unsigned short)byteCount); - if(status <= 0){ + status = + ecbPrepareIO(self, WRITE_BYTES, address, (unsigned short) byteCount); + if (status <= 0) { return 0; } /* - actual read - */ - status = GPIBsend(self->gpib,self->ecbDeviceID, buffer, byteCount); - if(status < 0){ + actual read + */ + status = GPIBsend(self->gpib, self->ecbDeviceID, buffer, byteCount); + if (status < 0) { self->lastError = status; return 0; } return 1; } + /*-----------------------------------------------------------------------*/ -void ecbErrorDescription(pECB self, char *buffer, int maxBuffer){ +void ecbErrorDescription(pECB self, char *buffer, int maxBuffer) +{ int positive; - switch(self->lastError){ + switch (self->lastError) { case ECBILLEGALFUNC: - strncpy(buffer,"Illegal ECB function called",maxBuffer); + strncpy(buffer, "Illegal ECB function called", maxBuffer); return; case ECBOVERFLOW: strncpy(buffer, - "You tried to copy more then 64K onto the poor ECB, REFUSED!", - maxBuffer); + "You tried to copy more then 64K onto the poor ECB, REFUSED!", + maxBuffer); return; } /* - GPIB error codes - */ - GPIBerrorDescription(self->gpib,self->lastError,buffer, maxBuffer); + GPIB error codes + */ + GPIBerrorDescription(self->gpib, self->lastError, buffer, maxBuffer); } + /*----------------------------------------------------------------------*/ -void ecbClear(pECB self){ +void ecbClear(pECB self) +{ GPIBclear(self->gpib, self->ecbDeviceID); } + /*-----------------------------------------------------------------------*/ -int fixECBError(pECB self){ +int fixECBError(pECB self) +{ int pos; - switch(self->lastError){ + switch (self->lastError) { case ECBILLEGALFUNC: case ECBOVERFLOW: return HWFault; } /* - GPIB error - */ + GPIB error + */ pos = -self->lastError; - switch(pos){ + switch (pos) { case GPIBEABO: return HWRedo; default: return HWFault; } } + /*------------------------------------------------------------------------*/ -int ECBAction(SConnection *pCon, SicsInterp *pSics, void *pData, - int argc, char *argv[]){ - pECB self = (pECB)pData; +int ECBAction(SConnection * pCon, SicsInterp * pSics, void *pData, + int argc, char *argv[]) +{ + pECB self = (pECB) pData; Z80_reg in, out; char pBuffer[80], pError[132]; int status, iVal, func = 0; @@ -289,209 +308,214 @@ int ECBAction(SConnection *pCon, SicsInterp *pSics, void *pData, assert(self != NULL); /* - Only managers will be allowed to wrestle directly with ECB - controllers. - */ - if(!SCinMacro(pCon)){ - if(!SCMatchRights(pCon,usMugger)){ + Only managers will be allowed to wrestle directly with ECB + controllers. + */ + if (!SCinMacro(pCon)) { + if (!SCMatchRights(pCon, usMugger)) { return 0; } } - if(argc < 2){ - SCWrite(pCon,"ERROR: keyword required for ECB",eError); + if (argc < 2) { + SCWrite(pCon, "ERROR: keyword required for ECB", eError); return 0; } strtolower(argv[1]); - if(strcmp(argv[1],"func") == 0){ - if(argc < 7){ - SCWrite(pCon,"ERROR: require function code and four register values", - eError); + if (strcmp(argv[1], "func") == 0) { + if (argc < 7) { + SCWrite(pCon, + "ERROR: require function code and four register values", + eError); return 0; } - status = Tcl_GetInt(pSics->pTcl, argv[2],&func); - if(status != TCL_OK){ - SCWrite(pCon,"ERROR: failed to convert argument to int",eError); + status = Tcl_GetInt(pSics->pTcl, argv[2], &func); + if (status != TCL_OK) { + SCWrite(pCon, "ERROR: failed to convert argument to int", eError); return 0; } - status = Tcl_GetInt(pSics->pTcl, argv[3],&iVal); - if(status != TCL_OK){ - SCWrite(pCon,"ERROR: failed to convert argument to int",eError); + status = Tcl_GetInt(pSics->pTcl, argv[3], &iVal); + if (status != TCL_OK) { + SCWrite(pCon, "ERROR: failed to convert argument to int", eError); return 0; } - in.d = (unsigned char)iVal; - status = Tcl_GetInt(pSics->pTcl, argv[4],&iVal); - if(status != TCL_OK){ - SCWrite(pCon,"ERROR: failed to convert argument to int",eError); + in.d = (unsigned char) iVal; + status = Tcl_GetInt(pSics->pTcl, argv[4], &iVal); + if (status != TCL_OK) { + SCWrite(pCon, "ERROR: failed to convert argument to int", eError); return 0; } - in.e = (unsigned char)iVal; - status = Tcl_GetInt(pSics->pTcl, argv[5],&iVal); - if(status != TCL_OK){ - SCWrite(pCon,"ERROR: failed to convert argument to int",eError); + in.e = (unsigned char) iVal; + status = Tcl_GetInt(pSics->pTcl, argv[5], &iVal); + if (status != TCL_OK) { + SCWrite(pCon, "ERROR: failed to convert argument to int", eError); return 0; } - in.b = (unsigned char)iVal; - status = Tcl_GetInt(pSics->pTcl, argv[6],&iVal); - if(status != TCL_OK){ - SCWrite(pCon,"ERROR: failed to convert argument to int",eError); + in.b = (unsigned char) iVal; + status = Tcl_GetInt(pSics->pTcl, argv[6], &iVal); + if (status != TCL_OK) { + SCWrite(pCon, "ERROR: failed to convert argument to int", eError); return 0; } - in.c = (unsigned char)iVal; + in.c = (unsigned char) iVal; - status = ecbExecute(self,func,in,&out); - if(status != 1){ - ecbErrorDescription(self,pBuffer,79); - sprintf(pError,"ERROR: %s", pBuffer); - SCWrite(pCon,pError,eError); + status = ecbExecute(self, func, in, &out); + if (status != 1) { + ecbErrorDescription(self, pBuffer, 79); + sprintf(pError, "ERROR: %s", pBuffer); + SCWrite(pCon, pError, eError); return 0; } - sprintf(pBuffer,"%d %d %d %d", - out.d, out.e, out.b, out.c); - SCWrite(pCon,pBuffer,eValue); + sprintf(pBuffer, "%d %d %d %d", out.d, out.e, out.b, out.c); + SCWrite(pCon, pBuffer, eValue); return 1; - } else if(strcmp(argv[1],"clear") == 0){ + } else if (strcmp(argv[1], "clear") == 0) { ecbClear(self); SCSendOK(pCon); return 1; - }else if(strcmp(argv[1],"toint")== 0){ - sprintf(pBuffer,"%d",argv[2][0]); - SCWrite(pCon,pBuffer,eValue); + } else if (strcmp(argv[1], "toint") == 0) { + sprintf(pBuffer, "%d", argv[2][0]); + SCWrite(pCon, pBuffer, eValue); return 1; } else { - SCWrite(pCon,"ERROR: ECB does not understand keyword", eError); + SCWrite(pCon, "ERROR: ECB does not understand keyword", eError); return 0; } } -/*---------------------------------------------------------------------*/ -int ecbAssignEncoder(pECB self, int encoder, int motorNumber){ - if(encoder <= 0 || encoder > 3){ +/*---------------------------------------------------------------------*/ +int ecbAssignEncoder(pECB self, int encoder, int motorNumber) +{ + + if (encoder <= 0 || encoder > 3) { return 0; } - self->encoder[encoder-1] = motorNumber; + self->encoder[encoder - 1] = motorNumber; self->encoderDirty = 1; return 1; } + /*----------------------------------------------------------------------*/ -int ecbLoadEncoder(pECB self){ +int ecbLoadEncoder(pECB self) +{ Z80_reg in, out; int status; - if(self->encoderDirty != 1){ + if (self->encoderDirty != 1) { /* - no need to do it if no change - */ + no need to do it if no change + */ return 1; } - if(self->encoder[0] != 0){ + if (self->encoder[0] != 0) { in.d = self->encoder[0]; - }else { + } else { in.d = 0; } - if(self->encoder[1] != 0){ + if (self->encoder[1] != 0) { in.e = self->encoder[1]; - }else { + } else { in.e = 0; } - if(self->encoder[2] != 0){ + if (self->encoder[2] != 0) { in.b = self->encoder[2]; - }else { + } else { in.b = 0; } in.c = 1; - status = ecbExecute(self,152,in,&out); + status = ecbExecute(self, 152, in, &out); return status; } + /*-----------------------------------------------------------------------*/ -void ECBKill(void *pData){ - pECB self = (pECB)pData; - - if(self == NULL){ +void ECBKill(void *pData) +{ + pECB self = (pECB) pData; + + if (self == NULL) { return; } /* - Detaching here may be dangerous: If the GPIB has been deleted first, - this makes a core dump. Best is the GPIB keeps a list of attached - things and cleans them itself. - - GPIBdetach(self->gpib,self->ecbDeviceID); - */ - if(self->pDes){ + Detaching here may be dangerous: If the GPIB has been deleted first, + this makes a core dump. Best is the GPIB keeps a list of attached + things and cleans them itself. + + GPIBdetach(self->gpib,self->ecbDeviceID); + */ + if (self->pDes) { DeleteDescriptor(self->pDes); } free(self); } + /*---------------------------------------------------------------------- MakeECB name gpibcontroller boardNo gpib-address -----------------------------------------------------------------------*/ -int MakeECB(SConnection *pCon, SicsInterp *pSics, void *pData, - int argc, char *argv[]){ +int MakeECB(SConnection * pCon, SicsInterp * pSics, void *pData, + int argc, char *argv[]) +{ pECB self = NULL; int address, status, boardNo; pGPIB gpib = NULL; char pError[132]; /* - we need a name, the GPIB controller and an address on the GPIB bus for - the ECB as arguments - */ - if(argc < 5){ - SCWrite(pCon,"ERROR: insufficient arguments to MakeECB",eError); + we need a name, the GPIB controller and an address on the GPIB bus for + the ECB as arguments + */ + if (argc < 5) { + SCWrite(pCon, "ERROR: insufficient arguments to MakeECB", eError); return 0; } - gpib = FindCommandData(pSics,argv[2],"GPIB"); - if(gpib == NULL){ - sprintf(pError,"ERROR: no GPIB controller %s found", argv[2]); - SCWrite(pCon,pError,eError); + gpib = FindCommandData(pSics, argv[2], "GPIB"); + if (gpib == NULL) { + sprintf(pError, "ERROR: no GPIB controller %s found", argv[2]); + SCWrite(pCon, pError, eError); return 0; } - status = Tcl_GetInt(pSics->pTcl,argv[3], &boardNo); - if(status != TCL_OK){ - sprintf(pError,"ERROR: failed to convert %s to integer",argv[3]); - SCWrite(pCon,pError,eError); + status = Tcl_GetInt(pSics->pTcl, argv[3], &boardNo); + if (status != TCL_OK) { + sprintf(pError, "ERROR: failed to convert %s to integer", argv[3]); + SCWrite(pCon, pError, eError); return 0; } - status = Tcl_GetInt(pSics->pTcl,argv[4], &address); - if(status != TCL_OK){ - sprintf(pError,"ERROR: failed to convert %s to integer",argv[4]); - SCWrite(pCon,pError,eError); + status = Tcl_GetInt(pSics->pTcl, argv[4], &address); + if (status != TCL_OK) { + sprintf(pError, "ERROR: failed to convert %s to integer", argv[4]); + SCWrite(pCon, pError, eError); return 0; } - if(address < 0 || address > 30){ - SCWrite(pCon,"ERROR: invalid GPIB address specified",eError); + if (address < 0 || address > 30) { + SCWrite(pCon, "ERROR: invalid GPIB address specified", eError); return 0; } - self = (pECB)malloc(sizeof(ECB)); - if(self == NULL){ - SCWrite(pCon,"ERROR: no memory to allocate ECB",eError); + self = (pECB) malloc(sizeof(ECB)); + if (self == NULL) { + SCWrite(pCon, "ERROR: no memory to allocate ECB", eError); return 0; } - memset(self,0,sizeof(ECB)); + memset(self, 0, sizeof(ECB)); self->pDes = CreateDescriptor("ECB"); - if(self->pDes == NULL){ - SCWrite(pCon,"ERROR: no memory to allocate ECB",eError); + if (self->pDes == NULL) { + SCWrite(pCon, "ERROR: no memory to allocate ECB", eError); return 0; } self->gpib = gpib; self->boardNumber = boardNo; self->ecbAddress = address; - self->ecbDeviceID =GPIBattach(self->gpib,self->boardNumber, - self->ecbAddress,0, - 13,0,1); - if(self->ecbDeviceID <= 0){ - SCWrite(pCon,"ERROR: failed to initialize ECB connection", - eError); + self->ecbDeviceID = GPIBattach(self->gpib, self->boardNumber, + self->ecbAddress, 0, 13, 0, 1); + if (self->ecbDeviceID <= 0) { + SCWrite(pCon, "ERROR: failed to initialize ECB connection", eError); ECBKill(self); return 0; } - AddCommand(pSics,argv[1],ECBAction,ECBKill,self); + AddCommand(pSics, argv[1], ECBAction, ECBKill, self); return 1; } - diff --git a/ecb.h b/ecb.h index dd5b861..3d7c7bb 100644 --- a/ecb.h +++ b/ecb.h @@ -17,29 +17,28 @@ typedef struct { - unsigned char d; /* D register in Z80 */ - unsigned char e; /* E register in Z80 */ - unsigned char b; /* B register in Z80 */ - unsigned char c; /* C register in Z80 */ - } Z80_reg; + unsigned char d; /* D register in Z80 */ + unsigned char e; /* E register in Z80 */ + unsigned char b; /* B register in Z80 */ + unsigned char c; /* C register in Z80 */ +} Z80_reg; /*-----------------------------------------------------------------------*/ - typedef struct __ECB *pECB; +typedef struct __ECB *pECB; - int ecbExecute(pECB self, int func, Z80_reg in, Z80_reg *out); - int ecbRead(pECB self, unsigned short address, - void *buffer, int byteCount); - int ecbWrite(pECB self, unsigned short address, - void *buffer, int byteCount); - int ecbDMARead(pECB self, unsigned short address, void *buffer, - unsigned short byteCount); - void ecbClear(pECB self); - int fixECBError(pECB self); - void ecbErrorDescription(pECB self, char *buffer, - int maxBytes); - int ecbAssignEncoder(pECB self, int encoder, int motorNumber); - int ecbLoadEncoder(pECB self); +int ecbExecute(pECB self, int func, Z80_reg in, Z80_reg * out); +int ecbRead(pECB self, unsigned short address, + void *buffer, int byteCount); +int ecbWrite(pECB self, unsigned short address, + void *buffer, int byteCount); +int ecbDMARead(pECB self, unsigned short address, void *buffer, + unsigned short byteCount); +void ecbClear(pECB self); +int fixECBError(pECB self); +void ecbErrorDescription(pECB self, char *buffer, int maxBytes); +int ecbAssignEncoder(pECB self, int encoder, int motorNumber); +int ecbLoadEncoder(pECB self); @@ -47,23 +46,21 @@ typedef struct { /*-----------------------------------------------------------------------*/ - int MakeECB(SConnection *pCon, SicsInterp *pSics, - void *pData, - int ragc, char *argv[]); +int MakeECB(SConnection * pCon, SicsInterp * pSics, + void *pData, int ragc, char *argv[]); /*---------------------------------------------------------------------- for byte packing. result must be an 32 bit integer ----------------------------------------------------------------------*/ -typedef union /* Used to extract and load data to Z80 regs. */{ - unsigned int result; - struct - { - unsigned char byt0; /* Least significant byte */ - unsigned char byt1; - unsigned char byt2; - unsigned char byt3; /* Most significant byte */ - }b; -}Ecb_pack; +typedef union { /* Used to extract and load data to Z80 regs. */ + unsigned int result; + struct { + unsigned char byt0; /* Least significant byte */ + unsigned char byt1; + unsigned char byt2; + unsigned char byt3; /* Most significant byte */ + } b; +} Ecb_pack; #endif diff --git a/ecbcounter.c b/ecbcounter.c index c204dc4..31e2ba2 100644 --- a/ecbcounter.c +++ b/ecbcounter.c @@ -19,21 +19,21 @@ /*------------------ our private data structure ------------------------*/ typedef struct { - pECB ecb; /* the ECB system we talk to */ - unsigned char prescaler[8]; /* an array for the prescaler values */ - int tfreq; /* timer frequency */ - unsigned char control; /* marks the control monitor */ - int state; /* current counting state */ -}ECBCounter, *pECBCounter; + pECB ecb; /* the ECB system we talk to */ + unsigned char prescaler[8]; /* an array for the prescaler values */ + int tfreq; /* timer frequency */ + unsigned char control; /* marks the control monitor */ + int state; /* current counting state */ +} ECBCounter, *pECBCounter; /*----------------- private defines ------------------------------------*/ #define STFRD 137 #define STREAD 138 -#define STOPS 136 +#define STOPS 136 #define STCLEA 134 #define PRELOA 139 #define STLOAD 156 -#define STCPRE 133 +#define STCPRE 133 #define STARTS 135 #define SPCSTA 169 @@ -42,7 +42,7 @@ typedef struct { #define COUNT 2 #define NOBEAM 3 /*--------------------------------------------------------------------*/ -#define MAX_COUNT 4294967295.0 +#define MAX_COUNT 4294967295.0 /*------------------ error codes --------------------------------------*/ #define COMMERROR -300 #define TOMANYCOUNTS -301 @@ -51,14 +51,15 @@ typedef struct { #define INVALIDPRESCALER -305 #define BADFREQ -306 /*======================================================================*/ -static int readScaler(pECBCounter pPriv, int scaler, int *count){ +static int readScaler(pECBCounter pPriv, int scaler, int *count) +{ int status; Z80_reg in, out; Ecb_pack data; - - in.c = (unsigned char)scaler; - status = ecbExecute(pPriv->ecb,STREAD,in,&out); - if(status != 1){ + + in.c = (unsigned char) scaler; + status = ecbExecute(pPriv->ecb, STREAD, in, &out); + if (status != 1) { return COMMERROR; } @@ -66,23 +67,25 @@ static int readScaler(pECBCounter pPriv, int scaler, int *count){ data.b.byt2 = out.b; data.b.byt1 = out.d; data.b.byt0 = out.e; - if(scaler == 0){ - *count = data.result/pPriv->tfreq; + if (scaler == 0) { + *count = data.result / pPriv->tfreq; } else { *count = data.result; } return 1; } + /*---------------------------------------------------------------------------*/ -static int readTime(pECBCounter pPriv,float *time){ +static int readTime(pECBCounter pPriv, float *time) +{ int status; Z80_reg in, out; Ecb_pack data; - - in.c = (unsigned char)0; - status = ecbExecute(pPriv->ecb,STREAD,in,&out); - if(status != 1){ + + in.c = (unsigned char) 0; + status = ecbExecute(pPriv->ecb, STREAD, in, &out); + if (status != 1) { return COMMERROR; } @@ -90,124 +93,135 @@ static int readTime(pECBCounter pPriv,float *time){ data.b.byt2 = out.b; data.b.byt1 = out.d; data.b.byt0 = out.e; - *time = (float)data.result/(float)pPriv->tfreq; + *time = (float) data.result / (float) pPriv->tfreq; return 1; } /*---------------------------------------------------------------------*/ -static int check4Beam(struct __COUNTER *pCter, int *beam){ +static int check4Beam(struct __COUNTER *pCter, int *beam) +{ Z80_reg in, out; pECBCounter self = NULL; int status; - self = (pECBCounter)pCter->pData; + self = (pECBCounter) pCter->pData; assert(self); in.c = 1; - status = ecbExecute(self->ecb,SPCSTA,in,&out); - if(status != 1){ + status = ecbExecute(self->ecb, SPCSTA, in, &out); + if (status != 1) { pCter->iErrorCode = COMMERROR; return HWFault; } - *beam = (int)out.d; + *beam = (int) out.d; return 1; } + /*----------------------------------------------------------------------*/ -static int stopScalers(pECBCounter self){ +static int stopScalers(pECBCounter self) +{ int status; Z80_reg in, out; - status = ecbExecute(self->ecb,STOPS,in,&out); - if(status != 1){ + status = ecbExecute(self->ecb, STOPS, in, &out); + if (status != 1) { return COMMERROR; } return 1; } + /*======================================================================== These two functions currently rely on the idea that the ECB stops and starts without clearing counters in between. The sequence of things necessary to start it, suggests this. If this is not the case then this will not work. ===========================================================================*/ -static int ECBPause(struct __COUNTER *self){ +static int ECBPause(struct __COUNTER *self) +{ int status; pECBCounter pPriv = NULL; assert(self); - pPriv = (pECBCounter)self->pData; + pPriv = (pECBCounter) self->pData; assert(pPriv); - if((status = stopScalers(pPriv)) <= 0){ + if ((status = stopScalers(pPriv)) <= 0) { self->iErrorCode = status; return HWFault; } return OKOK; } + /*=======================================================================*/ -static int ECBContinue(struct __COUNTER *self){ +static int ECBContinue(struct __COUNTER *self) +{ int status; pECBCounter pPriv = NULL; Z80_reg in, out; assert(self); - pPriv = (pECBCounter)self->pData; + pPriv = (pECBCounter) self->pData; assert(pPriv); - status = ecbExecute(pPriv->ecb,STARTS,in,&out); - if(status != 1){ + status = ecbExecute(pPriv->ecb, STARTS, in, &out); + if (status != 1) { self->iErrorCode = status; return HWFault; } return OKOK; } + /*=======================================================================*/ -static int ECBHalt(struct __COUNTER *self){ +static int ECBHalt(struct __COUNTER *self) +{ int status; pECBCounter pPriv = NULL; assert(self); - pPriv = (pECBCounter)self->pData; + pPriv = (pECBCounter) self->pData; assert(pPriv); pPriv->state = IDLE; - if((status = stopScalers(pPriv)) <= 0){ + if ((status = stopScalers(pPriv)) <= 0) { self->iErrorCode = status; return HWFault; } return OKOK; } + /*-----------------------------------------------------------------------*/ -static int ECBGetStatus(struct __COUNTER *self, float *fControl){ - pECBCounter pPriv = (pECBCounter)self->pData; +static int ECBGetStatus(struct __COUNTER *self, float *fControl) +{ + pECBCounter pPriv = (pECBCounter) self->pData; int status, result, scaler; Z80_reg in, out; int count, beam; float time; - + assert(pPriv); /* - This can happen after a stop - */ - if(pPriv->state == IDLE){ + This can happen after a stop + */ + if (pPriv->state == IDLE) { return HWIdle; } /* - read status bit - */ - status = ecbExecute(pPriv->ecb,STFRD,in,&out); - if(status != 1){ + read status bit + */ + status = ecbExecute(pPriv->ecb, STFRD, in, &out); + if (status != 1) { self->iErrorCode = COMMERROR; pPriv->state = IDLE; return HWFault; } /* - read beam status - */ - status = check4Beam(self,&beam); - if(status != 1){ + read beam status + */ + status = check4Beam(self, &beam); + if (status != 1) { self->iErrorCode = COMMERROR; return HWFault; } @@ -218,23 +232,23 @@ static int ECBGetStatus(struct __COUNTER *self, float *fControl){ the thing can be in. Complicated by the fact that the status becomes idle (out.d = 0) when the measurement is paused due to the lack of beam. - */ - if(pPriv->state == COUNT && beam == 1){ + */ + if (pPriv->state == COUNT && beam == 1) { ECBPause(self); pPriv->state = NOBEAM; SetStatus(eOutOfBeam); result = HWNoBeam; } - if(pPriv->state == NOBEAM && beam == 0){ + if (pPriv->state == NOBEAM && beam == 0) { ECBContinue(self); pPriv->state = COUNT; SetStatus(eCounting); return HWBusy; } - if(pPriv->state == NOBEAM && beam == 1){ + if (pPriv->state == NOBEAM && beam == 1) { return HWNoBeam; } - if(out.d == 0 && pPriv->state == COUNT){ + if (out.d == 0 && pPriv->state == COUNT) { result = HWIdle; pPriv->state = IDLE; } else { @@ -242,97 +256,105 @@ static int ECBGetStatus(struct __COUNTER *self, float *fControl){ } /* - select which scaler to read - */ - if(self->eMode == eTimer){ + select which scaler to read + */ + if (self->eMode == eTimer) { scaler = 0; - readTime(pPriv,fControl); - }else { + readTime(pPriv, fControl); + } else { scaler = pPriv->control; - readScaler(pPriv,scaler,&count); - *fControl = (float)count; + readScaler(pPriv, scaler, &count); + *fControl = (float) count; } - if(*fControl > self->fPreset){ + if (*fControl > self->fPreset) { ECBHalt(self); - } + } return result; } + /*=====================================================================*/ -static int clearScalers(pECBCounter self){ +static int clearScalers(pECBCounter self) +{ int status; Z80_reg in, out; - status = ecbExecute(self->ecb,STCLEA,in,&out); - if(status != 1){ + status = ecbExecute(self->ecb, STCLEA, in, &out); + if (status != 1) { return COMMERROR; } return 1; } + /*----------------------------------------------------------------------*/ -static int loadPrescalers(pECBCounter self){ +static int loadPrescalers(pECBCounter self) +{ Z80_reg in, out; int status, i; - for(i = 0; i < 8; i++){ - in.c = (unsigned char)i; + for (i = 0; i < 8; i++) { + in.c = (unsigned char) i; in.d = self->prescaler[i]; - status = ecbExecute(self->ecb,PRELOA,in,&out); - if(status != 1){ + status = ecbExecute(self->ecb, PRELOA, in, &out); + if (status != 1) { return COMMERROR; } } return 1; } + /*----------------------------------------------------------------------*/ -static int loadPreset(pECBCounter self, int preset, unsigned char control){ +static int loadPreset(pECBCounter self, int preset, unsigned char control) +{ Z80_reg in, out; Ecb_pack data; int status, i; data.result = preset; - + in.c = data.b.byt3; in.b = data.b.byt2; in.e = data.b.byt1; in.d = data.b.byt0; - status = ecbExecute(self->ecb,STLOAD,in,&out); - if(status != 1){ + status = ecbExecute(self->ecb, STLOAD, in, &out); + if (status != 1) { return COMMERROR; } in.b = data.b.byt2; in.e = data.b.byt1; in.d = data.b.byt0; - in.c = 4*control; - status = ecbExecute(self->ecb,STCPRE,in,&out); - if(status != 1){ + in.c = 4 * control; + status = ecbExecute(self->ecb, STCPRE, in, &out); + if (status != 1) { return COMMERROR; } return 1; } + /*-----------------------------------------------------------------------*/ -static int ECBStart(struct __COUNTER *self){ +static int ECBStart(struct __COUNTER *self) +{ pECBCounter pPriv = NULL; int preset, status, controlUnit; Z80_reg in, out; assert(self); - pPriv = (pECBCounter)self->pData; + pPriv = (pECBCounter) self->pData; assert(pPriv); /* - check if the preset is permissible - */ - preset = (int)rint(self->fPreset); - if(preset > MAX_COUNT){ + check if the preset is permissible + */ + preset = (int) rint(self->fPreset); + if (preset > MAX_COUNT) { self->iErrorCode = TOMANYCOUNTS; return HWFault; } - if(self->eMode == eTimer){ + if (self->eMode == eTimer) { controlUnit = 0; - preset *= pPriv->tfreq; - if(preset > MAX_COUNT){ + preset *= pPriv->tfreq; + if (preset > MAX_COUNT) { self->iErrorCode = TOMANYCOUNTS; return HWFault; } @@ -340,107 +362,114 @@ static int ECBStart(struct __COUNTER *self){ controlUnit = pPriv->control; } - if((status = stopScalers(pPriv)) <= 0){ + if ((status = stopScalers(pPriv)) <= 0) { self->iErrorCode = status; return HWFault; } - if((status = clearScalers(pPriv)) <= 0){ + if ((status = clearScalers(pPriv)) <= 0) { self->iErrorCode = status; return HWFault; } - if((status = loadPrescalers(pPriv)) <= 0){ + if ((status = loadPrescalers(pPriv)) <= 0) { self->iErrorCode = status; return HWFault; } - if((status = loadPreset(pPriv, preset,(unsigned char)controlUnit)) <= 0){ + if ((status = + loadPreset(pPriv, preset, (unsigned char) controlUnit)) <= 0) { self->iErrorCode = status; return HWFault; } - status = ecbExecute(pPriv->ecb,STARTS,in,&out); - if(status != 1){ + status = ecbExecute(pPriv->ecb, STARTS, in, &out); + if (status != 1) { self->iErrorCode = status; return HWFault; } - + pPriv->state = COUNT; return OKOK; } + /*=======================================================================*/ -static int ECBTransfer(struct __COUNTER *self){ +static int ECBTransfer(struct __COUNTER *self) +{ int status, count, i; pECBCounter pPriv = NULL; assert(self); - pPriv = (pECBCounter)self->pData; + pPriv = (pECBCounter) self->pData; assert(pPriv); /* - read time - */ - status = readTime(pPriv,&self->fTime); - if(status <= 0){ + read time + */ + status = readTime(pPriv, &self->fTime); + if (status <= 0) { self->iErrorCode = COMMERROR; return HWFault; } /* - read other scalers - */ - for(i = 1; i < 8; i++){ - status = readScaler(pPriv,i,&count); - if(status <= 0){ + read other scalers + */ + for (i = 1; i < 8; i++) { + status = readScaler(pPriv, i, &count); + if (status <= 0) { self->iErrorCode = COMMERROR; return HWFault; } - self->lCounts[i-1] = count; + self->lCounts[i - 1] = count; } return OKOK; } + /*======================================================================*/ static int ECBGetError(struct __COUNTER *self, int *iCode, - char *errorText, int errlen){ + char *errorText, int errlen) +{ char pBueffel[132]; *iCode = self->iErrorCode; - switch(self->iErrorCode){ + switch (self->iErrorCode) { case COMMERROR: - strncpy(errorText,"Communication error with ECB",errlen); + strncpy(errorText, "Communication error with ECB", errlen); break; case TOMANYCOUNTS: - strncpy(errorText,"Preset is to high!",errlen); + strncpy(errorText, "Preset is to high!", errlen); break; case NOSEND: - strncpy(errorText,"Cannot send naked data to ECB",errlen); + strncpy(errorText, "Cannot send naked data to ECB", errlen); break; case UNKNOWNPAR: - strncpy(errorText,"parameter unknown",errlen); + strncpy(errorText, "parameter unknown", errlen); break; case INVALIDCOUNTER: - strncpy(errorText,"Invalid counter number requested, 0-7 allowed", - errlen); + strncpy(errorText, "Invalid counter number requested, 0-7 allowed", + errlen); break; case INVALIDPRESCALER: - strncpy(errorText,"Invalid prescaler value, allowed 1 or 10", - errlen); + strncpy(errorText, "Invalid prescaler value, allowed 1 or 10", errlen); break; case BADFREQ: - strncpy(errorText,"Bad timer frequency: 10 or 1000 allowed",errlen); + strncpy(errorText, "Bad timer frequency: 10 or 1000 allowed", errlen); break; default: - sprintf(pBueffel,"Unknown error code %d", self->iErrorCode); - strncpy(errorText,pBueffel,errlen); + sprintf(pBueffel, "Unknown error code %d", self->iErrorCode); + strncpy(errorText, pBueffel, errlen); break; } return 1; } + /*=======================================================================*/ -static int ECBFixIt(struct __COUNTER *self, int iCode){ +static int ECBFixIt(struct __COUNTER *self, int iCode) +{ return COTERM; } + /*======================================================================*/ /******************************************************************************* @@ -449,72 +478,71 @@ static int ECBFixIt(struct __COUNTER *self, int iCode){ * of f.ex a motor position. 'divide' specifies how many times the po- * sition is to be divided by two before it is displayed. ******************************************************************************/ -static void -Dot_divide (int device, int data, pECB ecb) +static void Dot_divide(int device, int data, pECB ecb) { int function, dot, divide; Z80_reg x_inreg, out; - if (data == 0) /* If zero, dont send dot/divide) */ + if (data == 0) /* If zero, dont send dot/divide) */ return; dot = 0; - while ((data%10) == 0) - { - dot++; - data /= 10; - } + while ((data % 10) == 0) { + dot++; + data /= 10; + } divide = 0; - while ((data%2) == 0) - { - divide++; - data /= 2; - } - if (data != 1) /* If != 1, not a binary No. */ + while ((data % 2) == 0) { + divide++; + data /= 2; + } + if (data != 1) /* If != 1, not a binary No. */ return; if (dot > 0) dot = 8 - dot; - x_inreg.c = 0; /* Specify input */ + x_inreg.c = 0; /* Specify input */ x_inreg.b = (unsigned char) device; - x_inreg.d = (unsigned char) dot; /* Dot position */ - x_inreg.e = (unsigned char) divide; /* No. of times to divide by 2 */ + x_inreg.d = (unsigned char) dot; /* Dot position */ + x_inreg.e = (unsigned char) divide; /* No. of times to divide by 2 */ - ecbExecute(ecb,170,x_inreg,&out); + ecbExecute(ecb, 170, x_inreg, &out); return; } + /*-----------------------------------------------------------------------*/ -static int ECBSet(struct __COUNTER *self, char *name, - int iCter, float fVal){ +static int ECBSet(struct __COUNTER *self, char *name, + int iCter, float fVal) +{ pECBCounter pPriv = NULL; int iVal; assert(self); - pPriv = (pECBCounter)self->pData; + pPriv = (pECBCounter) self->pData; assert(pPriv); - iVal = (int)rint(fVal); + iVal = (int) rint(fVal); - if(strcmp(name,"prescaler") == 0){ - if(iCter < 0 || iCter > 7){ + if (strcmp(name, "prescaler") == 0) { + if (iCter < 0 || iCter > 7) { self->iErrorCode = INVALIDCOUNTER; return HWFault; } - if(iVal != 1 && iVal != 10){ + if (iVal != 1 && iVal != 10) { self->iErrorCode = INVALIDPRESCALER; return HWFault; } - pPriv->prescaler[iCter] = (unsigned char)iVal; + pPriv->prescaler[iCter] = (unsigned char) iVal; return OKOK; - } else if(strcmp(name,"tfreq") == 0){ - if(fVal == 1000){ + } else if (strcmp(name, "tfreq") == 0) { + if (fVal == 1000) { pPriv->prescaler[0] = 1; pPriv->tfreq = 1000; - Dot_divide(64,1000,pPriv->ecb); + Dot_divide(64, 1000, pPriv->ecb); return OKOK; - } else if(fVal == 10){ + } else if (fVal == 10) { pPriv->tfreq = 10; pPriv->prescaler[0] = 10; - Dot_divide(64,10,pPriv->ecb); + Dot_divide(64, 10, pPriv->ecb); return OKOK; } else { self->iErrorCode = BADFREQ; @@ -525,59 +553,65 @@ static int ECBSet(struct __COUNTER *self, char *name, return HWFault; } } + /*===================================================================*/ -static int ECBGet(struct __COUNTER *self, char *name, - int iCter, float *fVal){ +static int ECBGet(struct __COUNTER *self, char *name, + int iCter, float *fVal) +{ pECBCounter pPriv = NULL; assert(self); - pPriv = (pECBCounter)self->pData; + pPriv = (pECBCounter) self->pData; assert(pPriv); - if(strcmp(name,"prescaler") == 0){ - *fVal = (float)pPriv->prescaler[iCter]; + if (strcmp(name, "prescaler") == 0) { + *fVal = (float) pPriv->prescaler[iCter]; return OKOK; - } else if(strcmp(name,"tfreq") == 0){ - *fVal = (float)pPriv->tfreq; + } else if (strcmp(name, "tfreq") == 0) { + *fVal = (float) pPriv->tfreq; return OKOK; - } else{ + } else { self->iErrorCode = UNKNOWNPAR; return HWFault; } -} +} + /*=====================================================================*/ -static int ECBSend(struct __COUNTER *self, char *text, - char *reply, int replylen){ - strncpy(reply,"ECB does not feast on ASCII strings, refused!", - replylen); +static int ECBSend(struct __COUNTER *self, char *text, + char *reply, int replylen) +{ + strncpy(reply, "ECB does not feast on ASCII strings, refused!", + replylen); return OKOK; } + /*====================================================================*/ -pCounterDriver MakeECBCounter(char *ecb){ +pCounterDriver MakeECBCounter(char *ecb) +{ pECBCounter pPriv = NULL; pCounterDriver self = NULL; int i; /* - memory for everybody - */ - self = CreateCounterDriver("ecb","ecb"); - pPriv = (pECBCounter)malloc(sizeof(ECBCounter)); - if(self == NULL || pPriv == NULL){ + memory for everybody + */ + self = CreateCounterDriver("ecb", "ecb"); + pPriv = (pECBCounter) malloc(sizeof(ECBCounter)); + if (self == NULL || pPriv == NULL) { return NULL; } - memset(pPriv,0,sizeof(ECBCounter)); + memset(pPriv, 0, sizeof(ECBCounter)); /* - initialize private data structure - */ - pPriv->ecb = (pECB)FindCommandData(pServ->pSics,ecb,"ECB"); - if(pPriv->ecb == NULL){ + initialize private data structure + */ + pPriv->ecb = (pECB) FindCommandData(pServ->pSics, ecb, "ECB"); + if (pPriv->ecb == NULL) { DeleteCounterDriver(self); free(pPriv); return NULL; } - for(i = 0; i < 8; i++){ + for (i = 0; i < 8; i++) { pPriv->prescaler[i] = 1; } pPriv->tfreq = 1000; @@ -585,19 +619,19 @@ pCounterDriver MakeECBCounter(char *ecb){ /* - assign function pointers - */ - self->GetStatus = ECBGetStatus; - self->Start = ECBStart; - self->Pause = ECBPause; - self->Continue = ECBContinue; - self->Halt = ECBHalt; - self->ReadValues = ECBTransfer; - self->GetError = ECBGetError; + assign function pointers + */ + self->GetStatus = ECBGetStatus; + self->Start = ECBStart; + self->Pause = ECBPause; + self->Continue = ECBContinue; + self->Halt = ECBHalt; + self->ReadValues = ECBTransfer; + self->GetError = ECBGetError; self->TryAndFixIt = ECBFixIt; - self->Set = ECBSet; - self->Get = ECBGet; - self->Send = ECBSend; + self->Set = ECBSet; + self->Get = ECBGet; + self->Send = ECBSend; self->KillPrivate = NULL; self->iNoOfMonitors = 8; diff --git a/ecbcounter.h b/ecbcounter.h index eb12145..cbfad22 100644 --- a/ecbcounter.h +++ b/ecbcounter.h @@ -12,6 +12,6 @@ #include "countdriv.h" pCounterDriver MakeECBCounter(char *ecb); -void KillECBCounter(CounterDriver *pDriv); +void KillECBCounter(CounterDriver * pDriv); #endif diff --git a/ecbdriv.c b/ecbdriv.c index 51c3a9e..9ce527f 100644 --- a/ecbdriv.c +++ b/ecbdriv.c @@ -50,35 +50,35 @@ /*------------------------------------------------------------------------ Parameter indexes in ObPar array and meanings -------------------------------------------------------------------------*/ -#define ENCODER 0 /* encoder number, 0 if no encoder */ -#define CONTROL 1 /* control signals, > 1 means required. */ -#define RANGE 2 /* 0 = slow, 1 = fast */ -#define MULT 3 /* 0 = not multiplexed, > 0 multiplex motor number*/ -#define MULTCHAN 16 /* multiplexer channel */ -#define ACCTIME 4 /* acceleration time: 500, 1000 or 2000 milSecs */ -#define ROTDIR 5 /* rotation direction */ -#define STARTSPEED 6 /* start speed: 100-500 steps/s */ -#define MAXSPEED 7 /* maximum speed: 100-2000 steps/sec */ -#define SLOWAUTO 8 /* slow speed in auto mode */ -#define SLOWMAN 9 /* slow speed in manual mode */ -#define DELAY 10 /* start delay 0 - 2500 millSecs */ -#define OFFSET 11 /* encoder offset */ -#define TOLERANCE 12 /* tolerance in steps */ -#define STEPS2DEG 13 /* conversion factor motor steps to Degree */ -#define DEG2STEP 14 /* conversion factor from degree to encoder digits */ -#define BACKLASH 15 /* motor backlash */ -#define PORT 17 /* ECB port when multiplexed */ -#define DEC 18 /* Decimals in display */ +#define ENCODER 0 /* encoder number, 0 if no encoder */ +#define CONTROL 1 /* control signals, > 1 means required. */ +#define RANGE 2 /* 0 = slow, 1 = fast */ +#define MULT 3 /* 0 = not multiplexed, > 0 multiplex motor number */ +#define MULTCHAN 16 /* multiplexer channel */ +#define ACCTIME 4 /* acceleration time: 500, 1000 or 2000 milSecs */ +#define ROTDIR 5 /* rotation direction */ +#define STARTSPEED 6 /* start speed: 100-500 steps/s */ +#define MAXSPEED 7 /* maximum speed: 100-2000 steps/sec */ +#define SLOWAUTO 8 /* slow speed in auto mode */ +#define SLOWMAN 9 /* slow speed in manual mode */ +#define DELAY 10 /* start delay 0 - 2500 millSecs */ +#define OFFSET 11 /* encoder offset */ +#define TOLERANCE 12 /* tolerance in steps */ +#define STEPS2DEG 13 /* conversion factor motor steps to Degree */ +#define DEG2STEP 14 /* conversion factor from degree to encoder digits */ +#define BACKLASH 15 /* motor backlash */ +#define PORT 17 /* ECB port when multiplexed */ +#define DEC 18 /* Decimals in display */ -#define MAXPAR 20 /* 1 extra for the sentinel, do not forget to initialize! */ +#define MAXPAR 20 /* 1 extra for the sentinel, do not forget to initialize! */ /*------------------------------ ECB defines -------------------------*/ #define MAX_ENCODER 40 -#define FENCOR 167 /* read encoder */ -#define MOREAD 145 /* read motor steps */ -#define MOPARA 140 /* motor parameter */ +#define FENCOR 167 /* read encoder */ +#define MOREAD 145 /* read motor steps */ +#define MOPARA 140 /* motor parameter */ #define MOCLOA 146 -#define ABS(x) (x < 0 ? -(x) : (x)) +#define ABS(x) (x < 0 ? -(x) : (x)) #define MOSTEP 141 #define MOSTAT 144 @@ -93,54 +93,51 @@ Parameter indexes in ObPar array and meanings #define ECBLIMIT -307 #define ECBREADERROR -308 /*================== The Driver data structure ============================*/ - typedef struct __ECBMotorDriv { - /* general motor driver interface - fields. REQUIRED! - */ - float fUpper; /* upper limit */ - float fLower; /* lower limit */ - char *name; - int (*GetPosition)(void *self,float *fPos); - int (*RunTo)(void *self, float fNewVal); - int (*GetStatus)(void *self); - void (*GetError)(void *self, int *iCode, - char *buffer, int iBufLen); - int (*TryAndFixIt)(void *self,int iError, - float fNew); - int (*Halt)(void *self); - int (*GetDriverPar)(void *self, char *name, - float *value); - int (*SetDriverPar)(void *self,SConnection *pCon, - char *name, float newValue); - void (*ListDriverPar)(void *self, char *motorName, - SConnection *pCon); - void (*KillPrivate)(void *self); - - /* ECB specific fields */ - pECB ecb; /* ECB controller for everything */ - int ecbIndex; /* motor index in ECB */ - int errorCode; - int restart; /* flag if we have to restart - because of backlash - compensation - */ - float restartTarget; /* target to restart to */ - ObPar driverPar[MAXPAR]; /* parameters */ - } ECBMOTDriv, *pECBMotDriv; +typedef struct __ECBMotorDriv { + /* general motor driver interface + fields. REQUIRED! + */ + float fUpper; /* upper limit */ + float fLower; /* lower limit */ + char *name; + int (*GetPosition) (void *self, float *fPos); + int (*RunTo) (void *self, float fNewVal); + int (*GetStatus) (void *self); + void (*GetError) (void *self, int *iCode, char *buffer, int iBufLen); + int (*TryAndFixIt) (void *self, int iError, float fNew); + int (*Halt) (void *self); + int (*GetDriverPar) (void *self, char *name, float *value); + int (*SetDriverPar) (void *self, SConnection * pCon, + char *name, float newValue); + void (*ListDriverPar) (void *self, char *motorName, SConnection * pCon); + void (*KillPrivate) (void *self); + + /* ECB specific fields */ + pECB ecb; /* ECB controller for everything */ + int ecbIndex; /* motor index in ECB */ + int errorCode; + int restart; /* flag if we have to restart + because of backlash + compensation + */ + float restartTarget; /* target to restart to */ + ObPar driverPar[MAXPAR]; /* parameters */ +} ECBMOTDriv, *pECBMotDriv; /*======================================================================= Reading the motor position means reading the encoder if such a thing is present or the counted motor steps (Pseudo Encoder) if not. If the ECB answers us, the value has to be converted to physical values. ----------------------------------------------------------------------*/ -static int readEncoder(pECBMotDriv self, long *digits){ +static int readEncoder(pECBMotDriv self, long *digits) +{ int status; Z80_reg in, out; Ecb_pack data; - in.c = (unsigned char)ObVal(self->driverPar,ENCODER) + MAX_ENCODER; - status = ecbExecute(self->ecb,FENCOR,in,&out); - if(!status){ + in.c = (unsigned char) ObVal(self->driverPar, ENCODER) + MAX_ENCODER; + status = ecbExecute(self->ecb, FENCOR, in, &out); + if (!status) { self->errorCode = COMMERROR; return status; } @@ -150,22 +147,24 @@ static int readEncoder(pECBMotDriv self, long *digits){ data.b.byt2 = out.b; data.b.byt1 = out.d; data.b.byt0 = out.e; - if(out.c != 1){ + if (out.c != 1) { *digits = -data.result; } else { *digits = data.result; } return OKOK; } + /*---------------------------------------------------------------------*/ -static int readPseudoEncoder(pECBMotDriv self, long *digits){ +static int readPseudoEncoder(pECBMotDriv self, long *digits) +{ int status; Z80_reg in, out; Ecb_pack data; - in.c = (unsigned char)self->ecbIndex; - status = ecbExecute(self->ecb,MOREAD,in,&out); - if(!status){ + in.c = (unsigned char) self->ecbIndex; + status = ecbExecute(self->ecb, MOREAD, in, &out); + if (!status) { self->errorCode = COMMERROR; return status; } @@ -175,43 +174,45 @@ static int readPseudoEncoder(pECBMotDriv self, long *digits){ data.b.byt2 = out.b; data.b.byt1 = out.d; data.b.byt0 = out.e; - if(out.c != 1){ + if (out.c != 1) { *digits = -data.result; } else { *digits = data.result; } return OKOK; } + /*----------------------------------------------------------------------*/ -int ECBMOTGetPos(void *pData, float *fPos){ - pECBMotDriv self = (pECBMotDriv)pData; - long digits = 0; +int ECBMOTGetPos(void *pData, float *fPos) +{ + pECBMotDriv self = (pECBMotDriv) pData; + long digits = 0; int status; double step2degree; assert(self); self->errorCode = 0; - if((int)ObVal(self->driverPar,ENCODER) > 0){ + if ((int) ObVal(self->driverPar, ENCODER) > 0) { status = readEncoder(self, &digits); - step2degree = ObVal(self->driverPar,DEG2STEP); - if(step2degree == 0.0){ + step2degree = ObVal(self->driverPar, DEG2STEP); + if (step2degree == 0.0) { step2degree = 1; } - *fPos = (digits/step2degree) - - ObVal(self->driverPar,OFFSET); + *fPos = (digits / step2degree) - ObVal(self->driverPar, OFFSET); return status; } else { status = readPseudoEncoder(self, &digits); } - step2degree = ObVal(self->driverPar,STEPS2DEG); - if(step2degree == 0.0){ + step2degree = ObVal(self->driverPar, STEPS2DEG); + if (step2degree == 0.0) { step2degree = 1.; } - *fPos = (float)( (double)digits/step2degree); + *fPos = (float) ((double) digits / step2degree); return status; } + /*======================================================================== In order to start a motor we need to do a couple of steps: - check if the motors parameters have been changed or it is a multiplexed @@ -220,24 +221,27 @@ In order to start a motor we need to do a couple of steps: selected etc. - Then the motor can be started. ------------------------------------------------------------------------*/ -static int mustDownload(pECBMotDriv self){ +static int mustDownload(pECBMotDriv self) +{ int multi; - multi = (int)rint(ObVal(self->driverPar,MULT)); - if(multi > 0 || multi < 0) { + multi = (int) rint(ObVal(self->driverPar, MULT)); + if (multi > 0 || multi < 0) { return 1; } else { return 0; } } + /*--------------------------------------------------------------------*/ -static int checkMotorResult(pECBMotDriv self, Z80_reg out){ +static int checkMotorResult(pECBMotDriv self, Z80_reg out) +{ /* - checks the return values from a motor function invocation - and sets error codes in case of problems. - */ - if(out.c == '\0'){ - switch(out.b){ + checks the return values from a motor function invocation + and sets error codes in case of problems. + */ + if (out.c == '\0') { + switch (out.b) { case 128: self->errorCode = ECBMANUELL; break; @@ -258,7 +262,7 @@ static int checkMotorResult(pECBMotDriv self, Z80_reg out){ self->errorCode = ECBINUSE; break; default: - fprintf(stderr,"Unidentified ECB motor error code %d\n", out.b); + fprintf(stderr, "Unidentified ECB motor error code %d\n", out.b); self->errorCode = UNIDENTIFIED; break; } @@ -267,78 +271,85 @@ static int checkMotorResult(pECBMotDriv self, Z80_reg out){ return 1; } } + /*---------------------------------------------------------------------*/ -static int loadAcceleration(pECBMotDriv self){ +static int loadAcceleration(pECBMotDriv self) +{ unsigned char parameter; Z80_reg in, out; int accel, status; - accel = (int)rint(ObVal(self->driverPar,ACCTIME)); - if(accel == 500){ + accel = (int) rint(ObVal(self->driverPar, ACCTIME)); + if (accel == 500) { parameter = 1; - }else if(accel == 1000){ + } else if (accel == 1000) { parameter = 2; - }else if(accel == 2000){ + } else if (accel == 2000) { parameter = 3; } else { parameter = 0; } /* - apply rotation direction mask - */ - if(ObVal(self->driverPar,ROTDIR) < 0){ + apply rotation direction mask + */ + if (ObVal(self->driverPar, ROTDIR) < 0) { parameter += 128; } - in.c = (unsigned char)self->ecbIndex; + in.c = (unsigned char) self->ecbIndex; in.b = 7; in.e = parameter; in.d = 0; out.d = out.e = out.b = out.c = 0; - status = ecbExecute(self->ecb,MOPARA,in,&out); - if(!status){ + status = ecbExecute(self->ecb, MOPARA, in, &out); + if (!status) { self->errorCode = COMMERROR; return 0; - } + } - if(!checkMotorResult(self, out)){ + if (!checkMotorResult(self, out)) { return 0; } return 1; } -/*--------------------------- speed tables ------------------------------*/ -#define SPEED_TAB3 64 /* Size of speed table */ -const unsigned int low_2048[SPEED_TAB3] = { - 1, 2, 3, 4, 5, 6, 8, 10, 12, 14, - 16, 20, 24, 28, 32, 36, 40, 44, 48, 56, - 64, 72, 80, 88, 96,104,112,120,128,136, - 144,152,160,168,176,184,192,200,208,216, - 224,236,248,260,272,284,296,308,320,332, - 344,356,368,380,392,404,416,428,440,452, - 464,476,488,500 }; -#define SPEED_TAB4 96 /* Size of speed table */ +/*--------------------------- speed tables ------------------------------*/ +#define SPEED_TAB3 64 /* Size of speed table */ +const unsigned int low_2048[SPEED_TAB3] = { + 1, 2, 3, 4, 5, 6, 8, 10, 12, 14, + 16, 20, 24, 28, 32, 36, 40, 44, 48, 56, + 64, 72, 80, 88, 96, 104, 112, 120, 128, 136, + 144, 152, 160, 168, 176, 184, 192, 200, 208, 216, + 224, 236, 248, 260, 272, 284, 296, 308, 320, 332, + 344, 356, 368, 380, 392, 404, 416, 428, 440, 452, + 464, 476, 488, 500 +}; + +#define SPEED_TAB4 96 /* Size of speed table */ const unsigned int high_2048[SPEED_TAB4] = { - 11, 15, 20, 27, 36, 47, 59, 74, - 93, 107, 124, 143, 165, 190, 213, 239, - 268, 298, 331, 368, 405, 446, 491, 536, - 585, 632, 683, 731, 783, 827, 873, 922, - 974, 1028, 1085, 1146, 1211, 1278, 1349, 1424, - 1503, 1587, 1675, 1720, 1820, 1913, 2014, 2123, - 2237, 2360, 2483, 2620, 2755, 2905, 3058, 3221, - 3384, 3575, 3756, 3945, 4150, 4370, 4600, 4800, - 5000, 5250, 5533, 5822, 6120, 6440, 6770, 7090, - 7450, 7800, 8130, 8500, 8900, 9320, 9730, 10200, - 10700, 11200, 11700, 12200, 12800, 13300, 13900, 14500, - 15100, 15800, 16700, 17300, 18000, 18600, 19300, 20000 }; + 11, 15, 20, 27, 36, 47, 59, 74, + 93, 107, 124, 143, 165, 190, 213, 239, + 268, 298, 331, 368, 405, 446, 491, 536, + 585, 632, 683, 731, 783, 827, 873, 922, + 974, 1028, 1085, 1146, 1211, 1278, 1349, 1424, + 1503, 1587, 1675, 1720, 1820, 1913, 2014, 2123, + 2237, 2360, 2483, 2620, 2755, 2905, 3058, 3221, + 3384, 3575, 3756, 3945, 4150, 4370, 4600, 4800, + 5000, 5250, 5533, 5822, 6120, 6440, 6770, 7090, + 7450, 7800, 8130, 8500, 8900, 9320, 9730, 10200, + 10700, 11200, 11700, 12200, 12800, 13300, 13900, 14500, + 15100, 15800, 16700, 17300, 18000, 18600, 19300, 20000 +}; + /*---------------------------------------------------------------------*/ -static unsigned char getSpeedIndex(float value, - int range, int *actualValue ){ +static unsigned char getSpeedIndex(float value, + int range, int *actualValue) +{ unsigned char index; const unsigned int *table; int length; - if(range == 0){ + if (range == 0) { table = low_2048; length = SPEED_TAB3; } else { @@ -346,124 +357,135 @@ static unsigned char getSpeedIndex(float value, length = SPEED_TAB4; } - for(index = 0; index < length-1; index++){ - if(table[index] >= value){ + for (index = 0; index < length - 1; index++) { + if (table[index] >= value) { break; } } *actualValue = table[index]; return index; } + /*--------------------------------------------------------------------*/ -static int loadSpeed(pECBMotDriv self, float value, int code){ +static int loadSpeed(pECBMotDriv self, float value, int code) +{ unsigned char parameter; Z80_reg in, out; int accel, status, actual; - parameter = getSpeedIndex(value, (int)rint(ObVal(self->driverPar,RANGE)), - &actual); + parameter = + getSpeedIndex(value, (int) rint(ObVal(self->driverPar, RANGE)), + &actual); - in.c = (unsigned char)self->ecbIndex; + in.c = (unsigned char) self->ecbIndex; in.b = code; in.e = parameter; - status = ecbExecute(self->ecb,MOPARA,in,&out); - if(!status){ + status = ecbExecute(self->ecb, MOPARA, in, &out); + if (!status) { self->errorCode = COMMERROR; return 0; - } - if(!checkMotorResult(self, out)){ + } + if (!checkMotorResult(self, out)) { return 0; } return 1; } + /*-------------------------------------------------------------------*/ -static int loadDelay(pECBMotDriv self){ +static int loadDelay(pECBMotDriv self) +{ int parameter; Z80_reg in, out; int accel, status; unsigned char control; - parameter = (int)rint(ObVal(self->driverPar,DELAY)); - control = (unsigned char)rint(ObVal(self->driverPar,CONTROL)); - if(control & 3){ + parameter = (int) rint(ObVal(self->driverPar, DELAY)); + control = (unsigned char) rint(ObVal(self->driverPar, CONTROL)); + if (control & 3) { parameter = 5; - } else{ - parameter/= 10; + } else { + parameter /= 10; } - in.c = (unsigned char)self->ecbIndex; + in.c = (unsigned char) self->ecbIndex; in.b = 8; in.e = parameter; - status = ecbExecute(self->ecb,MOPARA,in,&out); - if(!status){ + status = ecbExecute(self->ecb, MOPARA, in, &out); + if (!status) { self->errorCode = COMMERROR; return 0; - } + } - if(!checkMotorResult(self, out)){ + if (!checkMotorResult(self, out)) { return 0; } return 1; } + /*---------------------------------------------------------------------*/ -static int loadMulti(pECBMotDriv self){ +static int loadMulti(pECBMotDriv self) +{ int multi, mult_chan; Z80_reg in, out; int status; - multi = rint(ObVal(self->driverPar,MULT)); - if(multi <= 0){ - return 1; /* not multiplexed */ + multi = rint(ObVal(self->driverPar, MULT)); + if (multi <= 0) { + return 1; /* not multiplexed */ } - mult_chan = (unsigned char)rint(ObVal(self->driverPar,MULTCHAN)); - in.b = -1; /* SET_PORT */ - in.d = (unsigned char)(multi + (mult_chan << 4)); - in.e = (unsigned char)rint(ObVal(self->driverPar,PORT)); + mult_chan = (unsigned char) rint(ObVal(self->driverPar, MULTCHAN)); + in.b = -1; /* SET_PORT */ + in.d = (unsigned char) (multi + (mult_chan << 4)); + in.e = (unsigned char) rint(ObVal(self->driverPar, PORT)); in.c = self->ecbIndex; - status = ecbExecute(self->ecb,MOPARA,in,&out); - if(status != 1){ + status = ecbExecute(self->ecb, MOPARA, in, &out); + if (status != 1) { self->errorCode = COMMERROR; return 0; } return 1; } + /*------------------------------------------------------------------*/ -static int loadOffset(pECBMotDriv self, float offset){ +static int loadOffset(pECBMotDriv self, float offset) +{ Z80_reg in, out; int status; Ecb_pack data; /* - ignored - */ - if(ObVal(self->driverPar,ENCODER) <=.0){ + ignored + */ + if (ObVal(self->driverPar, ENCODER) <= .0) { return 1; } - - data.result = offset * ObVal(self->driverPar,STEPS2DEG); + + data.result = offset * ObVal(self->driverPar, STEPS2DEG); in.b = data.b.byt2; in.d = data.b.byt1; in.e = data.b.byt0; - in.c = (unsigned char)rint(ObVal(self->driverPar,ENCODER)); + in.c = (unsigned char) rint(ObVal(self->driverPar, ENCODER)); - status = ecbExecute(self->ecb,168,in,&out); - if(status == 1){ + status = ecbExecute(self->ecb, 168, in, &out); + if (status == 1) { self->driverPar[OFFSET].fVal = offset; } else { self->errorCode = COMMERROR; } return status; } + /*--------------------------------------------------------------------- This loads the gearing parameters for the CRT display. This should not have any influence on the running of the motor ------------------------------------------------------------------------*/ -static double To_ten(int v) { +static double To_ten(int v) +{ double vv; - - vv = 1.0; + + vv = 1.0; if (v == 1) vv = 10.0; if (v == 2) @@ -480,50 +502,54 @@ static double To_ten(int v) { vv = 10000000.0; return (vv); } + /*----------------------------------------------------------------------*/ -static int loadGearing(pECBMotDriv self){ +static int loadGearing(pECBMotDriv self) +{ int status; double dgear; int gdec, dec = 0, ratio; Ecb_pack data; Z80_reg in, out; - dec = (int)ObVal(self->driverPar,DEC); + dec = (int) ObVal(self->driverPar, DEC); in.c = self->ecbIndex; - dgear = (double) ObVal(self->driverPar,STEPS2DEG);; + dgear = (double) ObVal(self->driverPar, STEPS2DEG);; - /* Calculate decimals in display and gearing ratio for the ECB system*/ - gdec = (int) (1.0 + (log10(dgear - .01))); + /* Calculate decimals in display and gearing ratio for the ECB system */ + gdec = (int) (1.0 + (log10(dgear - .01))); if (dec < gdec) - dec = gdec; /* Display does not work with decimals < gdec */ - ratio = (long) (0.5 + dgear*To_ten(6 + 1 - dec)); - - data.result = ratio; + dec = gdec; /* Display does not work with decimals < gdec */ + ratio = (long) (0.5 + dgear * To_ten(6 + 1 - dec)); + + data.result = ratio; in.b = data.b.byt2; in.d = data.b.byt1; in.e = data.b.byt0; - status = ecbExecute(self->ecb,174,in,&out); - if(status != 1){ + status = ecbExecute(self->ecb, 174, in, &out); + if (status != 1) { self->errorCode = COMMERROR; } - - if(ObVal(self->driverPar,ENCODER) == 0){ + + if (ObVal(self->driverPar, ENCODER) == 0) { in.b = self->ecbIndex; } else { in.b = 1; - in.e = (unsigned char)ObVal(self->driverPar,ENCODER); + in.e = (unsigned char) ObVal(self->driverPar, ENCODER); } in.d = 0; in.e = dec; - status = ecbExecute(self->ecb,173,in,&out); - if(status != 1){ + status = ecbExecute(self->ecb, 173, in, &out); + if (status != 1) { self->errorCode = COMMERROR; } return 1; } + /*----------------------------------------------------------------------*/ -static int downloadECBParam(pECBMotDriv self){ +static int downloadECBParam(pECBMotDriv self) +{ int status, parameter; unsigned char func_code; Z80_reg in, out; @@ -531,129 +557,133 @@ static int downloadECBParam(pECBMotDriv self){ /* We assume that all parameters have useful values. It is the task of SetDriverPar to ensure just that! - */ - if((status = loadAcceleration(self) <= 0)){ + */ + if ((status = loadAcceleration(self) <= 0)) { return 0; } - if((status = loadSpeed(self,ObVal(self->driverPar,STARTSPEED),6)) <= 0){ + if ((status = + loadSpeed(self, ObVal(self->driverPar, STARTSPEED), 6)) <= 0) { return 0; } - if((status = loadSpeed(self,ObVal(self->driverPar,MAXSPEED),5)) <= 0){ + if ((status = loadSpeed(self, ObVal(self->driverPar, MAXSPEED), 5)) <= 0) { return 0; } - if((status = loadSpeed(self,ObVal(self->driverPar,SLOWAUTO),4)) <= 0){ + if ((status = loadSpeed(self, ObVal(self->driverPar, SLOWAUTO), 4)) <= 0) { return 0; } - if((status = loadSpeed(self,ObVal(self->driverPar,SLOWMAN),10)) <= 0){ + if ((status = loadSpeed(self, ObVal(self->driverPar, SLOWMAN), 10)) <= 0) { return 0; } - if((status = loadDelay(self)) <= 0){ + if ((status = loadDelay(self)) <= 0) { return 0; } - if((status = loadMulti(self)) <= 0){ + if ((status = loadMulti(self)) <= 0) { return 0; } - if((status = ecbLoadEncoder(self->ecb)) <= 0){ + if ((status = ecbLoadEncoder(self->ecb)) <= 0) { return 0; } - if((status = loadOffset(self,ObVal(self->driverPar,OFFSET))) <= 0){ + if ((status = loadOffset(self, ObVal(self->driverPar, OFFSET))) <= 0) { return 0; } - + /* - It would be good practice to read the parameters written back - in order to check them. This does not seem to be supported with the - ECB system though. - */ - if(ObVal(self->driverPar,MULT) < 0.){ + It would be good practice to read the parameters written back + in order to check them. This does not seem to be supported with the + ECB system though. + */ + if (ObVal(self->driverPar, MULT) < 0.) { self->driverPar[MULT].fVal = .0; } - if((status = loadGearing(self)) <= 0){ + if ((status = loadGearing(self)) <= 0) { return 0; } return 1; } + /*--------------------------------------------------------------------*/ int degree2Step(pECBMotDriv self, float degree) { double steps; - steps = degree*ObVal(self->driverPar,STEPS2DEG); - if (ObVal(self->driverPar,ENCODER) > .0) - steps = steps*ObVal(self->driverPar,DEG2STEP); - if(degree < 0){ - steps = - steps; - } + steps = degree * ObVal(self->driverPar, STEPS2DEG); + if (ObVal(self->driverPar, ENCODER) > .0) + steps = steps * ObVal(self->driverPar, DEG2STEP); + if (degree < 0) { + steps = -steps; + } return ((int) steps); } + /*---------------------------------------------------------------------- controlMotor enables or disables the motor, according to flag enable. This is also used to switch on air cushions and the like. ------------------------------------------------------------------------*/ -static int controlMotor(pECBMotDriv self, int enable){ +static int controlMotor(pECBMotDriv self, int enable) +{ int status, delay, control; Z80_reg in, out; /* - nothing to do if we are not in control - */ - control = (int)rint(ObVal(self->driverPar,CONTROL)); - if(!(control & 1)){ + nothing to do if we are not in control + */ + control = (int) rint(ObVal(self->driverPar, CONTROL)); + if (!(control & 1)) { return 1; } - delay = (int)rint(ObVal(self->driverPar,DELAY)); - if(enable == 1){ + delay = (int) rint(ObVal(self->driverPar, DELAY)); + if (enable == 1) { /* - enabling - */ - in.e = 12; /* 8 + 4 */ - in.b = 11; /* set control signal */ - in.c = (unsigned char)self->ecbIndex; - status = ecbExecute(self->ecb,MOPARA,in,&out); - if(status != 1){ + enabling + */ + in.e = 12; /* 8 + 4 */ + in.b = 11; /* set control signal */ + in.c = (unsigned char) self->ecbIndex; + status = ecbExecute(self->ecb, MOPARA, in, &out); + if (status != 1) { self->errorCode = COMMERROR; return 0; } /* - wait for air cushions to settle - */ + wait for air cushions to settle + */ usleep(delay); return 1; - }else { + } else { /* - disable air cushions - */ - in.e = 8; - in.b = 11; /* set control signal */ + disable air cushions + */ + in.e = 8; + in.b = 11; /* set control signal */ in.c = self->ecbIndex; - status = ecbExecute(self->ecb,MOPARA,in,&out); - if(status != 1){ + status = ecbExecute(self->ecb, MOPARA, in, &out); + if (status != 1) { self->errorCode = COMMERROR; return 0; } usleep(delay); /* - clear enable - */ - in.e = 0; - in.b = 11; /* set control signal */ + clear enable + */ + in.e = 0; + in.b = 11; /* set control signal */ in.c = self->ecbIndex; - status = ecbExecute(self->ecb,MOPARA,in,&out); - if(status != 1){ + status = ecbExecute(self->ecb, MOPARA, in, &out); + if (status != 1) { self->errorCode = COMMERROR; return 0; } @@ -663,10 +693,12 @@ static int controlMotor(pECBMotDriv self, int enable){ return 1; } } + /*-----------------------------------------------------------------------*/ -static int ECBRunTo(void *pData, float newPosition){ - pECBMotDriv self = (pECBMotDriv)pData; - long digits = 0; +static int ECBRunTo(void *pData, float newPosition) +{ + pECBMotDriv self = (pECBMotDriv) pData; + long digits = 0; int status; float oldValue, diff, steps2degree, backlash; Ecb_pack data; @@ -674,240 +706,252 @@ static int ECBRunTo(void *pData, float newPosition){ assert(self); - if(mustDownload(self)){ + if (mustDownload(self)) { status = downloadECBParam(self); - if(!status){ + if (!status) { return 0; } } /* - read old position - */ - status = ECBMOTGetPos(self,&oldValue); - if(status != 1){ + read old position + */ + status = ECBMOTGetPos(self, &oldValue); + if (status != 1) { return status; } /* - do not start if there - */ + do not start if there + */ diff = newPosition - oldValue; - steps2degree= ObVal(self->driverPar,STEPS2DEG); - if(ABS(diff) <= ObVal(self->driverPar,TOLERANCE)){ + steps2degree = ObVal(self->driverPar, STEPS2DEG); + if (ABS(diff) <= ObVal(self->driverPar, TOLERANCE)) { return OKOK; } /* - if(ABS(diff) <= .5/steps2degree + ObVal(self->driverPar,TOLERANCE)){ - return OKOK; - } - */ + if(ABS(diff) <= .5/steps2degree + ObVal(self->driverPar,TOLERANCE)){ + return OKOK; + } + */ /* - save restartTarget for backlash handling - */ - self->restartTarget = newPosition; + save restartTarget for backlash handling + */ + self->restartTarget = newPosition; /* - enable and push up airy cushions - */ - status = controlMotor(self,1); - if(status != 1){ + enable and push up airy cushions + */ + status = controlMotor(self, 1); + if (status != 1) { return status; } /* - write control data - */ + write control data + */ in.d = 0; - if(diff > .0){ - in.d |= 32; /* positive direction */ + if (diff > .0) { + in.d |= 32; /* positive direction */ } - in.d |= 16; /* interrupts */ - if(rint(ObVal(self->driverPar,RANGE)) == 1.){ - in.d |= 64; /* fast speed */ + in.d |= 16; /* interrupts */ + if (rint(ObVal(self->driverPar, RANGE)) == 1.) { + in.d |= 64; /* fast speed */ } - in.c = (unsigned char)self->ecbIndex; - status = ecbExecute(self->ecb,MOCLOA,in,&out); - if(status != 1){ + in.c = (unsigned char) self->ecbIndex; + status = ecbExecute(self->ecb, MOCLOA, in, &out); + if (status != 1) { self->errorCode = COMMERROR; return 0; } /* - calculate steps - */ + calculate steps + */ self->restart = 0; - backlash = ObVal(self->driverPar,BACKLASH); - if(diff < 0){ + backlash = ObVal(self->driverPar, BACKLASH); + if (diff < 0) { diff = -diff; - if(backlash > 0.){ + if (backlash > 0.) { diff += backlash; self->restart = 1; } } else { - if(backlash < 0.){ + if (backlash < 0.) { diff -= backlash; self->restart = 1; } } - data.result = degree2Step(self,diff); + data.result = degree2Step(self, diff); /* finally start the motor - */ + */ in.b = data.b.byt2; in.d = data.b.byt1; in.e = data.b.byt0; - in.c = (unsigned char)self->ecbIndex; - status = ecbExecute(self->ecb,MOSTEP,in,&out); - if(status != 1){ + in.c = (unsigned char) self->ecbIndex; + status = ecbExecute(self->ecb, MOSTEP, in, &out); + if (status != 1) { self->errorCode = COMMERROR; return 0; } - if(!checkMotorResult(self, out)){ + if (!checkMotorResult(self, out)) { return 0; } return OKOK; } + /*=======================================================================*/ -static int checkStatusResponse(pECBMotDriv self, Z80_reg out){ - - if(out.c == '\0'){ - if(out.b & 4) { +static int checkStatusResponse(pECBMotDriv self, Z80_reg out) +{ + + if (out.c == '\0') { + if (out.b & 4) { self->errorCode = ECBINUSE; - } else { + } else { self->errorCode = ECBREADERROR; } return HWFault; - } + } - if(out.b & 128){ + if (out.b & 128) { self->errorCode = ECBMANUELL; return HWFault; - } else if(out.b & 32){ + } else if (out.b & 32) { return HWBusy; - } else if(out.b & 16){ + } else if (out.b & 16) { self->errorCode = ECBLIMIT; return HWFault; } return HWIdle; } + /*----------------------------------------------------------------------*/ -static int ECBGetStatus(void *pData){ - pECBMotDriv self = (pECBMotDriv)pData; +static int ECBGetStatus(void *pData) +{ + pECBMotDriv self = (pECBMotDriv) pData; Z80_reg in, out; int status, result; assert(self); - in.c = (unsigned char)self->ecbIndex; + in.c = (unsigned char) self->ecbIndex; in.b = 12; - status = ecbExecute(self->ecb,MOSTAT,in,&out); - if(status != 1){ + status = ecbExecute(self->ecb, MOSTAT, in, &out); + if (status != 1) { self->errorCode = COMMERROR; return HWFault; } - result = checkStatusResponse(self,out); - if(result == HWFault || result == HWIdle){ + result = checkStatusResponse(self, out); + if (result == HWFault || result == HWIdle) { /* - run down airy cushions ........ - */ - controlMotor(self,0); + run down airy cushions ........ + */ + controlMotor(self, 0); } /* - take care of backlash..... - */ - if(result == HWIdle && self->restart == 1){ + take care of backlash..... + */ + if (result == HWIdle && self->restart == 1) { self->restart = 0; - ECBRunTo(self,self->restartTarget); + ECBRunTo(self, self->restartTarget); return HWBusy; } return result; -} +} + /*======================================================================*/ -static void ECBGetError(void *pData, int *iCode, char *buffer, int bufferlen){ - pECBMotDriv self = (pECBMotDriv)pData; +static void ECBGetError(void *pData, int *iCode, char *buffer, + int bufferlen) +{ + pECBMotDriv self = (pECBMotDriv) pData; char pBueffel[132]; assert(self); - + *iCode = self->errorCode; - switch(self->errorCode){ + switch (self->errorCode) { case COMMERROR: - strncpy(buffer,"communication problem with ECB",bufferlen); + strncpy(buffer, "communication problem with ECB", bufferlen); break; case ECBMANUELL: - strncpy(buffer,"ECB is in manual mode, trying to switch...",bufferlen); + strncpy(buffer, "ECB is in manual mode, trying to switch...", + bufferlen); break; case ECBINUSE: - strncpy(buffer,"Power supply is in use",bufferlen); + strncpy(buffer, "Power supply is in use", bufferlen); break; case ECBINHIBIT: - strncpy(buffer,"motor is inhibited",bufferlen); + strncpy(buffer, "motor is inhibited", bufferlen); break; case ECBRUNNING: - strncpy(buffer,"motor is running",bufferlen); + strncpy(buffer, "motor is running", bufferlen); break; case ECBSTART: - strncpy(buffer,"failed to start motor",bufferlen); + strncpy(buffer, "failed to start motor", bufferlen); break; case ECBLIMIT: - strncpy(buffer,"hit limit switch or amplifier error",bufferlen); + strncpy(buffer, "hit limit switch or amplifier error", bufferlen); break; default: - strncpy(buffer,"unidentified error code",bufferlen); + strncpy(buffer, "unidentified error code", bufferlen); break; } } + /*========================================================================*/ -static int ECBHalt(void *pData){ - pECBMotDriv self = (pECBMotDriv)pData; +static int ECBHalt(void *pData) +{ + pECBMotDriv self = (pECBMotDriv) pData; Z80_reg in, out; unsigned char par = 2; assert(self); - if(rint(ObVal(self->driverPar,RANGE)) == 1){ + if (rint(ObVal(self->driverPar, RANGE)) == 1) { par |= 64; } in.b = 9; in.e = par; - in.c = (unsigned char)self->ecbIndex; - ecbExecute(self->ecb,MOPARA,in,&out); + in.c = (unsigned char) self->ecbIndex; + ecbExecute(self->ecb, MOPARA, in, &out); self->restart = 0; return 1; } + /*=======================================================================*/ -static int ECBTryAndFixIt(void *pData, int iCode, float fNew){ - pECBMotDriv self = (pECBMotDriv)pData; +static int ECBTryAndFixIt(void *pData, int iCode, float fNew) +{ + pECBMotDriv self = (pECBMotDriv) pData; int result; Z80_reg in, out; int i; assert(self); - - switch(iCode){ + + switch (iCode) { case ECBMANUELL: - in.d = 1 ; - ecbExecute(self->ecb,162,in,&out); + in.d = 1; + ecbExecute(self->ecb, 162, in, &out); result = MOTREDO; break; case ECBRUNNING: ECBHalt(pData); self->restart = 0; - for(i = 0; i < 7; i++){ - if(ECBGetStatus(pData) == HWIdle){ - break; + for (i = 0; i < 7; i++) { + if (ECBGetStatus(pData) == HWIdle) { + break; } - SicsWait(1); + SicsWait(1); } result = MOTREDO; break; @@ -921,54 +965,60 @@ static int ECBTryAndFixIt(void *pData, int iCode, float fNew){ } return result; } + /*=======================================================================*/ -static int ECBGetDriverPar(void *pData,char *name, float *value){ - pECBMotDriv self = (pECBMotDriv)pData; +static int ECBGetDriverPar(void *pData, char *name, float *value) +{ + pECBMotDriv self = (pECBMotDriv) pData; ObPar *par = NULL; assert(self); - if(strcmp(name,"ecbindex") == 0){ + if (strcmp(name, "ecbindex") == 0) { *value = self->ecbIndex; return 1; } /* * catch the command parameters */ - if(strcmp(name,"putpos") == 0 || strcmp(name,"download") == 0){ + if (strcmp(name, "putpos") == 0 || strcmp(name, "download") == 0) { *value = .0; return 1; } - par = ObParFind(self->driverPar,name); - if(par != NULL){ + par = ObParFind(self->driverPar, name); + if (par != NULL) { *value = par->fVal; return 1; } else { return 0; } } -/*=====================================================================*/ -static float fixAccTime(float newValue){ - float corrected, min, diff; - int val, possibleValues[4] = { 500, 1000, 2000, 5000}, i; - val = (int)rint(newValue); +/*=====================================================================*/ +static float fixAccTime(float newValue) +{ + float corrected, min, diff; + int val, possibleValues[4] = { 500, 1000, 2000, 5000 }, i; + + val = (int) rint(newValue); min = 9999999.99; - for(i = 0; i < 4; i++){ + for (i = 0; i < 4; i++) { diff = val - possibleValues[i]; - if(ABS(diff) < min){ + if (ABS(diff) < min) { min = ABS(diff); corrected = possibleValues[i]; } } return corrected; } + /*--------------------------------------------------------------------*/ -static void setDownloadFlag(pECBMotDriv self, int parNumber){ +static void setDownloadFlag(pECBMotDriv self, int parNumber) +{ int mustDownload; - switch(parNumber){ + switch (parNumber) { case CONTROL: case MULT: case MULTCHAN: @@ -985,46 +1035,50 @@ static void setDownloadFlag(pECBMotDriv self, int parNumber){ mustDownload = 0; break; } - - if(mustDownload && (self->driverPar[MULT].fVal == 0)){ + + if (mustDownload && (self->driverPar[MULT].fVal == 0)) { self->driverPar[MULT].fVal = -1.0; } } + /*--------------------------------------------------------------------*/ -static int putMotorPosition(pECBMotDriv self, float newValue){ - Z80_reg in,out; +static int putMotorPosition(pECBMotDriv self, float newValue) +{ + Z80_reg in, out; Ecb_pack data; float oldPos; int status; - if(ABS(ObVal(self->driverPar,ENCODER)) > .1){ - status = ECBMOTGetPos(self,&oldPos); - if(status != 1){ + if (ABS(ObVal(self->driverPar, ENCODER)) > .1) { + status = ECBMOTGetPos(self, &oldPos); + if (status != 1) { return status; } - return loadOffset(self,oldPos - newValue); + return loadOffset(self, oldPos - newValue); } else { - data.result = newValue*ObVal(self->driverPar,STEPS2DEG); + data.result = newValue * ObVal(self->driverPar, STEPS2DEG); in.b = data.b.byt2; in.d = data.b.byt1; in.e = data.b.byt0; - in.c = (unsigned char)self->ecbIndex; - status = ecbExecute(self->ecb,142,in,&out); - if(status != 1){ + in.c = (unsigned char) self->ecbIndex; + status = ecbExecute(self->ecb, 142, in, &out); + if (status != 1) { self->errorCode = COMMERROR; return 0; } - if(!checkMotorResult(self, out)){ + if (!checkMotorResult(self, out)) { return 0; } } return 1; } + /*---------------------------------------------------------------------*/ -static int ECBSetDriverPar(void *pData, SConnection *pCon, char *name, - float newValue){ - pECBMotDriv self = (pECBMotDriv)pData; +static int ECBSetDriverPar(void *pData, SConnection * pCon, char *name, + float newValue) +{ + pECBMotDriv self = (pECBMotDriv) pData; int parNumber, speedNumber, actualSpeed, status; char pBueffel[256]; float correctedValue; @@ -1033,102 +1087,102 @@ static int ECBSetDriverPar(void *pData, SConnection *pCon, char *name, /* - only managers shall edit these parameters.... - */ - if(!SCMatchRights(pCon,usMugger)){ + only managers shall edit these parameters.... + */ + if (!SCMatchRights(pCon, usMugger)) { return 0; } /* - this is rather a command and forces a parameter download - to the ECB - */ - if(strcmp(name,"download") == 0){ + this is rather a command and forces a parameter download + to the ECB + */ + if (strcmp(name, "download") == 0) { status = downloadECBParam(self); - if(status != 1){ - ECBGetError(self,&actualSpeed, pBueffel,254); - SCWrite(pCon,pBueffel,eError); + if (status != 1) { + ECBGetError(self, &actualSpeed, pBueffel, 254); + SCWrite(pCon, pBueffel, eError); return status; } } /* - this is another command and assigns a position to the current - motor place - */ - if(strcmp(name,"putpos") == 0){ - status = putMotorPosition(self,newValue); - if(status != 1){ - ECBGetError(self,&actualSpeed, pBueffel,254); - SCWrite(pCon,pBueffel,eError); + this is another command and assigns a position to the current + motor place + */ + if (strcmp(name, "putpos") == 0) { + status = putMotorPosition(self, newValue); + if (status != 1) { + ECBGetError(self, &actualSpeed, pBueffel, 254); + SCWrite(pCon, pBueffel, eError); return status; } return 1; } /* - get the parameter number - */ - parNumber = ObParIndex(self->driverPar,name); - if(parNumber < 0){ + get the parameter number + */ + parNumber = ObParIndex(self->driverPar, name); + if (parNumber < 0) { return 0; } - + /* - make these parameters right, at least as far as we can ....... - */ - switch(parNumber){ + make these parameters right, at least as far as we can ....... + */ + switch (parNumber) { case ACCTIME: correctedValue = fixAccTime(newValue); break; case STARTSPEED: - getSpeedIndex(rint(newValue),1,&actualSpeed); + getSpeedIndex(rint(newValue), 1, &actualSpeed); correctedValue = actualSpeed; - if(correctedValue < 10){ + if (correctedValue < 10) { correctedValue = 10; } - if(correctedValue > 4400){ + if (correctedValue > 4400) { correctedValue = 4400; } break; case MAXSPEED: - getSpeedIndex(rint(newValue),1,&actualSpeed); + getSpeedIndex(rint(newValue), 1, &actualSpeed); correctedValue = actualSpeed; break; case SLOWAUTO: case SLOWMAN: - getSpeedIndex(rint(newValue),0,&actualSpeed); + getSpeedIndex(rint(newValue), 0, &actualSpeed); correctedValue = actualSpeed; - if(correctedValue > 500){ + if (correctedValue > 500) { correctedValue = 500; } break; case DELAY: correctedValue = newValue; - if(correctedValue > 2500){ + if (correctedValue > 2500) { correctedValue = 2500; } - break; + break; case RANGE: correctedValue = newValue; - if(correctedValue != 0.0 && correctedValue != 1.0){ - correctedValue = .0; /* slow by default! */ + if (correctedValue != 0.0 && correctedValue != 1.0) { + correctedValue = .0; /* slow by default! */ } break; case ENCODER: - if(newValue < 0. || newValue > 3.){ - SCWrite(pCon,"ERROR: encoder numbers can only be 0 - 3", eError); + if (newValue < 0. || newValue > 3.) { + SCWrite(pCon, "ERROR: encoder numbers can only be 0 - 3", eError); return 0; - } else if(newValue == 0){ + } else if (newValue == 0) { correctedValue = newValue; } else { - ecbAssignEncoder(self->ecb,(int)newValue, self->ecbIndex); + ecbAssignEncoder(self->ecb, (int) newValue, self->ecbIndex); correctedValue = newValue; } break; case STEPS2DEG: case DEG2STEP: - if(ABS(newValue) < .1){ + if (ABS(newValue) < .1) { correctedValue = 1.; } else { correctedValue = newValue; @@ -1141,94 +1195,97 @@ static int ECBSetDriverPar(void *pData, SConnection *pCon, char *name, correctedValue = newValue; break; } - - if(ABS(correctedValue - newValue) > 0.){ - sprintf(pBueffel,"WARNING: Illegal value %6.2f verbosely coerced to %6.2f", - newValue,correctedValue); - SCWrite(pCon,pBueffel,eWarning); + + if (ABS(correctedValue - newValue) > 0.) { + sprintf(pBueffel, + "WARNING: Illegal value %6.2f verbosely coerced to %6.2f", + newValue, correctedValue); + SCWrite(pCon, pBueffel, eWarning); } - ObParSet(self->driverPar,self->name,name,correctedValue,pCon); + ObParSet(self->driverPar, self->name, name, correctedValue, pCon); - setDownloadFlag(self,parNumber); + setDownloadFlag(self, parNumber); return 1; } + /*=========================================================================*/ -static void ECBListPar(void *pData, char *motorName, SConnection *pCon){ - pECBMotDriv self = (pECBMotDriv)pData; +static void ECBListPar(void *pData, char *motorName, SConnection * pCon) +{ + pECBMotDriv self = (pECBMotDriv) pData; char pBueffel[256]; int i; assert(self); - for(i = 0; i < MAXPAR-1; i++){ - snprintf(pBueffel,255,"%s.%s = %f", - motorName,self->driverPar[i].name, - self->driverPar[i].fVal); - SCWrite(pCon,pBueffel,eValue); + for (i = 0; i < MAXPAR - 1; i++) { + snprintf(pBueffel, 255, "%s.%s = %f", + motorName, self->driverPar[i].name, self->driverPar[i].fVal); + SCWrite(pCon, pBueffel, eValue); } } + /*========================================================================*/ -static int interpretArguments(pECBMotDriv self, SConnection *pCon, - int argc, char *argv[]){ +static int interpretArguments(pECBMotDriv self, SConnection * pCon, + int argc, char *argv[]) +{ char pBueffel[256]; TokenList *pList, *pCurrent; - pList = SplitArguments(argc,argv); - if(!pList || argc < 4){ - SCWrite(pCon,"ERROR: no arguments to CreateECBMotor",eError); + pList = SplitArguments(argc, argv); + if (!pList || argc < 4) { + SCWrite(pCon, "ERROR: no arguments to CreateECBMotor", eError); return 0; } pCurrent = pList; /* - first should be the name of the ECB to use - */ - if(pCurrent->Type != eText){ - sprintf(pBueffel,"ERROR: expected EDB name, got: %s", - pCurrent->text); + first should be the name of the ECB to use + */ + if (pCurrent->Type != eText) { + sprintf(pBueffel, "ERROR: expected EDB name, got: %s", pCurrent->text); DeleteTokenList(pList); return 0; } - self->ecb = (pECB)FindCommandData(pServ->pSics,pCurrent->text,"ECB"); - if(!self->ecb){ - sprintf(pBueffel,"ERROR: %s is no ECB controller",pCurrent->text); - SCWrite(pCon,pBueffel,eError); + self->ecb = (pECB) FindCommandData(pServ->pSics, pCurrent->text, "ECB"); + if (!self->ecb) { + sprintf(pBueffel, "ERROR: %s is no ECB controller", pCurrent->text); + SCWrite(pCon, pBueffel, eError); DeleteTokenList(pList); return 0; } /* - next the motor number - */ + next the motor number + */ pCurrent = pCurrent->pNext; - if(pCurrent->Type != eInt){ - sprintf(pBueffel,"ERROR: expected int motor number, got %s", - pCurrent->text); - SCWrite(pCon,pBueffel,eError); + if (pCurrent->Type != eInt) { + sprintf(pBueffel, "ERROR: expected int motor number, got %s", + pCurrent->text); + SCWrite(pCon, pBueffel, eError); DeleteTokenList(pList); return 0; } self->ecbIndex = pCurrent->iVal; /* - next the limits - */ + next the limits + */ pCurrent = pCurrent->pNext; - if(pCurrent->Type != eFloat){ - sprintf(pBueffel,"ERROR: expected float type limit, got %s", - pCurrent->text); - SCWrite(pCon,pBueffel,eError); + if (pCurrent->Type != eFloat) { + sprintf(pBueffel, "ERROR: expected float type limit, got %s", + pCurrent->text); + SCWrite(pCon, pBueffel, eError); DeleteTokenList(pList); return 0; } self->fLower = pCurrent->fVal; pCurrent = pCurrent->pNext; - if(pCurrent->Type != eFloat){ - sprintf(pBueffel,"ERROR: expected float type limit, got %s", - pCurrent->text); - SCWrite(pCon,pBueffel,eError); + if (pCurrent->Type != eFloat) { + sprintf(pBueffel, "ERROR: expected float type limit, got %s", + pCurrent->text); + SCWrite(pCon, pBueffel, eError); DeleteTokenList(pList); return 0; } @@ -1237,51 +1294,57 @@ static int interpretArguments(pECBMotDriv self, SConnection *pCon, return 1; } -/*-----------------------------------------------------------------------*/ -static void initializeParameters(pECBMotDriv self){ - ObParInit(self->driverPar,ENCODER,"encoder",0,usMugger); - ObParInit(self->driverPar,CONTROL,"control",0,usMugger); - ObParInit(self->driverPar,RANGE,"range",1,usMugger); - ObParInit(self->driverPar,MULT,"multi",0,usMugger); - ObParInit(self->driverPar,MULTCHAN,"multchan",0,usMugger); - ObParInit(self->driverPar,ACCTIME,"acceleration",500,usMugger); - ObParInit(self->driverPar,ROTDIR,"rotation_dir",1,usMugger); - ObParInit(self->driverPar,STARTSPEED,"startspeed",100,usMugger); - ObParInit(self->driverPar,MAXSPEED,"maxspeed",2000,usMugger); - ObParInit(self->driverPar,SLOWAUTO,"auto",100,usMugger); - ObParInit(self->driverPar,SLOWMAN,"manuell",100,usMugger); - ObParInit(self->driverPar,DELAY,"delay",50,usMugger); - ObParInit(self->driverPar,OFFSET,"offset",0,usMugger); - ObParInit(self->driverPar,TOLERANCE,"dtolerance",0.,usMugger); - ObParInit(self->driverPar,STEPS2DEG,"step2deg",1,usMugger); - ObParInit(self->driverPar,DEG2STEP,"step2dig",0,usMugger); - ObParInit(self->driverPar,BACKLASH,"backlash",0,usMugger); - ObParInit(self->driverPar,PORT,"port",0,usMugger); - ObParInit(self->driverPar,DEC,"dec",1,usMugger); - ObParInit(self->driverPar,MAXPAR-1,"tueet",-100,-100); /* sentinel! */ -} -/*=======================================================================*/ -void KillECBMotor(void *pDriver){ - int i; - pECBMotDriv self = (pECBMotDriv)pDriver; - for(i = 0; i < MAXPAR; i++){ - if(self->driverPar[i].name != NULL){ +/*-----------------------------------------------------------------------*/ +static void initializeParameters(pECBMotDriv self) +{ + ObParInit(self->driverPar, ENCODER, "encoder", 0, usMugger); + ObParInit(self->driverPar, CONTROL, "control", 0, usMugger); + ObParInit(self->driverPar, RANGE, "range", 1, usMugger); + ObParInit(self->driverPar, MULT, "multi", 0, usMugger); + ObParInit(self->driverPar, MULTCHAN, "multchan", 0, usMugger); + ObParInit(self->driverPar, ACCTIME, "acceleration", 500, usMugger); + ObParInit(self->driverPar, ROTDIR, "rotation_dir", 1, usMugger); + ObParInit(self->driverPar, STARTSPEED, "startspeed", 100, usMugger); + ObParInit(self->driverPar, MAXSPEED, "maxspeed", 2000, usMugger); + ObParInit(self->driverPar, SLOWAUTO, "auto", 100, usMugger); + ObParInit(self->driverPar, SLOWMAN, "manuell", 100, usMugger); + ObParInit(self->driverPar, DELAY, "delay", 50, usMugger); + ObParInit(self->driverPar, OFFSET, "offset", 0, usMugger); + ObParInit(self->driverPar, TOLERANCE, "dtolerance", 0., usMugger); + ObParInit(self->driverPar, STEPS2DEG, "step2deg", 1, usMugger); + ObParInit(self->driverPar, DEG2STEP, "step2dig", 0, usMugger); + ObParInit(self->driverPar, BACKLASH, "backlash", 0, usMugger); + ObParInit(self->driverPar, PORT, "port", 0, usMugger); + ObParInit(self->driverPar, DEC, "dec", 1, usMugger); + ObParInit(self->driverPar, MAXPAR - 1, "tueet", -100, -100); /* sentinel! */ +} + +/*=======================================================================*/ +void KillECBMotor(void *pDriver) +{ + int i; + pECBMotDriv self = (pECBMotDriv) pDriver; + + for (i = 0; i < MAXPAR; i++) { + if (self->driverPar[i].name != NULL) { free(self->driverPar[i].name); } } } + /*------------------------------------------------------------------------*/ -MotorDriver *CreateECBMotor(SConnection *pCon, int argc, char *argv[]){ +MotorDriver *CreateECBMotor(SConnection * pCon, int argc, char *argv[]) +{ pECBMotDriv self = NULL; - self = (pECBMotDriv)malloc(sizeof(ECBMOTDriv)); - if(self == NULL){ + self = (pECBMotDriv) malloc(sizeof(ECBMOTDriv)); + if (self == NULL) { return NULL; } - memset(self,0,sizeof(ECBMOTDriv)); + memset(self, 0, sizeof(ECBMOTDriv)); - if(!interpretArguments(self,pCon,argc,argv)){ + if (!interpretArguments(self, pCon, argc, argv)) { free(self); return 0; } @@ -1289,8 +1352,8 @@ MotorDriver *CreateECBMotor(SConnection *pCon, int argc, char *argv[]){ initializeParameters(self); /* - set function pointers - */ + set function pointers + */ self->GetPosition = ECBMOTGetPos; self->RunTo = ECBRunTo; self->GetStatus = ECBGetStatus; @@ -1301,7 +1364,7 @@ MotorDriver *CreateECBMotor(SConnection *pCon, int argc, char *argv[]){ self->SetDriverPar = ECBSetDriverPar; self->ListDriverPar = ECBListPar; self->KillPrivate = KillECBMotor; - + self->errorCode = 0; - return (MotorDriver *)self; + return (MotorDriver *) self; } diff --git a/ecbdriv.h b/ecbdriv.h index eda63b5..c83d52a 100644 --- a/ecbdriv.h +++ b/ecbdriv.h @@ -37,9 +37,7 @@ #ifndef ECBDRIV #define ECBDRIV -MotorDriver *CreateECBMotor(SConnection *pCon, int argc, char *argv[]); -void KillECBMotor(void *driver); +MotorDriver *CreateECBMotor(SConnection * pCon, int argc, char *argv[]); +void KillECBMotor(void *driver); #endif - - diff --git a/el734dc.c b/el734dc.c index 291437f..9d5aac0 100644 --- a/el734dc.c +++ b/el734dc.c @@ -51,11 +51,11 @@ #include #include - static int EL734EncodeMSR(char *text, int iLen, - int iMSR, int iOMSR, int iFP, int iFR); +static int EL734EncodeMSR(char *text, int iLen, + int iMSR, int iOMSR, int iFP, int iFR); + +static int EL734AnalyzeMSR(int iMSR, int iOMSR); - static int EL734AnalyzeMSR(int iMSR, int iOMSR); - /* addional error codes for Status-things */ #define MSRBUSY -40 #define MSRONLIMIT -41 @@ -71,253 +71,230 @@ The motor driver structure. Please note that the first set of fields has be identical with the fields of AbstractModriv in ../modriv.h ------------------------------------------------------------------------*/ - typedef struct __MoDriv { - /* general motor driver interface - fields. REQUIRED! - */ - float fUpper; /* upper limit */ - float fLower; /* lower limit */ - char *name; - int (*GetPosition)(void *self,float *fPos); - int (*RunTo)(void *self, float fNewVal); - int (*GetStatus)(void *self); - void (*GetError)(void *self, int *iCode, char *buffer, int iBufLen); - int (*TryAndFixIt)(void *self,int iError, float fNew); - int (*Halt)(void *self); - int (*GetDriverPar)(void *self, char *name, - float *value); - int (*SetDriverPar)(void *self,SConnection *pCon, - char *name, float newValue); - void (*ListDriverPar)(void *self, char *motorName, - SConnection *pCon); - void (*KillPrivate)(void *self); - - - /* EL-734 specific fields */ - int iPort; - char *hostname; - int iChannel; - int iMotor; - void *EL734struct; - int iMSR; - } EL734Driv; - +typedef struct __MoDriv { + /* general motor driver interface + fields. REQUIRED! + */ + float fUpper; /* upper limit */ + float fLower; /* lower limit */ + char *name; + int (*GetPosition) (void *self, float *fPos); + int (*RunTo) (void *self, float fNewVal); + int (*GetStatus) (void *self); + void (*GetError) (void *self, int *iCode, char *buffer, int iBufLen); + int (*TryAndFixIt) (void *self, int iError, float fNew); + int (*Halt) (void *self); + int (*GetDriverPar) (void *self, char *name, float *value); + int (*SetDriverPar) (void *self, SConnection * pCon, + char *name, float newValue); + void (*ListDriverPar) (void *self, char *motorName, SConnection * pCon); + void (*KillPrivate) (void *self); + + + /* EL-734 specific fields */ + int iPort; + char *hostname; + int iChannel; + int iMotor; + void *EL734struct; + int iMSR; +} EL734Driv; + /* --------------------------------------------------------------------------*/ - static int GetPos(void *self, float *fData) - { - EL734Driv *pDriv; - float fPos; - int iRet, iMSR, iOMSR, iFRC,iFPC, iSS; - - assert(self); - - pDriv = (EL734Driv *)self; - iRet = EL734_GetStatus(&(pDriv->EL734struct), - &iMSR, - &iOMSR, - &iFPC, - &iFRC, - &iSS, - &fPos); - if(iMSR != 0) - { - pDriv->iMSR = iMSR; - } - *fData = fPos; - if(iRet != 1) - { - return HWFault; - } - else - return OKOK; - +static int GetPos(void *self, float *fData) +{ + EL734Driv *pDriv; + float fPos; + int iRet, iMSR, iOMSR, iFRC, iFPC, iSS; + + assert(self); + + pDriv = (EL734Driv *) self; + iRet = EL734_GetStatus(&(pDriv->EL734struct), + &iMSR, &iOMSR, &iFPC, &iFRC, &iSS, &fPos); + if (iMSR != 0) { + pDriv->iMSR = iMSR; } + *fData = fPos; + if (iRet != 1) { + return HWFault; + } else + return OKOK; + +} + /*--------------------------------------------------------------------------*/ - static int Run(void *self, float fNew) - { - EL734Driv *pDriv; - int iRet; - - assert(self); - - pDriv = (EL734Driv *)self; - iRet = EL734_MoveNoWait (&(pDriv->EL734struct), fNew); - if(iRet == 1) - { - return OKOK; - } - else - { - return HWFault; - } - } +static int Run(void *self, float fNew) +{ + EL734Driv *pDriv; + int iRet; + + assert(self); + + pDriv = (EL734Driv *) self; + iRet = EL734_MoveNoWait(&(pDriv->EL734struct), fNew); + if (iRet == 1) { + return OKOK; + } else { + return HWFault; + } +} /*--------------------------------------------------------------------------- EL734Error2Text converts between an EL734 error code to text -----------------------------------------------------------------------------*/ - static void EL734Error2Text(char *pBuffer, int iErr) - { - strcpy(pBuffer,"ERROR: HW:"); - switch(iErr) - { - case EL734__BAD_ADR: - strcat(pBuffer,"EL734__BAD_ADR"); - break; - case EL734__BAD_BIND: - strcat(pBuffer,"EL734__BAD_BIND"); - break; - case EL734__BAD_CMD: - strcat(pBuffer,"EL734__BAD_CMD"); - break; - case EL734__BAD_CONNECT: - strcat(pBuffer,"EL734__BAD_CONNECT"); - break; - case EL734__BAD_FLUSH: - strcat(pBuffer,"EL734__BAD_FLUSH"); - break; - case EL734__BAD_HOST: - strcat(pBuffer,"EL734__BAD_HOST"); - break; - case EL734__BAD_ID: - strcat(pBuffer,"EL734__BAD_ID"); - break; - case EL734__BAD_ILLG: - strcat(pBuffer,"EL734__BAD_ILLG"); - break; - case EL734__BAD_LOC: - strcat(pBuffer,"EL734__BAD_LOC"); - break; - case EL734__BAD_MALLOC: - strcat(pBuffer,"EL734__BAD_MALLOC"); - break; - case EL734__BAD_NOT_BCD: - strcat(pBuffer,"EL734__BAD_NOT_BCD"); - break; - case EL734__BAD_OFL: - strcat(pBuffer,"EL734__BAD_OFL"); - break; - case EL734__BAD_PAR: - strcat(pBuffer,"EL734__BAD_PAR"); - break; - - case EL734__BAD_RECV: - strcat(pBuffer,"EL734__BAD_RECV"); - break; - case EL734__BAD_RECV_NET: - strcat(pBuffer,"EL734__BAD_RECV_NET"); - break; - case EL734__BAD_RECV_PIPE: - strcat(pBuffer,"EL734__BAD_RECV_PIPE"); - break; - case EL734__BAD_RECV_UNKN: - strcat(pBuffer,"EL734__BAD_RECV_UNKN"); - break; - case EL734__BAD_RECVLEN: - strcat(pBuffer,"EL734__BAD_RECVLEN"); - break; - case EL734__BAD_RECV1: - strcat(pBuffer,"EL734__BAD_RECV1"); - break; - case EL734__BAD_RECV1_NET: - strcat(pBuffer,"EL734__BAD_RECV1_NET"); - break; - case EL734__BAD_RECV1_PIPE: - strcat(pBuffer,"EL734__BAD_RECV1_PIPE"); - break; - case EL734__BAD_RNG: - strcat(pBuffer,"EL734__BAD_RNG"); - break; - case EL734__BAD_SEND: - strcat(pBuffer,"EL734__BAD_SEND"); - break; - case EL734__BAD_SEND_PIPE: - strcat(pBuffer,"EL734__BAD_SEND_PIPE"); - break; - case EL734__BAD_SEND_NET: - strcat(pBuffer,"EL734__BAD_SEND_NET"); - break; - case EL734__BAD_SEND_UNKN: - strcat(pBuffer,"EL734__BAD_SEND_UNKN"); - break; - case EL734__BAD_SENDLEN: - strcat(pBuffer,"EL734__BAD_SENDLEN"); - break; - case EL734__BAD_SOCKET: - strcat(pBuffer,"EL734__BAD_SOCKET"); - break; - case EL734__BAD_TMO: - strcat(pBuffer,"EL734__BAD_TMO"); - break; - case EL734__FORCED_CLOSED: - strcat(pBuffer,"EL734__FORCED_CLOSED"); - break; - case EL734__BAD_STP: - strcat(pBuffer,"EL734__BAD_STP"); - break; - case EL734__EMERG_STOP: - strcat(pBuffer,"EL734__EMERG_STOP"); - break; - case EL734__NOT_OPEN: - strcat(pBuffer,"EL734__NOT_OPEN"); - break; - case EL734__BAD_ASYNSRV: - strcat(pBuffer,"EL734__BAD_ASYNSRV"); - break; - default: - sprintf(pBuffer,"Unknown EL734 error %d", iErr); - break; - } - } - +static void EL734Error2Text(char *pBuffer, int iErr) +{ + strcpy(pBuffer, "ERROR: HW:"); + switch (iErr) { + case EL734__BAD_ADR: + strcat(pBuffer, "EL734__BAD_ADR"); + break; + case EL734__BAD_BIND: + strcat(pBuffer, "EL734__BAD_BIND"); + break; + case EL734__BAD_CMD: + strcat(pBuffer, "EL734__BAD_CMD"); + break; + case EL734__BAD_CONNECT: + strcat(pBuffer, "EL734__BAD_CONNECT"); + break; + case EL734__BAD_FLUSH: + strcat(pBuffer, "EL734__BAD_FLUSH"); + break; + case EL734__BAD_HOST: + strcat(pBuffer, "EL734__BAD_HOST"); + break; + case EL734__BAD_ID: + strcat(pBuffer, "EL734__BAD_ID"); + break; + case EL734__BAD_ILLG: + strcat(pBuffer, "EL734__BAD_ILLG"); + break; + case EL734__BAD_LOC: + strcat(pBuffer, "EL734__BAD_LOC"); + break; + case EL734__BAD_MALLOC: + strcat(pBuffer, "EL734__BAD_MALLOC"); + break; + case EL734__BAD_NOT_BCD: + strcat(pBuffer, "EL734__BAD_NOT_BCD"); + break; + case EL734__BAD_OFL: + strcat(pBuffer, "EL734__BAD_OFL"); + break; + case EL734__BAD_PAR: + strcat(pBuffer, "EL734__BAD_PAR"); + break; + + case EL734__BAD_RECV: + strcat(pBuffer, "EL734__BAD_RECV"); + break; + case EL734__BAD_RECV_NET: + strcat(pBuffer, "EL734__BAD_RECV_NET"); + break; + case EL734__BAD_RECV_PIPE: + strcat(pBuffer, "EL734__BAD_RECV_PIPE"); + break; + case EL734__BAD_RECV_UNKN: + strcat(pBuffer, "EL734__BAD_RECV_UNKN"); + break; + case EL734__BAD_RECVLEN: + strcat(pBuffer, "EL734__BAD_RECVLEN"); + break; + case EL734__BAD_RECV1: + strcat(pBuffer, "EL734__BAD_RECV1"); + break; + case EL734__BAD_RECV1_NET: + strcat(pBuffer, "EL734__BAD_RECV1_NET"); + break; + case EL734__BAD_RECV1_PIPE: + strcat(pBuffer, "EL734__BAD_RECV1_PIPE"); + break; + case EL734__BAD_RNG: + strcat(pBuffer, "EL734__BAD_RNG"); + break; + case EL734__BAD_SEND: + strcat(pBuffer, "EL734__BAD_SEND"); + break; + case EL734__BAD_SEND_PIPE: + strcat(pBuffer, "EL734__BAD_SEND_PIPE"); + break; + case EL734__BAD_SEND_NET: + strcat(pBuffer, "EL734__BAD_SEND_NET"); + break; + case EL734__BAD_SEND_UNKN: + strcat(pBuffer, "EL734__BAD_SEND_UNKN"); + break; + case EL734__BAD_SENDLEN: + strcat(pBuffer, "EL734__BAD_SENDLEN"); + break; + case EL734__BAD_SOCKET: + strcat(pBuffer, "EL734__BAD_SOCKET"); + break; + case EL734__BAD_TMO: + strcat(pBuffer, "EL734__BAD_TMO"); + break; + case EL734__FORCED_CLOSED: + strcat(pBuffer, "EL734__FORCED_CLOSED"); + break; + case EL734__BAD_STP: + strcat(pBuffer, "EL734__BAD_STP"); + break; + case EL734__EMERG_STOP: + strcat(pBuffer, "EL734__EMERG_STOP"); + break; + case EL734__NOT_OPEN: + strcat(pBuffer, "EL734__NOT_OPEN"); + break; + case EL734__BAD_ASYNSRV: + strcat(pBuffer, "EL734__BAD_ASYNSRV"); + break; + default: + sprintf(pBuffer, "Unknown EL734 error %d", iErr); + break; + } +} + /*-------------------------------------------------------------------------*/ - static void GetErr(void *self, int *iCode, char *buffer, int iBufLen) - { - EL734Driv *pDriv; - char pBueffel[512]; - int iMSR, iOMSR, iSS; - int iRet, iFPC, iFRC; - int iErr; - float fPos; - char *pErr; - - assert(self); - - /* get EL734 error codes */ - pDriv = (EL734Driv *)self; - EL734_ErrInfo(&pErr,&iMSR,&iOMSR, &iSS); - if(iMSR != 0) - { - EL734Error2Text(pBueffel,iMSR); - strncpy(buffer,pBueffel,(iBufLen-1)); - *iCode = iMSR; - return; - } - else - { /* check status flag for addional errors */ - iRet = EL734_GetStatus(&(pDriv->EL734struct), - &iMSR, - &iOMSR, - &iFPC, - &iFRC, - &iSS, - &fPos); - if(iRet != 1) - { /* failure on this one, this has to be handled */ - EL734_ErrInfo(&pErr,&iMSR,&iOMSR, &iSS); - EL734Error2Text(pBueffel,iMSR); - strncpy(buffer,pBueffel,(iBufLen-1)); - *iCode = iMSR; - return; - - } - else - { - /* we really come down to looking at status flags */ - *iCode = EL734EncodeMSR(buffer,iBufLen,iMSR, iOMSR,iFPC,iFRC); - } - } - } +static void GetErr(void *self, int *iCode, char *buffer, int iBufLen) +{ + EL734Driv *pDriv; + char pBueffel[512]; + int iMSR, iOMSR, iSS; + int iRet, iFPC, iFRC; + int iErr; + float fPos; + char *pErr; + + assert(self); + + /* get EL734 error codes */ + pDriv = (EL734Driv *) self; + EL734_ErrInfo(&pErr, &iMSR, &iOMSR, &iSS); + if (iMSR != 0) { + EL734Error2Text(pBueffel, iMSR); + strncpy(buffer, pBueffel, (iBufLen - 1)); + *iCode = iMSR; + return; + } else { /* check status flag for addional errors */ + iRet = EL734_GetStatus(&(pDriv->EL734struct), + &iMSR, &iOMSR, &iFPC, &iFRC, &iSS, &fPos); + if (iRet != 1) { /* failure on this one, this has to be handled */ + EL734_ErrInfo(&pErr, &iMSR, &iOMSR, &iSS); + EL734Error2Text(pBueffel, iMSR); + strncpy(buffer, pBueffel, (iBufLen - 1)); + *iCode = iMSR; + return; + + } else { + /* we really come down to looking at status flags */ + *iCode = EL734EncodeMSR(buffer, iBufLen, iMSR, iOMSR, iFPC, iFRC); + } + } +} + /* ------------------------------------------------------------------------ Types of errors possible on EL734: @@ -329,612 +306,587 @@ Some things cannot be fixed. */ - static int FixError(void *self, int iError, float fNew) - { - EL734Driv *pDriv; - int iRet; - char pBueffel[512]; - int iMSR, iOMSR, iSS; - float fPos; - - assert(self); - pDriv = (EL734Driv *)self; - sprintf(pBueffel,"EL734 : %s %d %d %d Problem:",pDriv->hostname, - pDriv->iPort, pDriv->iChannel, pDriv->iMotor); - - /* get & check MSR flags */ - +static int FixError(void *self, int iError, float fNew) +{ + EL734Driv *pDriv; + int iRet; + char pBueffel[512]; + int iMSR, iOMSR, iSS; + float fPos; - /* check for codes */ - switch(iError) - { - case 0: /* no error at all */ - return MOTOK; - case EL734__BAD_ID: /* ID */ - case EL734__BAD_ADR: /* ADR */ - case EL734__BAD_CMD: /* CMD */ - case EL734__BAD_ILLG: /* ILLG */ - case EL734__BAD_PAR: /* PAR */ - case EL734__BAD_TMO: - SICSLogWrite(pBueffel,eHWError); - SICSLogWrite("BAD Command or dodgy RS-232",eHWError); - return MOTREDO; - case EL734__EMERG_STOP: - return MOTFAIL; - case EL734__BAD_RNG: /* RNG */ - case MSRONLIMIT: - SICSLogWrite(pBueffel,eHWError); - SICSLogWrite("Out of Range",eHWError); - return MOTFAIL; - case EL734__BAD_STP: - return MOTFAIL; - break; - case MSRBUSY: - return MOTREDO; - case MSRRUNFAULT: - SICSLogWrite(pBueffel,eHWError); - SICSLogWrite("------ RUN Fault in Controller ---- ",eHWError); - return MOTFAIL; - case MSRPOSFAULT: - SICSLogWrite(pBueffel,eHWError); - SICSLogWrite("------ POS Fault in Controller ---- ",eHWError); - return MOTFAIL; - case MSRDEADCUSHION: - SICSLogWrite(pBueffel,eHWError); - SICSLogWrite("------ Air cushion Fault in Controller ---- ",eHWError); - return MOTFAIL; - case MSRFAULT: - return MOTFAIL; - case MSRHALT: - case MSRSTOP: - return MOTFAIL; - case EL734__FORCED_CLOSED: - case EL734__NOT_OPEN: - iRet = EL734_Open(&(pDriv->EL734struct),pDriv->hostname, - pDriv->iPort,pDriv->iChannel, - pDriv->iMotor,"DCMC EL734"); - if(iRet != 1) - { - return MOTFAIL; - } - else - { - return MOTREDO; - } - break; - case EL734__BAD_LOC: /* LO2 */ - case EL734__BAD_OFL: - EL734_Close(&(pDriv->EL734struct),0); - iRet = EL734_Open(&(pDriv->EL734struct),pDriv->hostname, - pDriv->iPort,pDriv->iChannel, - pDriv->iMotor,"DCMC EL734"); - if(iRet != 1) - { - return MOTFAIL; - } - else - { - return MOTREDO; - } - break; + assert(self); + pDriv = (EL734Driv *) self; + sprintf(pBueffel, "EL734 : %s %d %d %d Problem:", pDriv->hostname, + pDriv->iPort, pDriv->iChannel, pDriv->iMotor); + + /* get & check MSR flags */ + + + /* check for codes */ + switch (iError) { + case 0: /* no error at all */ + return MOTOK; + case EL734__BAD_ID: /* ID */ + case EL734__BAD_ADR: /* ADR */ + case EL734__BAD_CMD: /* CMD */ + case EL734__BAD_ILLG: /* ILLG */ + case EL734__BAD_PAR: /* PAR */ + case EL734__BAD_TMO: + SICSLogWrite(pBueffel, eHWError); + SICSLogWrite("BAD Command or dodgy RS-232", eHWError); + return MOTREDO; + case EL734__EMERG_STOP: + return MOTFAIL; + case EL734__BAD_RNG: /* RNG */ + case MSRONLIMIT: + SICSLogWrite(pBueffel, eHWError); + SICSLogWrite("Out of Range", eHWError); + return MOTFAIL; + case EL734__BAD_STP: + return MOTFAIL; + break; + case MSRBUSY: + return MOTREDO; + case MSRRUNFAULT: + SICSLogWrite(pBueffel, eHWError); + SICSLogWrite("------ RUN Fault in Controller ---- ", eHWError); + return MOTFAIL; + case MSRPOSFAULT: + SICSLogWrite(pBueffel, eHWError); + SICSLogWrite("------ POS Fault in Controller ---- ", eHWError); + return MOTFAIL; + case MSRDEADCUSHION: + SICSLogWrite(pBueffel, eHWError); + SICSLogWrite("------ Air cushion Fault in Controller ---- ", eHWError); + return MOTFAIL; + case MSRFAULT: + return MOTFAIL; + case MSRHALT: + case MSRSTOP: + return MOTFAIL; + case EL734__FORCED_CLOSED: + case EL734__NOT_OPEN: + iRet = EL734_Open(&(pDriv->EL734struct), pDriv->hostname, + pDriv->iPort, pDriv->iChannel, + pDriv->iMotor, "DCMC EL734"); + if (iRet != 1) { + return MOTFAIL; + } else { + return MOTREDO; + } + break; + case EL734__BAD_LOC: /* LO2 */ + case EL734__BAD_OFL: + EL734_Close(&(pDriv->EL734struct), 0); + iRet = EL734_Open(&(pDriv->EL734struct), pDriv->hostname, + pDriv->iPort, pDriv->iChannel, + pDriv->iMotor, "DCMC EL734"); + if (iRet != 1) { + return MOTFAIL; + } else { + return MOTREDO; + } + break; /* case EL734__BAD_ASYNSRV: EL734_Close(&(pDriv->EL734struct),1); return MOTREDO; - break; -*/ default: - SICSLogWrite(pBueffel,eHWError); - SICSLogWrite("Network problem, trying to reopen",eHWError); - EL734_Close(&(pDriv->EL734struct),1); - iRet = EL734_Open(&(pDriv->EL734struct),pDriv->hostname, - pDriv->iPort,pDriv->iChannel, - pDriv->iMotor,"DCMC EL734"); - if(iRet != 1) - { - return MOTFAIL; - } - else - { - return MOTREDO; - } - } - - } -/*--------------------------------------------------------------------------*/ - static int Halt(void *self) - { - EL734Driv *pDriv; - int iRet; - char pBueffel[80]; - - assert(self); - pDriv = (EL734Driv *)self; - iRet = EL734_Stop(&(pDriv->EL734struct)); - if(iRet != 1) - { - return OKOK; + break; +*/ default: + SICSLogWrite(pBueffel, eHWError); + SICSLogWrite("Network problem, trying to reopen", eHWError); + EL734_Close(&(pDriv->EL734struct), 1); + iRet = EL734_Open(&(pDriv->EL734struct), pDriv->hostname, + pDriv->iPort, pDriv->iChannel, + pDriv->iMotor, "DCMC EL734"); + if (iRet != 1) { + return MOTFAIL; + } else { + return MOTREDO; } + } + +} + +/*--------------------------------------------------------------------------*/ +static int Halt(void *self) +{ + EL734Driv *pDriv; + int iRet; + char pBueffel[80]; + + assert(self); + pDriv = (EL734Driv *) self; + iRet = EL734_Stop(&(pDriv->EL734struct)); + if (iRet != 1) { + return OKOK; + } + return HWFault; +} + +/*--------------------------------------------------------------------------*/ +static int GetStat(void *self) +{ + EL734Driv *pDriv; + float fPos; + int iRet, iMSR, iOMSR, iFRC, iFPC, iSS; + int eRet; + int iTest; + char pBueffel[80]; + + assert(self); + + pDriv = (EL734Driv *) self; + iRet = EL734_GetStatus(&(pDriv->EL734struct), + &iMSR, &iOMSR, &iFPC, &iFRC, &iSS, &fPos); + if (iRet != 1) { return HWFault; - } -/*--------------------------------------------------------------------------*/ - static int GetStat(void *self) - { - EL734Driv *pDriv; - float fPos; - int iRet, iMSR, iOMSR, iFRC,iFPC, iSS; - int eRet; - int iTest; - char pBueffel[80]; - - assert(self); - - pDriv = (EL734Driv *)self; - iRet = EL734_GetStatus(&(pDriv->EL734struct), - &iMSR, - &iOMSR, - &iFPC, - &iFRC, - &iSS, - &fPos); - if(iRet != 1) - { - return HWFault; - } - - if(iMSR != 0) - { - pDriv->iMSR = iMSR; - } - - iTest = EL734AnalyzeMSR(iMSR,iOMSR); - switch(iTest) - { - case MSRDEADCUSHION: - case MSRONLIMIT: - case MSRREF: - case MSRHALT: - case MSRSTOP: - return HWFault; - break; - case MSRRUNFAULT: - case MSRPOSFAULT: - return HWPosFault; - break; - case MSRBUSY: - return HWBusy; - break; - case MSRFAULT: - return HWWarn; - break; - default: - return HWIdle; - break; - } - } -/*--------------------------------------------------------------------------*/ -extern void KillEL734(void *pdata); /* from el734driv.c */ -/*---------------------------------------------------------------------------*/ - static EL734Driv *MakeEL734DC(char *hostname, int iPort, int iChannel, - int iMotor) - { - EL734Driv *pDriv = NULL; - int iError; - char pBueffel[80]; - char *pErr; - int iRet; - int iDummy; - - /* create a new struct */ - pDriv = (EL734Driv *)malloc(sizeof(EL734Driv)); - if(!pDriv) - { - return NULL; - } - memset(pDriv,0,sizeof(EL734Driv)); - - /* fill in some of the data entered */ - pDriv->hostname = strdup(hostname); - pDriv->iPort = iPort; - pDriv->iChannel = iChannel; - pDriv->iMotor = iMotor; - pDriv->name = strdup("EL734"); - - /* try opening the motor */ - iRet = EL734_Open(&(pDriv->EL734struct), hostname,iPort, - iChannel,iMotor,"DCMC EL734"); - if(iRet != 1) - { - EL734_ErrInfo(&pErr,&iError,&iRet, &iDummy); - KillEL734((void *)pDriv); - return NULL; - } - - /* now get the limits */ - EL734_GetLimits(&(pDriv->EL734struct),&(pDriv->fLower), - &(pDriv->fUpper)); - - - /* initialise the function pointers */ - pDriv->GetPosition = GetPos; - pDriv->RunTo = Run; - pDriv->GetError = GetErr; - pDriv->GetStatus = GetStat; - pDriv->Halt = Halt; - pDriv->TryAndFixIt = FixError; - pDriv->KillPrivate = KillEL734; - - return pDriv; - } + if (iMSR != 0) { + pDriv->iMSR = iMSR; + } + + iTest = EL734AnalyzeMSR(iMSR, iOMSR); + switch (iTest) { + case MSRDEADCUSHION: + case MSRONLIMIT: + case MSRREF: + case MSRHALT: + case MSRSTOP: + return HWFault; + break; + case MSRRUNFAULT: + case MSRPOSFAULT: + return HWPosFault; + break; + case MSRBUSY: + return HWBusy; + break; + case MSRFAULT: + return HWWarn; + break; + default: + return HWIdle; + break; + } + +} + +/*--------------------------------------------------------------------------*/ +extern void KillEL734(void *pdata); /* from el734driv.c */ +/*---------------------------------------------------------------------------*/ +static EL734Driv *MakeEL734DC(char *hostname, int iPort, int iChannel, + int iMotor) +{ + EL734Driv *pDriv = NULL; + + int iError; + char pBueffel[80]; + char *pErr; + int iRet; + int iDummy; + + /* create a new struct */ + pDriv = (EL734Driv *) malloc(sizeof(EL734Driv)); + if (!pDriv) { + return NULL; + } + memset(pDriv, 0, sizeof(EL734Driv)); + + /* fill in some of the data entered */ + pDriv->hostname = strdup(hostname); + pDriv->iPort = iPort; + pDriv->iChannel = iChannel; + pDriv->iMotor = iMotor; + pDriv->name = strdup("EL734"); + + /* try opening the motor */ + iRet = EL734_Open(&(pDriv->EL734struct), hostname, iPort, + iChannel, iMotor, "DCMC EL734"); + if (iRet != 1) { + EL734_ErrInfo(&pErr, &iError, &iRet, &iDummy); + KillEL734((void *) pDriv); + return NULL; + } + + /* now get the limits */ + EL734_GetLimits(&(pDriv->EL734struct), &(pDriv->fLower), + &(pDriv->fUpper)); + + + /* initialise the function pointers */ + pDriv->GetPosition = GetPos; + pDriv->RunTo = Run; + pDriv->GetError = GetErr; + pDriv->GetStatus = GetStat; + pDriv->Halt = Halt; + pDriv->TryAndFixIt = FixError; + pDriv->KillPrivate = KillEL734; + + return pDriv; +} + /*-------------------------------------------------------------------------- interpreting the driver parameters is up to the driver, this below inplements just this */ - MotorDriver *CreateEL734DC(SConnection *pCon, int argc, char *argv[]) - { - EL734Driv *pDriv = NULL; - TokenList *pList = NULL; - TokenList *pCurrent; - char *hostname; - int iPort, iChannel, iMotor; - char pBueffel[512]; - - assert(pCon); - - /* split arguments */ - pList = SplitArguments(argc,argv); - if(!pList) - { - SCWrite(pCon,"Error parsing arguments",eError); - return NULL; - } - - /* first must be hostname */ - pCurrent = pList; - if(pCurrent->Type != eText) - { - sprintf(pBueffel,"EL734DC: Expected hostname but got --> %s <--", - pCurrent->text); - SCWrite(pCon,pBueffel,eError); - DeleteTokenList(pList); - return NULL; - } - hostname = pCurrent->text; - - /* next should be port */ - pCurrent = pCurrent->pNext; - if(!pCurrent) - { - SCWrite(pCon,"EL734DC: Insufficient number of arguments",eError); - DeleteTokenList(pList); - return NULL; - } - if(pCurrent->Type != eInt) - { - sprintf(pBueffel,"EL734DC: Expected Integer as Port number, got --> %s <--", - pCurrent->text); - SCWrite(pCon,pBueffel,eError); - DeleteTokenList(pList); - return NULL; - } - iPort = pCurrent->iVal; +MotorDriver *CreateEL734DC(SConnection * pCon, int argc, char *argv[]) +{ + EL734Driv *pDriv = NULL; + TokenList *pList = NULL; + TokenList *pCurrent; + char *hostname; + int iPort, iChannel, iMotor; + char pBueffel[512]; - - /* next should be Channel number */ - pCurrent = pCurrent->pNext; - if(!pCurrent) - { - SCWrite(pCon,"EL734DC: Insufficient number of arguments",eError); - DeleteTokenList(pList); - return NULL; - } - if(pCurrent->Type != eInt) - { - sprintf(pBueffel,"EL734DC: Expected Integer as channel number, got --> %s <--", - pCurrent->text); - SCWrite(pCon,pBueffel,eError); - DeleteTokenList(pList); - return NULL; - } - iChannel = pCurrent->iVal; - - /* finally motor number */ - pCurrent = pCurrent->pNext; - if(!pCurrent) - { - - SCWrite(pCon,"EL734DC: Insufficient number of arguments",eError); - DeleteTokenList(pList); - return NULL; - } - if(pCurrent->Type != eInt) - { - sprintf(pBueffel,"EL734DC: Expected Integer as motor number, got --> %s <--", - pCurrent->text); - SCWrite(pCon,pBueffel,eError); - DeleteTokenList(pList); - return NULL; - } - iMotor = pCurrent->iVal; - - - /* finally initialize driver */ - pDriv = MakeEL734DC(hostname,iPort,iChannel,iMotor); - if(!pDriv) - { - SCWrite(pCon,"EL734DC: error opening motor, check adress",eError); - pDriv = NULL; - } - - /* clean up */ - DeleteTokenList(pList); - return (MotorDriver *)pDriv; + assert(pCon); + + /* split arguments */ + pList = SplitArguments(argc, argv); + if (!pList) { + SCWrite(pCon, "Error parsing arguments", eError); + return NULL; } + + /* first must be hostname */ + pCurrent = pList; + if (pCurrent->Type != eText) { + sprintf(pBueffel, "EL734DC: Expected hostname but got --> %s <--", + pCurrent->text); + SCWrite(pCon, pBueffel, eError); + DeleteTokenList(pList); + return NULL; + } + hostname = pCurrent->text; + + /* next should be port */ + pCurrent = pCurrent->pNext; + if (!pCurrent) { + SCWrite(pCon, "EL734DC: Insufficient number of arguments", eError); + DeleteTokenList(pList); + return NULL; + } + if (pCurrent->Type != eInt) { + sprintf(pBueffel, + "EL734DC: Expected Integer as Port number, got --> %s <--", + pCurrent->text); + SCWrite(pCon, pBueffel, eError); + DeleteTokenList(pList); + return NULL; + } + iPort = pCurrent->iVal; + + + /* next should be Channel number */ + pCurrent = pCurrent->pNext; + if (!pCurrent) { + SCWrite(pCon, "EL734DC: Insufficient number of arguments", eError); + DeleteTokenList(pList); + return NULL; + } + if (pCurrent->Type != eInt) { + sprintf(pBueffel, + "EL734DC: Expected Integer as channel number, got --> %s <--", + pCurrent->text); + SCWrite(pCon, pBueffel, eError); + DeleteTokenList(pList); + return NULL; + } + iChannel = pCurrent->iVal; + + /* finally motor number */ + pCurrent = pCurrent->pNext; + if (!pCurrent) { + + SCWrite(pCon, "EL734DC: Insufficient number of arguments", eError); + DeleteTokenList(pList); + return NULL; + } + if (pCurrent->Type != eInt) { + sprintf(pBueffel, + "EL734DC: Expected Integer as motor number, got --> %s <--", + pCurrent->text); + SCWrite(pCon, pBueffel, eError); + DeleteTokenList(pList); + return NULL; + } + iMotor = pCurrent->iVal; + + + /* finally initialize driver */ + pDriv = MakeEL734DC(hostname, iPort, iChannel, iMotor); + if (!pDriv) { + SCWrite(pCon, "EL734DC: error opening motor, check adress", eError); + pDriv = NULL; + } + + /* clean up */ + DeleteTokenList(pList); + return (MotorDriver *) pDriv; +} + /*------------------------------------------------------------------------- Stolen from David and modified to return an integer error code as well */ - static int EL734EncodeMSR (char *text, int text_len, - int msr, - int ored_msr, - int fp_cntr, - int fr_cntr) { - int len; - char my_text[132]; - char my_text_0[32]; - int iRet = 0; +static int EL734EncodeMSR(char *text, int text_len, + int msr, int ored_msr, int fp_cntr, int fr_cntr) +{ + int len; + char my_text[132]; + char my_text_0[32]; + int iRet = 0; - if (msr == 0) { - ored_msr = ored_msr & ~(MSR__BUSY); /* Zero "Busy" bit */ - if (ored_msr == MSR__OK) { - StrJoin (text, text_len, "Status, MSR = Idle. Positioned OK.", ""); - }else { - if ((ored_msr & MSR__OK) != 0) { - StrJoin (text, text_len, "Status, MSR = Idle. Positioned OK. ", ""); - }else { - StrJoin (text, text_len, "Status, MSR = Idle. ", ""); - } - if ((ored_msr & MSR__REF_OK) != 0) { - StrJoin (my_text, sizeof (my_text), text, ""); - StrJoin (text, text_len, my_text, "Ref. Pos'n OK. "); - } - if ((ored_msr & MSR__LIM_ERR) != 0) { - StrJoin (my_text, sizeof (my_text), text, ""); - StrJoin (text, text_len, my_text, "Limit Switch Problem. "); - iRet = MSRONLIMIT; - } - if ((ored_msr & MSR__AC_FAIL) != 0) { - StrJoin (my_text, sizeof (my_text), text, ""); - StrJoin (text, text_len, my_text, "Air-Cushion Error. "); - iRet = MSRDEADCUSHION; - } - if ((ored_msr & MSR__REF_FAIL) != 0) { - StrJoin (my_text, sizeof (my_text), text, ""); - StrJoin (text, text_len, my_text, "Ref. Pos'n Fail. "); - } - if ((ored_msr & MSR__POS_FAIL) != 0) { - StrJoin (my_text, sizeof (my_text), text, ""); - StrJoin (text, text_len, my_text, "Pos'n Fail. "); - iRet = MSRPOSFAULT; - } - if ((ored_msr & MSR__POS_FAULT) != 0) { - StrJoin (my_text, sizeof (my_text), text, ""); - if (fp_cntr == 1) { - StrJoin (text, text_len, my_text, "1 Pos'n Fault. "); - }else { - sprintf (my_text_0, "%d Pos'n Faults. ", fp_cntr); - StrJoin (text, text_len, my_text, my_text_0); - } - } - if ((ored_msr & MSR__RUN_FAIL) != 0) { - StrJoin (my_text, sizeof (my_text), text, ""); - StrJoin (text, text_len, my_text, "Run Fail. "); - iRet = MSRRUNFAULT; - } - if ((ored_msr & MSR__RUN_FAULT) != 0) { - StrJoin (my_text, sizeof (my_text), text, ""); - if (fr_cntr == 1) { - StrJoin (text, text_len, my_text, "1 Run Fault. "); - }else { - sprintf (my_text_0, "%d Run Faults. ", fr_cntr); - StrJoin (text, text_len, my_text, my_text_0); - } - } - if ((ored_msr & MSR__HALT) != 0) { - StrJoin (my_text, sizeof (my_text), text, ""); - StrJoin (text, text_len, my_text, "Halt. "); - iRet = MSRHALT; - } - if ((ored_msr & MSR__HI_LIM) != 0) { - StrJoin (my_text, sizeof (my_text), text, ""); - StrJoin (text, text_len, my_text, "Hit HiLim. "); - iRet = MSRONLIMIT; - } - if ((ored_msr & MSR__LO_LIM) != 0) { - StrJoin (my_text, sizeof (my_text), text, ""); - StrJoin (text, text_len, my_text, "Hit LoLim. "); - iRet = MSRONLIMIT; - } - if ((ored_msr & MSR__STOPPED) != 0) { - StrJoin (my_text, sizeof (my_text), text, ""); - StrJoin (text, text_len, my_text, "Stopped. "); - iRet = MSRSTOP; - } + if (msr == 0) { + ored_msr = ored_msr & ~(MSR__BUSY); /* Zero "Busy" bit */ + if (ored_msr == MSR__OK) { + StrJoin(text, text_len, "Status, MSR = Idle. Positioned OK.", ""); + } else { + if ((ored_msr & MSR__OK) != 0) { + StrJoin(text, text_len, "Status, MSR = Idle. Positioned OK. ", ""); + } else { + StrJoin(text, text_len, "Status, MSR = Idle. ", ""); } - }else if ((msr & ~(0x2fff)) != 0) { - StrJoin (text, text_len, "Status, MSR = ??", ""); - }else { - sprintf (my_text, "%#x ", msr); - StrJoin (text, text_len, "Status, MSR = ", my_text); - if ((msr & MSR__LIM_ERR) != 0) { - StrJoin (my_text, sizeof (my_text), text, ""); - StrJoin (text, text_len, my_text, "Limit Switch Problem/"); + if ((ored_msr & MSR__REF_OK) != 0) { + StrJoin(my_text, sizeof(my_text), text, ""); + StrJoin(text, text_len, my_text, "Ref. Pos'n OK. "); + } + if ((ored_msr & MSR__LIM_ERR) != 0) { + StrJoin(my_text, sizeof(my_text), text, ""); + StrJoin(text, text_len, my_text, "Limit Switch Problem. "); iRet = MSRONLIMIT; } - if ((msr & MSR__AC_FAIL) != 0) { - StrJoin (my_text, sizeof (my_text), text, ""); - StrJoin (text, text_len, my_text, "Air-Cushion Error/"); + if ((ored_msr & MSR__AC_FAIL) != 0) { + StrJoin(my_text, sizeof(my_text), text, ""); + StrJoin(text, text_len, my_text, "Air-Cushion Error. "); iRet = MSRDEADCUSHION; } - if ((msr & MSR__REF_FAIL) != 0) { - StrJoin (my_text, sizeof (my_text), text, ""); - StrJoin (text, text_len, my_text, "Ref. Pos'n Fail/"); + if ((ored_msr & MSR__REF_FAIL) != 0) { + StrJoin(my_text, sizeof(my_text), text, ""); + StrJoin(text, text_len, my_text, "Ref. Pos'n Fail. "); } - if ((msr & MSR__POS_FAIL) != 0) { - StrJoin (my_text, sizeof (my_text), text, ""); - StrJoin (text, text_len, my_text, "Pos'n Fail/"); + if ((ored_msr & MSR__POS_FAIL) != 0) { + StrJoin(my_text, sizeof(my_text), text, ""); + StrJoin(text, text_len, my_text, "Pos'n Fail. "); iRet = MSRPOSFAULT; } - if ((msr & MSR__POS_FAULT) != 0) { - StrJoin (my_text, sizeof (my_text), text, ""); - StrJoin (text, text_len, my_text, "Pos'n Fault/"); + if ((ored_msr & MSR__POS_FAULT) != 0) { + StrJoin(my_text, sizeof(my_text), text, ""); + if (fp_cntr == 1) { + StrJoin(text, text_len, my_text, "1 Pos'n Fault. "); + } else { + sprintf(my_text_0, "%d Pos'n Faults. ", fp_cntr); + StrJoin(text, text_len, my_text, my_text_0); + } } - if ((msr & MSR__RUN_FAIL) != 0) { - StrJoin (my_text, sizeof (my_text), text, ""); - StrJoin (text, text_len, my_text, "Run Fail/"); + if ((ored_msr & MSR__RUN_FAIL) != 0) { + StrJoin(my_text, sizeof(my_text), text, ""); + StrJoin(text, text_len, my_text, "Run Fail. "); iRet = MSRRUNFAULT; } - if ((msr & MSR__RUN_FAULT) != 0) { - StrJoin (my_text, sizeof (my_text), text, ""); - StrJoin (text, text_len, my_text, "Run Fault/"); + if ((ored_msr & MSR__RUN_FAULT) != 0) { + StrJoin(my_text, sizeof(my_text), text, ""); + if (fr_cntr == 1) { + StrJoin(text, text_len, my_text, "1 Run Fault. "); + } else { + sprintf(my_text_0, "%d Run Faults. ", fr_cntr); + StrJoin(text, text_len, my_text, my_text_0); + } } - if ((msr & MSR__HALT) != 0) { - StrJoin (my_text, sizeof (my_text), text, ""); - StrJoin (text, text_len, my_text, "Halt/"); + if ((ored_msr & MSR__HALT) != 0) { + StrJoin(my_text, sizeof(my_text), text, ""); + StrJoin(text, text_len, my_text, "Halt. "); iRet = MSRHALT; } - if ((msr & MSR__HI_LIM) != 0) { - StrJoin (my_text, sizeof (my_text), text, ""); - StrJoin (text, text_len, my_text, "Hit HiLim/"); + if ((ored_msr & MSR__HI_LIM) != 0) { + StrJoin(my_text, sizeof(my_text), text, ""); + StrJoin(text, text_len, my_text, "Hit HiLim. "); iRet = MSRONLIMIT; } - if ((msr & MSR__LO_LIM) != 0) { - StrJoin (my_text, sizeof (my_text), text, ""); - StrJoin (text, text_len, my_text, "Hit LoLim/"); + if ((ored_msr & MSR__LO_LIM) != 0) { + StrJoin(my_text, sizeof(my_text), text, ""); + StrJoin(text, text_len, my_text, "Hit LoLim. "); iRet = MSRONLIMIT; } - if ((msr & MSR__STOPPED) != 0) { - StrJoin (my_text, sizeof (my_text), text, ""); - StrJoin (text, text_len, my_text, "Stopped/"); + if ((ored_msr & MSR__STOPPED) != 0) { + StrJoin(my_text, sizeof(my_text), text, ""); + StrJoin(text, text_len, my_text, "Stopped. "); iRet = MSRSTOP; } - if ((msr & MSR__REF_OK) != 0) { - StrJoin (my_text, sizeof (my_text), text, ""); - StrJoin (text, text_len, my_text, "Ref. Pos'n OK/"); - } - if ((msr & MSR__OK) != 0) { - StrJoin (my_text, sizeof (my_text), text, ""); - StrJoin (text, text_len, my_text, "OK/"); - } - if ((msr & MSR__BUSY) != 0) { - StrJoin (my_text, sizeof (my_text), text, ""); - StrJoin (text, text_len, my_text, "Busy/"); - } - len = strlen (text); - text[len-1] = '\0'; } - return iRet; + } else if ((msr & ~(0x2fff)) != 0) { + StrJoin(text, text_len, "Status, MSR = ??", ""); + } else { + sprintf(my_text, "%#x ", msr); + StrJoin(text, text_len, "Status, MSR = ", my_text); + if ((msr & MSR__LIM_ERR) != 0) { + StrJoin(my_text, sizeof(my_text), text, ""); + StrJoin(text, text_len, my_text, "Limit Switch Problem/"); + iRet = MSRONLIMIT; + } + if ((msr & MSR__AC_FAIL) != 0) { + StrJoin(my_text, sizeof(my_text), text, ""); + StrJoin(text, text_len, my_text, "Air-Cushion Error/"); + iRet = MSRDEADCUSHION; + } + if ((msr & MSR__REF_FAIL) != 0) { + StrJoin(my_text, sizeof(my_text), text, ""); + StrJoin(text, text_len, my_text, "Ref. Pos'n Fail/"); + } + if ((msr & MSR__POS_FAIL) != 0) { + StrJoin(my_text, sizeof(my_text), text, ""); + StrJoin(text, text_len, my_text, "Pos'n Fail/"); + iRet = MSRPOSFAULT; + } + if ((msr & MSR__POS_FAULT) != 0) { + StrJoin(my_text, sizeof(my_text), text, ""); + StrJoin(text, text_len, my_text, "Pos'n Fault/"); + } + if ((msr & MSR__RUN_FAIL) != 0) { + StrJoin(my_text, sizeof(my_text), text, ""); + StrJoin(text, text_len, my_text, "Run Fail/"); + iRet = MSRRUNFAULT; + } + if ((msr & MSR__RUN_FAULT) != 0) { + StrJoin(my_text, sizeof(my_text), text, ""); + StrJoin(text, text_len, my_text, "Run Fault/"); + } + if ((msr & MSR__HALT) != 0) { + StrJoin(my_text, sizeof(my_text), text, ""); + StrJoin(text, text_len, my_text, "Halt/"); + iRet = MSRHALT; + } + if ((msr & MSR__HI_LIM) != 0) { + StrJoin(my_text, sizeof(my_text), text, ""); + StrJoin(text, text_len, my_text, "Hit HiLim/"); + iRet = MSRONLIMIT; + } + if ((msr & MSR__LO_LIM) != 0) { + StrJoin(my_text, sizeof(my_text), text, ""); + StrJoin(text, text_len, my_text, "Hit LoLim/"); + iRet = MSRONLIMIT; + } + if ((msr & MSR__STOPPED) != 0) { + StrJoin(my_text, sizeof(my_text), text, ""); + StrJoin(text, text_len, my_text, "Stopped/"); + iRet = MSRSTOP; + } + if ((msr & MSR__REF_OK) != 0) { + StrJoin(my_text, sizeof(my_text), text, ""); + StrJoin(text, text_len, my_text, "Ref. Pos'n OK/"); + } + if ((msr & MSR__OK) != 0) { + StrJoin(my_text, sizeof(my_text), text, ""); + StrJoin(text, text_len, my_text, "OK/"); + } + if ((msr & MSR__BUSY) != 0) { + StrJoin(my_text, sizeof(my_text), text, ""); + StrJoin(text, text_len, my_text, "Busy/"); + } + len = strlen(text); + text[len - 1] = '\0'; } + return iRet; +} + /*-------------------------------------------------------------------------*/ - static int EL734AnalyzeMSR(int msr,int ored_msr) - { - int iRet = 0; +static int EL734AnalyzeMSR(int msr, int ored_msr) +{ + int iRet = 0; /* this means the motor is done */ - if (msr == 0) { - ored_msr = ored_msr & ~(MSR__BUSY); /* Zero "Busy" bit */ - if (ored_msr == MSR__OK) { - iRet = MSROK; - }else { - if ((ored_msr & MSR__OK) != 0) { - iRet = MSROK; - }else { - iRet = MSROK; - } - if ((ored_msr & MSR__REF_OK) != 0) { - iRet = MSROK; - } - if ((ored_msr & MSR__LIM_ERR) != 0) { - return MSRONLIMIT; - } - if ((ored_msr & MSR__AC_FAIL) != 0) { - return MSRDEADCUSHION; - } - if ((ored_msr & MSR__REF_FAIL) != 0) { - iRet = MSRREF; - } - if ((ored_msr & MSR__POS_FAIL) != 0) { - return MSRPOSFAULT; - } - if ((ored_msr & MSR__POS_FAULT) != 0) { - iRet = MSRFAULT; - } - if ((ored_msr & MSR__RUN_FAIL) != 0) { - return MSRRUNFAULT; - } - if ((ored_msr & MSR__RUN_FAULT) != 0) { - iRet = MSRFAULT; - } - if ((ored_msr & MSR__HALT) != 0) { - return MSRHALT; - } - if ((ored_msr & MSR__HI_LIM) != 0) { - return MSRONLIMIT; - } - if ((ored_msr & MSR__LO_LIM) != 0) { - return MSRONLIMIT; - } - if ((ored_msr & MSR__STOPPED) != 0) { - return MSRSTOP; - } - } - /* the motor is still fighting along */ - }else if ((msr & ~(0x2fff)) != 0) { + if (msr == 0) { + ored_msr = ored_msr & ~(MSR__BUSY); /* Zero "Busy" bit */ + if (ored_msr == MSR__OK) { iRet = MSROK; - }else { - if ((msr & MSR__LIM_ERR) != 0) { + } else { + if ((ored_msr & MSR__OK) != 0) { + iRet = MSROK; + } else { + iRet = MSROK; + } + if ((ored_msr & MSR__REF_OK) != 0) { + iRet = MSROK; + } + if ((ored_msr & MSR__LIM_ERR) != 0) { return MSRONLIMIT; } - if ((msr & MSR__AC_FAIL) != 0) { + if ((ored_msr & MSR__AC_FAIL) != 0) { return MSRDEADCUSHION; } - if ((msr & MSR__REF_FAIL) != 0) { + if ((ored_msr & MSR__REF_FAIL) != 0) { iRet = MSRREF; } - if ((msr & MSR__POS_FAIL) != 0) { + if ((ored_msr & MSR__POS_FAIL) != 0) { return MSRPOSFAULT; } - if ((msr & MSR__POS_FAULT) != 0) { + if ((ored_msr & MSR__POS_FAULT) != 0) { iRet = MSRFAULT; } - if ((msr & MSR__RUN_FAIL) != 0) { + if ((ored_msr & MSR__RUN_FAIL) != 0) { return MSRRUNFAULT; } - if ((msr & MSR__RUN_FAULT) != 0) { + if ((ored_msr & MSR__RUN_FAULT) != 0) { iRet = MSRFAULT; } - if ((msr & MSR__HALT) != 0) { + if ((ored_msr & MSR__HALT) != 0) { return MSRHALT; } - if ((msr & MSR__HI_LIM) != 0) { + if ((ored_msr & MSR__HI_LIM) != 0) { return MSRONLIMIT; } - if ((msr & MSR__LO_LIM) != 0) { + if ((ored_msr & MSR__LO_LIM) != 0) { return MSRONLIMIT; } - if ((msr & MSR__STOPPED) != 0) { + if ((ored_msr & MSR__STOPPED) != 0) { return MSRSTOP; } - if ((msr & MSR__REF_OK) != 0) { - iRet = MSROK; - } - if ((msr & MSR__OK) != 0) { - iRet = MSROK; - } - if ((msr & MSR__BUSY) != 0) { - iRet = MSRBUSY; - } } - return iRet; + /* the motor is still fighting along */ + } else if ((msr & ~(0x2fff)) != 0) { + iRet = MSROK; + } else { + if ((msr & MSR__LIM_ERR) != 0) { + return MSRONLIMIT; + } + if ((msr & MSR__AC_FAIL) != 0) { + return MSRDEADCUSHION; + } + if ((msr & MSR__REF_FAIL) != 0) { + iRet = MSRREF; + } + if ((msr & MSR__POS_FAIL) != 0) { + return MSRPOSFAULT; + } + if ((msr & MSR__POS_FAULT) != 0) { + iRet = MSRFAULT; + } + if ((msr & MSR__RUN_FAIL) != 0) { + return MSRRUNFAULT; + } + if ((msr & MSR__RUN_FAULT) != 0) { + iRet = MSRFAULT; + } + if ((msr & MSR__HALT) != 0) { + return MSRHALT; + } + if ((msr & MSR__HI_LIM) != 0) { + return MSRONLIMIT; + } + if ((msr & MSR__LO_LIM) != 0) { + return MSRONLIMIT; + } + if ((msr & MSR__STOPPED) != 0) { + return MSRSTOP; + } + if ((msr & MSR__REF_OK) != 0) { + iRet = MSROK; + } + if ((msr & MSR__OK) != 0) { + iRet = MSROK; + } + if ((msr & MSR__BUSY) != 0) { + iRet = MSRBUSY; + } } - - + return iRet; +} diff --git a/el734driv.c b/el734driv.c index 5e4f8c0..885133f 100644 --- a/el734driv.c +++ b/el734driv.c @@ -53,42 +53,40 @@ The motor driver structure. Please note that the first set of fields has be identical with the fields of AbstractModriv in ../modriv.h ------------------------------------------------------------------------*/ - typedef struct __MoDriv { - /* general motor driver interface - fields. REQUIRED! - */ - float fUpper; /* upper limit */ - float fLower; /* lower limit */ - char *name; - int (*GetPosition)(void *self,float *fPos); - int (*RunTo)(void *self, float fNewVal); - int (*GetStatus)(void *self); - void (*GetError)(void *self, int *iCode, char *buffer, int iBufLen); - int (*TryAndFixIt)(void *self,int iError, float fNew); - int (*Halt)(void *self); - int (*GetDriverPar)(void *self, char *name, - float *value); - int (*SetDriverPar)(void *self,SConnection *pCon, - char *name, float newValue); - void (*ListDriverPar)(void *self, char *motorName, - SConnection *pCon); - void (*KillPrivate)(void *self); - - - /* EL-734 specific fields */ - int iPort; - char *hostname; - int iChannel; - int iMotor; - void *EL734struct; - int iMSR; - } EL734Driv; +typedef struct __MoDriv { + /* general motor driver interface + fields. REQUIRED! + */ + float fUpper; /* upper limit */ + float fLower; /* lower limit */ + char *name; + int (*GetPosition) (void *self, float *fPos); + int (*RunTo) (void *self, float fNewVal); + int (*GetStatus) (void *self); + void (*GetError) (void *self, int *iCode, char *buffer, int iBufLen); + int (*TryAndFixIt) (void *self, int iError, float fNew); + int (*Halt) (void *self); + int (*GetDriverPar) (void *self, char *name, float *value); + int (*SetDriverPar) (void *self, SConnection * pCon, + char *name, float newValue); + void (*ListDriverPar) (void *self, char *motorName, SConnection * pCon); + void (*KillPrivate) (void *self); - static int EL734EncodeMSR(char *text, int iLen, - int iMSR, int iOMSR, int iFP, int iFR); - static int EL734AnalyzeMSR(int iMSR, int iOMSR); - + /* EL-734 specific fields */ + int iPort; + char *hostname; + int iChannel; + int iMotor; + void *EL734struct; + int iMSR; +} EL734Driv; + +static int EL734EncodeMSR(char *text, int iLen, + int iMSR, int iOMSR, int iFP, int iFR); + +static int EL734AnalyzeMSR(int iMSR, int iOMSR); + /* addional error codes for Status-things */ #define MSRBUSY -40 #define MSRONLIMIT -41 @@ -101,228 +99,205 @@ #define MSRREF -48 #define MSRFAULT -49 /* --------------------------------------------------------------------------*/ - static int GetPos(void *self, float *fData) - { - EL734Driv *pDriv; - float fPos; - int iRet, iMSR, iOMSR, iFRC,iFPC, iSS; - - assert(self); - - pDriv = (EL734Driv *)self; - iRet = EL734_GetStatus(&(pDriv->EL734struct), - &iMSR, - &iOMSR, - &iFPC, - &iFRC, - &iSS, - &fPos); - if(iMSR != 0) - { - pDriv->iMSR = iMSR; - } - *fData = fPos; - if(iRet != 1) - { - return HWFault; - } - else - return OKOK; - +static int GetPos(void *self, float *fData) +{ + EL734Driv *pDriv; + float fPos; + int iRet, iMSR, iOMSR, iFRC, iFPC, iSS; + + assert(self); + + pDriv = (EL734Driv *) self; + iRet = EL734_GetStatus(&(pDriv->EL734struct), + &iMSR, &iOMSR, &iFPC, &iFRC, &iSS, &fPos); + if (iMSR != 0) { + pDriv->iMSR = iMSR; } + *fData = fPos; + if (iRet != 1) { + return HWFault; + } else + return OKOK; + +} + /*--------------------------------------------------------------------------*/ - static int Run(void *self, float fNew) - { - EL734Driv *pDriv; - int iRet; - - assert(self); - - pDriv = (EL734Driv *)self; - iRet = EL734_MoveNoWait (&(pDriv->EL734struct), fNew); - if(iRet == 1) - { - return OKOK; - } - else - { - return HWFault; - } - } +static int Run(void *self, float fNew) +{ + EL734Driv *pDriv; + int iRet; + + assert(self); + + pDriv = (EL734Driv *) self; + iRet = EL734_MoveNoWait(&(pDriv->EL734struct), fNew); + if (iRet == 1) { + return OKOK; + } else { + return HWFault; + } +} /*--------------------------------------------------------------------------- EL734Error2Text converts between an EL734 error code to text -----------------------------------------------------------------------------*/ - extern char EL734_IllgText[256]; +extern char EL734_IllgText[256]; + +static void EL734Error2Text(char *pBuffer, int iErr) +{ + strcpy(pBuffer, "ERROR: HW:"); + switch (iErr) { + case EL734__BAD_ADR: + strcat(pBuffer, "EL734__BAD_ADR"); + break; + case EL734__BAD_BIND: + strcat(pBuffer, "EL734__BAD_BIND"); + break; + case EL734__BAD_CMD: + strcat(pBuffer, "EL734__BAD_CMD"); + break; + case EL734__BAD_CONNECT: + strcat(pBuffer, "EL734__BAD_CONNECT"); + break; + case EL734__BAD_FLUSH: + strcat(pBuffer, "EL734__BAD_FLUSH"); + break; + case EL734__BAD_HOST: + strcat(pBuffer, "EL734__BAD_HOST"); + break; + case EL734__BAD_ID: + strcat(pBuffer, "EL734__BAD_ID"); + break; + case EL734__BAD_ILLG: + strcat(pBuffer, "EL734__BAD_ILLG "); + + strcat(pBuffer, EL734_IllgText); + + break; + case EL734__BAD_LOC: + strcat(pBuffer, "EL734__BAD_LOC"); + break; + case EL734__BAD_MALLOC: + strcat(pBuffer, "EL734__BAD_MALLOC"); + break; + case EL734__BAD_NOT_BCD: + strcat(pBuffer, "EL734__BAD_NOT_BCD"); + break; + case EL734__BAD_OFL: + strcat(pBuffer, "EL734__BAD_OFL"); + break; + case EL734__BAD_PAR: + strcat(pBuffer, "EL734__BAD_PAR"); + break; + + case EL734__BAD_RECV: + strcat(pBuffer, "EL734__BAD_RECV"); + break; + case EL734__BAD_RECV_NET: + strcat(pBuffer, "EL734__BAD_RECV_NET"); + break; + case EL734__BAD_RECV_PIPE: + strcat(pBuffer, "EL734__BAD_RECV_PIPE"); + break; + case EL734__BAD_RECV_UNKN: + strcat(pBuffer, "EL734__BAD_RECV_UNKN"); + break; + case EL734__BAD_RECVLEN: + strcat(pBuffer, "EL734__BAD_RECVLEN"); + break; + case EL734__BAD_RECV1: + strcat(pBuffer, "EL734__BAD_RECV1"); + break; + case EL734__BAD_RECV1_NET: + strcat(pBuffer, "EL734__BAD_RECV1_NET"); + break; + case EL734__BAD_RECV1_PIPE: + strcat(pBuffer, "EL734__BAD_RECV1_PIPE"); + break; + case EL734__BAD_RNG: + strcat(pBuffer, "EL734__BAD_RNG"); + break; + case EL734__BAD_SEND: + strcat(pBuffer, "EL734__BAD_SEND"); + break; + case EL734__BAD_SEND_PIPE: + strcat(pBuffer, "EL734__BAD_SEND_PIPE"); + break; + case EL734__BAD_SEND_NET: + strcat(pBuffer, "EL734__BAD_SEND_NET"); + break; + case EL734__BAD_SEND_UNKN: + strcat(pBuffer, "EL734__BAD_SEND_UNKN"); + break; + case EL734__BAD_SENDLEN: + strcat(pBuffer, "EL734__BAD_SENDLEN"); + break; + case EL734__BAD_SOCKET: + strcat(pBuffer, "EL734__BAD_SOCKET"); + break; + case EL734__BAD_TMO: + strcat(pBuffer, "EL734__BAD_TMO"); + break; + case EL734__FORCED_CLOSED: + strcat(pBuffer, "EL734__FORCED_CLOSED"); + break; + case EL734__BAD_STP: + strcat(pBuffer, "The motor is switched off at the motor controller"); + break; + case EL734__EMERG_STOP: + strcat(pBuffer, "Emergency stop button depressed, please release"); + break; + case EL734__NOT_OPEN: + strcat(pBuffer, "EL734__NOT_OPEN"); + break; + case EL734__BAD_ASYNSRV: + strcat(pBuffer, "EL734__BAD_ASYNSRV"); + break; + default: + sprintf(pBuffer, "Unknown EL734 error %d", iErr); + break; + } +} - static void EL734Error2Text(char *pBuffer, int iErr) - { - strcpy(pBuffer,"ERROR: HW:"); - switch(iErr) - { - case EL734__BAD_ADR: - strcat(pBuffer,"EL734__BAD_ADR"); - break; - case EL734__BAD_BIND: - strcat(pBuffer,"EL734__BAD_BIND"); - break; - case EL734__BAD_CMD: - strcat(pBuffer,"EL734__BAD_CMD"); - break; - case EL734__BAD_CONNECT: - strcat(pBuffer,"EL734__BAD_CONNECT"); - break; - case EL734__BAD_FLUSH: - strcat(pBuffer,"EL734__BAD_FLUSH"); - break; - case EL734__BAD_HOST: - strcat(pBuffer,"EL734__BAD_HOST"); - break; - case EL734__BAD_ID: - strcat(pBuffer,"EL734__BAD_ID"); - break; - case EL734__BAD_ILLG: - strcat(pBuffer,"EL734__BAD_ILLG "); - - strcat(pBuffer,EL734_IllgText); - - break; - case EL734__BAD_LOC: - strcat(pBuffer,"EL734__BAD_LOC"); - break; - case EL734__BAD_MALLOC: - strcat(pBuffer,"EL734__BAD_MALLOC"); - break; - case EL734__BAD_NOT_BCD: - strcat(pBuffer,"EL734__BAD_NOT_BCD"); - break; - case EL734__BAD_OFL: - strcat(pBuffer,"EL734__BAD_OFL"); - break; - case EL734__BAD_PAR: - strcat(pBuffer,"EL734__BAD_PAR"); - break; - - case EL734__BAD_RECV: - strcat(pBuffer,"EL734__BAD_RECV"); - break; - case EL734__BAD_RECV_NET: - strcat(pBuffer,"EL734__BAD_RECV_NET"); - break; - case EL734__BAD_RECV_PIPE: - strcat(pBuffer,"EL734__BAD_RECV_PIPE"); - break; - case EL734__BAD_RECV_UNKN: - strcat(pBuffer,"EL734__BAD_RECV_UNKN"); - break; - case EL734__BAD_RECVLEN: - strcat(pBuffer,"EL734__BAD_RECVLEN"); - break; - case EL734__BAD_RECV1: - strcat(pBuffer,"EL734__BAD_RECV1"); - break; - case EL734__BAD_RECV1_NET: - strcat(pBuffer,"EL734__BAD_RECV1_NET"); - break; - case EL734__BAD_RECV1_PIPE: - strcat(pBuffer,"EL734__BAD_RECV1_PIPE"); - break; - case EL734__BAD_RNG: - strcat(pBuffer,"EL734__BAD_RNG"); - break; - case EL734__BAD_SEND: - strcat(pBuffer,"EL734__BAD_SEND"); - break; - case EL734__BAD_SEND_PIPE: - strcat(pBuffer,"EL734__BAD_SEND_PIPE"); - break; - case EL734__BAD_SEND_NET: - strcat(pBuffer,"EL734__BAD_SEND_NET"); - break; - case EL734__BAD_SEND_UNKN: - strcat(pBuffer,"EL734__BAD_SEND_UNKN"); - break; - case EL734__BAD_SENDLEN: - strcat(pBuffer,"EL734__BAD_SENDLEN"); - break; - case EL734__BAD_SOCKET: - strcat(pBuffer,"EL734__BAD_SOCKET"); - break; - case EL734__BAD_TMO: - strcat(pBuffer,"EL734__BAD_TMO"); - break; - case EL734__FORCED_CLOSED: - strcat(pBuffer,"EL734__FORCED_CLOSED"); - break; - case EL734__BAD_STP: - strcat(pBuffer, - "The motor is switched off at the motor controller"); - break; - case EL734__EMERG_STOP: - strcat(pBuffer, - "Emergency stop button depressed, please release"); - break; - case EL734__NOT_OPEN: - strcat(pBuffer,"EL734__NOT_OPEN"); - break; - case EL734__BAD_ASYNSRV: - strcat(pBuffer,"EL734__BAD_ASYNSRV"); - break; - default: - sprintf(pBuffer,"Unknown EL734 error %d",iErr); - break; - } - } - /*-------------------------------------------------------------------------*/ - static void GetErr(void *self, int *iCode, char *buffer, int iBufLen) - { - EL734Driv *pDriv; - char pBueffel[512]; - int iMSR, iOMSR, iSS; - int iRet, iFPC, iFRC; - int iErr; - float fPos; - char *pErr; - - assert(self); - - /* get EL734 error codes */ - pDriv = (EL734Driv *)self; - EL734_ErrInfo(&pErr,&iMSR,&iOMSR, &iSS); - if(iMSR != 0) - { - EL734Error2Text(pBueffel,iMSR); - strncpy(buffer,pBueffel,(iBufLen-1)); - *iCode = iMSR; - return; - } - else - { /* check status flag for addional errors */ - iRet = EL734_GetStatus(&(pDriv->EL734struct), - &iMSR, - &iOMSR, - &iFPC, - &iFRC, - &iSS, - &fPos); - if(iRet != 1) - { /* failure on this one, this has to be handled */ - EL734_ErrInfo(&pErr,&iMSR,&iOMSR, &iSS); - EL734Error2Text(pBueffel,iMSR); - strncpy(buffer,pBueffel,(iBufLen-1)); - *iCode = iMSR; - return; - - } - else - { - /* we really come down to looking at status flags */ - *iCode = EL734EncodeMSR(buffer,iBufLen,iMSR, iOMSR,iFPC,iFRC); - } - } - } +static void GetErr(void *self, int *iCode, char *buffer, int iBufLen) +{ + EL734Driv *pDriv; + char pBueffel[512]; + int iMSR, iOMSR, iSS; + int iRet, iFPC, iFRC; + int iErr; + float fPos; + char *pErr; + + assert(self); + + /* get EL734 error codes */ + pDriv = (EL734Driv *) self; + EL734_ErrInfo(&pErr, &iMSR, &iOMSR, &iSS); + if (iMSR != 0) { + EL734Error2Text(pBueffel, iMSR); + strncpy(buffer, pBueffel, (iBufLen - 1)); + *iCode = iMSR; + return; + } else { /* check status flag for addional errors */ + iRet = EL734_GetStatus(&(pDriv->EL734struct), + &iMSR, &iOMSR, &iFPC, &iFRC, &iSS, &fPos); + if (iRet != 1) { /* failure on this one, this has to be handled */ + EL734_ErrInfo(&pErr, &iMSR, &iOMSR, &iSS); + EL734Error2Text(pBueffel, iMSR); + strncpy(buffer, pBueffel, (iBufLen - 1)); + *iCode = iMSR; + return; + + } else { + /* we really come down to looking at status flags */ + *iCode = EL734EncodeMSR(buffer, iBufLen, iMSR, iOMSR, iFPC, iFRC); + } + } +} + /* ------------------------------------------------------------------------ Types of errors possible on EL734: @@ -333,624 +308,598 @@ Some things cannot be fixed. */ - - static int FixError(void *self, int iError, float fNew) - { - EL734Driv *pDriv; - int iRet; - char pBueffel[512]; - int iMSR, iOMSR, iSS; - float fPos; - - assert(self); - pDriv = (EL734Driv *)self; - sprintf(pBueffel,"EL734 : %s %d %d %d Problem:",pDriv->hostname, - pDriv->iPort, pDriv->iChannel, pDriv->iMotor); - - /* get & check MSR flags */ - - /* check for codes */ - switch(iError) - { - case 0: /* no error at all */ - return MOTOK; - case EL734__BAD_ID: /* ID */ - case EL734__BAD_ADR: /* ADR */ - case EL734__BAD_CMD: /* CMD */ - case EL734__BAD_ILLG: /* ILLG */ - case EL734__BAD_PAR: /* PAR */ - case EL734__BAD_TMO: /* timeout */ - SICSLogWrite(pBueffel,eHWError); - SICSLogWrite("BAD Command or dodgy RS-232",eHWError); - return MOTREDO; - case EL734__EMERG_STOP: - return MOTFAIL; - case EL734__BAD_STP: /* motor disabled by switch */ - return MOTFAIL; - break; - case EL734__BAD_RNG: /* RNG */ - case MSRONLIMIT: - SICSLogWrite(pBueffel,eHWError); - SICSLogWrite("Out of Range",eHWError); - return MOTFAIL; - case MSRBUSY: - return MOTREDO; - case MSRRUNFAULT: - SICSLogWrite(pBueffel,eHWError); - SICSLogWrite("------ RUN Fault in Controller ---- ",eHWError); - return MOTFAIL; - case MSRPOSFAULT: - SICSLogWrite(pBueffel,eHWError); - SICSLogWrite("------ POS Fault in Controller ---- ",eHWError); - return MOTFAIL; - case MSRDEADCUSHION: - SICSLogWrite(pBueffel,eHWError); - SICSLogWrite("------ Air cushion Fault in Controller ---- ",eHWError); - return MOTFAIL; - case MSRFAULT: - return MOTFAIL; - case MSRHALT: - case MSRSTOP: - return MOTFAIL; - case EL734__FORCED_CLOSED: - case EL734__NOT_OPEN: - iRet = EL734_Open(&(pDriv->EL734struct),pDriv->hostname, - pDriv->iPort,pDriv->iChannel, - pDriv->iMotor,"STPMC EL734"); - if(iRet != 1) - { - return MOTFAIL; - } - else - { - return MOTREDO; - } - break; - case EL734__BAD_OFL: - case EL734__BAD_LOC: /* LOocal mode */ - EL734_Close(&(pDriv->EL734struct),0); - iRet = EL734_Open(&(pDriv->EL734struct),pDriv->hostname, - pDriv->iPort,pDriv->iChannel, - pDriv->iMotor,"STPMC EL734"); - if(iRet != 1) - { - return MOTFAIL; - } - else - { - return MOTREDO; - } - break; +static int FixError(void *self, int iError, float fNew) +{ + EL734Driv *pDriv; + int iRet; + char pBueffel[512]; + int iMSR, iOMSR, iSS; + float fPos; + + assert(self); + pDriv = (EL734Driv *) self; + sprintf(pBueffel, "EL734 : %s %d %d %d Problem:", pDriv->hostname, + pDriv->iPort, pDriv->iChannel, pDriv->iMotor); + + /* get & check MSR flags */ + + + /* check for codes */ + switch (iError) { + case 0: /* no error at all */ + return MOTOK; + case EL734__BAD_ID: /* ID */ + case EL734__BAD_ADR: /* ADR */ + case EL734__BAD_CMD: /* CMD */ + case EL734__BAD_ILLG: /* ILLG */ + case EL734__BAD_PAR: /* PAR */ + case EL734__BAD_TMO: /* timeout */ + SICSLogWrite(pBueffel, eHWError); + SICSLogWrite("BAD Command or dodgy RS-232", eHWError); + return MOTREDO; + case EL734__EMERG_STOP: + return MOTFAIL; + case EL734__BAD_STP: /* motor disabled by switch */ + return MOTFAIL; + break; + case EL734__BAD_RNG: /* RNG */ + case MSRONLIMIT: + SICSLogWrite(pBueffel, eHWError); + SICSLogWrite("Out of Range", eHWError); + return MOTFAIL; + case MSRBUSY: + return MOTREDO; + case MSRRUNFAULT: + SICSLogWrite(pBueffel, eHWError); + SICSLogWrite("------ RUN Fault in Controller ---- ", eHWError); + return MOTFAIL; + case MSRPOSFAULT: + SICSLogWrite(pBueffel, eHWError); + SICSLogWrite("------ POS Fault in Controller ---- ", eHWError); + return MOTFAIL; + case MSRDEADCUSHION: + SICSLogWrite(pBueffel, eHWError); + SICSLogWrite("------ Air cushion Fault in Controller ---- ", eHWError); + return MOTFAIL; + case MSRFAULT: + return MOTFAIL; + case MSRHALT: + case MSRSTOP: + return MOTFAIL; + case EL734__FORCED_CLOSED: + case EL734__NOT_OPEN: + iRet = EL734_Open(&(pDriv->EL734struct), pDriv->hostname, + pDriv->iPort, pDriv->iChannel, + pDriv->iMotor, "STPMC EL734"); + if (iRet != 1) { + return MOTFAIL; + } else { + return MOTREDO; + } + break; + case EL734__BAD_OFL: + case EL734__BAD_LOC: /* LOocal mode */ + EL734_Close(&(pDriv->EL734struct), 0); + iRet = EL734_Open(&(pDriv->EL734struct), pDriv->hostname, + pDriv->iPort, pDriv->iChannel, + pDriv->iMotor, "STPMC EL734"); + if (iRet != 1) { + return MOTFAIL; + } else { + return MOTREDO; + } + break; /* case EL734__BAD_ASYNSRV: EL734_Close(&(pDriv->EL734struct),1); return MOTREDO; */ - default: - SICSLogWrite(pBueffel,eHWError); - SICSLogWrite("Network problem, trying to reopen",eHWError); - EL734_Close(&(pDriv->EL734struct),1); - iRet = EL734_Open(&(pDriv->EL734struct),pDriv->hostname, - pDriv->iPort,pDriv->iChannel, - pDriv->iMotor,"STPMC EL734"); - if(iRet != 1) - { - return MOTFAIL; - } - else - { - return MOTREDO; - } - } - - } -/*--------------------------------------------------------------------------*/ - static int Halt(void *self) - { - EL734Driv *pDriv; - int iRet; - char pBueffel[80]; - - assert(self); - pDriv = (EL734Driv *)self; - iRet = EL734_Stop(&(pDriv->EL734struct)); - if(iRet == 1) - { - return OKOK; + default: + SICSLogWrite(pBueffel, eHWError); + SICSLogWrite("Network problem, trying to reopen", eHWError); + EL734_Close(&(pDriv->EL734struct), 1); + iRet = EL734_Open(&(pDriv->EL734struct), pDriv->hostname, + pDriv->iPort, pDriv->iChannel, + pDriv->iMotor, "STPMC EL734"); + if (iRet != 1) { + return MOTFAIL; + } else { + return MOTREDO; } + } + +} + +/*--------------------------------------------------------------------------*/ +static int Halt(void *self) +{ + EL734Driv *pDriv; + int iRet; + char pBueffel[80]; + + assert(self); + pDriv = (EL734Driv *) self; + iRet = EL734_Stop(&(pDriv->EL734struct)); + if (iRet == 1) { + return OKOK; + } + return HWFault; +} + +/*--------------------------------------------------------------------------*/ +static int GetStat(void *self) +{ + EL734Driv *pDriv; + float fPos; + int iRet, iMSR, iOMSR, iFRC, iFPC, iSS; + int eRet; + int iTest; + char pBueffel[80]; + + assert(self); + + pDriv = (EL734Driv *) self; + iRet = EL734_GetStatus(&(pDriv->EL734struct), + &iMSR, &iOMSR, &iFPC, &iFRC, &iSS, &fPos); + if (iRet != 1) { return HWFault; - } -/*--------------------------------------------------------------------------*/ - static int GetStat(void *self) - { - EL734Driv *pDriv; - float fPos; - int iRet, iMSR, iOMSR, iFRC,iFPC, iSS; - int eRet; - int iTest; - char pBueffel[80]; - - assert(self); - - pDriv = (EL734Driv *)self; - iRet = EL734_GetStatus(&(pDriv->EL734struct), - &iMSR, - &iOMSR, - &iFPC, - &iFRC, - &iSS, - &fPos); - if(iRet != 1) - { - return HWFault; - } - - if(iMSR != 0) - { - pDriv->iMSR = iMSR; - } - - iTest = EL734AnalyzeMSR(iMSR,iOMSR); - switch(iTest) - { - case MSRDEADCUSHION: - case MSRONLIMIT: - case MSRREF: - case MSRHALT: - case MSRSTOP: - return HWFault; - break; - case MSRRUNFAULT: - case MSRPOSFAULT: - return HWPosFault; - break; - case MSRBUSY: - return HWBusy; - break; - case MSRFAULT: - return HWWarn; - break; - default: - return HWIdle; - break; - } } -/*--------------------------------------------------------------------------*/ - void KillEL734(void *self) - { - EL734Driv *pDriv; - - assert(self); - pDriv = (EL734Driv *)self; - - EL734_Close(&(pDriv->EL734struct),0); - if(pDriv->hostname) - free(pDriv->hostname); + if (iMSR != 0) { + pDriv->iMSR = iMSR; } + iTest = EL734AnalyzeMSR(iMSR, iOMSR); + switch (iTest) { + case MSRDEADCUSHION: + case MSRONLIMIT: + case MSRREF: + case MSRHALT: + case MSRSTOP: + return HWFault; + break; + case MSRRUNFAULT: + case MSRPOSFAULT: + return HWPosFault; + break; + case MSRBUSY: + return HWBusy; + break; + case MSRFAULT: + return HWWarn; + break; + default: + return HWIdle; + break; + } +} + +/*--------------------------------------------------------------------------*/ +void KillEL734(void *self) +{ + EL734Driv *pDriv; + + assert(self); + pDriv = (EL734Driv *) self; + + EL734_Close(&(pDriv->EL734struct), 0); + if (pDriv->hostname) + free(pDriv->hostname); +} + /*---------------------------------------------------------------------------*/ - static EL734Driv *MakeEL734(char *hostname, int iPort, int iChannel, - int iMotor) - { - EL734Driv *pDriv = NULL; +static EL734Driv *MakeEL734(char *hostname, int iPort, int iChannel, + int iMotor) +{ + EL734Driv *pDriv = NULL; + + int iError; + char pBueffel[80]; + char *pErr; + int iRet; + int iDummy; + + /* create a new struct */ + pDriv = (EL734Driv *) malloc(sizeof(EL734Driv)); + if (!pDriv) { + return NULL; + } + memset(pDriv, 0, sizeof(EL734Driv)); + + /* fill in some of the data entered */ + pDriv->hostname = strdup(hostname); + pDriv->iPort = iPort; + pDriv->iChannel = iChannel; + pDriv->iMotor = iMotor; + pDriv->name = strdup("EL734"); + + /* try opening the motor */ + iRet = EL734_Open(&(pDriv->EL734struct), hostname, iPort, + iChannel, iMotor, "STPMC EL734"); + if (iRet != 1) { + EL734_ErrInfo(&pErr, &iError, &iRet, &iDummy); + KillEL734((void *) pDriv); + return NULL; + } + + /* now get the limits */ + EL734_GetLimits(&(pDriv->EL734struct), &(pDriv->fLower), + &(pDriv->fUpper)); + + + /* initialise the function pointers */ + pDriv->GetPosition = GetPos; + pDriv->RunTo = Run; + pDriv->GetError = GetErr; + pDriv->GetStatus = GetStat; + pDriv->Halt = Halt; + pDriv->TryAndFixIt = FixError; + pDriv->KillPrivate = KillEL734; + + return pDriv; +} - int iError; - char pBueffel[80]; - char *pErr; - int iRet; - int iDummy; - - /* create a new struct */ - pDriv = (EL734Driv *)malloc(sizeof(EL734Driv)); - if(!pDriv) - { - return NULL; - } - memset(pDriv,0,sizeof(EL734Driv)); - - /* fill in some of the data entered */ - pDriv->hostname = strdup(hostname); - pDriv->iPort = iPort; - pDriv->iChannel = iChannel; - pDriv->iMotor = iMotor; - pDriv->name = strdup("EL734"); - - /* try opening the motor */ - iRet = EL734_Open(&(pDriv->EL734struct), hostname,iPort, - iChannel,iMotor,"STPMC EL734"); - if(iRet != 1) - { - EL734_ErrInfo(&pErr,&iError,&iRet, &iDummy); - KillEL734((void *)pDriv); - return NULL; - } - - /* now get the limits */ - EL734_GetLimits(&(pDriv->EL734struct),&(pDriv->fLower), - &(pDriv->fUpper)); - - - /* initialise the function pointers */ - pDriv->GetPosition = GetPos; - pDriv->RunTo = Run; - pDriv->GetError = GetErr; - pDriv->GetStatus = GetStat; - pDriv->Halt = Halt; - pDriv->TryAndFixIt = FixError; - pDriv->KillPrivate = KillEL734; - - return pDriv; - } /*-------------------------------------------------------------------------- interpreting the driver parameters is up to the driver, this below inplements just this */ - MotorDriver *CreateEL734(SConnection *pCon, int argc, char *argv[]) - { - EL734Driv *pDriv = NULL; - TokenList *pList = NULL; - TokenList *pCurrent; - char *hostname; - int iPort, iChannel, iMotor; - char pBueffel[512]; - - assert(pCon); - - /* split arguments */ - pList = SplitArguments(argc,argv); - if(!pList) - { - SCWrite(pCon,"Error parsing arguments",eError); - return NULL; - } - - /* first must be hostname */ - pCurrent = pList; - if(pCurrent->Type != eText) - { - sprintf(pBueffel,"EL734: Expected hostname but got --> %s <--", - pCurrent->text); - SCWrite(pCon,pBueffel,eError); - DeleteTokenList(pList); - return NULL; - } - hostname = pCurrent->text; - - /* next should be port */ - pCurrent = pCurrent->pNext; - if(!pCurrent) - { - SCWrite(pCon,"EL734: Insufficient number of arguments",eError); - DeleteTokenList(pList); - return NULL; - } - if(pCurrent->Type != eInt) - { - sprintf(pBueffel,"EL734: Expected Integer as Port number, got --> %s <--", - pCurrent->text); - SCWrite(pCon,pBueffel,eError); - DeleteTokenList(pList); - return NULL; - } - iPort = pCurrent->iVal; +MotorDriver *CreateEL734(SConnection * pCon, int argc, char *argv[]) +{ + EL734Driv *pDriv = NULL; + TokenList *pList = NULL; + TokenList *pCurrent; + char *hostname; + int iPort, iChannel, iMotor; + char pBueffel[512]; - - /* next should be Channel number */ - pCurrent = pCurrent->pNext; - if(!pCurrent) - { - SCWrite(pCon,"EL734: Insufficient number of arguments",eError); - DeleteTokenList(pList); - return NULL; - } - if(pCurrent->Type != eInt) - { - sprintf(pBueffel,"EL734: Expected Integer as channel number, got --> %s <--", - pCurrent->text); - SCWrite(pCon,pBueffel,eError); - DeleteTokenList(pList); - return NULL; - } - iChannel = pCurrent->iVal; - - /* finally motor number */ - pCurrent = pCurrent->pNext; - if(!pCurrent) - { - - SCWrite(pCon,"EL734: Insufficient number of arguments",eError); - DeleteTokenList(pList); - return NULL; - } - if(pCurrent->Type != eInt) - { - sprintf(pBueffel,"EL734: Expected Integer as motor number, got --> %s <--", - pCurrent->text); - SCWrite(pCon,pBueffel,eError); - DeleteTokenList(pList); - return NULL; - } - iMotor = pCurrent->iVal; - - - /* finally initialize driver */ - pDriv = MakeEL734(hostname,iPort,iChannel,iMotor); - if(!pDriv) - { - SCWrite(pCon,"EL734: error opening motor, check adress",eError); - pDriv = NULL; - } - - /* clean up */ - DeleteTokenList(pList); - return (MotorDriver *)pDriv; + assert(pCon); + + /* split arguments */ + pList = SplitArguments(argc, argv); + if (!pList) { + SCWrite(pCon, "Error parsing arguments", eError); + return NULL; } + + /* first must be hostname */ + pCurrent = pList; + if (pCurrent->Type != eText) { + sprintf(pBueffel, "EL734: Expected hostname but got --> %s <--", + pCurrent->text); + SCWrite(pCon, pBueffel, eError); + DeleteTokenList(pList); + return NULL; + } + hostname = pCurrent->text; + + /* next should be port */ + pCurrent = pCurrent->pNext; + if (!pCurrent) { + SCWrite(pCon, "EL734: Insufficient number of arguments", eError); + DeleteTokenList(pList); + return NULL; + } + if (pCurrent->Type != eInt) { + sprintf(pBueffel, + "EL734: Expected Integer as Port number, got --> %s <--", + pCurrent->text); + SCWrite(pCon, pBueffel, eError); + DeleteTokenList(pList); + return NULL; + } + iPort = pCurrent->iVal; + + + /* next should be Channel number */ + pCurrent = pCurrent->pNext; + if (!pCurrent) { + SCWrite(pCon, "EL734: Insufficient number of arguments", eError); + DeleteTokenList(pList); + return NULL; + } + if (pCurrent->Type != eInt) { + sprintf(pBueffel, + "EL734: Expected Integer as channel number, got --> %s <--", + pCurrent->text); + SCWrite(pCon, pBueffel, eError); + DeleteTokenList(pList); + return NULL; + } + iChannel = pCurrent->iVal; + + /* finally motor number */ + pCurrent = pCurrent->pNext; + if (!pCurrent) { + + SCWrite(pCon, "EL734: Insufficient number of arguments", eError); + DeleteTokenList(pList); + return NULL; + } + if (pCurrent->Type != eInt) { + sprintf(pBueffel, + "EL734: Expected Integer as motor number, got --> %s <--", + pCurrent->text); + SCWrite(pCon, pBueffel, eError); + DeleteTokenList(pList); + return NULL; + } + iMotor = pCurrent->iVal; + + + /* finally initialize driver */ + pDriv = MakeEL734(hostname, iPort, iChannel, iMotor); + if (!pDriv) { + SCWrite(pCon, "EL734: error opening motor, check adress", eError); + pDriv = NULL; + } + + /* clean up */ + DeleteTokenList(pList); + return (MotorDriver *) pDriv; +} + /*------------------------------------------------------------------------- Stolen from David and modified to return an integer error code as well */ - static int EL734EncodeMSR (char *text, int text_len, - int msr, - int ored_msr, - int fp_cntr, - int fr_cntr) { - int len; - char my_text[132]; - char my_text_0[32]; - int iRet = 0; +static int EL734EncodeMSR(char *text, int text_len, + int msr, int ored_msr, int fp_cntr, int fr_cntr) +{ + int len; + char my_text[132]; + char my_text_0[32]; + int iRet = 0; - if (msr == 0) { - ored_msr = ored_msr & ~(MSR__BUSY); /* Zero "Busy" bit */ - if (ored_msr == MSR__OK) { - StrJoin (text, text_len, "Status, MSR = Idle. Positioned OK.", ""); - }else { - if ((ored_msr & MSR__OK) != 0) { - StrJoin (text, text_len, "Status, MSR = Idle. Positioned OK. ", ""); - }else { - StrJoin (text, text_len, "Status, MSR = Idle. ", ""); - } - if ((ored_msr & MSR__REF_OK) != 0) { - StrJoin (my_text, sizeof (my_text), text, ""); - StrJoin (text, text_len, my_text, "Ref. Pos'n OK. "); - } - if ((ored_msr & MSR__LIM_ERR) != 0) { - StrJoin (my_text, sizeof (my_text), text, ""); - StrJoin (text, text_len, my_text, "Limit Switch Problem. "); - iRet = MSRONLIMIT; - } - if ((ored_msr & MSR__AC_FAIL) != 0) { - StrJoin (my_text, sizeof (my_text), text, ""); - StrJoin (text, text_len, my_text, "Air-Cushion Error. "); - iRet = MSRDEADCUSHION; - } - if ((ored_msr & MSR__REF_FAIL) != 0) { - StrJoin (my_text, sizeof (my_text), text, ""); - StrJoin (text, text_len, my_text, "Ref. Pos'n Fail. "); - } - if ((ored_msr & MSR__POS_FAIL) != 0) { - StrJoin (my_text, sizeof (my_text), text, ""); - StrJoin (text, text_len, my_text, "Pos'n Fail. "); - iRet = MSRPOSFAULT; - } - if ((ored_msr & MSR__POS_FAULT) != 0) { - StrJoin (my_text, sizeof (my_text), text, ""); - if (fp_cntr == 1) { - StrJoin (text, text_len, my_text, "1 Pos'n Fault. "); - }else { - sprintf (my_text_0, "%d Pos'n Faults. ", fp_cntr); - StrJoin (text, text_len, my_text, my_text_0); - } - } - if ((ored_msr & MSR__RUN_FAIL) != 0) { - StrJoin (my_text, sizeof (my_text), text, ""); - StrJoin (text, text_len, my_text, "Run Fail. "); - iRet = MSRRUNFAULT; - } - if ((ored_msr & MSR__RUN_FAULT) != 0) { - StrJoin (my_text, sizeof (my_text), text, ""); - if (fr_cntr == 1) { - StrJoin (text, text_len, my_text, "1 Run Fault. "); - }else { - sprintf (my_text_0, "%d Run Faults. ", fr_cntr); - StrJoin (text, text_len, my_text, my_text_0); - } - } - if ((ored_msr & MSR__HALT) != 0) { - StrJoin (my_text, sizeof (my_text), text, ""); - StrJoin (text, text_len, my_text, "Halt. "); - iRet = MSRHALT; - } - if ((ored_msr & MSR__HI_LIM) != 0) { - StrJoin (my_text, sizeof (my_text), text, ""); - StrJoin (text, text_len, my_text, "Hit HiLim. "); - iRet = MSRONLIMIT; - } - if ((ored_msr & MSR__LO_LIM) != 0) { - StrJoin (my_text, sizeof (my_text), text, ""); - StrJoin (text, text_len, my_text, "Hit LoLim. "); - iRet = MSRONLIMIT; - } - if ((ored_msr & MSR__STOPPED) != 0) { - StrJoin (my_text, sizeof (my_text), text, ""); - StrJoin (text, text_len, my_text, "Stopped. "); - iRet = MSRSTOP; - } + if (msr == 0) { + ored_msr = ored_msr & ~(MSR__BUSY); /* Zero "Busy" bit */ + if (ored_msr == MSR__OK) { + StrJoin(text, text_len, "Status, MSR = Idle. Positioned OK.", ""); + } else { + if ((ored_msr & MSR__OK) != 0) { + StrJoin(text, text_len, "Status, MSR = Idle. Positioned OK. ", ""); + } else { + StrJoin(text, text_len, "Status, MSR = Idle. ", ""); } - }else if ((msr & ~(0x2fff)) != 0) { - StrJoin (text, text_len, "Status, MSR = ??", ""); - }else { - sprintf (my_text, "%#x ", msr); - StrJoin (text, text_len, "Status, MSR = ", my_text); - if ((msr & MSR__LIM_ERR) != 0) { - StrJoin (my_text, sizeof (my_text), text, ""); - StrJoin (text, text_len, my_text, "Limit Switch Problem/"); + if ((ored_msr & MSR__REF_OK) != 0) { + StrJoin(my_text, sizeof(my_text), text, ""); + StrJoin(text, text_len, my_text, "Ref. Pos'n OK. "); + } + if ((ored_msr & MSR__LIM_ERR) != 0) { + StrJoin(my_text, sizeof(my_text), text, ""); + StrJoin(text, text_len, my_text, "Limit Switch Problem. "); iRet = MSRONLIMIT; } - if ((msr & MSR__AC_FAIL) != 0) { - StrJoin (my_text, sizeof (my_text), text, ""); - StrJoin (text, text_len, my_text, "Air-Cushion Error/"); + if ((ored_msr & MSR__AC_FAIL) != 0) { + StrJoin(my_text, sizeof(my_text), text, ""); + StrJoin(text, text_len, my_text, "Air-Cushion Error. "); iRet = MSRDEADCUSHION; } - if ((msr & MSR__REF_FAIL) != 0) { - StrJoin (my_text, sizeof (my_text), text, ""); - StrJoin (text, text_len, my_text, "Ref. Pos'n Fail/"); + if ((ored_msr & MSR__REF_FAIL) != 0) { + StrJoin(my_text, sizeof(my_text), text, ""); + StrJoin(text, text_len, my_text, "Ref. Pos'n Fail. "); } - if ((msr & MSR__POS_FAIL) != 0) { - StrJoin (my_text, sizeof (my_text), text, ""); - StrJoin (text, text_len, my_text, "Pos'n Fail/"); + if ((ored_msr & MSR__POS_FAIL) != 0) { + StrJoin(my_text, sizeof(my_text), text, ""); + StrJoin(text, text_len, my_text, "Pos'n Fail. "); iRet = MSRPOSFAULT; } - if ((msr & MSR__POS_FAULT) != 0) { - StrJoin (my_text, sizeof (my_text), text, ""); - StrJoin (text, text_len, my_text, "Pos'n Fault/"); + if ((ored_msr & MSR__POS_FAULT) != 0) { + StrJoin(my_text, sizeof(my_text), text, ""); + if (fp_cntr == 1) { + StrJoin(text, text_len, my_text, "1 Pos'n Fault. "); + } else { + sprintf(my_text_0, "%d Pos'n Faults. ", fp_cntr); + StrJoin(text, text_len, my_text, my_text_0); + } } - if ((msr & MSR__RUN_FAIL) != 0) { - StrJoin (my_text, sizeof (my_text), text, ""); - StrJoin (text, text_len, my_text, "Run Fail/"); + if ((ored_msr & MSR__RUN_FAIL) != 0) { + StrJoin(my_text, sizeof(my_text), text, ""); + StrJoin(text, text_len, my_text, "Run Fail. "); iRet = MSRRUNFAULT; } - if ((msr & MSR__RUN_FAULT) != 0) { - StrJoin (my_text, sizeof (my_text), text, ""); - StrJoin (text, text_len, my_text, "Run Fault/"); + if ((ored_msr & MSR__RUN_FAULT) != 0) { + StrJoin(my_text, sizeof(my_text), text, ""); + if (fr_cntr == 1) { + StrJoin(text, text_len, my_text, "1 Run Fault. "); + } else { + sprintf(my_text_0, "%d Run Faults. ", fr_cntr); + StrJoin(text, text_len, my_text, my_text_0); + } } - if ((msr & MSR__HALT) != 0) { - StrJoin (my_text, sizeof (my_text), text, ""); - StrJoin (text, text_len, my_text, "Halt/"); + if ((ored_msr & MSR__HALT) != 0) { + StrJoin(my_text, sizeof(my_text), text, ""); + StrJoin(text, text_len, my_text, "Halt. "); iRet = MSRHALT; } - if ((msr & MSR__HI_LIM) != 0) { - StrJoin (my_text, sizeof (my_text), text, ""); - StrJoin (text, text_len, my_text, "Hit HiLim/"); + if ((ored_msr & MSR__HI_LIM) != 0) { + StrJoin(my_text, sizeof(my_text), text, ""); + StrJoin(text, text_len, my_text, "Hit HiLim. "); iRet = MSRONLIMIT; } - if ((msr & MSR__LO_LIM) != 0) { - StrJoin (my_text, sizeof (my_text), text, ""); - StrJoin (text, text_len, my_text, "Hit LoLim/"); + if ((ored_msr & MSR__LO_LIM) != 0) { + StrJoin(my_text, sizeof(my_text), text, ""); + StrJoin(text, text_len, my_text, "Hit LoLim. "); iRet = MSRONLIMIT; } - if ((msr & MSR__STOPPED) != 0) { - StrJoin (my_text, sizeof (my_text), text, ""); - StrJoin (text, text_len, my_text, "Stopped/"); + if ((ored_msr & MSR__STOPPED) != 0) { + StrJoin(my_text, sizeof(my_text), text, ""); + StrJoin(text, text_len, my_text, "Stopped. "); iRet = MSRSTOP; } - if ((msr & MSR__REF_OK) != 0) { - StrJoin (my_text, sizeof (my_text), text, ""); - StrJoin (text, text_len, my_text, "Ref. Pos'n OK/"); - } - if ((msr & MSR__OK) != 0) { - StrJoin (my_text, sizeof (my_text), text, ""); - StrJoin (text, text_len, my_text, "OK/"); - } - if ((msr & MSR__BUSY) != 0) { - StrJoin (my_text, sizeof (my_text), text, ""); - StrJoin (text, text_len, my_text, "Busy/"); - } - len = strlen (text); - text[len-1] = '\0'; } - return iRet; + } else if ((msr & ~(0x2fff)) != 0) { + StrJoin(text, text_len, "Status, MSR = ??", ""); + } else { + sprintf(my_text, "%#x ", msr); + StrJoin(text, text_len, "Status, MSR = ", my_text); + if ((msr & MSR__LIM_ERR) != 0) { + StrJoin(my_text, sizeof(my_text), text, ""); + StrJoin(text, text_len, my_text, "Limit Switch Problem/"); + iRet = MSRONLIMIT; + } + if ((msr & MSR__AC_FAIL) != 0) { + StrJoin(my_text, sizeof(my_text), text, ""); + StrJoin(text, text_len, my_text, "Air-Cushion Error/"); + iRet = MSRDEADCUSHION; + } + if ((msr & MSR__REF_FAIL) != 0) { + StrJoin(my_text, sizeof(my_text), text, ""); + StrJoin(text, text_len, my_text, "Ref. Pos'n Fail/"); + } + if ((msr & MSR__POS_FAIL) != 0) { + StrJoin(my_text, sizeof(my_text), text, ""); + StrJoin(text, text_len, my_text, "Pos'n Fail/"); + iRet = MSRPOSFAULT; + } + if ((msr & MSR__POS_FAULT) != 0) { + StrJoin(my_text, sizeof(my_text), text, ""); + StrJoin(text, text_len, my_text, "Pos'n Fault/"); + } + if ((msr & MSR__RUN_FAIL) != 0) { + StrJoin(my_text, sizeof(my_text), text, ""); + StrJoin(text, text_len, my_text, "Run Fail/"); + iRet = MSRRUNFAULT; + } + if ((msr & MSR__RUN_FAULT) != 0) { + StrJoin(my_text, sizeof(my_text), text, ""); + StrJoin(text, text_len, my_text, "Run Fault/"); + } + if ((msr & MSR__HALT) != 0) { + StrJoin(my_text, sizeof(my_text), text, ""); + StrJoin(text, text_len, my_text, "Halt/"); + iRet = MSRHALT; + } + if ((msr & MSR__HI_LIM) != 0) { + StrJoin(my_text, sizeof(my_text), text, ""); + StrJoin(text, text_len, my_text, "Hit HiLim/"); + iRet = MSRONLIMIT; + } + if ((msr & MSR__LO_LIM) != 0) { + StrJoin(my_text, sizeof(my_text), text, ""); + StrJoin(text, text_len, my_text, "Hit LoLim/"); + iRet = MSRONLIMIT; + } + if ((msr & MSR__STOPPED) != 0) { + StrJoin(my_text, sizeof(my_text), text, ""); + StrJoin(text, text_len, my_text, "Stopped/"); + iRet = MSRSTOP; + } + if ((msr & MSR__REF_OK) != 0) { + StrJoin(my_text, sizeof(my_text), text, ""); + StrJoin(text, text_len, my_text, "Ref. Pos'n OK/"); + } + if ((msr & MSR__OK) != 0) { + StrJoin(my_text, sizeof(my_text), text, ""); + StrJoin(text, text_len, my_text, "OK/"); + } + if ((msr & MSR__BUSY) != 0) { + StrJoin(my_text, sizeof(my_text), text, ""); + StrJoin(text, text_len, my_text, "Busy/"); + } + len = strlen(text); + text[len - 1] = '\0'; } + return iRet; +} + /*-------------------------------------------------------------------------*/ - static int EL734AnalyzeMSR(int msr,int ored_msr) - { - int iRet = 0; +static int EL734AnalyzeMSR(int msr, int ored_msr) +{ + int iRet = 0; /* this means the motor is done */ - if (msr == 0) { - ored_msr = ored_msr & ~(MSR__BUSY); /* Zero "Busy" bit */ - if (ored_msr == MSR__OK) { - iRet = MSROK; - }else { - if ((ored_msr & MSR__OK) != 0) { - iRet = MSROK; - }else { - iRet = MSROK; - } - if ((ored_msr & MSR__REF_OK) != 0) { - iRet = MSROK; - } - if ((ored_msr & MSR__LIM_ERR) != 0) { - return MSRONLIMIT; - } - if ((ored_msr & MSR__AC_FAIL) != 0) { - return MSRDEADCUSHION; - } - if ((ored_msr & MSR__REF_FAIL) != 0) { - iRet = MSRREF; - } - if ((ored_msr & MSR__POS_FAIL) != 0) { - return MSRPOSFAULT; - } - if ((ored_msr & MSR__POS_FAULT) != 0) { - iRet = MSRFAULT; - } - if ((ored_msr & MSR__RUN_FAIL) != 0) { - return MSRRUNFAULT; - } - if ((ored_msr & MSR__RUN_FAULT) != 0) { - iRet = MSRFAULT; - } - if ((ored_msr & MSR__HALT) != 0) { - return MSRHALT; - } - if ((ored_msr & MSR__HI_LIM) != 0) { - return MSRONLIMIT; - } - if ((ored_msr & MSR__LO_LIM) != 0) { - return MSRONLIMIT; - } - if ((ored_msr & MSR__STOPPED) != 0) { - return MSRSTOP; - } - } - /* the motor is still fighting along */ - }else if ((msr & ~(0x2fff)) != 0) { + if (msr == 0) { + ored_msr = ored_msr & ~(MSR__BUSY); /* Zero "Busy" bit */ + if (ored_msr == MSR__OK) { iRet = MSROK; - }else { - if ((msr & MSR__LIM_ERR) != 0) { + } else { + if ((ored_msr & MSR__OK) != 0) { + iRet = MSROK; + } else { + iRet = MSROK; + } + if ((ored_msr & MSR__REF_OK) != 0) { + iRet = MSROK; + } + if ((ored_msr & MSR__LIM_ERR) != 0) { return MSRONLIMIT; } - if ((msr & MSR__AC_FAIL) != 0) { + if ((ored_msr & MSR__AC_FAIL) != 0) { return MSRDEADCUSHION; } - if ((msr & MSR__REF_FAIL) != 0) { + if ((ored_msr & MSR__REF_FAIL) != 0) { iRet = MSRREF; } - if ((msr & MSR__POS_FAIL) != 0) { + if ((ored_msr & MSR__POS_FAIL) != 0) { return MSRPOSFAULT; } - if ((msr & MSR__POS_FAULT) != 0) { + if ((ored_msr & MSR__POS_FAULT) != 0) { iRet = MSRFAULT; } - if ((msr & MSR__RUN_FAIL) != 0) { + if ((ored_msr & MSR__RUN_FAIL) != 0) { return MSRRUNFAULT; } - if ((msr & MSR__RUN_FAULT) != 0) { + if ((ored_msr & MSR__RUN_FAULT) != 0) { iRet = MSRFAULT; } - if ((msr & MSR__HALT) != 0) { + if ((ored_msr & MSR__HALT) != 0) { return MSRHALT; } - if ((msr & MSR__HI_LIM) != 0) { + if ((ored_msr & MSR__HI_LIM) != 0) { return MSRONLIMIT; } - if ((msr & MSR__LO_LIM) != 0) { + if ((ored_msr & MSR__LO_LIM) != 0) { return MSRONLIMIT; } - if ((msr & MSR__STOPPED) != 0) { + if ((ored_msr & MSR__STOPPED) != 0) { return MSRSTOP; } - if ((msr & MSR__REF_OK) != 0) { - iRet = MSROK; - } - if ((msr & MSR__OK) != 0) { - iRet = MSROK; - } - if ((msr & MSR__BUSY) != 0) { - iRet = MSRBUSY; - } } - return iRet; + /* the motor is still fighting along */ + } else if ((msr & ~(0x2fff)) != 0) { + iRet = MSROK; + } else { + if ((msr & MSR__LIM_ERR) != 0) { + return MSRONLIMIT; + } + if ((msr & MSR__AC_FAIL) != 0) { + return MSRDEADCUSHION; + } + if ((msr & MSR__REF_FAIL) != 0) { + iRet = MSRREF; + } + if ((msr & MSR__POS_FAIL) != 0) { + return MSRPOSFAULT; + } + if ((msr & MSR__POS_FAULT) != 0) { + iRet = MSRFAULT; + } + if ((msr & MSR__RUN_FAIL) != 0) { + return MSRRUNFAULT; + } + if ((msr & MSR__RUN_FAULT) != 0) { + iRet = MSRFAULT; + } + if ((msr & MSR__HALT) != 0) { + return MSRHALT; + } + if ((msr & MSR__HI_LIM) != 0) { + return MSRONLIMIT; + } + if ((msr & MSR__LO_LIM) != 0) { + return MSRONLIMIT; + } + if ((msr & MSR__STOPPED) != 0) { + return MSRSTOP; + } + if ((msr & MSR__REF_OK) != 0) { + iRet = MSROK; + } + if ((msr & MSR__OK) != 0) { + iRet = MSROK; + } + if ((msr & MSR__BUSY) != 0) { + iRet = MSRBUSY; + } } - - + return iRet; +} diff --git a/el734hp.c b/el734hp.c index ac9ce9c..5f8020c 100644 --- a/el734hp.c +++ b/el734hp.c @@ -28,39 +28,37 @@ The motor driver structure. Please note that the first set of fields has be identical with the fields of AbstractModriv in ../modriv.h ------------------------------------------------------------------------*/ - typedef struct __MoDriv { - /* general motor driver interface - fields. REQUIRED! - */ - float fUpper; /* upper limit */ - float fLower; /* lower limit */ - char *name; - int (*GetPosition)(void *self,float *fPos); - int (*RunTo)(void *self, float fNewVal); - int (*GetStatus)(void *self); - void (*GetError)(void *self, int *iCode, char *buffer, int iBufLen); - int (*TryAndFixIt)(void *self,int iError, float fNew); - int (*Halt)(void *self); - int (*GetDriverPar)(void *self, char *name, - float *value); - int (*SetDriverPar)(void *self,SConnection *pCon, - char *name, float newValue); - void (*ListDriverPar)(void *self, char *motorName, - SConnection *pCon); - void (*KillPrivate)(void *self); - - - /* EL-734 specific fields */ - prs232 controller; - int iMotor; - float lastValue; - int errorCode; - int oredMsr; - int posCount; - int runCount; - char errorReply[80]; - time_t valueExpiry; - } EL734Driv, *pEL734Driv; +typedef struct __MoDriv { + /* general motor driver interface + fields. REQUIRED! + */ + float fUpper; /* upper limit */ + float fLower; /* lower limit */ + char *name; + int (*GetPosition) (void *self, float *fPos); + int (*RunTo) (void *self, float fNewVal); + int (*GetStatus) (void *self); + void (*GetError) (void *self, int *iCode, char *buffer, int iBufLen); + int (*TryAndFixIt) (void *self, int iError, float fNew); + int (*Halt) (void *self); + int (*GetDriverPar) (void *self, char *name, float *value); + int (*SetDriverPar) (void *self, SConnection * pCon, + char *name, float newValue); + void (*ListDriverPar) (void *self, char *motorName, SConnection * pCon); + void (*KillPrivate) (void *self); + + + /* EL-734 specific fields */ + prs232 controller; + int iMotor; + float lastValue; + int errorCode; + int oredMsr; + int posCount; + int runCount; + char errorReply[80]; + time_t valueExpiry; +} EL734Driv, *pEL734Driv; /*------------------- error codes ----------------------------------*/ #define BADADR -1 #define BADBSY -2 @@ -72,7 +70,7 @@ #define BADSTP -8 #define BADEMERG -9 #define LOWLIM -10 -#define HILIM -11 +#define HILIM -11 #define RUNFAULT -12 #define POSFAULT -13 #define BADCUSHION -14 @@ -83,38 +81,39 @@ line even after releasing the emergency stop button --------------------------------------------------------------------*/ static int transactEL734(prs232 self, void *send, int sendLen, - void *reply, int replylen){ + void *reply, int replylen) +{ int status, len, oldTimeout; char *pReply = NULL; /* - try to read away rubbish on the line first - */ + try to read away rubbish on the line first + */ oldTimeout = getRS232Timeout(self); - setRS232Timeout(self,0); - if(availableRS232(self)){ + setRS232Timeout(self, 0); + if (availableRS232(self)) { len = replylen; - readRS232(self,reply,&len); + readRS232(self, reply, &len); } - setRS232Timeout(self,oldTimeout); + setRS232Timeout(self, oldTimeout); /* - Actually do something. Some controllers send one erroneus *ES when the - emergency stop had been released. Therefore we believe an emergency stop - message only at the second try. This is the logic below. - */ - status = transactRS232(self,send,sendLen,reply,replylen); - if(status >= 1){ - pReply = (char *)reply; - if(strstr(pReply,"*ES") != NULL){ - if(availableRS232(self)){ - len = replylen; - readRS232TillTerm(self,reply,&len); + Actually do something. Some controllers send one erroneus *ES when the + emergency stop had been released. Therefore we believe an emergency stop + message only at the second try. This is the logic below. + */ + status = transactRS232(self, send, sendLen, reply, replylen); + if (status >= 1) { + pReply = (char *) reply; + if (strstr(pReply, "*ES") != NULL) { + if (availableRS232(self)) { + len = replylen; + readRS232TillTerm(self, reply, &len); } - status = transactRS232(self,send,sendLen,reply,replylen); - if(status >= 1){ - return 1; + status = transactRS232(self, send, sendLen, reply, replylen); + if (status >= 1) { + return 1; } } else { return 1; @@ -122,306 +121,324 @@ static int transactEL734(prs232 self, void *send, int sendLen, } else { return status; } - return 0; /* not reached */ + return 0; /* not reached */ } + /*------------------------------------------------------------------- If we get an empty reply when we expect some response data, then, maybe, the controller has sent us "\r*ES\r". Therefore this checks on empty messages if there is some more, i.e: the *ES --------------------------------------------------------------------*/ -static void checkEmpty(pEL734Driv self, char *pReply, int *replylen){ +static void checkEmpty(pEL734Driv self, char *pReply, int *replylen) +{ int oldTimeout; - if(strlen(pReply) < 1) { + if (strlen(pReply) < 1) { oldTimeout = getRS232Timeout(self->controller); - setRS232Timeout(self->controller,0); - if(availableRS232(self->controller)){ - readRS232(self->controller,pReply,replylen); + setRS232Timeout(self->controller, 0); + if (availableRS232(self->controller)) { + readRS232(self->controller, pReply, replylen); } - setRS232Timeout(self->controller,oldTimeout); + setRS232Timeout(self->controller, oldTimeout); } } + /*--------------------------------------------------------------------*/ -static int checkResponse(pEL734Driv self, char *pReply){ +static int checkResponse(pEL734Driv self, char *pReply) +{ /* - error messages start with ?, if none we are done - */ - if(strstr(pReply,"?") == NULL && strstr(pReply,"*") == NULL){ + error messages start with ?, if none we are done + */ + if (strstr(pReply, "?") == NULL && strstr(pReply, "*") == NULL) { return 1; } strtolower(pReply); - if(strstr(pReply,"?adr") != NULL){ + if (strstr(pReply, "?adr") != NULL) { self->errorCode = BADADR; - } else if(strstr(pReply,"?bsy") != NULL){ + } else if (strstr(pReply, "?bsy") != NULL) { self->errorCode = BADBSY; - } else if(strstr(pReply,"?cmd") != NULL){ + } else if (strstr(pReply, "?cmd") != NULL) { self->errorCode = BADCMD; - } else if(strstr(pReply,"?loc") != NULL){ + } else if (strstr(pReply, "?loc") != NULL) { self->errorCode = BADLOC; - } else if(strstr(pReply,"?par") != NULL){ + } else if (strstr(pReply, "?par") != NULL) { self->errorCode = BADPAR; - } else if(strstr(pReply,"?rng") != NULL){ + } else if (strstr(pReply, "?rng") != NULL) { self->errorCode = BADRNG; - }else if(strstr(pReply,"*es") != NULL){ + } else if (strstr(pReply, "*es") != NULL) { self->errorCode = BADEMERG; - }else if(strstr(pReply,"*ms") != NULL){ + } else if (strstr(pReply, "*ms") != NULL) { self->errorCode = BADSTP; } else { - strncpy(self->errorReply,pReply,79); + strncpy(self->errorReply, pReply, 79); self->errorCode = BADUNKNOWN; } return 0; } + /*---------------------------------------------------------------------*/ -static int EL734GetPos(void *pData, float *fPos){ +static int EL734GetPos(void *pData, float *fPos) +{ pEL734Driv self = NULL; int status, replyLen; - char pCommand[50],pReply[80]; + char pCommand[50], pReply[80]; - self = (pEL734Driv)pData; + self = (pEL734Driv) pData; assert(self); - if(time(NULL) < self->valueExpiry){ + if (time(NULL) < self->valueExpiry) { *fPos = self->lastValue; return OKOK; } - snprintf(pCommand,79,"u %d\r",self->iMotor); - status = transactEL734(self->controller,pCommand,strlen(pCommand), - pReply,79); - if(status != 1){ + snprintf(pCommand, 79, "u %d\r", self->iMotor); + status = transactEL734(self->controller, pCommand, strlen(pCommand), + pReply, 79); + if (status != 1) { self->errorCode = status; return HWFault; } replyLen = 79; - checkEmpty(self,pReply,&replyLen); + checkEmpty(self, pReply, &replyLen); - if(!checkResponse(self,pReply)){ + if (!checkResponse(self, pReply)) { return HWFault; } - sscanf(pReply,"%f",fPos); + sscanf(pReply, "%f", fPos); self->lastValue = *fPos; self->valueExpiry = time(NULL) + 3; return OKOK; } + /*----------------------------------------------------------------------*/ -static int EL734Run(void *pData,float fValue){ +static int EL734Run(void *pData, float fValue) +{ pEL734Driv self = NULL; int status; - char pCommand[50],pReply[80]; + char pCommand[50], pReply[80]; - self = (pEL734Driv)pData; + self = (pEL734Driv) pData; assert(self); self->oredMsr = 3; - snprintf(pCommand,79,"p %d %.3f\r",self->iMotor,fValue); - status = transactEL734(self->controller,pCommand,strlen(pCommand), - pReply,79); - if(status != 1){ + snprintf(pCommand, 79, "p %d %.3f\r", self->iMotor, fValue); + status = transactEL734(self->controller, pCommand, strlen(pCommand), + pReply, 79); + if (status != 1) { self->errorCode = status; return HWFault; } - if(!checkResponse(self,pReply)){ + if (!checkResponse(self, pReply)) { return HWFault; } - self->posCount =0; + self->posCount = 0; self->runCount = 0; return OKOK; } + /*-----------------------------------------------------------------------*/ -static int decodeMSR(pEL734Driv self, int msr){ - if (msr == 0){ - if(self->posCount > 0 || self->runCount > 0){ +static int decodeMSR(pEL734Driv self, int msr) +{ + if (msr == 0) { + if (self->posCount > 0 || self->runCount > 0) { self->errorCode = BADCOUNT; return HWPosFault; } /* - we are done: check ored_msr for troubles - */ - if(self->oredMsr & 0x2){ + we are done: check ored_msr for troubles + */ + if (self->oredMsr & 0x2) { return HWIdle; - } else if(self->oredMsr & 0x10){ + } else if (self->oredMsr & 0x10) { self->errorCode = LOWLIM; return HWFault; - } else if(self->oredMsr & 0x20){ + } else if (self->oredMsr & 0x20) { self->errorCode = HILIM; return HWFault; - } else if(self->oredMsr & 0x80){ + } else if (self->oredMsr & 0x80) { self->errorCode = RUNFAULT; return HWPosFault; - } else if(self->oredMsr & 0x200){ + } else if (self->oredMsr & 0x200) { self->errorCode = POSFAULT; return HWPosFault; - } else if(self->oredMsr & 0x1000){ + } else if (self->oredMsr & 0x1000) { self->errorCode = BADCUSHION; return HWFault; - } else if(self->oredMsr & 0x40) { + } else if (self->oredMsr & 0x40) { self->errorCode = BADSTP; return HWFault; - } else if(self->oredMsr & 0x100){ + } else if (self->oredMsr & 0x100) { self->errorCode = POSFAULT; return HWFault; - } else if(self->oredMsr & 0x400){ + } else if (self->oredMsr & 0x400) { self->errorCode = POSFAULT; return HWFault; } else { self->errorCode = BADUNKNOWN; - return HWFault; /* should not happen */ + return HWFault; /* should not happen */ } } else { /* - we are still tugging along ............ - */ - if(msr & 0x80){ + we are still tugging along ............ + */ + if (msr & 0x80) { self->runCount++; - }else if(msr & 0x20){ - self->errorCode = HILIM; - return HWFault; - }else if(msr & 0x10){ - self->errorCode = LOWLIM; - return HWFault; - }else if(msr & 0x1000){ - self->errorCode = BADCUSHION; - return HWFault; - }else if(msr & 0x40){ - self->errorCode = BADSTP; - return HWFault; - } else if(msr & 0x200) { + } else if (msr & 0x20) { + self->errorCode = HILIM; + return HWFault; + } else if (msr & 0x10) { + self->errorCode = LOWLIM; + return HWFault; + } else if (msr & 0x1000) { + self->errorCode = BADCUSHION; + return HWFault; + } else if (msr & 0x40) { + self->errorCode = BADSTP; + return HWFault; + } else if (msr & 0x200) { self->posCount++; - } else if(msr & 0x100) { + } else if (msr & 0x100) { self->errorCode = POSFAULT; return HWFault; - } else if(msr & 0x400) { + } else if (msr & 0x400) { self->errorCode = POSFAULT; - return HWFault; + return HWFault; } - + return HWBusy; } } + /*------------------------------------------------------------------------*/ -static int EL734Status(void *pData){ +static int EL734Status(void *pData) +{ pEL734Driv self = NULL; int status, msr, replyLen = 79; - char pCommand[50],pReply[80]; + char pCommand[50], pReply[80]; - self = (pEL734Driv)pData; + self = (pEL734Driv) pData; assert(self); - snprintf(pCommand,79,"msr %d\r",self->iMotor); - status = transactEL734(self->controller,pCommand,strlen(pCommand), - pReply,79); - if(status < 0){ + snprintf(pCommand, 79, "msr %d\r", self->iMotor); + status = transactEL734(self->controller, pCommand, strlen(pCommand), + pReply, 79); + if (status < 0) { self->errorCode = status; return HWFault; } - checkEmpty(self,pReply,&replyLen); + checkEmpty(self, pReply, &replyLen); - if(!checkResponse(self,pReply)){ + if (!checkResponse(self, pReply)) { return HWFault; } - sscanf(pReply,"%x",&msr); - self->oredMsr |= msr; + sscanf(pReply, "%x", &msr); + self->oredMsr |= msr; self->valueExpiry = -1; - return decodeMSR(self,msr); + return decodeMSR(self, msr); } + /*----------------------------------------------------------------------*/ -static void EL734Error(void *pData, int *iCode, char *error, int errLen){ +static void EL734Error(void *pData, int *iCode, char *error, int errLen) +{ pEL734Driv self = NULL; char pBueffel[132]; - self = (pEL734Driv)pData; + self = (pEL734Driv) pData; assert(self); *iCode = self->errorCode; - switch(*iCode){ + switch (*iCode) { case BADADR: - strncpy(error,"Bad address",errLen); + strncpy(error, "Bad address", errLen); break; case BADBSY: - strncpy(error,"Motor still busy",errLen); + strncpy(error, "Motor still busy", errLen); break; case BADCMD: - strncpy(error,"Bad command",errLen); + strncpy(error, "Bad command", errLen); break; case BADLOC: - strncpy(error,"Motor controller is on local",errLen); + strncpy(error, "Motor controller is on local", errLen); break; case BADPAR: - strncpy(error,"Bad parameter",errLen); + strncpy(error, "Bad parameter", errLen); break; case BADRNG: - strncpy(error,"Bad range",errLen); + strncpy(error, "Bad range", errLen); break; case BADUNKNOWN: - snprintf(pBueffel,131,"Unknown response: %s",self->errorReply); - strncpy(error,pBueffel,errLen); + snprintf(pBueffel, 131, "Unknown response: %s", self->errorReply); + strncpy(error, pBueffel, errLen); break; case BADSTP: - strncpy(error,"Motor is switched off at motor controller",errLen); + strncpy(error, "Motor is switched off at motor controller", errLen); break; case BADEMERG: - strncpy(error,"Emergency stop is engaged, please release",errLen); + strncpy(error, "Emergency stop is engaged, please release", errLen); break; case LOWLIM: - strncpy(error,"Crashed into lower limit switch",errLen); + strncpy(error, "Crashed into lower limit switch", errLen); break; case HILIM: - strncpy(error,"Crashed into upper limit switch",errLen); + strncpy(error, "Crashed into upper limit switch", errLen); break; case RUNFAULT: - strncpy(error,"Run fault detected",errLen); + strncpy(error, "Run fault detected", errLen); break; case POSFAULT: - strncpy(error,"Positioning fault detected",errLen); + strncpy(error, "Positioning fault detected", errLen); break; case BADCUSHION: - strncpy(error,"Air cushion problem",errLen); + strncpy(error, "Air cushion problem", errLen); break; case BADCOUNT: - snprintf(pBueffel,131,"%d RunFaults, %d PosFaults", - self->runCount, self->posCount); - strncpy(error,pBueffel,errLen); + snprintf(pBueffel, 131, "%d RunFaults, %d PosFaults", + self->runCount, self->posCount); + strncpy(error, pBueffel, errLen); break; default: - getRS232Error(*iCode,error,errLen); + getRS232Error(*iCode, error, errLen); break; } } + /*----------------------------------------------------------------------*/ -static int EL734Halt(void *pData){ +static int EL734Halt(void *pData) +{ pEL734Driv self = NULL; int status; - char pCommand[50],pReply[80]; + char pCommand[50], pReply[80]; - self = (pEL734Driv)pData; + self = (pEL734Driv) pData; assert(self); - snprintf(pCommand,79,"s %d\r",self->iMotor); - status = transactEL734(self->controller,pCommand,strlen(pCommand), - pReply,79); - if(status != 1){ + snprintf(pCommand, 79, "s %d\r", self->iMotor); + status = transactEL734(self->controller, pCommand, strlen(pCommand), + pReply, 79); + if (status != 1) { self->errorCode = status; return 0; } - if(!checkResponse(self,pReply)){ + if (!checkResponse(self, pReply)) { return 0; } return 1; } + /*----------------------------------------------------------------------*/ -static int EL734Fix(void *pData, int iCode, float fValue){ +static int EL734Fix(void *pData, int iCode, float fValue) +{ pEL734Driv self = NULL; int status, msr, i, len = 49; - char pCommand[50],pReply[80]; + char pCommand[50], pReply[80]; - self = (pEL734Driv)pData; + self = (pEL734Driv) pData; assert(self); - switch(iCode){ + switch (iCode) { case BADADR: case BADCMD: case BADPAR: @@ -431,40 +448,42 @@ static int EL734Fix(void *pData, int iCode, float fValue){ SicsWait(1); return MOTREDO; case TIMEOUT: - for(i = 0; i < 3; i++){ + for (i = 0; i < 3; i++) { len = 49; - status = readRS232TillTerm(self->controller,pReply,&len); - if(status == 1){ - return MOTREDO; + status = readRS232TillTerm(self->controller, pReply, &len); + if (status == 1) { + return MOTREDO; } } /* - If nothing can be read, the only fixable cause is a network breakdown - Try to fix this. If this does not work: give up - */ + If nothing can be read, the only fixable cause is a network breakdown + Try to fix this. If this does not work: give up + */ closeRS232(self->controller); SicsWait(60); status = initRS232(self->controller); - if(status != 1){ + if (status != 1) { return MOTFAIL; } else { return MOTREDO; } break; case BADUNKNOWN: - if(availableRS232(self->controller)){ + if (availableRS232(self->controller)) { len = 79; - readRS232TillTerm(self->controller,pReply,&len); + readRS232TillTerm(self->controller, pReply, &len); return MOTREDO; } return MOTFAIL; break; case BADLOC: - snprintf(pCommand,49,"RMT 1\r"); - transactEL734(self->controller,pCommand,strlen(pCommand),pReply,79); - snprintf(pCommand,49,"ECHO 0\r"); - transactEL734(self->controller,pCommand,strlen(pCommand),pReply,79); - return MOTREDO; + snprintf(pCommand, 49, "RMT 1\r"); + transactEL734(self->controller, pCommand, strlen(pCommand), pReply, + 79); + snprintf(pCommand, 49, "ECHO 0\r"); + transactEL734(self->controller, pCommand, strlen(pCommand), pReply, + 79); + return MOTREDO; case NOTCONNECTED: initRS232(self->controller); return MOTREDO; @@ -477,12 +496,12 @@ static int EL734Fix(void *pData, int iCode, float fValue){ return MOTOK; case BADSEND: /* - network problem: try to reopen connection - */ + network problem: try to reopen connection + */ closeRS232(self->controller); - SicsWait(60); + SicsWait(60); status = initRS232(self->controller); - if(status != 1){ + if (status != 1) { return MOTFAIL; } else { return MOTREDO; @@ -490,136 +509,146 @@ static int EL734Fix(void *pData, int iCode, float fValue){ } return MOTFAIL; } + /*--------------------------------------------------------------------*/ -static int EL734GetPar(void *pData, char *name, - float *fValue){ +static int EL734GetPar(void *pData, char *name, float *fValue) +{ pEL734Driv self = NULL; int status, replyLen = 79; - char pCommand[50],pReply[80]; + char pCommand[50], pReply[80]; - self = (pEL734Driv)pData; + self = (pEL734Driv) pData; assert(self); - if(strcmp(name,"speed") == 0){ - snprintf(pCommand,79,"J %d\r",self->iMotor); - status = transactEL734(self->controller,pCommand,strlen(pCommand), - pReply,79); - if(status != 1){ + if (strcmp(name, "speed") == 0) { + snprintf(pCommand, 79, "J %d\r", self->iMotor); + status = transactEL734(self->controller, pCommand, strlen(pCommand), + pReply, 79); + if (status != 1) { self->errorCode = status; return 0; } - checkEmpty(self,pReply,&replyLen); + checkEmpty(self, pReply, &replyLen); - if(!checkResponse(self,pReply)){ + if (!checkResponse(self, pReply)) { return 0; } - sscanf(pReply,"%f",fValue); + sscanf(pReply, "%f", fValue); return 1; } return 0; } + /*--------------------------------------------------------------------*/ -static int EL734SetPar(void *pData, SConnection *pCon, - char *name, float newValue){ +static int EL734SetPar(void *pData, SConnection * pCon, + char *name, float newValue) +{ pEL734Driv self = NULL; int status; - char pCommand[50],pReply[80]; + char pCommand[50], pReply[80]; - self = (pEL734Driv)pData; + self = (pEL734Driv) pData; assert(self); - pCommand[0] ='\0'; - if(strcmp(name,"speed") == 0){ - snprintf(pCommand,79,"J %d %d\r",self->iMotor,(int)newValue); - } else if(strcmp(name,"forceupper") == 0){ - if(!SCMatchRights(pCon,usMugger)){ + pCommand[0] = '\0'; + if (strcmp(name, "speed") == 0) { + snprintf(pCommand, 79, "J %d %d\r", self->iMotor, (int) newValue); + } else if (strcmp(name, "forceupper") == 0) { + if (!SCMatchRights(pCon, usMugger)) { return 0; } self->fUpper = newValue; - snprintf(pCommand,79,"H %d %8.3f %8.3f\r",self->iMotor,self->fLower, self->fUpper); - } else if(strcmp(name,"forcelower") == 0){ - if(!SCMatchRights(pCon,usMugger)){ + snprintf(pCommand, 79, "H %d %8.3f %8.3f\r", self->iMotor, + self->fLower, self->fUpper); + } else if (strcmp(name, "forcelower") == 0) { + if (!SCMatchRights(pCon, usMugger)) { return 0; } self->fLower = newValue; - snprintf(pCommand,79,"H %d %8.3f %8.3f\r",self->iMotor,self->fLower, self->fUpper); - } else if(strcmp(name,"forcepos") == 0){ - if(!SCMatchRights(pCon,usMugger)){ + snprintf(pCommand, 79, "H %d %8.3f %8.3f\r", self->iMotor, + self->fLower, self->fUpper); + } else if (strcmp(name, "forcepos") == 0) { + if (!SCMatchRights(pCon, usMugger)) { return 0; } - snprintf(pCommand,79,"U %d %8.3f\r",self->iMotor,newValue); + snprintf(pCommand, 79, "U %d %8.3f\r", self->iMotor, newValue); } - if(strlen(pCommand) > 1){ - status = transactEL734(self->controller,pCommand,strlen(pCommand), - pReply,79); - if(status != 1){ + if (strlen(pCommand) > 1) { + status = transactEL734(self->controller, pCommand, strlen(pCommand), + pReply, 79); + if (status != 1) { self->errorCode = status; return 0; } - if(!checkResponse(self,pReply)){ - snprintf(pCommand,79,"ERROR %s while setting parameter",pReply); - SCWrite(pCon,pCommand,eError); + if (!checkResponse(self, pReply)) { + snprintf(pCommand, 79, "ERROR %s while setting parameter", pReply); + SCWrite(pCon, pCommand, eError); return 0; } return 1; } return 0; } + /*--------------------------------------------------------------------*/ -static void EL734List(void *self, char *name, SConnection *pCon){ +static void EL734List(void *self, char *name, SConnection * pCon) +{ float value; char pBueffel[256]; - EL734GetPar(self,"speed",&value); - snprintf(pBueffel,255,"%s speed = %f",name,value); - SCWrite(pCon,pBueffel,eValue); + EL734GetPar(self, "speed", &value); + snprintf(pBueffel, 255, "%s speed = %f", name, value); + SCWrite(pCon, pBueffel, eValue); return; } + /*---------------------------------------------------------------------*/ -static void KillEL734(void *pData){ +static void KillEL734(void *pData) +{ /* - the controller is owned by the controller object and will be - deleted when that object is removed - */ + the controller is owned by the controller object and will be + deleted when that object is removed + */ return; } + /*------------------------------------------------------------------*/ -MotorDriver *CreateEL734HP(SConnection *pCon, int argc, char *argv[]){ +MotorDriver *CreateEL734HP(SConnection * pCon, int argc, char *argv[]) +{ pEL734Driv pNew = NULL; int motor, status, i, success; prs232 controller = NULL; - char pCommand[50],pReply[80], pError[255]; + char pCommand[50], pReply[80], pError[255]; /* - check arguments - */ - if(argc < 2){ - SCWrite(pCon,"ERROR: not enough arguments to create EL734HP driver", - eError); + check arguments + */ + if (argc < 2) { + SCWrite(pCon, "ERROR: not enough arguments to create EL734HP driver", + eError); return NULL; } - controller = (prs232)FindCommandData(pServ->pSics,argv[0], - "RS232 Controller"); - if(!controller){ - SCWrite(pCon,"ERROR: motor controller not found",eError); + controller = (prs232) FindCommandData(pServ->pSics, argv[0], + "RS232 Controller"); + if (!controller) { + SCWrite(pCon, "ERROR: motor controller not found", eError); return NULL; } motor = atoi(argv[1]); - if(motor < 0 || motor > 12){ - SCWrite(pCon,"ERROR: invalid motor number",eError); + if (motor < 0 || motor > 12) { + SCWrite(pCon, "ERROR: invalid motor number", eError); return NULL; } /* - allocate and initialize data structure - */ - pNew = (pEL734Driv)malloc(sizeof(EL734Driv)); - if(!pNew){ - SCWrite(pCon,"ERROR: no memory to allocate motor driver", - eError); + allocate and initialize data structure + */ + pNew = (pEL734Driv) malloc(sizeof(EL734Driv)); + if (!pNew) { + SCWrite(pCon, "ERROR: no memory to allocate motor driver", eError); return NULL; } - memset(pNew,0,sizeof(EL734Driv)); + memset(pNew, 0, sizeof(EL734Driv)); pNew->GetPosition = EL734GetPos; pNew->RunTo = EL734Run; pNew->GetStatus = EL734Status; @@ -635,74 +664,72 @@ MotorDriver *CreateEL734HP(SConnection *pCon, int argc, char *argv[]){ pNew->oredMsr = 3; /* - connection will already have been set up, read limits - */ - snprintf(pCommand,49,"h %d\r",pNew->iMotor); + connection will already have been set up, read limits + */ + snprintf(pCommand, 49, "h %d\r", pNew->iMotor); success = 0; - for(i = 0; i < 3; i++){ - status = transactEL734(pNew->controller, pCommand,strlen(pCommand), - pReply,79); - if(status != 1){ - getRS232Error(status,pReply,79); - snprintf(pError,255,"ERROR: %s",pReply); - SCWrite(pCon,pError,eError); + for (i = 0; i < 3; i++) { + status = transactEL734(pNew->controller, pCommand, strlen(pCommand), + pReply, 79); + if (status != 1) { + getRS232Error(status, pReply, 79); + snprintf(pError, 255, "ERROR: %s", pReply); + SCWrite(pCon, pError, eError); closeRS232(pNew->controller); SicsWait(60); initRS232(pNew->controller); } else { - if(checkResponse(pNew,pReply)){ - if(sscanf(pReply,"%f %f",&pNew->fLower,&pNew->fUpper)!= 2){ - snprintf(pError,255, - "ERROR: received shitty HW limit response from SICS: %s", - pReply); - SCWrite(pCon,pError,eError); - } else{ - success = 1; - break; - } + if (checkResponse(pNew, pReply)) { + if (sscanf(pReply, "%f %f", &pNew->fLower, &pNew->fUpper) != 2) { + snprintf(pError, 255, + "ERROR: received shitty HW limit response from SICS: %s", + pReply); + SCWrite(pCon, pError, eError); + } else { + success = 1; + break; + } } - } + } } - if(success == 0){ - SCWrite(pCon, - "ERROR: invalid response when reading HW limits, defaulting..", - eError); - pNew->fLower = -180.; - pNew->fUpper = 180.; + if (success == 0) { + SCWrite(pCon, + "ERROR: invalid response when reading HW limits, defaulting..", + eError); + pNew->fLower = -180.; + pNew->fUpper = 180.; } - snprintf(pError,255,"EL734 returned HW-limits of: %s", pReply); - SCWrite(pCon,pError,eError); - return (MotorDriver *)pNew; + snprintf(pError, 255, "EL734 returned HW-limits of: %s", pReply); + SCWrite(pCon, pError, eError); + return (MotorDriver *) pNew; } + /*================ a 1000 scaled motor for SANSLI =================*/ -static int EL734TRun(void *pData,float fValue){ - return EL734Run(pData, fValue*1000); +static int EL734TRun(void *pData, float fValue) +{ + return EL734Run(pData, fValue * 1000); } + /*-----------------------------------------------------------------*/ -static int EL734TGetPos(void *pData, float *fPos){ - int status; - status = EL734GetPos(pData, fPos); - *fPos /= 1000; - return status; +static int EL734TGetPos(void *pData, float *fPos) +{ + int status; + status = EL734GetPos(pData, fPos); + *fPos /= 1000; + return status; } + /*-------------------------------------------------------------------*/ -MotorDriver *CreateEL734HPT(SConnection *pCon, int argc, - char *argv[]){ - MotorDriver *pDriv = NULL; - pDriv = CreateEL734HP(pCon,argc,argv); - if(pDriv != NULL){ - pDriv->GetPosition = EL734TGetPos; - pDriv->RunTo = EL734TRun; - pDriv->fLower /= 1000.; - pDriv->fUpper /= 1000.; - } - return pDriv; +MotorDriver *CreateEL734HPT(SConnection * pCon, int argc, char *argv[]) +{ + MotorDriver *pDriv = NULL; + pDriv = CreateEL734HP(pCon, argc, argv); + if (pDriv != NULL) { + pDriv->GetPosition = EL734TGetPos; + pDriv->RunTo = EL734TRun; + pDriv->fLower /= 1000.; + pDriv->fUpper /= 1000.; + } + return pDriv; } - - - - - - - diff --git a/el737driv.c b/el737driv.c index 3321cb3..446b17d 100644 --- a/el737driv.c +++ b/el737driv.c @@ -20,700 +20,632 @@ #define BADTRANGE -117766 /*----------------------------- EL737 ------------------------------------*/ - typedef struct { - char *host; - int iPort; - int iChannel; - void *pData; - int finishCount; - } EL737st; +typedef struct { + char *host; + int iPort; + int iChannel; + void *pData; + int finishCount; +} EL737st; /*------------------------------------------------------------------------*/ - static int EL737GetStatus(struct __COUNTER *self, float *fControl) - { - int iRet; - int iC1, iC2, iC3,iC4,iRS; - float fTime; - EL737st *pEL737; - - assert(self); - pEL737 = (EL737st *)self->pData; - assert(pEL737); - iRet = EL737_GetStatus(&pEL737->pData,&iC1,&iC2,&iC3,&iC4,&fTime,&iRS); - if(self->eMode == eTimer) - { - *fControl = fTime; - } - else - { - *fControl = iC1; - } - /* store time */ - self->fTime = fTime; - - if(iRet != 1) - { - return HWFault; - } - self->lCounts[0] = iC2; - self->lCounts[1] = iC1; - self->lCounts[2] = iC3; - self->lCounts[3] = iC4; - - /* get extra counters for 8-fold counter boxes */ - iRet = EL737_GetStatusExtra(&pEL737->pData,&iC1,&iC2,&iC3,&iC4); - self->lCounts[4] = iC1; - self->lCounts[5] = iC2; - self->lCounts[6] = iC3; - self->lCounts[7] = iC4; - if(iRS == 0) - { - pEL737->finishCount++; - if(pEL737->finishCount >= 2) - { - return HWIdle; - } - else - { - return HWBusy; - } - } - else if((iRS == 1) || (iRS == 2)) - { - pEL737->finishCount = 0; +static int EL737GetStatus(struct __COUNTER *self, float *fControl) +{ + int iRet; + int iC1, iC2, iC3, iC4, iRS; + float fTime; + EL737st *pEL737; + + assert(self); + pEL737 = (EL737st *) self->pData; + assert(pEL737); + iRet = + EL737_GetStatus(&pEL737->pData, &iC1, &iC2, &iC3, &iC4, &fTime, + &iRS); + if (self->eMode == eTimer) { + *fControl = fTime; + } else { + *fControl = iC1; + } + /* store time */ + self->fTime = fTime; + + if (iRet != 1) { + return HWFault; + } + self->lCounts[0] = iC2; + self->lCounts[1] = iC1; + self->lCounts[2] = iC3; + self->lCounts[3] = iC4; + + /* get extra counters for 8-fold counter boxes */ + iRet = EL737_GetStatusExtra(&pEL737->pData, &iC1, &iC2, &iC3, &iC4); + self->lCounts[4] = iC1; + self->lCounts[5] = iC2; + self->lCounts[6] = iC3; + self->lCounts[7] = iC4; + if (iRS == 0) { + pEL737->finishCount++; + if (pEL737->finishCount >= 2) { + return HWIdle; + } else { return HWBusy; } - else if( (iRS == 5) || (iRS == 6)) - { - pEL737->finishCount = 0; - return HWNoBeam; - } - else - { - pEL737->finishCount = 0; - return HWPause; - } + } else if ((iRS == 1) || (iRS == 2)) { + pEL737->finishCount = 0; + return HWBusy; + } else if ((iRS == 5) || (iRS == 6)) { + pEL737->finishCount = 0; + return HWNoBeam; + } else { + pEL737->finishCount = 0; + return HWPause; } +} + #ifdef NONINTF - extern float nintf(float f); -#endif +extern float nintf(float f); +#endif /*-------------------------------------------------------------------------*/ - static int EL737Start(struct __COUNTER *self) - { - int iRet, iRS; - EL737st *pEL737; - - assert(self); - pEL737 = (EL737st *)self->pData; - assert(pEL737); - - - self->fTime = 0.; - - if(self->eMode == ePreset) - { - iRet = EL737_StartCnt(&pEL737->pData,(int)nintf(self->fPreset),&iRS); - if(iRet == 1) - { - pEL737->finishCount = 0; - return OKOK; - } - else - { - return HWFault; - } - } - else if(self->eMode == eTimer) - { - if(self->fPreset < .1 || self->fPreset > 200000) - { - self->iErrorCode = BADTRANGE; - return HWFault; - } - iRet = EL737_StartTime(&pEL737->pData,self->fPreset,&iRS); - if(iRet == 1) - { - pEL737->finishCount = 0; - return OKOK; - } - else - { - return HWFault; - } - } - return 0; - } -/*-------------------------------------------------------------------------*/ - static int EL737Pause(struct __COUNTER *self) - { - int iRet, iRS; - EL737st *pEL737; - - assert(self); - pEL737 = (EL737st *)self->pData; - assert(pEL737); - - - iRet = EL737_Pause(&pEL737->pData,&iRS); - if(iRet == 1) - { - return OKOK; - } - else - { - return HWFault; - } - return 0; - } -/*-------------------------------------------------------------------------*/ - static int EL737Continue(struct __COUNTER *self) - { - int iRet, iRS; - EL737st *pEL737; - - assert(self); - pEL737 = (EL737st *)self->pData; - assert(pEL737); - - - iRet = EL737_Continue(&pEL737->pData,&iRS); - if(iRet == 1) - { - return OKOK; - } - else - { - return HWFault; - } - return 0; - } -/*--------------------------------------------------------------------------*/ - static int EL737Halt(struct __COUNTER *self) - { - int iRet, iC1, iC2, iC3, iC4,iRS; - float fPreset; - EL737st *pEL737; - - assert(self); - pEL737 = (EL737st *)self->pData; - assert(pEL737); - - - - iRet = EL737_Stop(&pEL737->pData,&iC1, &iC2,&iC3,&iC4,&fPreset,&iRS); - if(iRet == 1) - { - self->lCounts[0] = iC2; - self->lCounts[1] = iC1; - self->lCounts[2] = iC3; - self->lCounts[3] = iC4; +static int EL737Start(struct __COUNTER *self) +{ + int iRet, iRS; + EL737st *pEL737; + + assert(self); + pEL737 = (EL737st *) self->pData; + assert(pEL737); + + + self->fTime = 0.; + + if (self->eMode == ePreset) { + iRet = + EL737_StartCnt(&pEL737->pData, (int) nintf(self->fPreset), &iRS); + if (iRet == 1) { + pEL737->finishCount = 0; return OKOK; - } - return HWFault; - } -/*--------------------------------------------------------------------------*/ - static int EL737ReadValues(struct __COUNTER *self) - { - int iRet; - int iC1, iC2, iC3,iC4,iRS; - float fTime; - EL737st *pEL737; - - assert(self); - pEL737 = (EL737st *)self->pData; - assert(pEL737); - - - iRet = EL737_GetStatus(&pEL737->pData,&iC1,&iC2,&iC3,&iC4,&fTime,&iRS); - if(iRet != 1) - { + } else { return HWFault; } - self->fTime = fTime; - + } else if (self->eMode == eTimer) { + if (self->fPreset < .1 || self->fPreset > 200000) { + self->iErrorCode = BADTRANGE; + return HWFault; + } + iRet = EL737_StartTime(&pEL737->pData, self->fPreset, &iRS); + if (iRet == 1) { + pEL737->finishCount = 0; + return OKOK; + } else { + return HWFault; + } + } + return 0; +} + +/*-------------------------------------------------------------------------*/ +static int EL737Pause(struct __COUNTER *self) +{ + int iRet, iRS; + EL737st *pEL737; + + assert(self); + pEL737 = (EL737st *) self->pData; + assert(pEL737); + + + iRet = EL737_Pause(&pEL737->pData, &iRS); + if (iRet == 1) { + return OKOK; + } else { + return HWFault; + } + return 0; +} + +/*-------------------------------------------------------------------------*/ +static int EL737Continue(struct __COUNTER *self) +{ + int iRet, iRS; + EL737st *pEL737; + + assert(self); + pEL737 = (EL737st *) self->pData; + assert(pEL737); + + + iRet = EL737_Continue(&pEL737->pData, &iRS); + if (iRet == 1) { + return OKOK; + } else { + return HWFault; + } + return 0; +} + +/*--------------------------------------------------------------------------*/ +static int EL737Halt(struct __COUNTER *self) +{ + int iRet, iC1, iC2, iC3, iC4, iRS; + float fPreset; + EL737st *pEL737; + + assert(self); + pEL737 = (EL737st *) self->pData; + assert(pEL737); + + + + iRet = + EL737_Stop(&pEL737->pData, &iC1, &iC2, &iC3, &iC4, &fPreset, &iRS); + if (iRet == 1) { self->lCounts[0] = iC2; self->lCounts[1] = iC1; self->lCounts[2] = iC3; self->lCounts[3] = iC4; - /* get extra counters for 8-fold counter boxes */ - iRet = EL737_GetStatusExtra(&pEL737->pData,&iC1,&iC2,&iC3,&iC4); - self->lCounts[4] = iC1; - self->lCounts[5] = iC2; - self->lCounts[6] = iC3; - self->lCounts[7] = iC4; - - return OKOK; + return OKOK; } + return HWFault; +} + +/*--------------------------------------------------------------------------*/ +static int EL737ReadValues(struct __COUNTER *self) +{ + int iRet; + int iC1, iC2, iC3, iC4, iRS; + float fTime; + EL737st *pEL737; + + assert(self); + pEL737 = (EL737st *) self->pData; + assert(pEL737); + + + iRet = + EL737_GetStatus(&pEL737->pData, &iC1, &iC2, &iC3, &iC4, &fTime, + &iRS); + if (iRet != 1) { + return HWFault; + } + self->fTime = fTime; + + self->lCounts[0] = iC2; + self->lCounts[1] = iC1; + self->lCounts[2] = iC3; + self->lCounts[3] = iC4; + /* get extra counters for 8-fold counter boxes */ + iRet = EL737_GetStatusExtra(&pEL737->pData, &iC1, &iC2, &iC3, &iC4); + self->lCounts[4] = iC1; + self->lCounts[5] = iC2; + self->lCounts[6] = iC3; + self->lCounts[7] = iC4; + + return OKOK; +} + /*--------------------------------------------------------------------------- EL737Error2Text converts between an EL734 error code to text -----------------------------------------------------------------------------*/ - static void EL737Error2Text(char *pBuffer, int iErr) - { - switch(iErr) - { - case EL737__BAD_ADR: - strcpy(pBuffer,"EL737__BAD_ADR"); - break; - case EL737__BAD_OVFL: - strcpy(pBuffer,"EL737__BAD_OVFL"); - break; - case EL737__BAD_BSY: - strcpy(pBuffer,"EL737__BAD_BSY"); - break; - case EL737__BAD_SNTX: - strcpy(pBuffer,"EL737__BAD_SNTX"); - break; - case EL737__BAD_CONNECT: - strcpy(pBuffer,"EL737__BAD_CONNECT"); - break; - case EL737__BAD_FLUSH: - strcpy(pBuffer,"EL737__BAD_FLUSH"); - break; - case EL737__BAD_DEV: - strcpy(pBuffer,"EL734__BAD_DEV"); - break; - case EL737__BAD_ID: - strcpy(pBuffer,"EL737__BAD_ID"); - break; - case EL737__BAD_ILLG: - strcpy(pBuffer,"EL737__BAD_ILLG"); - break; - case EL737__BAD_LOC: - strcpy(pBuffer,"EL737__BAD_LOC"); - break; - case EL737__BAD_MALLOC: - strcpy(pBuffer,"EL737__BAD_MALLOC"); - break; - case EL737__BAD_NOT_BCD: - strcpy(pBuffer,"EL737__BAD_NOT_BCD"); - break; - case EL737__BAD_OFL: - strcpy(pBuffer,"EL737__BAD_OFL"); - break; - case EL737__BAD_PAR: - strcpy(pBuffer,"EL737__BAD_PAR"); - break; - - case EL737__BAD_RECV: - strcpy(pBuffer,"EL737__BAD_RECV"); - break; - case EL737__BAD_RECV_NET: - strcpy(pBuffer,"EL737__BAD_RECV_NET"); - break; - case EL737__BAD_RECV_PIPE: - strcpy(pBuffer,"EL737__BAD_RECV_PIPE"); - break; - case EL737__BAD_RECV_UNKN: - strcpy(pBuffer,"EL737__BAD_RECV_UNKN"); - break; - case EL737__BAD_RECVLEN: - strcpy(pBuffer,"EL737__BAD_RECVLEN"); - break; - case EL737__BAD_RECV1: - strcpy(pBuffer,"EL737__BAD_RECV1"); - break; - case EL737__BAD_RECV1_NET: - strcpy(pBuffer,"EL737__BAD_RECV1_NET"); - break; - case EL737__BAD_RECV1_PIPE: - strcpy(pBuffer,"EL737__BAD_RECV1_PIPE"); - break; - case EL737__BAD_RNG: - strcpy(pBuffer,"EL737__BAD_RNG"); - break; - case EL737__BAD_SEND: - strcpy(pBuffer,"EL737__BAD_SEND"); - break; - case EL737__BAD_SEND_PIPE: - strcpy(pBuffer,"EL737__BAD_SEND_PIPE"); - break; - case EL737__BAD_SEND_NET: - strcpy(pBuffer,"EL737__BAD_SEND_NET"); - break; - case EL737__BAD_SEND_UNKN: - strcpy(pBuffer,"EL737__BAD_SEND_UNKN"); - break; - case EL737__BAD_SENDLEN: - strcpy(pBuffer,"EL737__BAD_SENDLEN"); - break; - case EL737__BAD_SOCKET: - strcpy(pBuffer,"EL737__BAD_SOCKET"); - break; - case EL737__BAD_TMO: - strcpy(pBuffer,"EL737__BAD_TMO"); - break; - case EL737__FORCED_CLOSED: - strcpy(pBuffer,"EL737__FORCED_CLOSED"); - break; - case EL737__BAD_ASYNSRV: - strcpy(pBuffer,"EL737__BAD_ASYNSRV"); - break; - default: - sprintf(pBuffer,"Unknown EL737 error %d", iErr); - break; - } - } - -/*--------------------------------------------------------------------------*/ - static int EL737GetError(struct __COUNTER *self, int *iCode, - char *error, int iErrLen) - { - char *pErr = NULL; - int iC1, iC2, iC3; - char pBueffel[256]; +static void EL737Error2Text(char *pBuffer, int iErr) +{ + switch (iErr) { + case EL737__BAD_ADR: + strcpy(pBuffer, "EL737__BAD_ADR"); + break; + case EL737__BAD_OVFL: + strcpy(pBuffer, "EL737__BAD_OVFL"); + break; + case EL737__BAD_BSY: + strcpy(pBuffer, "EL737__BAD_BSY"); + break; + case EL737__BAD_SNTX: + strcpy(pBuffer, "EL737__BAD_SNTX"); + break; + case EL737__BAD_CONNECT: + strcpy(pBuffer, "EL737__BAD_CONNECT"); + break; + case EL737__BAD_FLUSH: + strcpy(pBuffer, "EL737__BAD_FLUSH"); + break; + case EL737__BAD_DEV: + strcpy(pBuffer, "EL734__BAD_DEV"); + break; + case EL737__BAD_ID: + strcpy(pBuffer, "EL737__BAD_ID"); + break; + case EL737__BAD_ILLG: + strcpy(pBuffer, "EL737__BAD_ILLG"); + break; + case EL737__BAD_LOC: + strcpy(pBuffer, "EL737__BAD_LOC"); + break; + case EL737__BAD_MALLOC: + strcpy(pBuffer, "EL737__BAD_MALLOC"); + break; + case EL737__BAD_NOT_BCD: + strcpy(pBuffer, "EL737__BAD_NOT_BCD"); + break; + case EL737__BAD_OFL: + strcpy(pBuffer, "EL737__BAD_OFL"); + break; + case EL737__BAD_PAR: + strcpy(pBuffer, "EL737__BAD_PAR"); + break; - if(self->iErrorCode == UNKNOWNPAR) - { - strncpy(error,"unknown internal parameter code",iErrLen); - *iCode = self->iErrorCode; - self->iErrorCode = 0; - return 1; - } - else if(self->iErrorCode == BADCOUNTER) - { - strncpy(error,"monitor cannot be selected",iErrLen); - *iCode = self->iErrorCode; - self->iErrorCode = 0; - return 1; - } - else if(self->iErrorCode == BADTRANGE) - { - strncpy(error,"preset time out of range",iErrLen); - *iCode = self->iErrorCode; - self->iErrorCode = 0; - return 1; - } - - - EL737_ErrInfo(&pErr,&iC1,&iC2, &iC3); - EL737Error2Text(pBueffel,iC1); - - strncpy(error,pBueffel,iErrLen); - *iCode = iC1; - return 1; + case EL737__BAD_RECV: + strcpy(pBuffer, "EL737__BAD_RECV"); + break; + case EL737__BAD_RECV_NET: + strcpy(pBuffer, "EL737__BAD_RECV_NET"); + break; + case EL737__BAD_RECV_PIPE: + strcpy(pBuffer, "EL737__BAD_RECV_PIPE"); + break; + case EL737__BAD_RECV_UNKN: + strcpy(pBuffer, "EL737__BAD_RECV_UNKN"); + break; + case EL737__BAD_RECVLEN: + strcpy(pBuffer, "EL737__BAD_RECVLEN"); + break; + case EL737__BAD_RECV1: + strcpy(pBuffer, "EL737__BAD_RECV1"); + break; + case EL737__BAD_RECV1_NET: + strcpy(pBuffer, "EL737__BAD_RECV1_NET"); + break; + case EL737__BAD_RECV1_PIPE: + strcpy(pBuffer, "EL737__BAD_RECV1_PIPE"); + break; + case EL737__BAD_RNG: + strcpy(pBuffer, "EL737__BAD_RNG"); + break; + case EL737__BAD_SEND: + strcpy(pBuffer, "EL737__BAD_SEND"); + break; + case EL737__BAD_SEND_PIPE: + strcpy(pBuffer, "EL737__BAD_SEND_PIPE"); + break; + case EL737__BAD_SEND_NET: + strcpy(pBuffer, "EL737__BAD_SEND_NET"); + break; + case EL737__BAD_SEND_UNKN: + strcpy(pBuffer, "EL737__BAD_SEND_UNKN"); + break; + case EL737__BAD_SENDLEN: + strcpy(pBuffer, "EL737__BAD_SENDLEN"); + break; + case EL737__BAD_SOCKET: + strcpy(pBuffer, "EL737__BAD_SOCKET"); + break; + case EL737__BAD_TMO: + strcpy(pBuffer, "EL737__BAD_TMO"); + break; + case EL737__FORCED_CLOSED: + strcpy(pBuffer, "EL737__FORCED_CLOSED"); + break; + case EL737__BAD_ASYNSRV: + strcpy(pBuffer, "EL737__BAD_ASYNSRV"); + break; + default: + sprintf(pBuffer, "Unknown EL737 error %d", iErr); + break; } -/*--------------------------------------------------------------------------*/ - static int EL737TryAndFixIt(struct __COUNTER *self, int iCode) - { - EL737st *pEL737; - int iRet; - char pCommand[50], pReply[50]; - - assert(self); - pEL737 = (EL737st *)self->pData; - assert(pEL737); +} - switch(iCode) - { - case EL737__BAD_ILLG: - case EL737__BAD_ADR: - case EL737__BAD_PAR: - case EL737__BAD_TMO: - case EL737__BAD_REPLY: - case EL737__BAD_SNTX: - case EL737__BAD_OVFL: - return COREDO; - break; - case EL737__BAD_BSY: - strcpy(pCommand,"S \r"); - iRet = EL737_SendCmnd(&pEL737->pData,pCommand,pReply,49); - if(iRet < 0) - { - return COTERM; - } - else - { - return COREDO; - } - break; - case EL737__BAD_LOC: - strcpy(pCommand,"rmt 1\r"); - iRet = EL737_SendCmnd(&pEL737->pData,pCommand,pReply,49); - if(iRet < 0) - { - return COTERM; - } - strcpy(pCommand,"echo 2\r"); - iRet = EL737_SendCmnd(&pEL737->pData,pCommand,pReply,49); - if(iRet < 0) - { - return COTERM; - } - strcpy(pCommand,"ra\r"); - iRet = EL737_SendCmnd(&pEL737->pData,pCommand,pReply,49); - if(iRet < 0) - { - return COTERM; - } - return COREDO; - break; - case EL737__BAD_DEV: - case EL737__BAD_ID: - case EL737__BAD_NOT_BCD: - case UNKNOWNPAR: - case BADCOUNTER: - case BADTRANGE: - return COTERM; - break; - case EL737__FORCED_CLOSED: - iRet = EL737_Open(&pEL737->pData,pEL737->host, pEL737->iPort, - pEL737->iChannel); - if(iRet == 1) - { - return COREDO; - } - else - { - return COTERM; - } - break; - case EL737__BAD_OFL: - EL737_Close(&pEL737->pData,0); - iRet = EL737_Open(&pEL737->pData,pEL737->host, pEL737->iPort, - pEL737->iChannel); - if(iRet == 1) - { - return COREDO; - } - else - { - return COTERM; - } - break; +/*--------------------------------------------------------------------------*/ +static int EL737GetError(struct __COUNTER *self, int *iCode, + char *error, int iErrLen) +{ + char *pErr = NULL; + int iC1, iC2, iC3; + char pBueffel[256]; + + if (self->iErrorCode == UNKNOWNPAR) { + strncpy(error, "unknown internal parameter code", iErrLen); + *iCode = self->iErrorCode; + self->iErrorCode = 0; + return 1; + } else if (self->iErrorCode == BADCOUNTER) { + strncpy(error, "monitor cannot be selected", iErrLen); + *iCode = self->iErrorCode; + self->iErrorCode = 0; + return 1; + } else if (self->iErrorCode == BADTRANGE) { + strncpy(error, "preset time out of range", iErrLen); + *iCode = self->iErrorCode; + self->iErrorCode = 0; + return 1; + } + + + EL737_ErrInfo(&pErr, &iC1, &iC2, &iC3); + EL737Error2Text(pBueffel, iC1); + + strncpy(error, pBueffel, iErrLen); + *iCode = iC1; + return 1; +} + +/*--------------------------------------------------------------------------*/ +static int EL737TryAndFixIt(struct __COUNTER *self, int iCode) +{ + EL737st *pEL737; + int iRet; + char pCommand[50], pReply[50]; + + assert(self); + pEL737 = (EL737st *) self->pData; + assert(pEL737); + + switch (iCode) { + case EL737__BAD_ILLG: + case EL737__BAD_ADR: + case EL737__BAD_PAR: + case EL737__BAD_TMO: + case EL737__BAD_REPLY: + case EL737__BAD_SNTX: + case EL737__BAD_OVFL: + return COREDO; + break; + case EL737__BAD_BSY: + strcpy(pCommand, "S \r"); + iRet = EL737_SendCmnd(&pEL737->pData, pCommand, pReply, 49); + if (iRet < 0) { + return COTERM; + } else { + return COREDO; + } + break; + case EL737__BAD_LOC: + strcpy(pCommand, "rmt 1\r"); + iRet = EL737_SendCmnd(&pEL737->pData, pCommand, pReply, 49); + if (iRet < 0) { + return COTERM; + } + strcpy(pCommand, "echo 2\r"); + iRet = EL737_SendCmnd(&pEL737->pData, pCommand, pReply, 49); + if (iRet < 0) { + return COTERM; + } + strcpy(pCommand, "ra\r"); + iRet = EL737_SendCmnd(&pEL737->pData, pCommand, pReply, 49); + if (iRet < 0) { + return COTERM; + } + return COREDO; + break; + case EL737__BAD_DEV: + case EL737__BAD_ID: + case EL737__BAD_NOT_BCD: + case UNKNOWNPAR: + case BADCOUNTER: + case BADTRANGE: + return COTERM; + break; + case EL737__FORCED_CLOSED: + iRet = EL737_Open(&pEL737->pData, pEL737->host, pEL737->iPort, + pEL737->iChannel); + if (iRet == 1) { + return COREDO; + } else { + return COTERM; + } + break; + case EL737__BAD_OFL: + EL737_Close(&pEL737->pData, 0); + iRet = EL737_Open(&pEL737->pData, pEL737->host, pEL737->iPort, + pEL737->iChannel); + if (iRet == 1) { + return COREDO; + } else { + return COTERM; + } + break; /* case EL737__BAD_ASYNSRV: EL737_Close(&pEL737->pData,1); - return COREDO; -*/ default: - /* try to reopen connection */ - - EL737_Close(&pEL737->pData,1); - iRet = EL737_Open(&pEL737->pData,pEL737->host, pEL737->iPort, - pEL737->iChannel); - if(iRet == 1) - { return COREDO; - } - else - { - return COTERM; - } - break; - } - return COTERM; - } +*/ default: + /* try to reopen connection */ + + EL737_Close(&pEL737->pData, 1); + iRet = EL737_Open(&pEL737->pData, pEL737->host, pEL737->iPort, + pEL737->iChannel); + if (iRet == 1) { + return COREDO; + } else { + return COTERM; + } + break; + } + return COTERM; +} + /*-------------------------------------------------------------------------*/ - static int EL737Set(struct __COUNTER *self, char *name, int iCter, - float fVal) - { - int iRet; - EL737st *pEL737; - char pCommand[80],pReply[80]; - - assert(self); - pEL737 = (EL737st *)self->pData; - assert(pEL737); - - if(strcmp(name,"threshold") == 0) - { - sprintf(pCommand,"DL %1.1d %6.2f\r",iCter,fVal); - iRet = EL737_SendCmnd(&pEL737->pData,pCommand,pReply,79); - if(iRet == 1) - { - if(pReply[0] == '?') - { - self->iErrorCode = BADCOUNTER; - return HWFault; - } - } - else - { - return HWFault; - } - sprintf(pCommand,"DR %1.1d \r",iCter); - iRet = EL737_SendCmnd(&pEL737->pData,pCommand,pReply,79); - if(iRet == 1) - { - if(pCommand[0] == '?') - { - self->iErrorCode = BADCOUNTER; - return HWFault; - } - return OKOK; - } - else - { - return HWFault; - } - } - else - { - self->iErrorCode = UNKNOWNPAR; +static int EL737Set(struct __COUNTER *self, char *name, int iCter, + float fVal) +{ + int iRet; + EL737st *pEL737; + char pCommand[80], pReply[80]; + + assert(self); + pEL737 = (EL737st *) self->pData; + assert(pEL737); + + if (strcmp(name, "threshold") == 0) { + sprintf(pCommand, "DL %1.1d %6.2f\r", iCter, fVal); + iRet = EL737_SendCmnd(&pEL737->pData, pCommand, pReply, 79); + if (iRet == 1) { + if (pReply[0] == '?') { + self->iErrorCode = BADCOUNTER; + return HWFault; + } + } else { return HWFault; } - } -/*-------------------------------------------------------------------------*/ - static int EL737Get(struct __COUNTER *self, char *name, int iCter, - float *fVal) - { - int iRet; - EL737st *pEL737; - char pCommand[80],pReply[80]; - - assert(self); - pEL737 = (EL737st *)self->pData; - assert(pEL737); - - if(strcmp(name,"threshold") == 0) - { - sprintf(pCommand,"DL %1.1d\r",iCter); - iRet = EL737_SendCmnd(&pEL737->pData,pCommand,pReply,79); - if(iRet == 1) - { - if(pReply[0] == '?') - { - self->iErrorCode = BADCOUNTER; - return HWFault; - } - sscanf(pReply,"%f",fVal); - return OKOK; - } - else - { - return HWFault; - } - } - else - { - self->iErrorCode = UNKNOWNPAR; + sprintf(pCommand, "DR %1.1d \r", iCter); + iRet = EL737_SendCmnd(&pEL737->pData, pCommand, pReply, 79); + if (iRet == 1) { + if (pCommand[0] == '?') { + self->iErrorCode = BADCOUNTER; + return HWFault; + } + return OKOK; + } else { return HWFault; } - } + } else { + self->iErrorCode = UNKNOWNPAR; + return HWFault; + } +} + /*-------------------------------------------------------------------------*/ - static int EL737Send(struct __COUNTER *self, char *pText, char *pReply, - int iReplyLen) - { - EL737st *pEL737; - char pBuffer[256]; +static int EL737Get(struct __COUNTER *self, char *name, int iCter, + float *fVal) +{ + int iRet; + EL737st *pEL737; + char pCommand[80], pReply[80]; - assert(self); - pEL737 = (EL737st *)self->pData; - assert(pEL737); + assert(self); + pEL737 = (EL737st *) self->pData; + assert(pEL737); - /* ensure a \r at the end of the text */ - if(strlen(pText) > 254) - { - strncpy(pReply,"Command to long",iReplyLen); - return 1; - } - strcpy(pBuffer,pText); - if(strchr(pBuffer,(int)'\r') == NULL) - { - strcat(pBuffer,"\r"); + if (strcmp(name, "threshold") == 0) { + sprintf(pCommand, "DL %1.1d\r", iCter); + iRet = EL737_SendCmnd(&pEL737->pData, pCommand, pReply, 79); + if (iRet == 1) { + if (pReply[0] == '?') { + self->iErrorCode = BADCOUNTER; + return HWFault; + } + sscanf(pReply, "%f", fVal); + return OKOK; + } else { + return HWFault; } + } else { + self->iErrorCode = UNKNOWNPAR; + return HWFault; + } +} - return EL737_SendCmnd(&pEL737->pData,pBuffer,pReply,iReplyLen); - } /*-------------------------------------------------------------------------*/ -pCounterDriver CreateEL737Counter(SConnection *pCon, char *name, - int argc, char *argv[]){ +static int EL737Send(struct __COUNTER *self, char *pText, char *pReply, + int iReplyLen) +{ + EL737st *pEL737; + char pBuffer[256]; + + assert(self); + pEL737 = (EL737st *) self->pData; + assert(pEL737); + + /* ensure a \r at the end of the text */ + if (strlen(pText) > 254) { + strncpy(pReply, "Command to long", iReplyLen); + return 1; + } + strcpy(pBuffer, pText); + if (strchr(pBuffer, (int) '\r') == NULL) { + strcat(pBuffer, "\r"); + } + + return EL737_SendCmnd(&pEL737->pData, pBuffer, pReply, iReplyLen); +} + +/*-------------------------------------------------------------------------*/ +pCounterDriver CreateEL737Counter(SConnection * pCon, char *name, + int argc, char *argv[]) +{ char *pHost; int iPort, iChannel; - if(argc < 3){ + if (argc < 3) { SCWrite(pCon, - "ERROR: insuficient number of arguments to create EL737 counter", - eError); + "ERROR: insuficient number of arguments to create EL737 counter", + eError); return NULL; } - if(!isNumeric(argv[1]) || !isNumeric(argv[2])){ - SCWrite(pCon,"ERROR: expected numeric arguments for port and channel", - eError); + if (!isNumeric(argv[1]) || !isNumeric(argv[2])) { + SCWrite(pCon, "ERROR: expected numeric arguments for port and channel", + eError); return NULL; } iPort = atoi(argv[1]); iChannel = atoi(argv[2]); - return NewEL737Counter(name,argv[0],iPort,iChannel); + return NewEL737Counter(name, argv[0], iPort, iChannel); } + /*--------------------------------------------------------------------------*/ - pCounterDriver NewEL737Counter(char *name, char *host, int iPort, int iChannel) - { - pCounterDriver pRes = NULL; - EL737st *pData = NULL; - int iRet; - int iC1, iC2, iC3; - char *pErr; - char pBueffel[132]; - - pRes = CreateCounterDriver(name, "EL737"); - if(!pRes) - { - return NULL; - } - - /* open connection to counter */ - pData = (EL737st *)malloc(sizeof(EL737st)); - if(!pData) - { - DeleteCounterDriver(pRes); - return NULL; - } - pData->host = strdup(host); - pData->iPort = iPort; - pData->iChannel = iChannel; - pData->pData = NULL; - iRet = EL737_Open(&(pData->pData), host,iPort,iChannel); - if(iRet != 1) - { - EL737_ErrInfo(&pErr,&iC1,&iC2, &iC3); - DeleteCounterDriver(pRes); - if(pData->host) - { - free(pData->host); - } - return NULL; - } - pRes->pData = (void *)pData; - - /* assign functions */ - pRes->GetStatus = EL737GetStatus; - pRes->Start = EL737Start; - pRes->Halt = EL737Halt; - pRes->ReadValues = EL737ReadValues; - pRes->GetError = EL737GetError; - pRes->TryAndFixIt = EL737TryAndFixIt; - pRes->Pause = EL737Pause; - pRes->Continue = EL737Continue; - pRes->Set = EL737Set; - pRes->Get = EL737Get; - pRes->Send = EL737Send; - pRes->KillPrivate = KillEL737Counter; - pRes->iNoOfMonitors = 7; - pRes->fTime = 0.; - - return pRes; -} -/*--------------------------------------------------------------------------*/ - void KillEL737Counter(pCounterDriver self) - { - EL737st *pEL737 = NULL; - - assert(self); - pEL737 = (EL737st *)self->pData; - assert(pEL737); - - EL737_Close(&pEL737->pData,0); - if(pEL737->host) - { - free(pEL737->host); - } +pCounterDriver NewEL737Counter(char *name, char *host, int iPort, + int iChannel) +{ + pCounterDriver pRes = NULL; + EL737st *pData = NULL; + int iRet; + int iC1, iC2, iC3; + char *pErr; + char pBueffel[132]; + + pRes = CreateCounterDriver(name, "EL737"); + if (!pRes) { + return NULL; } + /* open connection to counter */ + pData = (EL737st *) malloc(sizeof(EL737st)); + if (!pData) { + DeleteCounterDriver(pRes); + return NULL; + } + pData->host = strdup(host); + pData->iPort = iPort; + pData->iChannel = iChannel; + pData->pData = NULL; + iRet = EL737_Open(&(pData->pData), host, iPort, iChannel); + if (iRet != 1) { + EL737_ErrInfo(&pErr, &iC1, &iC2, &iC3); + DeleteCounterDriver(pRes); + if (pData->host) { + free(pData->host); + } + return NULL; + } + pRes->pData = (void *) pData; + /* assign functions */ + pRes->GetStatus = EL737GetStatus; + pRes->Start = EL737Start; + pRes->Halt = EL737Halt; + pRes->ReadValues = EL737ReadValues; + pRes->GetError = EL737GetError; + pRes->TryAndFixIt = EL737TryAndFixIt; + pRes->Pause = EL737Pause; + pRes->Continue = EL737Continue; + pRes->Set = EL737Set; + pRes->Get = EL737Get; + pRes->Send = EL737Send; + pRes->KillPrivate = KillEL737Counter; + pRes->iNoOfMonitors = 7; + pRes->fTime = 0.; + return pRes; +} +/*--------------------------------------------------------------------------*/ +void KillEL737Counter(pCounterDriver self) +{ + EL737st *pEL737 = NULL; + assert(self); + pEL737 = (EL737st *) self->pData; + assert(pEL737); - - - - + EL737_Close(&pEL737->pData, 0); + if (pEL737->host) { + free(pEL737->host); + } +} diff --git a/el737hpdriv.c b/el737hpdriv.c index 61d3edb..1ed52b2 100644 --- a/el737hpdriv.c +++ b/el737hpdriv.c @@ -29,20 +29,20 @@ ------------------------------------------------------------------------*/ typedef struct { prs232 controller; - int monitorCount; /* read monitors if this is above MONTHRESH */ + int monitorCount; /* read monitors if this is above MONTHRESH */ float cachedControl; int errorCode; - int finishCount; /* need RS = 0 2 times before really sure finished */ + int finishCount; /* need RS = 0 2 times before really sure finished */ int statusMode; time_t startRequest; - int lastStatus; /* need to remember last status, otherwise I get oscillating - NoBeam and Counting status if the beam goes off - */ + int lastStatus; /* need to remember last status, otherwise I get oscillating + NoBeam and Counting status if the beam goes off + */ char *badReply; - int readErrorCount; /* need to remember failed reads: on RDOE, upper level - code will see busy's and thus not catch the case of - multiple failures - */ + int readErrorCount; /* need to remember failed reads: on RDOE, upper level + code will see busy's and thus not catch the case of + multiple failures + */ } EL737hp, *pEL737hp; /*--------------------- ERROR CODES -------------------------------------*/ #define OFFLINE -1 @@ -57,118 +57,128 @@ typedef struct { #define TIMEOUT737 -12 #define TOMANYREADERRORS -23 /*---------------------------------------------------------------------*/ -static void setBadReply(pEL737hp self, char *reply){ - if(self->badReply != NULL){ +static void setBadReply(pEL737hp self, char *reply) +{ + if (self->badReply != NULL) { free(self->badReply); } self->badReply = strdup(reply); } + /*----------------------------------------------------------------------- search errors in a reply from the EL737. Returns 1 on success or a negative error code in case of trouble. ------------------------------------------------------------------------*/ -static int checkEL737Error(char *pReply){ +static int checkEL737Error(char *pReply) +{ /* - all error start with a ?, if no ? in reply, answer is OK! - */ - if(strstr(pReply,"?") == NULL){ + all error start with a ?, if no ? in reply, answer is OK! + */ + if (strstr(pReply, "?") == NULL) { return 1; } /* - Now there is an error and we have to identify it - */ - if(strstr(pReply,"?OF") != NULL){ + Now there is an error and we have to identify it + */ + if (strstr(pReply, "?OF") != NULL) { return OFFLINE; - } else if(strstr(pReply,"?OV") != NULL){ + } else if (strstr(pReply, "?OV") != NULL) { return OVERFLOW; - } else if(strstr(pReply,"?1") != NULL){ + } else if (strstr(pReply, "?1") != NULL) { return BADRANGE; - } else if(strstr(pReply,"?2") != NULL){ + } else if (strstr(pReply, "?2") != NULL) { return BADCOMMAND; - } else if(strstr(pReply,"?3") != NULL){ + } else if (strstr(pReply, "?3") != NULL) { return BADPARAM; - } else if(strstr(pReply,"?4") != NULL){ + } else if (strstr(pReply, "?4") != NULL) { return BADCOUNTER; - } else if(strstr(pReply,"?5") != NULL){ + } else if (strstr(pReply, "?5") != NULL) { return NOPARAM; - } else if(strstr(pReply,"?6") != NULL){ + } else if (strstr(pReply, "?6") != NULL) { return TOMANYCOUNTS; - } else { + } else { return SYSERROR; } } + /*--------------------------------------------------------------- fixMode checks if we are in STATRECEIVE mode, reads any pending data and sets the mode to STATSEND. This would fix the problem if another client wishes to give a command while we are expecting a status response ---------------------------------------------------------------*/ -static void fixMode(pEL737hp pPriv){ +static void fixMode(pEL737hp pPriv) +{ char pBuffer[256]; int len = 255; - if(pPriv->statusMode == STATRECEIVE){ - readRS232TillTerm(pPriv->controller,pBuffer,&len); + if (pPriv->statusMode == STATRECEIVE) { + readRS232TillTerm(pPriv->controller, pBuffer, &len); pPriv->statusMode = STATSEND; } } + /*---------------------------------------------------------------*/ static int EL737Command(pEL737hp pPriv, char *pCommand, - char *pReply, int replylen){ + char *pReply, int replylen) +{ int status; - status = transactRS232(pPriv->controller,pCommand,strlen(pCommand), - pReply,replylen); - if(status < 0){ + status = transactRS232(pPriv->controller, pCommand, strlen(pCommand), + pReply, replylen); + if (status < 0) { pPriv->errorCode = status; return 0; } status = checkEL737Error(pReply); - if(status < 0){ + if (status < 0) { pPriv->errorCode = status; return 0; } return 1; -} +} + /*----------------------------------------------------------------*/ -static int readRS(pEL737hp pPriv, int *RS){ +static int readRS(pEL737hp pPriv, int *RS) +{ int status, len = 131; char reply[132]; - status = readRS232TillTerm(pPriv->controller, - reply,&len); - if(status < 0) { + status = readRS232TillTerm(pPriv->controller, reply, &len); + if (status < 0) { pPriv->readErrorCount++; pPriv->errorCode = status; return 0; } status = checkEL737Error(reply); - if(status < 0){ + if (status < 0) { pPriv->readErrorCount++; pPriv->errorCode = status; return 0; } - status = sscanf(reply,"%d",RS); - if(status < 1){ + status = sscanf(reply, "%d", RS); + if (status < 1) { pPriv->readErrorCount++; pPriv->errorCode = BADREPLY; - setBadReply(pPriv,reply); + setBadReply(pPriv, reply); printf("Bad reply to EL737 RS command: %s\n", reply); return 0; } pPriv->readErrorCount = 0; return 1; } + /*-----------------------------------------------------------------*/ -static int decodeRS(pEL737hp pPriv, int RS){ +static int decodeRS(pEL737hp pPriv, int RS) +{ int returnValue; - switch(RS){ + switch (RS) { case 0: pPriv->finishCount++; - if(pPriv->finishCount > 2){ + if (pPriv->finishCount > 2) { returnValue = HWIdle; } else { returnValue = HWBusy; @@ -191,33 +201,36 @@ static int decodeRS(pEL737hp pPriv, int RS){ } return returnValue; } + /*-----------------------------------------------------------------*/ -static int updateMonitors(struct __COUNTER *self){ +static int updateMonitors(struct __COUNTER *self) +{ int status; - long m1,m2,m3,m4,m5,m6,m7,m8; + long m1, m2, m3, m4, m5, m6, m7, m8; float fTime; pEL737hp pPriv = NULL; char reply[132]; - pPriv = (pEL737hp)self->pData; + pPriv = (pEL737hp) self->pData; - if(!EL737Command(pPriv,"RA\r",reply,131)){ + if (!EL737Command(pPriv, "RA\r", reply, 131)) { return 0; } /* - There are two forms of RA replys: new form with 8 monitors - */ - status = sscanf(reply,"%f %ld %ld %ld %ld %ld %ld %ld %ld", - &fTime,&m1,&m2,&m3,&m4,&m5,&m6,&m7,&m8); - if(status != 9){ + There are two forms of RA replys: new form with 8 monitors + */ + status = sscanf(reply, "%f %ld %ld %ld %ld %ld %ld %ld %ld", + &fTime, &m1, &m2, &m3, &m4, &m5, &m6, &m7, &m8); + if (status != 9) { /* - old form with 4 monitors - */ - status = sscanf(reply,"%ld %ld %ld %ld %f",&m1,&m2,&m3,&m4,&fTime); - if(status != 5){ + old form with 4 monitors + */ + status = + sscanf(reply, "%ld %ld %ld %ld %f", &m1, &m2, &m3, &m4, &fTime); + if (status != 5) { pPriv->errorCode = BADREPLY; - setBadReply(pPriv,reply); + setBadReply(pPriv, reply); printf("Bad reply to EL737 RA command: %s\n", reply); return 0; } @@ -232,27 +245,29 @@ static int updateMonitors(struct __COUNTER *self){ self->lCounts[7] = m8; self->fTime = fTime; - if(self->eMode == eTimer){ + if (self->eMode == eTimer) { pPriv->cachedControl = fTime; } else { pPriv->cachedControl = m1; } return 1; } + /*------------------------------------------------------------------*/ -static int EL737Status(struct __COUNTER *self, float *fControl){ +static int EL737Status(struct __COUNTER *self, float *fControl) +{ int status, RS, returnValue; pEL737hp pPriv = NULL; assert(self); - pPriv = (pEL737hp)self->pData; + pPriv = (pEL737hp) self->pData; /* - handle STATSEND mode - */ - if(pPriv->statusMode == STATSEND){ - status = writeRS232(pPriv->controller,"RS\r",3); - if(status < 0){ + handle STATSEND mode + */ + if (pPriv->statusMode == STATSEND) { + status = writeRS232(pPriv->controller, "RS\r", 3); + if (status < 0) { pPriv->errorCode = status; return HWFault; } @@ -263,10 +278,10 @@ static int EL737Status(struct __COUNTER *self, float *fControl){ } /* - now we are dealing with STATRECEIVE mode. - Check for timeout first. - */ - if(time(NULL) > pPriv->startRequest + 10){ + now we are dealing with STATRECEIVE mode. + Check for timeout first. + */ + if (time(NULL) > pPriv->startRequest + 10) { pPriv->statusMode = STATSEND; pPriv->errorCode = TIMEOUT737; pPriv->readErrorCount++; @@ -274,13 +289,13 @@ static int EL737Status(struct __COUNTER *self, float *fControl){ } /* - check availability of data - */ + check availability of data + */ status = availableNetRS232(pPriv->controller); - if(status == 0){ + if (status == 0) { *fControl = pPriv->cachedControl; return pPriv->lastStatus; - } else if(status < 0) { + } else if (status < 0) { *fControl = pPriv->cachedControl; pPriv->statusMode = STATSEND; pPriv->errorCode = SELECTFAIL; @@ -288,175 +303,192 @@ static int EL737Status(struct __COUNTER *self, float *fControl){ } /* - The snail in the counter box has replied. Read and process - the data - */ + The snail in the counter box has replied. Read and process + the data + */ pPriv->statusMode = STATSEND; - if(!readRS(pPriv,&RS)){ + if (!readRS(pPriv, &RS)) { return HWFault; } /* - decode it - */ - returnValue = decodeRS(pPriv,RS); + decode it + */ + returnValue = decodeRS(pPriv, RS); pPriv->lastStatus = returnValue; /* - check for excessive failed reads - */ - if(pPriv->readErrorCount > 3){ + check for excessive failed reads + */ + if (pPriv->readErrorCount > 3) { pPriv->errorCode = TOMANYREADERRORS; return HWFault; } /* - check if we update the monitors and do it - */ + check if we update the monitors and do it + */ pPriv->monitorCount++; - if(pPriv->monitorCount > MONTHRESH){ + if (pPriv->monitorCount > MONTHRESH) { status = updateMonitors(self); pPriv->monitorCount = 0; - if(!status){ + if (!status) { return HWFault; } } *fControl = pPriv->cachedControl; return returnValue; -} +} + /*-------------------------------------------------------------------*/ -static int EL737Start(struct __COUNTER *self){ +static int EL737Start(struct __COUNTER *self) +{ pEL737hp pPriv = NULL; int status; char pCommand[50], pReply[30]; assert(self); - pPriv = (pEL737hp)self->pData; + pPriv = (pEL737hp) self->pData; fixMode(pPriv); pPriv->readErrorCount = 0; - if(self->eMode == ePreset){ - snprintf(pCommand,49,"MP %d\r",(int)self->fPreset); + if (self->eMode == ePreset) { + snprintf(pCommand, 49, "MP %d\r", (int) self->fPreset); } else { - if(self->fPreset < .1 || self->fPreset > 200000) - { - self->iErrorCode = BADTRANGE; - return HWFault; + if (self->fPreset < .1 || self->fPreset > 200000) { + self->iErrorCode = BADTRANGE; + return HWFault; } - snprintf(pCommand,49,"TP %.2f\r", self->fPreset); + snprintf(pCommand, 49, "TP %.2f\r", self->fPreset); } - if(EL737Command(pPriv,pCommand,pReply,29) != 1){ + if (EL737Command(pPriv, pCommand, pReply, 29) != 1) { return 0; } pPriv->finishCount = 0; pPriv->lastStatus = HWBusy; return 1; } + /* --------------------------------------------------------------------*/ -static int EL737Pause(struct __COUNTER *self){ +static int EL737Pause(struct __COUNTER *self) +{ pEL737hp pPriv = NULL; int status; char pCommand[50], pReply[30]; assert(self); - pPriv = (pEL737hp)self->pData; + pPriv = (pEL737hp) self->pData; fixMode(pPriv); pPriv->lastStatus = HWPause; - return EL737Command(pPriv,"PS\r",pReply,29); + return EL737Command(pPriv, "PS\r", pReply, 29); } + /*----------------------------------------------------------------------*/ -static int EL737Continue(struct __COUNTER *self){ +static int EL737Continue(struct __COUNTER *self) +{ pEL737hp pPriv = NULL; int status; char pCommand[50], pReply[30]; assert(self); - pPriv = (pEL737hp)self->pData; + pPriv = (pEL737hp) self->pData; fixMode(pPriv); pPriv->lastStatus = HWBusy; - return EL737Command(pPriv,"CO\r",pReply,29); + return EL737Command(pPriv, "CO\r", pReply, 29); } + /*---------------------------------------------------------------------*/ -static int EL737Halt(struct __COUNTER *self){ +static int EL737Halt(struct __COUNTER *self) +{ pEL737hp pPriv = NULL; int status; char pCommand[50], pReply[30]; assert(self); - pPriv = (pEL737hp)self->pData; + pPriv = (pEL737hp) self->pData; fixMode(pPriv); pPriv->lastStatus = HWBusy; - return EL737Command(pPriv,"S\r",pReply,29); + return EL737Command(pPriv, "S\r", pReply, 29); } + /*-------------------------------------------------------------------*/ -static int EL737Transfer(struct __COUNTER *self){ +static int EL737Transfer(struct __COUNTER *self) +{ pEL737hp pPriv = NULL; assert(self); - pPriv = (pEL737hp)self->pData; + pPriv = (pEL737hp) self->pData; fixMode(pPriv); return updateMonitors(self); } + /*--------------------------------------------------------------------*/ -static int EL737GetError(struct __COUNTER *self, int *iCode, - char *pError, int errLen){ +static int EL737GetError(struct __COUNTER *self, int *iCode, + char *pError, int errLen) +{ pEL737hp pPriv = NULL; assert(self); - pPriv = (pEL737hp)self->pData; + pPriv = (pEL737hp) self->pData; *iCode = pPriv->errorCode; - switch(pPriv->errorCode){ + switch (pPriv->errorCode) { case OFFLINE: - strncpy(pError,"EL737 is offline",errLen); + strncpy(pError, "EL737 is offline", errLen); break; case OVERFLOW: - strncpy(pError,"EL737 reported overflow, communication problem",errLen); + strncpy(pError, "EL737 reported overflow, communication problem", + errLen); break; case BADRANGE: - strncpy(pError,"EL737 parameter is out of range",errLen); + strncpy(pError, "EL737 parameter is out of range", errLen); break; case BADTRANGE: - strncpy(pError,"preset timer out of range",errLen); + strncpy(pError, "preset timer out of range", errLen); break; case BADCOMMAND: - strncpy(pError,"EL737 received unknown command or is busy",errLen); + strncpy(pError, "EL737 received unknown command or is busy", errLen); break; case BADPARAM: - strncpy(pError,"EL737 parameter is awful",errLen); + strncpy(pError, "EL737 parameter is awful", errLen); break; case NOPARAM: - strncpy(pError,"EL737 parameter missing",errLen); + strncpy(pError, "EL737 parameter missing", errLen); break; case TOMANYCOUNTS: - strncpy(pError,"EL737 counters overflowed",errLen); + strncpy(pError, "EL737 counters overflowed", errLen); break; case SYSERROR: - strncpy(pError,"EL737 has an internal system error",errLen); + strncpy(pError, "EL737 has an internal system error", errLen); break; case BADREPLY: - snprintf(pError,errLen,"EL737 sent an unexpected reply: %s", - pPriv->badReply); + snprintf(pError, errLen, "EL737 sent an unexpected reply: %s", + pPriv->badReply); break; case SELECTFAIL: - strncpy(pError,"select system call failed, network trouble",errLen); + strncpy(pError, "select system call failed, network trouble", errLen); break; case TIMEOUT737: - strncpy(pError,"timeout or network problem while waiting for status repsonse",errLen); + strncpy(pError, + "timeout or network problem while waiting for status repsonse", + errLen); break; case TOMANYREADERRORS: - strncpy(pError,"Failed more then three times to read counter box",errLen); + strncpy(pError, "Failed more then three times to read counter box", + errLen); break; default: - getRS232Error(pPriv->errorCode,pError,errLen); + getRS232Error(pPriv->errorCode, pError, errLen); } return 1; } + /*--------------------------------------------------------------------*/ -static int EL737FixIt(struct __COUNTER *self, int iCode){ +static int EL737FixIt(struct __COUNTER *self, int iCode) +{ pEL737hp pPriv = NULL; int status; char pReply[50]; @@ -465,9 +497,9 @@ static int EL737FixIt(struct __COUNTER *self, int iCode){ int i; assert(self); - pPriv = (pEL737hp)self->pData; + pPriv = (pEL737hp) self->pData; - switch(iCode){ + switch (iCode) { case BADPARAM: case NOPARAM: case BADRANGE: @@ -478,100 +510,104 @@ static int EL737FixIt(struct __COUNTER *self, int iCode){ case BADREPLY: case TIMEOUT737: case TIMEOUT: - for(i = 0; i < 3; i++){ - status = readRS232TillTerm(pPriv->controller,buffer,&dataLen); - if(status == 1){ - return COREDO; + for (i = 0; i < 3; i++) { + status = readRS232TillTerm(pPriv->controller, buffer, &dataLen); + if (status == 1) { + return COREDO; } } /* - If nothing can be read, the only fixable cause is a network breakdown - Try to fix this. If this does not work: give up - */ + If nothing can be read, the only fixable cause is a network breakdown + Try to fix this. If this does not work: give up + */ closeRS232(pPriv->controller); SicsWait(60); status = initRS232(pPriv->controller); - if(status != 1){ + if (status != 1) { return COTERM; } else { return COREDO; } break; case OFFLINE: - EL737Command(pPriv,"RMT 1\r",pReply,49); - EL737Command(pPriv,"echo 2\r",pReply,49); + EL737Command(pPriv, "RMT 1\r", pReply, 49); + EL737Command(pPriv, "echo 2\r", pReply, 49); return COREDO; break; - case BADCOMMAND: /* can be busy, stop it and try again */ - EL737Command(pPriv,"S\r",pReply,49); + case BADCOMMAND: /* can be busy, stop it and try again */ + EL737Command(pPriv, "S\r", pReply, 49); return COREDO; break; case TOMANYCOUNTS: case SYSERROR: - return COTERM; + return COTERM; break; default: /* - network problem; try to reopen - */ + network problem; try to reopen + */ closeRS232(pPriv->controller); - SicsWait(60); + SicsWait(60); status = initRS232(pPriv->controller); - if(status != 1){ + if (status != 1) { return COTERM; } else { return COREDO; } } } + /*------------------------------------------------------------------------*/ -static int EL737Set(struct __COUNTER *self, char *name, int iCter, - float fVal){ +static int EL737Set(struct __COUNTER *self, char *name, int iCter, + float fVal) +{ pEL737hp pPriv = NULL; int status; char pCommand[80], pReply[50]; assert(self); - pPriv = (pEL737hp)self->pData; + pPriv = (pEL737hp) self->pData; fixMode(pPriv); - if(strcmp(name,"threshold") == 0){ - sprintf(pCommand,"DL %1.1d %f\r",iCter, fVal); - if(!EL737Command(pPriv,pCommand,pReply,49)){ + if (strcmp(name, "threshold") == 0) { + sprintf(pCommand, "DL %1.1d %f\r", iCter, fVal); + if (!EL737Command(pPriv, pCommand, pReply, 49)) { return 0; } - sprintf(pCommand,"DR %1.1d\r",iCter); - if(!EL737Command(pPriv,pCommand,pReply,49)){ + sprintf(pCommand, "DR %1.1d\r", iCter); + if (!EL737Command(pPriv, pCommand, pReply, 49)) { return 0; } return 1; - } else if(strcmp(name,"debug") == 0){ - setRS232Debug(pPriv->controller,(int)fVal); + } else if (strcmp(name, "debug") == 0) { + setRS232Debug(pPriv->controller, (int) fVal); return 1; } else { self->iErrorCode = UNKNOWNPAR; return 0; } } + /*----------------------------------------------------------------------*/ -static int EL737Get(struct __COUNTER *self, char *name, int iCter, - float *fVal){ +static int EL737Get(struct __COUNTER *self, char *name, int iCter, + float *fVal) +{ pEL737hp pPriv = NULL; int status; char pCommand[80], pReply[50]; assert(self); - pPriv = (pEL737hp)self->pData; + pPriv = (pEL737hp) self->pData; fixMode(pPriv); - if(strcmp(name,"threshold") == 0){ - sprintf(pCommand,"DL %1.1d\r",iCter); - if(!EL737Command(pPriv,pCommand,pReply,49)){ + if (strcmp(name, "threshold") == 0) { + sprintf(pCommand, "DL %1.1d\r", iCter); + if (!EL737Command(pPriv, pCommand, pReply, 49)) { return 0; } - sscanf(pReply,"%f", fVal); + sscanf(pReply, "%f", fVal); return 1; - } else if(strcmp(name,"debug") == 0){ + } else if (strcmp(name, "debug") == 0) { *fVal = pPriv->controller->debug; return 1; } else { @@ -579,104 +615,107 @@ static int EL737Get(struct __COUNTER *self, char *name, int iCter, return 0; } } + /*--------------------------------------------------------------------*/ static int EL737Send(struct __COUNTER *self, char *pText, char *pReply, - int iReplyLen){ + int iReplyLen) +{ pEL737hp pPriv = NULL; assert(self); - pPriv = (pEL737hp)self->pData; + pPriv = (pEL737hp) self->pData; fixMode(pPriv); - return EL737Command(pPriv,pText,pReply,iReplyLen); + return EL737Command(pPriv, pText, pReply, iReplyLen); } + /*---------------------------------------------------------------------*/ -static void KillHP(pCounterDriver self){ +static void KillHP(pCounterDriver self) +{ pEL737hp pPriv = NULL; assert(self); - pPriv = (pEL737hp)self->pData; + pPriv = (pEL737hp) self->pData; - if(!pPriv){ + if (!pPriv) { return; } - if(pPriv->controller != NULL){ + if (pPriv->controller != NULL) { KillRS232(pPriv->controller); } - if(pPriv->badReply != NULL){ + if (pPriv->badReply != NULL) { free(pPriv->badReply); } free(pPriv); } + /*-------------------------------------------------------------------*/ -pCounterDriver MakeEL737HP(SConnection *pCon, char *name, - int argc, char *argv[]){ +pCounterDriver MakeEL737HP(SConnection * pCon, char *name, + int argc, char *argv[]) +{ pCounterDriver pNew = NULL; pEL737hp pPriv = NULL; char pHost[132]; int port, status; /* - check arguments - */ - if(argc < 2) { - SCWrite(pCon,"ERROR: insufficient no af arguments to create EL737HP", - eError); + check arguments + */ + if (argc < 2) { + SCWrite(pCon, "ERROR: insufficient no af arguments to create EL737HP", + eError); return NULL; } - if(!isNumeric(argv[1])){ - SCWrite(pCon,"ERROR: expected numeric argument for port number", - eError); + if (!isNumeric(argv[1])) { + SCWrite(pCon, "ERROR: expected numeric argument for port number", + eError); return NULL; } port = atoi(argv[1]); - strncpy(pHost,argv[0],131); + strncpy(pHost, argv[0], 131); /* - allocate a bank worth of memory ........... - */ - pNew = CreateCounterDriver(name,"EL737HP"); - pPriv = (pEL737hp)malloc(sizeof(EL737hp)); - if(!pNew || !pPriv){ + allocate a bank worth of memory ........... + */ + pNew = CreateCounterDriver(name, "EL737HP"); + pPriv = (pEL737hp) malloc(sizeof(EL737hp)); + if (!pNew || !pPriv) { return NULL; } - memset(pPriv,0,sizeof(EL737hp)); - pPriv->controller = createRS232(pHost,port); - if(!pPriv->controller){ + memset(pPriv, 0, sizeof(EL737hp)); + pPriv->controller = createRS232(pHost, port); + if (!pPriv->controller) { DeleteCounterDriver(pNew); return NULL; } /* assign functions */ - pNew->GetStatus = EL737Status; - pNew->Start = EL737Start; - pNew->Halt = EL737Halt; - pNew->ReadValues = EL737Transfer; - pNew->GetError = EL737GetError; + pNew->GetStatus = EL737Status; + pNew->Start = EL737Start; + pNew->Halt = EL737Halt; + pNew->ReadValues = EL737Transfer; + pNew->GetError = EL737GetError; pNew->TryAndFixIt = EL737FixIt; - pNew->Pause = EL737Pause; - pNew->Continue = EL737Continue; - pNew->Set = EL737Set; - pNew->Get = EL737Get; - pNew->Send = EL737Send; + pNew->Pause = EL737Pause; + pNew->Continue = EL737Continue; + pNew->Set = EL737Set; + pNew->Get = EL737Get; + pNew->Send = EL737Send; pNew->KillPrivate = KillHP; pNew->iNoOfMonitors = 7; pNew->fTime = 0.; pNew->pData = pPriv; /* - initialize connection - */ - setRS232Debug(pPriv->controller,0); - setRS232ReplyTerminator(pPriv->controller,"\r"); + initialize connection + */ + setRS232Debug(pPriv->controller, 0); + setRS232ReplyTerminator(pPriv->controller, "\r"); setRS232Timeout(pPriv->controller, 4000); status = initRS232(pPriv->controller); - status = EL737Command(pPriv,"RMT 1\r",pHost,131); - status = EL737Command(pPriv,"RMT 1\r",pHost,131); - status = EL737Command(pPriv,"ECHO 2\r",pHost,131); + status = EL737Command(pPriv, "RMT 1\r", pHost, 131); + status = EL737Command(pPriv, "RMT 1\r", pHost, 131); + status = EL737Command(pPriv, "ECHO 2\r", pHost, 131); return pNew; } - - - diff --git a/el737hpdrivsps.c b/el737hpdrivsps.c index b8a91a2..b867b6b 100644 --- a/el737hpdrivsps.c +++ b/el737hpdrivsps.c @@ -36,21 +36,21 @@ ------------------------------------------------------------------------*/ typedef struct { prs232 controller; - int monitorCount; /* read monitors if this is above MONTHRESH */ + int monitorCount; /* read monitors if this is above MONTHRESH */ float cachedControl; int errorCode; - int finishCount; /* need RS = 0 2 times before really sure finished */ + int finishCount; /* need RS = 0 2 times before really sure finished */ int statusMode; time_t startRequest; - int lastStatus; /* need to remember last status, otherwise I get oscillating - NoBeam and Counting status if the beam goes off - */ + int lastStatus; /* need to remember last status, otherwise I get oscillating + NoBeam and Counting status if the beam goes off + */ char *badReply; - int readErrorCount; /* need to remember failed reads: on RDOE, upper level - code will see busy's and thus not catch the case of - multiple failures - */ - pSPS sps; + int readErrorCount; /* need to remember failed reads: on RDOE, upper level + code will see busy's and thus not catch the case of + multiple failures + */ + pSPS sps; } EL737hpsps, *pEL737hpsps; /*--------------------- ERROR CODES -------------------------------------*/ #define OFFLINE -1 @@ -66,117 +66,127 @@ typedef struct { #define TOMANYREADERRORS -23 #define DETOVERLOAD -24 /*---------------------------------------------------------------------*/ -static void setBadReply(pEL737hpsps self, char *reply){ - if(self->badReply != NULL){ +static void setBadReply(pEL737hpsps self, char *reply) +{ + if (self->badReply != NULL) { free(self->badReply); } self->badReply = strdup(reply); } + /*----------------------------------------------------------------------- search errors in a reply from the EL737. Returns 1 on success or a negative error code in case of trouble. ------------------------------------------------------------------------*/ -static int checkEL737Error(char *pReply){ +static int checkEL737Error(char *pReply) +{ /* - all error start with a ?, if no ? in reply, answer is OK! - */ - if(strstr(pReply,"?") == NULL){ + all error start with a ?, if no ? in reply, answer is OK! + */ + if (strstr(pReply, "?") == NULL) { return 1; } /* - Now there is an error and we have to identify it - */ - if(strstr(pReply,"?OF") != NULL){ + Now there is an error and we have to identify it + */ + if (strstr(pReply, "?OF") != NULL) { return OFFLINE; - } else if(strstr(pReply,"?OV") != NULL){ + } else if (strstr(pReply, "?OV") != NULL) { return OVERFLOW; - } else if(strstr(pReply,"?1") != NULL){ + } else if (strstr(pReply, "?1") != NULL) { return BADRANGE; - } else if(strstr(pReply,"?2") != NULL){ + } else if (strstr(pReply, "?2") != NULL) { return BADCOMMAND; - } else if(strstr(pReply,"?3") != NULL){ + } else if (strstr(pReply, "?3") != NULL) { return BADPARAM; - } else if(strstr(pReply,"?4") != NULL){ + } else if (strstr(pReply, "?4") != NULL) { return BADCOUNTER; - } else if(strstr(pReply,"?5") != NULL){ + } else if (strstr(pReply, "?5") != NULL) { return NOPARAM; - } else if(strstr(pReply,"?6") != NULL){ + } else if (strstr(pReply, "?6") != NULL) { return TOMANYCOUNTS; - } else { + } else { return SYSERROR; } } + /*--------------------------------------------------------------- fixMode checks if we are in STATRECEIVE mode, reads any pending data and sets the mode to STATSEND. This would fix the problem if another client wishes to give a command while we are expecting a status response ---------------------------------------------------------------*/ -static void fixMode(pEL737hpsps pPriv){ +static void fixMode(pEL737hpsps pPriv) +{ char pBuffer[256]; int len = 255; - if(pPriv->statusMode == STATRECEIVE){ - readRS232TillTerm(pPriv->controller,pBuffer,&len); + if (pPriv->statusMode == STATRECEIVE) { + readRS232TillTerm(pPriv->controller, pBuffer, &len); pPriv->statusMode = STATSEND; } } + /*---------------------------------------------------------------*/ static int EL737SCommand(pEL737hpsps pPriv, char *pCommand, - char *pReply, int replylen){ + char *pReply, int replylen) +{ int status; - status = transactRS232(pPriv->controller,pCommand,strlen(pCommand), - pReply,replylen); - if(status < 0){ + status = transactRS232(pPriv->controller, pCommand, strlen(pCommand), + pReply, replylen); + if (status < 0) { pPriv->errorCode = status; return 0; } status = checkEL737Error(pReply); - if(status < 0){ + if (status < 0) { pPriv->errorCode = status; return 0; } return 1; -} +} + /*----------------------------------------------------------------*/ -static int readRS(pEL737hpsps pPriv, int *RS){ +static int readRS(pEL737hpsps pPriv, int *RS) +{ int status, len = 131; char reply[132]; - status = readRS232TillTerm(pPriv->controller, - reply,&len); - if(status < 0) { + status = readRS232TillTerm(pPriv->controller, reply, &len); + if (status < 0) { pPriv->readErrorCount++; pPriv->errorCode = status; return 0; } status = checkEL737Error(reply); - if(status < 0){ + if (status < 0) { pPriv->readErrorCount++; pPriv->errorCode = status; return 0; } - status = sscanf(reply,"%d",RS); - if(status < 1){ + status = sscanf(reply, "%d", RS); + if (status < 1) { pPriv->readErrorCount++; pPriv->errorCode = BADREPLY; - setBadReply(pPriv,reply); + setBadReply(pPriv, reply); return 0; } pPriv->readErrorCount = 0; return 1; } + /*-----------------------------------------------------------------*/ -static int decodeRS(pEL737hpsps pPriv, int RS){ +static int decodeRS(pEL737hpsps pPriv, int RS) +{ int returnValue; - switch(RS){ + switch (RS) { case 0: pPriv->finishCount++; - if(pPriv->finishCount > 2){ + if (pPriv->finishCount > 2) { returnValue = HWIdle; } else { returnValue = HWBusy; @@ -199,33 +209,35 @@ static int decodeRS(pEL737hpsps pPriv, int RS){ } return returnValue; } + /*-----------------------------------------------------------------*/ -static int updateMonitors(struct __COUNTER *self){ +static int updateMonitors(struct __COUNTER *self) +{ int status; - int m1,m2,m3,m4,m5,m6,m7,m8; + int m1, m2, m3, m4, m5, m6, m7, m8; float fTime; pEL737hpsps pPriv = NULL; char reply[132]; - pPriv = (pEL737hpsps)self->pData; + pPriv = (pEL737hpsps) self->pData; - if(!EL737SCommand(pPriv,"RA\r",reply,131)){ + if (!EL737SCommand(pPriv, "RA\r", reply, 131)) { return 0; } /* - There are two forms of RA replys: new form with 8 monitors - */ - status = sscanf(reply,"%f %d %d %d %d %d %d %d %d", - &fTime,&m1,&m2,&m3,&m4,&m5,&m6,&m7,&m8); - if(status != 9){ + There are two forms of RA replys: new form with 8 monitors + */ + status = sscanf(reply, "%f %d %d %d %d %d %d %d %d", + &fTime, &m1, &m2, &m3, &m4, &m5, &m6, &m7, &m8); + if (status != 9) { /* - old form with 4 monitors - */ - status = sscanf(reply,"%d %d %d %d %f",&m1,&m2,&m3,&m4,&fTime); - if(status != 5){ + old form with 4 monitors + */ + status = sscanf(reply, "%d %d %d %d %f", &m1, &m2, &m3, &m4, &fTime); + if (status != 5) { pPriv->errorCode = BADREPLY; - setBadReply(pPriv,reply); + setBadReply(pPriv, reply); printf("Bad reply to EL737 RA command: %s\n", reply); return 0; } @@ -240,28 +252,30 @@ static int updateMonitors(struct __COUNTER *self){ self->lCounts[7] = m8; self->fTime = fTime; - if(self->eMode == eTimer){ + if (self->eMode == eTimer) { pPriv->cachedControl = fTime; } else { pPriv->cachedControl = m1; } return 1; } + /*------------------------------------------------------------------*/ -static int EL737SStatus(struct __COUNTER *self, float *fControl){ +static int EL737SStatus(struct __COUNTER *self, float *fControl) +{ int status, RS, returnValue; pEL737hpsps pPriv = NULL; int iBit = 0; assert(self); - pPriv = (pEL737hpsps)self->pData; + pPriv = (pEL737hpsps) self->pData; /* - handle STATSEND mode - */ - if(pPriv->statusMode == STATSEND){ - status = writeRS232(pPriv->controller,"RS\r",3); - if(status < 0){ + handle STATSEND mode + */ + if (pPriv->statusMode == STATSEND) { + status = writeRS232(pPriv->controller, "RS\r", 3); + if (status < 0) { pPriv->errorCode = status; return HWFault; } @@ -272,10 +286,10 @@ static int EL737SStatus(struct __COUNTER *self, float *fControl){ } /* - now we are dealing with STATRECEIVE mode. - Check for timeout first. - */ - if(time(NULL) > pPriv->startRequest + 10){ + now we are dealing with STATRECEIVE mode. + Check for timeout first. + */ + if (time(NULL) > pPriv->startRequest + 10) { pPriv->statusMode = STATSEND; pPriv->errorCode = TIMEOUT737; pPriv->readErrorCount++; @@ -283,13 +297,13 @@ static int EL737SStatus(struct __COUNTER *self, float *fControl){ } /* - check availability of data - */ + check availability of data + */ status = availableNetRS232(pPriv->controller); - if(status == 0){ + if (status == 0) { *fControl = pPriv->cachedControl; return pPriv->lastStatus; - } else if(status < 0) { + } else if (status < 0) { *fControl = pPriv->cachedControl; pPriv->statusMode = STATSEND; pPriv->errorCode = SELECTFAIL; @@ -297,188 +311,205 @@ static int EL737SStatus(struct __COUNTER *self, float *fControl){ } /* - The snail in the counter box has replied. Read and process - the data - */ + The snail in the counter box has replied. Read and process + the data + */ pPriv->statusMode = STATSEND; - if(!readRS(pPriv,&RS)){ + if (!readRS(pPriv, &RS)) { return HWFault; } /* - decode it - */ - returnValue = decodeRS(pPriv,RS); + decode it + */ + returnValue = decodeRS(pPriv, RS); pPriv->lastStatus = returnValue; /* - check for excessive failed reads - */ - if(pPriv->readErrorCount > 3){ + check for excessive failed reads + */ + if (pPriv->readErrorCount > 3) { pPriv->errorCode = TOMANYREADERRORS; return HWFault; } /* - check if we update the monitors and do it - */ + check if we update the monitors and do it + */ pPriv->monitorCount++; - if(pPriv->monitorCount > MONTHRESH){ + if (pPriv->monitorCount > MONTHRESH) { status = updateMonitors(self); pPriv->monitorCount = 0; - if(!status){ + if (!status) { return HWFault; } } *fControl = pPriv->cachedControl; - - if(returnValue == HWNoBeam){ + + if (returnValue == HWNoBeam) { /* ToDo: put in proper bit address when properly known */ - SPSGetStatus(pPriv->sps,79,&iBit); - if(iBit == 1){ - pPriv->errorCode = DETOVERLOAD; - return HWFault; + SPSGetStatus(pPriv->sps, 79, &iBit); + if (iBit == 1) { + pPriv->errorCode = DETOVERLOAD; + return HWFault; } } - + return returnValue; -} +} + /*-------------------------------------------------------------------*/ -static int EL737SStart(struct __COUNTER *self){ +static int EL737SStart(struct __COUNTER *self) +{ pEL737hpsps pPriv = NULL; int status; char pCommand[50], pReply[30]; assert(self); - pPriv = (pEL737hpsps)self->pData; + pPriv = (pEL737hpsps) self->pData; fixMode(pPriv); pPriv->readErrorCount = 0; - if(self->eMode == ePreset){ - snprintf(pCommand,49,"MP %d\r",(int)self->fPreset); + if (self->eMode == ePreset) { + snprintf(pCommand, 49, "MP %d\r", (int) self->fPreset); } else { - if(self->fPreset < .1 || self->fPreset > 200000) - { - self->iErrorCode = BADTRANGE; - return HWFault; + if (self->fPreset < .1 || self->fPreset > 200000) { + self->iErrorCode = BADTRANGE; + return HWFault; } - snprintf(pCommand,49,"TP %.2f\r", self->fPreset); + snprintf(pCommand, 49, "TP %.2f\r", self->fPreset); } - if(EL737SCommand(pPriv,pCommand,pReply,29) != 1){ + if (EL737SCommand(pPriv, pCommand, pReply, 29) != 1) { return 0; } pPriv->finishCount = 0; pPriv->lastStatus = HWBusy; return 1; } + /* --------------------------------------------------------------------*/ -static int EL737SPause(struct __COUNTER *self){ +static int EL737SPause(struct __COUNTER *self) +{ pEL737hpsps pPriv = NULL; int status; char pCommand[50], pReply[30]; assert(self); - pPriv = (pEL737hpsps)self->pData; + pPriv = (pEL737hpsps) self->pData; fixMode(pPriv); pPriv->lastStatus = HWPause; - return EL737SCommand(pPriv,"PS\r",pReply,29); + return EL737SCommand(pPriv, "PS\r", pReply, 29); } + /*----------------------------------------------------------------------*/ -static int EL737SContinue(struct __COUNTER *self){ +static int EL737SContinue(struct __COUNTER *self) +{ pEL737hpsps pPriv = NULL; int status; char pCommand[50], pReply[30]; assert(self); - pPriv = (pEL737hpsps)self->pData; + pPriv = (pEL737hpsps) self->pData; fixMode(pPriv); pPriv->lastStatus = HWBusy; - return EL737SCommand(pPriv,"CO\r",pReply,29); + return EL737SCommand(pPriv, "CO\r", pReply, 29); } + /*---------------------------------------------------------------------*/ -static int EL737SHalt(struct __COUNTER *self){ +static int EL737SHalt(struct __COUNTER *self) +{ pEL737hpsps pPriv = NULL; int status; char pCommand[50], pReply[30]; assert(self); - pPriv = (pEL737hpsps)self->pData; + pPriv = (pEL737hpsps) self->pData; fixMode(pPriv); pPriv->lastStatus = HWBusy; - return EL737SCommand(pPriv,"S\r",pReply,29); + return EL737SCommand(pPriv, "S\r", pReply, 29); } + /*-------------------------------------------------------------------*/ -static int EL737STransfer(struct __COUNTER *self){ +static int EL737STransfer(struct __COUNTER *self) +{ pEL737hpsps pPriv = NULL; assert(self); - pPriv = (pEL737hpsps)self->pData; + pPriv = (pEL737hpsps) self->pData; fixMode(pPriv); return updateMonitors(self); } + /*--------------------------------------------------------------------*/ -static int EL737SGetError(struct __COUNTER *self, int *iCode, - char *pError, int errLen){ +static int EL737SGetError(struct __COUNTER *self, int *iCode, + char *pError, int errLen) +{ pEL737hpsps pPriv = NULL; assert(self); - pPriv = (pEL737hpsps)self->pData; + pPriv = (pEL737hpsps) self->pData; *iCode = pPriv->errorCode; - switch(pPriv->errorCode){ + switch (pPriv->errorCode) { case OFFLINE: - strncpy(pError,"EL737 is offline",errLen); + strncpy(pError, "EL737 is offline", errLen); break; case OVERFLOW: - strncpy(pError,"EL737 reported overflow, communication problem",errLen); + strncpy(pError, "EL737 reported overflow, communication problem", + errLen); break; case BADRANGE: - strncpy(pError,"EL737 parameter is out of range",errLen); + strncpy(pError, "EL737 parameter is out of range", errLen); break; case BADTRANGE: - strncpy(pError,"preset timer out of range",errLen); + strncpy(pError, "preset timer out of range", errLen); break; case BADCOMMAND: - strncpy(pError,"EL737 received unknown command or is busy",errLen); + strncpy(pError, "EL737 received unknown command or is busy", errLen); break; case BADPARAM: - strncpy(pError,"EL737 parameter is awful",errLen); + strncpy(pError, "EL737 parameter is awful", errLen); break; case NOPARAM: - strncpy(pError,"EL737 parameter missing",errLen); + strncpy(pError, "EL737 parameter missing", errLen); break; case TOMANYCOUNTS: - strncpy(pError,"EL737 counters overflowed",errLen); + strncpy(pError, "EL737 counters overflowed", errLen); break; case SYSERROR: - strncpy(pError,"EL737 has an internal system error",errLen); + strncpy(pError, "EL737 has an internal system error", errLen); break; case BADREPLY: - snprintf(pError,errLen,"EL737 sent an unexpected reply: %s", - pPriv->badReply); + snprintf(pError, errLen, "EL737 sent an unexpected reply: %s", + pPriv->badReply); break; case SELECTFAIL: - strncpy(pError,"select system call failed, network trouble",errLen); + strncpy(pError, "select system call failed, network trouble", errLen); break; case TIMEOUT737: - strncpy(pError,"timeout or network problem while waiting for status repsonse",errLen); + strncpy(pError, + "timeout or network problem while waiting for status repsonse", + errLen); break; case TOMANYREADERRORS: - strncpy(pError,"Failed more then three times to read counter box",errLen); + strncpy(pError, "Failed more then three times to read counter box", + errLen); break; case DETOVERLOAD: - strncpy(pError,"Shutter closed due to detector overload",errLen); + strncpy(pError, "Shutter closed due to detector overload", errLen); break; default: - getRS232Error(pPriv->errorCode,pError,errLen); + getRS232Error(pPriv->errorCode, pError, errLen); } return 1; } + /*--------------------------------------------------------------------*/ -static int EL737SFixIt(struct __COUNTER *self, int iCode){ +static int EL737SFixIt(struct __COUNTER *self, int iCode) +{ pEL737hpsps pPriv = NULL; int status; char pReply[50]; @@ -487,9 +518,9 @@ static int EL737SFixIt(struct __COUNTER *self, int iCode){ int i; assert(self); - pPriv = (pEL737hpsps)self->pData; + pPriv = (pEL737hpsps) self->pData; - switch(iCode){ + switch (iCode) { case BADPARAM: case NOPARAM: case BADRANGE: @@ -500,71 +531,73 @@ static int EL737SFixIt(struct __COUNTER *self, int iCode){ case BADREPLY: case TIMEOUT737: case TIMEOUT: - for(i = 0; i < 3; i++){ - status = readRS232TillTerm(pPriv->controller,buffer,&dataLen); - if(status == 1){ - return COREDO; + for (i = 0; i < 3; i++) { + status = readRS232TillTerm(pPriv->controller, buffer, &dataLen); + if (status == 1) { + return COREDO; } } /* - If nothing can be read, the only fixable cause is a network breakdown - Try to fix this. If this does not work: give up - */ + If nothing can be read, the only fixable cause is a network breakdown + Try to fix this. If this does not work: give up + */ closeRS232(pPriv->controller); SicsWait(60); status = initRS232(pPriv->controller); - if(status != 1){ + if (status != 1) { return COTERM; } else { return COREDO; } break; case OFFLINE: - EL737SCommand(pPriv,"RMT 1\r",pReply,49); - EL737SCommand(pPriv,"echo 2\r",pReply,49); + EL737SCommand(pPriv, "RMT 1\r", pReply, 49); + EL737SCommand(pPriv, "echo 2\r", pReply, 49); return COREDO; break; - case BADCOMMAND: /* can be busy, stop it and try again */ - EL737SCommand(pPriv,"S\r",pReply,49); + case BADCOMMAND: /* can be busy, stop it and try again */ + EL737SCommand(pPriv, "S\r", pReply, 49); return COREDO; break; case TOMANYCOUNTS: case SYSERROR: case DETOVERLOAD: - return COTERM; + return COTERM; break; default: /* - network problem; try to reopen - */ + network problem; try to reopen + */ closeRS232(pPriv->controller); - SicsWait(60); + SicsWait(60); status = initRS232(pPriv->controller); - if(status != 1){ + if (status != 1) { return COTERM; } else { return COREDO; } } } + /*------------------------------------------------------------------------*/ -static int EL737SSet(struct __COUNTER *self, char *name, int iCter, - float fVal){ +static int EL737SSet(struct __COUNTER *self, char *name, int iCter, + float fVal) +{ pEL737hpsps pPriv = NULL; int status; char pCommand[80], pReply[50]; assert(self); - pPriv = (pEL737hpsps)self->pData; + pPriv = (pEL737hpsps) self->pData; fixMode(pPriv); - if(strcmp(name,"threshold") == 0){ - sprintf(pCommand,"DL %1.1d %f\r",iCter, fVal); - if(!EL737SCommand(pPriv,pCommand,pReply,49)){ + if (strcmp(name, "threshold") == 0) { + sprintf(pCommand, "DL %1.1d %f\r", iCter, fVal); + if (!EL737SCommand(pPriv, pCommand, pReply, 49)) { return 0; } - sprintf(pCommand,"DR %1.1d\r",iCter); - if(!EL737SCommand(pPriv,pCommand,pReply,49)){ + sprintf(pCommand, "DR %1.1d\r", iCter); + if (!EL737SCommand(pPriv, pCommand, pReply, 49)) { return 0; } return 1; @@ -573,132 +606,138 @@ static int EL737SSet(struct __COUNTER *self, char *name, int iCter, return 0; } } + /*----------------------------------------------------------------------*/ -static int EL737SGet(struct __COUNTER *self, char *name, int iCter, - float *fVal){ +static int EL737SGet(struct __COUNTER *self, char *name, int iCter, + float *fVal) +{ pEL737hpsps pPriv = NULL; int status; char pCommand[80], pReply[50]; assert(self); - pPriv = (pEL737hpsps)self->pData; + pPriv = (pEL737hpsps) self->pData; fixMode(pPriv); - if(strcmp(name,"threshold") == 0){ - sprintf(pCommand,"DL %1.1d\r",iCter); - if(!EL737SCommand(pPriv,pCommand,pReply,49)){ + if (strcmp(name, "threshold") == 0) { + sprintf(pCommand, "DL %1.1d\r", iCter); + if (!EL737SCommand(pPriv, pCommand, pReply, 49)) { return 0; } - sscanf(pReply,"%f", fVal); + sscanf(pReply, "%f", fVal); return 1; } else { self->iErrorCode = UNKNOWNPAR; return 0; } } + /*--------------------------------------------------------------------*/ static int EL737SSend(struct __COUNTER *self, char *pText, char *pReply, - int iReplyLen){ + int iReplyLen) +{ pEL737hpsps pPriv = NULL; assert(self); - pPriv = (pEL737hpsps)self->pData; + pPriv = (pEL737hpsps) self->pData; fixMode(pPriv); - return EL737SCommand(pPriv,pText,pReply,iReplyLen); + return EL737SCommand(pPriv, pText, pReply, iReplyLen); } + /*---------------------------------------------------------------------*/ -static void KillHP(pCounterDriver self){ +static void KillHP(pCounterDriver self) +{ pEL737hpsps pPriv = NULL; assert(self); - pPriv = (pEL737hpsps)self->pData; + pPriv = (pEL737hpsps) self->pData; - if(!pPriv){ + if (!pPriv) { return; } - if(pPriv->controller != NULL){ + if (pPriv->controller != NULL) { KillRS232(pPriv->controller); } - if(pPriv->badReply != NULL){ + if (pPriv->badReply != NULL) { free(pPriv->badReply); } free(pPriv); } + /*-------------------------------------------------------------------*/ -pCounterDriver MakeEL737hpsps(SConnection *pCon, char *name, - int argc, char *argv[]){ +pCounterDriver MakeEL737hpsps(SConnection * pCon, char *name, + int argc, char *argv[]) +{ pCounterDriver pNew = NULL; pEL737hpsps pPriv = NULL; char pHost[132]; int port, status; /* - check arguments - */ - if(argc < 3) { - SCWrite(pCon,"ERROR: insufficient no af arguments to create EL737HPSPS", - eError); + check arguments + */ + if (argc < 3) { + SCWrite(pCon, + "ERROR: insufficient no af arguments to create EL737HPSPS", + eError); return NULL; } - if(!isNumeric(argv[1])){ - SCWrite(pCon,"ERROR: expected numeric argument for port number", - eError); + if (!isNumeric(argv[1])) { + SCWrite(pCon, "ERROR: expected numeric argument for port number", + eError); return NULL; } port = atoi(argv[1]); - strncpy(pHost,argv[0],131); + strncpy(pHost, argv[0], 131); /* - allocate a bank worth of memory ........... - */ - pNew = CreateCounterDriver(name,"EL737HPSPS"); - pPriv = (pEL737hpsps)malloc(sizeof(EL737hpsps)); - if(!pNew || !pPriv){ + allocate a bank worth of memory ........... + */ + pNew = CreateCounterDriver(name, "EL737HPSPS"); + pPriv = (pEL737hpsps) malloc(sizeof(EL737hpsps)); + if (!pNew || !pPriv) { return NULL; } - memset(pPriv,0,sizeof(EL737hpsps)); - pPriv->controller = createRS232(pHost,port); - if(!pPriv->controller){ + memset(pPriv, 0, sizeof(EL737hpsps)); + pPriv->controller = createRS232(pHost, port); + if (!pPriv->controller) { DeleteCounterDriver(pNew); return NULL; } - pPriv->sps = (pSPS)FindCommandData(pServ->pSics,argv[2],"SPS"); - if(pPriv->sps == NULL){ - SCWrite(pCon,"ERROR: SPS not found",eError); + pPriv->sps = (pSPS) FindCommandData(pServ->pSics, argv[2], "SPS"); + if (pPriv->sps == NULL) { + SCWrite(pCon, "ERROR: SPS not found", eError); DeleteCounterDriver(pNew); return NULL; } /* assign functions */ - pNew->GetStatus = EL737SStatus; - pNew->Start = EL737SStart; - pNew->Halt = EL737SHalt; - pNew->ReadValues = EL737STransfer; - pNew->GetError = EL737SGetError; + pNew->GetStatus = EL737SStatus; + pNew->Start = EL737SStart; + pNew->Halt = EL737SHalt; + pNew->ReadValues = EL737STransfer; + pNew->GetError = EL737SGetError; pNew->TryAndFixIt = EL737SFixIt; - pNew->Pause = EL737SPause; - pNew->Continue = EL737SContinue; - pNew->Set = EL737SSet; - pNew->Get = EL737SGet; - pNew->Send = EL737SSend; + pNew->Pause = EL737SPause; + pNew->Continue = EL737SContinue; + pNew->Set = EL737SSet; + pNew->Get = EL737SGet; + pNew->Send = EL737SSend; pNew->KillPrivate = KillHP; pNew->iNoOfMonitors = 7; pNew->fTime = 0.; pNew->pData = pPriv; /* - initialize connection - */ - setRS232Debug(pPriv->controller,0); - setRS232ReplyTerminator(pPriv->controller,"\r"); + initialize connection + */ + setRS232Debug(pPriv->controller, 0); + setRS232ReplyTerminator(pPriv->controller, "\r"); status = initRS232(pPriv->controller); - status = EL737SCommand(pPriv,"RMT 1\r",pHost,131); - status = EL737SCommand(pPriv,"RMT 1\r",pHost,131); - status = EL737SCommand(pPriv,"ECHO 2\r",pHost,131); + status = EL737SCommand(pPriv, "RMT 1\r", pHost, 131); + status = EL737SCommand(pPriv, "RMT 1\r", pHost, 131); + status = EL737SCommand(pPriv, "ECHO 2\r", pHost, 131); return pNew; } - - - diff --git a/el737hpv2driv.c b/el737hpv2driv.c index 0f3d651..0c05aea 100644 --- a/el737hpv2driv.c +++ b/el737hpv2driv.c @@ -25,7 +25,7 @@ ------------------------------------------------------------------------*/ typedef struct { prs232 controller; - int monitorCount; /* read monitors if this is above MONTHRESH */ + int monitorCount; /* read monitors if this is above MONTHRESH */ float cachedControl; int errorCode; char savedStarMessage[20]; @@ -47,96 +47,101 @@ typedef struct { search errors in a reply from the EL737. Returns 1 on success or a negative error code in case of trouble. ------------------------------------------------------------------------*/ -static int checkEL737Error(pEL737hp self, char *pReply){ +static int checkEL737Error(pEL737hp self, char *pReply) +{ /* - all error start with a ?, if no ? in reply, answer is OK! - */ - if(strstr(pReply,"?") == NULL){ + all error start with a ?, if no ? in reply, answer is OK! + */ + if (strstr(pReply, "?") == NULL) { return 1; } /* - Now there is an error and we have to identify it - */ - if(strstr(pReply,"?OF") != NULL){ + Now there is an error and we have to identify it + */ + if (strstr(pReply, "?OF") != NULL) { return OFFLINE; - } else if(strstr(pReply,"?OV") != NULL){ + } else if (strstr(pReply, "?OV") != NULL) { return OVERFLOW; - } else if(strstr(pReply,"?1") != NULL){ + } else if (strstr(pReply, "?1") != NULL) { return BADRANGE; - } else if(strstr(pReply,"?2") != NULL){ + } else if (strstr(pReply, "?2") != NULL) { return BADCOMMAND; - } else if(strstr(pReply,"?3") != NULL){ + } else if (strstr(pReply, "?3") != NULL) { return BADPARAM; - } else if(strstr(pReply,"?4") != NULL){ + } else if (strstr(pReply, "?4") != NULL) { return BADCOUNTER; - } else if(strstr(pReply,"?5") != NULL){ + } else if (strstr(pReply, "?5") != NULL) { return NOPARAM; - } else if(strstr(pReply,"?6") != NULL){ + } else if (strstr(pReply, "?6") != NULL) { return TOMANYCOUNTS; - } else { + } else { return SYSERROR; } } + /*---------------------------------------------------------------*/ static int EL737Command(pEL737hp pPriv, char *pCommand, - char *pReply, int replylen){ + char *pReply, int replylen) +{ int status, savedLen; savedLen = replylen; - status = transactRS232(pPriv->controller,pCommand,strlen(pCommand), - pReply,replylen); - if(status < 0){ + status = transactRS232(pPriv->controller, pCommand, strlen(pCommand), + pReply, replylen); + if (status < 0) { pPriv->errorCode = status; return 0; } /* - save any * message which may have arrrived, and if so: read again - */ - if(strstr(pReply,"*") != NULL){ - memset(pPriv->savedStarMessage,0,20); - strncpy(pPriv->savedStarMessage,pReply,19); + save any * message which may have arrrived, and if so: read again + */ + if (strstr(pReply, "*") != NULL) { + memset(pPriv->savedStarMessage, 0, 20); + strncpy(pPriv->savedStarMessage, pReply, 19); pPriv->haveSavedStarMessage = 1; status = readRS232TillTerm(pPriv->controller, pReply, &savedLen); - if(status < 0){ + if (status < 0) { pPriv->errorCode = status; return 0; } } status = checkEL737Error(pPriv, pReply); - if(status < 0){ + if (status < 0) { pPriv->errorCode = status; return 0; } return 1; -} +} + /*-----------------------------------------------------------------*/ -static int updateMonitors(struct __COUNTER *self){ +static int updateMonitors(struct __COUNTER *self) +{ int status; - int m1,m2,m3,m4,m5,m6,m7,m8; + int m1, m2, m3, m4, m5, m6, m7, m8; float fTime; pEL737hp pPriv = NULL; char reply[132]; - pPriv = (pEL737hp)self->pData; + pPriv = (pEL737hp) self->pData; - if(!EL737Command(pPriv,"RA\r",reply,131)){ + if (!EL737Command(pPriv, "RA\r", reply, 131)) { return 0; } /* - There are two forms of RA replys: new form with 8 monitors - */ - status = sscanf(reply,"%f %d %d %d %d %d %d %d %d", - &fTime,&m1,&m2,&m3,&m4,&m5,&m6,&m7,&m8); - if(status != 9){ + There are two forms of RA replys: new form with 8 monitors + */ + status = sscanf(reply, "%f %d %d %d %d %d %d %d %d", + &fTime, &m1, &m2, &m3, &m4, &m5, &m6, &m7, &m8); + if (status != 9) { /* - old form with 4 monitors - */ - status = sscanf(reply,"%d %d %d %d %f",&m1,&m2,&m3,&m4,&fTime); - if(status != 5){ + old form with 4 monitors + */ + status = sscanf(reply, "%d %d %d %d %f", &m1, &m2, &m3, &m4, &fTime); + if (status != 5) { printf("Bad reply: %s\n", reply); pPriv->errorCode = BADREPLY; return 0; @@ -152,205 +157,223 @@ static int updateMonitors(struct __COUNTER *self){ self->lCounts[7] = m8; self->fTime = fTime; - if(self->eMode == eTimer){ + if (self->eMode == eTimer) { pPriv->cachedControl = fTime; } else { pPriv->cachedControl = m2; } return 1; } + /*-----------------------------------------------------------------*/ -static void decodeStarMessage(pEL737hp self, char *message){ +static void decodeStarMessage(pEL737hp self, char *message) +{ strtolower(message); - if(strstr(message,"*cf") != NULL){ + if (strstr(message, "*cf") != NULL) { self->lastStatus = HWIdle; - } else if(strstr(message,"*lr") != NULL){ + } else if (strstr(message, "*lr") != NULL) { self->lastStatus = HWNoBeam; - } else if(strstr(message,"*hr") != NULL){ + } else if (strstr(message, "*hr") != NULL) { self->lastStatus = HWBusy; } else { printf("Bad star mesage: %s\n", message); } } + /*------------------------------------------------------------------*/ -static int EL737Status(struct __COUNTER *self, float *fControl){ +static int EL737Status(struct __COUNTER *self, float *fControl) +{ int status, returnValue, len; pEL737hp pPriv = NULL; char starMessage[10]; assert(self); - pPriv = (pEL737hp)self->pData; + pPriv = (pEL737hp) self->pData; /* - now we are dealing with STATRECEIVE mode. - Check for data availability first. - */ + now we are dealing with STATRECEIVE mode. + Check for data availability first. + */ status = availableNetRS232(pPriv->controller); - if(status == 0){ + if (status == 0) { *fControl = pPriv->cachedControl; returnValue = pPriv->lastStatus; - } else if(status < 0) { + } else if (status < 0) { *fControl = pPriv->cachedControl; pPriv->errorCode = SELECTFAIL; return HWFault; } else { /* - we have data: read and decode the * message we are waiting fore - */ + we have data: read and decode the * message we are waiting fore + */ len = 9; - status = readRS232TillTerm(pPriv->controller,starMessage,&len); - if(status < 0){ + status = readRS232TillTerm(pPriv->controller, starMessage, &len); + if (status < 0) { pPriv->errorCode = status; return HWFault; } - decodeStarMessage(pPriv,starMessage); + decodeStarMessage(pPriv, starMessage); returnValue = pPriv->lastStatus; } /* - check if we update the monitors and do it - */ + check if we update the monitors and do it + */ pPriv->monitorCount++; - if(pPriv->monitorCount > pPriv->monitorThreshold){ + if (pPriv->monitorCount > pPriv->monitorThreshold) { status = updateMonitors(self); pPriv->monitorCount = 0; - if(!status){ + if (!status) { return HWFault; } } /* - check for a saved starMessage - */ - if(pPriv->haveSavedStarMessage != 0){ - decodeStarMessage(pPriv,pPriv->savedStarMessage); + check for a saved starMessage + */ + if (pPriv->haveSavedStarMessage != 0) { + decodeStarMessage(pPriv, pPriv->savedStarMessage); pPriv->haveSavedStarMessage = 0; returnValue = pPriv->lastStatus; } *fControl = pPriv->cachedControl; return returnValue; -} +} + /*-------------------------------------------------------------------*/ -static int EL737Start(struct __COUNTER *self){ +static int EL737Start(struct __COUNTER *self) +{ pEL737hp pPriv = NULL; int status; char pCommand[50], pReply[30]; assert(self); - pPriv = (pEL737hp)self->pData; + pPriv = (pEL737hp) self->pData; - if(self->eMode == ePreset){ - snprintf(pCommand,49,"MP %d\r",(int)self->fPreset); + if (self->eMode == ePreset) { + snprintf(pCommand, 49, "MP %d\r", (int) self->fPreset); } else { - snprintf(pCommand,49,"TP %.2f\r", self->fPreset); + snprintf(pCommand, 49, "TP %.2f\r", self->fPreset); } - if(EL737Command(pPriv,pCommand,pReply,29) != 1){ + if (EL737Command(pPriv, pCommand, pReply, 29) != 1) { return 0; } pPriv->lastStatus = HWBusy; return 1; } + /* --------------------------------------------------------------------*/ -static int EL737Pause(struct __COUNTER *self){ +static int EL737Pause(struct __COUNTER *self) +{ pEL737hp pPriv = NULL; int status; char pCommand[50], pReply[30]; assert(self); - pPriv = (pEL737hp)self->pData; + pPriv = (pEL737hp) self->pData; - status = EL737Command(pPriv,"PS\r",pReply,29); - if(status > 0){ - pPriv->lastStatus= HWPause; + status = EL737Command(pPriv, "PS\r", pReply, 29); + if (status > 0) { + pPriv->lastStatus = HWPause; } return status; } + /*----------------------------------------------------------------------*/ -static int EL737Continue(struct __COUNTER *self){ +static int EL737Continue(struct __COUNTER *self) +{ pEL737hp pPriv = NULL; int status; char pCommand[50], pReply[30]; assert(self); - pPriv = (pEL737hp)self->pData; + pPriv = (pEL737hp) self->pData; - status = EL737Command(pPriv,"CO\r",pReply,29); - if(status > 0){ + status = EL737Command(pPriv, "CO\r", pReply, 29); + if (status > 0) { pPriv->lastStatus = HWBusy; } return status; } + /*---------------------------------------------------------------------*/ -static int EL737Halt(struct __COUNTER *self){ +static int EL737Halt(struct __COUNTER *self) +{ pEL737hp pPriv = NULL; int status; char pCommand[50], pReply[30]; assert(self); - pPriv = (pEL737hp)self->pData; + pPriv = (pEL737hp) self->pData; - return EL737Command(pPriv,"S\r",pReply,29); + return EL737Command(pPriv, "S\r", pReply, 29); } + /*-------------------------------------------------------------------*/ -static int EL737Transfer(struct __COUNTER *self){ +static int EL737Transfer(struct __COUNTER *self) +{ pEL737hp pPriv = NULL; assert(self); - pPriv = (pEL737hp)self->pData; + pPriv = (pEL737hp) self->pData; return updateMonitors(self); } + /*--------------------------------------------------------------------*/ -static int EL737GetError(struct __COUNTER *self, int *iCode, - char *pError, int errLen){ +static int EL737GetError(struct __COUNTER *self, int *iCode, + char *pError, int errLen) +{ pEL737hp pPriv = NULL; assert(self); - pPriv = (pEL737hp)self->pData; + pPriv = (pEL737hp) self->pData; *iCode = pPriv->errorCode; - switch(pPriv->errorCode){ + switch (pPriv->errorCode) { case OFFLINE: - strncpy(pError,"EL737 is offline",errLen); + strncpy(pError, "EL737 is offline", errLen); break; case BADRANGE: - strncpy(pError,"EL737 parameter is out of range",errLen); + strncpy(pError, "EL737 parameter is out of range", errLen); break; case BADCOMMAND: - strncpy(pError,"EL737 received unknown command or is busy",errLen); + strncpy(pError, "EL737 received unknown command or is busy", errLen); break; case BADPARAM: - strncpy(pError,"EL737 parameter is awful",errLen); + strncpy(pError, "EL737 parameter is awful", errLen); break; case NOPARAM: - strncpy(pError,"EL737 parameter missing",errLen); + strncpy(pError, "EL737 parameter missing", errLen); break; case TOMANYCOUNTS: - strncpy(pError,"EL737 counters overflowed",errLen); + strncpy(pError, "EL737 counters overflowed", errLen); break; case SYSERROR: - strncpy(pError,"EL737 has an internal system error",errLen); + strncpy(pError, "EL737 has an internal system error", errLen); break; case BADREPLY: - strncpy(pError,"EL737 sent an unexpected reply",errLen); + strncpy(pError, "EL737 sent an unexpected reply", errLen); break; case SELECTFAIL: - strncpy(pError,"select system call failed, network trouble",errLen); + strncpy(pError, "select system call failed, network trouble", errLen); default: - getRS232Error(pPriv->errorCode,pError,errLen); + getRS232Error(pPriv->errorCode, pError, errLen); } return 1; } + /*--------------------------------------------------------------------*/ -static int EL737FixIt(struct __COUNTER *self, int iCode){ +static int EL737FixIt(struct __COUNTER *self, int iCode) +{ pEL737hp pPriv = NULL; int status; char pReply[50]; assert(self); - pPriv = (pEL737hp)self->pData; + pPriv = (pEL737hp) self->pData; - switch(iCode){ + switch (iCode) { case TIMEOUT: case BADREPLY: case BADPARAM: @@ -359,12 +382,12 @@ static int EL737FixIt(struct __COUNTER *self, int iCode){ return COREDO; break; case OFFLINE: - EL737Command(pPriv,"RMT 1\r",pReply,49); - EL737Command(pPriv,"echo 0\r",pReply,49); + EL737Command(pPriv, "RMT 1\r", pReply, 49); + EL737Command(pPriv, "echo 0\r", pReply, 49); return COREDO; break; - case BADCOMMAND: /* can be busy, stop it and try again */ - EL737Command(pPriv,"S\r",pReply,49); + case BADCOMMAND: /* can be busy, stop it and try again */ + EL737Command(pPriv, "S\r", pReply, 49); return COREDO; break; case TOMANYCOUNTS: @@ -373,162 +396,169 @@ static int EL737FixIt(struct __COUNTER *self, int iCode){ break; default: /* - network problem; try to reopen - */ + network problem; try to reopen + */ status = initRS232(pPriv->controller); - if(status != 1){ + if (status != 1) { return COTERM; } else { return COREDO; } } } + /*------------------------------------------------------------------------*/ -static int EL737Set(struct __COUNTER *self, char *name, int iCter, - float fVal){ +static int EL737Set(struct __COUNTER *self, char *name, int iCter, + float fVal) +{ pEL737hp pPriv = NULL; int status; char pCommand[80], pReply[50]; assert(self); - pPriv = (pEL737hp)self->pData; + pPriv = (pEL737hp) self->pData; - if(strcmp(name,"threshold") == 0){ - sprintf(pCommand,"DL %1.1d %f\r",iCter, fVal); - if(!EL737Command(pPriv,pCommand,pReply,49)){ + if (strcmp(name, "threshold") == 0) { + sprintf(pCommand, "DL %1.1d %f\r", iCter, fVal); + if (!EL737Command(pPriv, pCommand, pReply, 49)) { return 0; } - sprintf(pCommand,"DR %1.1d\r",iCter); - if(!EL737Command(pPriv,pCommand,pReply,49)){ + sprintf(pCommand, "DR %1.1d\r", iCter); + if (!EL737Command(pPriv, pCommand, pReply, 49)) { return 0; } return 1; - } else if(strcmp(name,"monitorupdate") != 0){ - pPriv->monitorThreshold = (int)fVal; - return 1; - }else { - self->iErrorCode = UNKNOWNPAR; - return 0; - } -} -/*----------------------------------------------------------------------*/ -static int EL737Get(struct __COUNTER *self, char *name, int iCter, - float *fVal){ - pEL737hp pPriv = NULL; - int status; - char pCommand[80], pReply[50]; - - assert(self); - pPriv = (pEL737hp)self->pData; - - if(strcmp(name,"threshold") == 0){ - sprintf(pCommand,"DL %1.1d\r",iCter); - if(!EL737Command(pPriv,pCommand,pReply,49)){ - return 0; - } - sscanf(pReply,"%f", fVal); - return 1; - } else if(strcmp(name,"monitorupdate") == 0){ - *fVal = (float)pPriv->monitorThreshold; + } else if (strcmp(name, "monitorupdate") != 0) { + pPriv->monitorThreshold = (int) fVal; return 1; } else { self->iErrorCode = UNKNOWNPAR; return 0; } } + +/*----------------------------------------------------------------------*/ +static int EL737Get(struct __COUNTER *self, char *name, int iCter, + float *fVal) +{ + pEL737hp pPriv = NULL; + int status; + char pCommand[80], pReply[50]; + + assert(self); + pPriv = (pEL737hp) self->pData; + + if (strcmp(name, "threshold") == 0) { + sprintf(pCommand, "DL %1.1d\r", iCter); + if (!EL737Command(pPriv, pCommand, pReply, 49)) { + return 0; + } + sscanf(pReply, "%f", fVal); + return 1; + } else if (strcmp(name, "monitorupdate") == 0) { + *fVal = (float) pPriv->monitorThreshold; + return 1; + } else { + self->iErrorCode = UNKNOWNPAR; + return 0; + } +} + /*--------------------------------------------------------------------*/ static int EL737Send(struct __COUNTER *self, char *pText, char *pReply, - int iReplyLen){ + int iReplyLen) +{ pEL737hp pPriv = NULL; assert(self); - pPriv = (pEL737hp)self->pData; + pPriv = (pEL737hp) self->pData; - return EL737Command(pPriv,pText,pReply,iReplyLen); + return EL737Command(pPriv, pText, pReply, iReplyLen); } + /*---------------------------------------------------------------------*/ -static void KillHP(pCounterDriver self){ +static void KillHP(pCounterDriver self) +{ pEL737hp pPriv = NULL; assert(self); - pPriv = (pEL737hp)self->pData; + pPriv = (pEL737hp) self->pData; - if(!pPriv){ + if (!pPriv) { return; } - if(pPriv->controller != NULL){ + if (pPriv->controller != NULL) { KillRS232(pPriv->controller); } free(pPriv); } + /*-------------------------------------------------------------------*/ -pCounterDriver MakeEL737HPV2(SConnection *pCon, char *name, - int argc, char *argv[]){ +pCounterDriver MakeEL737HPV2(SConnection * pCon, char *name, + int argc, char *argv[]) +{ pCounterDriver pNew = NULL; pEL737hp pPriv = NULL; char pHost[132]; int port, status; /* - check arguments - */ - if(argc < 2) { - SCWrite(pCon,"ERROR: insufficient no af arguments to create EL737HP", - eError); + check arguments + */ + if (argc < 2) { + SCWrite(pCon, "ERROR: insufficient no af arguments to create EL737HP", + eError); return NULL; } - if(!isNumeric(argv[1])){ - SCWrite(pCon,"ERROR: expected numeric argument for port number", - eError); + if (!isNumeric(argv[1])) { + SCWrite(pCon, "ERROR: expected numeric argument for port number", + eError); return NULL; } port = atoi(argv[1]); - strncpy(pHost,argv[0],131); + strncpy(pHost, argv[0], 131); /* - allocate a bank worth of memory ........... - */ - pNew = CreateCounterDriver(name,"EL737HP"); - pPriv = (pEL737hp)malloc(sizeof(EL737hp)); - if(!pNew || !pPriv){ + allocate a bank worth of memory ........... + */ + pNew = CreateCounterDriver(name, "EL737HP"); + pPriv = (pEL737hp) malloc(sizeof(EL737hp)); + if (!pNew || !pPriv) { return NULL; } - memset(pPriv,0,sizeof(EL737hp)); - pPriv->controller = createRS232(pHost,port); - if(!pPriv->controller){ + memset(pPriv, 0, sizeof(EL737hp)); + pPriv->controller = createRS232(pHost, port); + if (!pPriv->controller) { DeleteCounterDriver(pNew); return NULL; } /* assign functions */ - pNew->GetStatus = EL737Status; - pNew->Start = EL737Start; - pNew->Halt = EL737Halt; - pNew->ReadValues = EL737Transfer; - pNew->GetError = EL737GetError; + pNew->GetStatus = EL737Status; + pNew->Start = EL737Start; + pNew->Halt = EL737Halt; + pNew->ReadValues = EL737Transfer; + pNew->GetError = EL737GetError; pNew->TryAndFixIt = EL737FixIt; - pNew->Pause = EL737Pause; - pNew->Continue = EL737Continue; - pNew->Set = EL737Set; - pNew->Get = EL737Get; - pNew->Send = EL737Send; + pNew->Pause = EL737Pause; + pNew->Continue = EL737Continue; + pNew->Set = EL737Set; + pNew->Get = EL737Get; + pNew->Send = EL737Send; pNew->KillPrivate = KillHP; pNew->iNoOfMonitors = 7; pNew->fTime = 0.; pNew->pData = pPriv; /* - initialize connection - */ - setRS232Debug(pPriv->controller,0); - setRS232ReplyTerminator(pPriv->controller,"\r"); + initialize connection + */ + setRS232Debug(pPriv->controller, 0); + setRS232ReplyTerminator(pPriv->controller, "\r"); status = initRS232(pPriv->controller); - status = EL737Command(pPriv,"RMT 1\r",pHost,131); - status = EL737Command(pPriv,"RMT 1\r",pHost,131); - status = EL737Command(pPriv,"ECHO 0\r",pHost,131); + status = EL737Command(pPriv, "RMT 1\r", pHost, 131); + status = EL737Command(pPriv, "RMT 1\r", pHost, 131); + status = EL737Command(pPriv, "ECHO 0\r", pHost, 131); return pNew; } - - - diff --git a/el755driv.c b/el755driv.c index f7ffbc6..08a15db 100644 --- a/el755driv.c +++ b/el755driv.c @@ -25,317 +25,313 @@ #define CAPSIZED -8090 -#define ABS(x) (x < 0 ? -(x) : (x)) +#define ABS(x) (x < 0 ? -(x) : (x)) /*-----------------------------------------------------------------------*/ - typedef struct { - void *pData; - char *pHost; - int iPort; - int iChannel; - int iIndex; - int iLastError; - int iCapCount; - } EL755Driv, *pEL755Driv; +typedef struct { + void *pData; + char *pHost; + int iPort; + int iChannel; + int iIndex; + int iLastError; + int iCapCount; +} EL755Driv, *pEL755Driv; /*---------------------------------------------------------------------------*/ - static int GetEL755Pos(pEVDriver self, float *fPos) - { - pEL755Driv pMe = NULL; - int iRet; - float fSoll; - - assert(self); - pMe = (pEL755Driv)self->pPrivate; - assert(pMe); +static int GetEL755Pos(pEVDriver self, float *fPos) +{ + pEL755Driv pMe = NULL; + int iRet; + float fSoll; - iRet = EL755_GetCurrents(&(pMe->pData),&fSoll,fPos); - if(iRet != 1) - { - return 0; - } + assert(self); + pMe = (pEL755Driv) self->pPrivate; + assert(pMe); + + iRet = EL755_GetCurrents(&(pMe->pData), &fSoll, fPos); + if (iRet != 1) { + return 0; + } /** * This here is a check for the condition when the current breaks down. * This situation is characterized by the fSoll being something and the * fPos being 0. */ - if(ABS(*fPos) < .1 && ABS(fSoll) > .1 ){ - pMe->iCapCount++; - if(pMe->iCapCount > 3){ - pMe->iLastError = CAPSIZED; - return 0; - } - } - else - { - pMe->iCapCount = 0; - } - return 1; - } -/*----------------------------------------------------------------------------*/ - static int EL755Run(pEVDriver self, float fVal) - { - pEL755Driv pMe = NULL; - int iRet; - - assert(self); - pMe = (pEL755Driv )self->pPrivate; - assert(pMe); - - iRet = EL755_SetCurrent(&(pMe->pData),fVal); - pMe->iCapCount = 0; - if(iRet != 1) - { - return 0; - } - return 1; - } -/*--------------------------------------------------------------------------*/ - static int EL755Error(pEVDriver self, int *iCode, char *error, int iErrLen) - { - pEL755Driv pMe = NULL; - char *pPtr = NULL; - int i1, i2; - char pBueffel[132]; - - assert(self); - pMe = (pEL755Driv)self->pPrivate; - assert(pMe); - - /* retrieve error */ - EL755_ErrInfo(&pPtr,iCode,&i1,&i2); - switch(*iCode) - { - case CAPSIZED: - strncpy(error,"Powersupply has capsized, try lower current", iErrLen); - break; - case EL755__TURNED_OFF: - strncpy(error,"EL755__TURNED_OF",iErrLen); - break; - case EL755__TOO_MANY: - strncpy(error,"EL755__TO_MANY",iErrLen); - break; - case EL755__TOO_LARGE: - strncpy(error,"EL755__TOO_LARGE",iErrLen); - break; - case EL755__OVFLOW: - strncpy(error,"EL755_OVFLOW",iErrLen); - break; - case EL755__OUT_OF_RANGE: - strncpy(error,"EL755_OUT_OF_RANGE",iErrLen); - break; - case EL755__OFFLINE: - strncpy(error,"EL755_OFFLINE",iErrLen); - break; - case EL755__NO_SOCKET: - strncpy(error,"EL755__NO_SOCKET",iErrLen); - break; - case EL755__NOT_OPEN: - strncpy(error,"EL755__NOT_OPEN",iErrLen); - break; - case EL755__FORCED_CLOSED: - strncpy(error,"EL755__FORCED_CLOSED",iErrLen); - break; - case EL755__BAD_TMO: - strncpy(error,"EL755__BAD_TMO",iErrLen); - break; - case EL755__BAD_SOCKET: - strncpy(error,"EL755__BAD_SOCKET",iErrLen); - break; - case EL755__BAD_PAR: - strncpy(error,"EL755__BAD_PAR",iErrLen); - break; - case EL755__BAD_OFL: - strncpy(error,"EL755__BAD_OFL",iErrLen); - break; - case EL755__BAD_MALLOC: - strncpy(error,"EL755__BAD_MALLOC",iErrLen); - break; - case EL755__BAD_ILLG: - strncpy(error,"EL755__BAD_ILLG",iErrLen); - break; - case EL755__BAD_DEV: - strncpy(error,"EL755__BAD_DEV",iErrLen); - break; - case EL755__BAD_CMD: - strncpy(error,"EL755__BAD_CMD",iErrLen); - break; - case EL755__BAD_ASYNSRV: - strncpy(error,"EL755__BAD_ASYNSRV",iErrLen); - break; - default: - sprintf(pBueffel,"Unknown error %d found",*iCode); - strncpy(error,pBueffel,iErrLen); - break; - } - - return 1; + if (ABS(*fPos) < .1 && ABS(fSoll) > .1) { + pMe->iCapCount++; + if (pMe->iCapCount > 3) { + pMe->iLastError = CAPSIZED; + return 0; + } + } else { + pMe->iCapCount = 0; } + return 1; +} + +/*----------------------------------------------------------------------------*/ +static int EL755Run(pEVDriver self, float fVal) +{ + pEL755Driv pMe = NULL; + int iRet; + + assert(self); + pMe = (pEL755Driv) self->pPrivate; + assert(pMe); + + iRet = EL755_SetCurrent(&(pMe->pData), fVal); + pMe->iCapCount = 0; + if (iRet != 1) { + return 0; + } + return 1; +} + +/*--------------------------------------------------------------------------*/ +static int EL755Error(pEVDriver self, int *iCode, char *error, int iErrLen) +{ + pEL755Driv pMe = NULL; + char *pPtr = NULL; + int i1, i2; + char pBueffel[132]; + + assert(self); + pMe = (pEL755Driv) self->pPrivate; + assert(pMe); + + /* retrieve error */ + EL755_ErrInfo(&pPtr, iCode, &i1, &i2); + switch (*iCode) { + case CAPSIZED: + strncpy(error, "Powersupply has capsized, try lower current", iErrLen); + break; + case EL755__TURNED_OFF: + strncpy(error, "EL755__TURNED_OF", iErrLen); + break; + case EL755__TOO_MANY: + strncpy(error, "EL755__TO_MANY", iErrLen); + break; + case EL755__TOO_LARGE: + strncpy(error, "EL755__TOO_LARGE", iErrLen); + break; + case EL755__OVFLOW: + strncpy(error, "EL755_OVFLOW", iErrLen); + break; + case EL755__OUT_OF_RANGE: + strncpy(error, "EL755_OUT_OF_RANGE", iErrLen); + break; + case EL755__OFFLINE: + strncpy(error, "EL755_OFFLINE", iErrLen); + break; + case EL755__NO_SOCKET: + strncpy(error, "EL755__NO_SOCKET", iErrLen); + break; + case EL755__NOT_OPEN: + strncpy(error, "EL755__NOT_OPEN", iErrLen); + break; + case EL755__FORCED_CLOSED: + strncpy(error, "EL755__FORCED_CLOSED", iErrLen); + break; + case EL755__BAD_TMO: + strncpy(error, "EL755__BAD_TMO", iErrLen); + break; + case EL755__BAD_SOCKET: + strncpy(error, "EL755__BAD_SOCKET", iErrLen); + break; + case EL755__BAD_PAR: + strncpy(error, "EL755__BAD_PAR", iErrLen); + break; + case EL755__BAD_OFL: + strncpy(error, "EL755__BAD_OFL", iErrLen); + break; + case EL755__BAD_MALLOC: + strncpy(error, "EL755__BAD_MALLOC", iErrLen); + break; + case EL755__BAD_ILLG: + strncpy(error, "EL755__BAD_ILLG", iErrLen); + break; + case EL755__BAD_DEV: + strncpy(error, "EL755__BAD_DEV", iErrLen); + break; + case EL755__BAD_CMD: + strncpy(error, "EL755__BAD_CMD", iErrLen); + break; + case EL755__BAD_ASYNSRV: + strncpy(error, "EL755__BAD_ASYNSRV", iErrLen); + break; + default: + sprintf(pBueffel, "Unknown error %d found", *iCode); + strncpy(error, pBueffel, iErrLen); + break; + } + + return 1; +} + /*-----------------------------------------------------------------------*/ - int EL755_Send(void **handle, char *pCom, char *reply, int iLen); +int EL755_Send(void **handle, char *pCom, char *reply, int iLen); /* * added to el755_utility by M.K. - */ + */ /*--------------------------------------------------------------------------*/ - static int EL755Send(pEVDriver self, char *pCommand, char *pReply, int iLen) - { - pEL755Driv pMe = NULL; - char *pPtr = NULL; - char pBueffel[132]; - int iRet; - - assert(self); - pMe = (pEL755Driv)self->pPrivate; - assert(pMe); - - if(strlen(pCommand) > 130) - return 0; +static int EL755Send(pEVDriver self, char *pCommand, char *pReply, + int iLen) +{ + pEL755Driv pMe = NULL; + char *pPtr = NULL; + char pBueffel[132]; + int iRet; - /* make sure that we have a \r at the end */ - strcpy(pBueffel,pCommand); - if(strrchr(pBueffel,(int)'\r') == NULL) - { - strcat(pBueffel,"\r"); - } + assert(self); + pMe = (pEL755Driv) self->pPrivate; + assert(pMe); + + if (strlen(pCommand) > 130) + return 0; + + /* make sure that we have a \r at the end */ + strcpy(pBueffel, pCommand); + if (strrchr(pBueffel, (int) '\r') == NULL) { + strcat(pBueffel, "\r"); + } + + return EL755_Send(&(pMe->pData), pBueffel, pReply, iLen); +} - return EL755_Send(&(pMe->pData),pBueffel,pReply,iLen); - } /*--------------------------------------------------------------------------*/ - static int EL755Init(pEVDriver self) - { - pEL755Driv pMe = NULL; - int iRet; - - assert(self); - pMe = (pEL755Driv )self->pPrivate; - assert(pMe); +static int EL755Init(pEVDriver self) +{ + pEL755Driv pMe = NULL; + int iRet; + + assert(self); + pMe = (pEL755Driv) self->pPrivate; + assert(pMe); + + pMe->pData = NULL; + iRet = EL755_Open(&(pMe->pData), pMe->pHost, pMe->iPort, pMe->iChannel, + pMe->iIndex); + return iRet; +} - pMe->pData = NULL; - iRet = EL755_Open(&(pMe->pData),pMe->pHost,pMe->iPort,pMe->iChannel, - pMe->iIndex); - return iRet; - } /*--------------------------------------------------------------------------*/ - static int EL755Close(pEVDriver self) - { - pEL755Driv pMe = NULL; - int iRet; - - assert(self); - pMe = (pEL755Driv )self->pPrivate; - assert(pMe); +static int EL755Close(pEVDriver self) +{ + pEL755Driv pMe = NULL; + int iRet; + + assert(self); + pMe = (pEL755Driv) self->pPrivate; + assert(pMe); + + EL755_Close(&(pMe->pData), 0); + return 1; +} - EL755_Close(&(pMe->pData),0); - return 1; - } /*---------------------------------------------------------------------------*/ - static int EL755Fix(pEVDriver self, int iError) - { - pEL755Driv pMe = NULL; - int iRet; - - assert(self); - pMe = (pEL755Driv )self->pPrivate; - assert(pMe); +static int EL755Fix(pEVDriver self, int iError) +{ + pEL755Driv pMe = NULL; + int iRet; - switch(iError) - { - case CAPSIZED: - case EL755__TURNED_OFF: - case EL755__TOO_MANY: - case EL755__TOO_LARGE: - case EL755__OUT_OF_RANGE: - case EL755__BAD_PAR: - case EL755__BAD_SOCKET: - case EL755__BAD_MALLOC: - case EL755__BAD_DEV: - case EL755__BAD_CMD: - case EL755__BAD_ASYNSRV: - return DEVFAULT; - break; - case EL755__OVFLOW: - case EL755__BAD_TMO: - case EL755__BAD_ILLG: - return DEVREDO; - break; - case EL755__OFFLINE: - case EL755__BAD_OFL: - EL755_PutOnline(&(pMe->pData),2); - return DEVREDO; - break; - case EL755__NO_SOCKET: - case EL755__NOT_OPEN: - case EL755__FORCED_CLOSED: - EL755_Open(&(pMe->pData),pMe->pHost,pMe->iPort, - pMe->iChannel,pMe->iIndex); - return DEVREDO; - break; - default: - return DEVFAULT; - break; - } + assert(self); + pMe = (pEL755Driv) self->pPrivate; + assert(pMe); + switch (iError) { + case CAPSIZED: + case EL755__TURNED_OFF: + case EL755__TOO_MANY: + case EL755__TOO_LARGE: + case EL755__OUT_OF_RANGE: + case EL755__BAD_PAR: + case EL755__BAD_SOCKET: + case EL755__BAD_MALLOC: + case EL755__BAD_DEV: + case EL755__BAD_CMD: + case EL755__BAD_ASYNSRV: + return DEVFAULT; + break; + case EL755__OVFLOW: + case EL755__BAD_TMO: + case EL755__BAD_ILLG: + return DEVREDO; + break; + case EL755__OFFLINE: + case EL755__BAD_OFL: + EL755_PutOnline(&(pMe->pData), 2); + return DEVREDO; + break; + case EL755__NO_SOCKET: + case EL755__NOT_OPEN: + case EL755__FORCED_CLOSED: + EL755_Open(&(pMe->pData), pMe->pHost, pMe->iPort, + pMe->iChannel, pMe->iIndex); + return DEVREDO; + break; + default: + return DEVFAULT; + break; } - + +} + /*--------------------------------------------------------------------------*/ - static int EL755Halt(pEVDriver *self) - { - assert(self); - - return 1; +static int EL755Halt(pEVDriver * self) +{ + assert(self); + + return 1; +} + +/*------------------------------------------------------------------------*/ +void KillEL755(void *pData) +{ + pEL755Driv pMe = NULL; + + pMe = (pEL755Driv) pData; + assert(pMe); + + if (pMe->pHost) { + free(pMe->pHost); } -/*------------------------------------------------------------------------*/ - void KillEL755(void *pData) - { - pEL755Driv pMe = NULL; - - pMe = (pEL755Driv)pData; - assert(pMe); - - if(pMe->pHost) - { - free(pMe->pHost); - } - free(pMe); - } -/*------------------------------------------------------------------------*/ - pEVDriver CreateEL755Driv(int argc, char *argv[]) - { - pEVDriver pNew = NULL; - pEL755Driv pSim = NULL; - - /* check for arguments */ - if(argc < 4) - { - return NULL; - } - - pNew = CreateEVDriver(argc,argv); - pSim = (pEL755Driv)malloc(sizeof(EL755Driv)); - memset(pSim,0,sizeof(EL755Driv)); - if(!pNew || !pSim) - { - return NULL; - } - pNew->pPrivate = pSim; - pNew->KillPrivate = KillEL755; - - pSim->iLastError = 0; - pSim->pHost = strdup(argv[0]); - pSim->iPort = atoi(argv[1]); - pSim->iChannel = atoi(argv[2]); - pSim->iIndex = atoi(argv[3]); - - /* initialise function pointers */ - pNew->SetValue = EL755Run; - pNew->GetValue = GetEL755Pos; - pNew->Send = EL755Send; - pNew->GetError = EL755Error; - pNew->TryFixIt = EL755Fix; - pNew->Init = EL755Init; - pNew->Close = EL755Close; - - return pNew; - } - + free(pMe); +} +/*------------------------------------------------------------------------*/ +pEVDriver CreateEL755Driv(int argc, char *argv[]) +{ + pEVDriver pNew = NULL; + pEL755Driv pSim = NULL; + /* check for arguments */ + if (argc < 4) { + return NULL; + } + + pNew = CreateEVDriver(argc, argv); + pSim = (pEL755Driv) malloc(sizeof(EL755Driv)); + memset(pSim, 0, sizeof(EL755Driv)); + if (!pNew || !pSim) { + return NULL; + } + pNew->pPrivate = pSim; + pNew->KillPrivate = KillEL755; + + pSim->iLastError = 0; + pSim->pHost = strdup(argv[0]); + pSim->iPort = atoi(argv[1]); + pSim->iChannel = atoi(argv[2]); + pSim->iIndex = atoi(argv[3]); + + /* initialise function pointers */ + pNew->SetValue = EL755Run; + pNew->GetValue = GetEL755Pos; + pNew->Send = EL755Send; + pNew->GetError = EL755Error; + pNew->TryFixIt = EL755Fix; + pNew->Init = EL755Init; + pNew->Close = EL755Close; + + return pNew; +} diff --git a/el755driv.h b/el755driv.h index 22ec747..62eabf8 100644 --- a/el755driv.h +++ b/el755driv.h @@ -10,6 +10,6 @@ ---------------------------------------------------------------------------*/ #ifndef EL755DRIV #define EL755DRIV - pEVDriver CreateEL755Driv(int argc, char *argv[]); +pEVDriver CreateEL755Driv(int argc, char *argv[]); -#endif +#endif diff --git a/euro2kdriv.c b/euro2kdriv.c index 41d4782..e5d9b65 100644 --- a/euro2kdriv.c +++ b/euro2kdriv.c @@ -34,7 +34,7 @@ Markus Zolliker, August 2005 #define EURO2K_MODE 2 #define EURO2K_PAR 3 -typedef enum {read_only, settable, to_set} Euro2kAccess; +typedef enum { read_only, settable, to_set } Euro2kAccess; typedef struct Euro2kPar { struct Euro2kPar *next; @@ -42,8 +42,8 @@ typedef struct Euro2kPar { char *unit; char *fmt; int adr; - ModBusType type; /* 0: float, 1: int, 2: time */ - Euro2kAccess set; /* 0: read-only; 1: settable; 2: to be set */ + ModBusType type; /* 0: float, 1: int, 2: time */ + Euro2kAccess set; /* 0: read-only; 1: settable; 2: to be set */ float par; } Euro2kPar; @@ -70,14 +70,16 @@ typedef struct { static ParClass euro2kClass = { "EURO2K", sizeof(Euro2k) }; /*----------------------------------------------------------------------------*/ -static int Euro2kMakePar(void *object, void *userarg, int argc, char *argv[]) +static int Euro2kMakePar(void *object, void *userarg, int argc, + char *argv[]) { Euro2k *drv = ParCast(&euro2kClass, object); Euro2kPar *par, **last; int iarg; - + assert(drv); - if (argc < 2) goto Usage; + if (argc < 2) + goto Usage; last = &drv->pars; for (par = drv->pars; par != NULL; par = par->next) { if (strcasecmp(argv[0], par->name) == 0) { @@ -87,40 +89,47 @@ static int Euro2kMakePar(void *object, void *userarg, int argc, char *argv[]) } if (par == NULL) { par = calloc(1, sizeof(Euro2kPar)); - if (par == NULL) return 0; + if (par == NULL) + return 0; *last = par; par->unit = NULL; par->fmt = NULL; par->par = PAR_NAN; } else { if (par->unit) { - free(par->unit); par->unit=NULL; + free(par->unit); + par->unit = NULL; } if (par->fmt) { - free(par->fmt); par->fmt=NULL; + free(par->fmt); + par->fmt = NULL; } } par->name = strdup(argv[0]); iarg = 1; - if (strcasecmp(argv[iarg],"w") == 0) { /* writeable */ + if (strcasecmp(argv[iarg], "w") == 0) { /* writeable */ par->set = settable; iarg++; } else { par->set = read_only; } par->type = modBusFloat; - if (iarg>=argc) goto Usage; - if (strcasecmp(argv[iarg],"int") == 0) { - par->type = modBusInt; iarg++; + if (iarg >= argc) + goto Usage; + if (strcasecmp(argv[iarg], "int") == 0) { + par->type = modBusInt; + iarg++; par->fmt = "%.0f"; - } else if (strcasecmp(argv[iarg],"time") == 0) { - par->type = modBusTime; iarg++; + } else if (strcasecmp(argv[iarg], "time") == 0) { + par->type = modBusTime; + iarg++; par->unit = "sec"; par->fmt = "%.4g"; } else { par->type = modBusFloat; } - if (iarg >= argc) goto Usage; + if (iarg >= argc) + goto Usage; par->adr = atoi(argv[iarg]); iarg++; if (iarg < argc) { @@ -133,59 +142,87 @@ static int Euro2kMakePar(void *object, void *userarg, int argc, char *argv[]) par->fmt = argv[iarg]; } iarg++; - if (iarg < argc) goto Usage; + if (iarg < argc) + goto Usage; } } - if (par->unit) par->unit = strdup(par->unit); - if (par->fmt) par->fmt = strdup(par->fmt); + if (par->unit) + par->unit = strdup(par->unit); + if (par->fmt) + par->fmt = strdup(par->fmt); ParInitPar(object, par->name); EaseParHasChanged(); drv->readPar = NULL; return 1; - Usage: - ParPrintf(object, eError, "Usage: %s makepar [w] [int|time] adr [unit] [fmt]" - , drv->d.b.p.name); - return 0; +Usage: + ParPrintf(object, eError, + "Usage: %s makepar [w] [int|time] adr [unit] [fmt]", + drv->d.b.p.name); + return 0; } + /*----------------------------------------------------------------------------*/ -void Euro2kParDef(void *object) { +void Euro2kParDef(void *object) +{ Euro2k *drv = ParCast(&euro2kClass, object); ParData *obj = object; - Euro2kPar *par, *next; + Euro2kPar *par, *next; FILE *saveFile; char *w, *t, *u, *f; - static char *modeList[]={"auto", "manual", NULL }; + static char *modeList[] = { "auto", "manual", NULL }; - ParName(""); ParTail(drv->unit); + ParName(""); + ParTail(drv->unit); ParFloat(&drv->value, PAR_NAN); - - ParName("unit"); ParAccess(usUser); ParLogAs(NULL); + + ParName("unit"); + ParAccess(usUser); + ParLogAs(NULL); ParStr(&drv->unit, "C"); - - ParName("mode"); ParEnum(modeList); ParList(0); EaseUpdate(EURO2K_MODE); + + ParName("mode"); + ParEnum(modeList); + ParList(0); + EaseUpdate(EURO2K_MODE); ParInt(&drv->mode, 1); - ParName("pbPow"); ParAccess(usUser); ParFloat(&drv->pbPow, 0.0); - ParName("pbMin"); ParAccess(usUser); ParFloat(&drv->pbMin, 8.0); - ParName("pbScl"); ParAccess(usUser); ParFloat(&drv->pbScl, 3.0); + ParName("pbPow"); + ParAccess(usUser); + ParFloat(&drv->pbPow, 0.0); + ParName("pbMin"); + ParAccess(usUser); + ParFloat(&drv->pbMin, 8.0); + ParName("pbScl"); + ParAccess(usUser); + ParFloat(&drv->pbScl, 3.0); - ParName("output"); ParTail("%"); + ParName("output"); + ParTail("%"); ParFloat(&drv->output, PAR_NAN); - ParName("position"); ParTail("%"); ParAccess(usUser); + ParName("position"); + ParTail("%"); + ParAccess(usUser); ParFloat(&drv->position, 50.0); - ParName("asymmetry"); ParAccess(usUser); + ParName("asymmetry"); + ParAccess(usUser); ParFloat(&drv->asymmetry, PAR_NAN); - ParName("range"); ParAccess(usUser); + ParName("range"); + ParAccess(usUser); ParFloat(&drv->range, PAR_NAN); - - ParName("set"); ParTail(drv->unit); EaseUpdate(EURO2K_SET); + + ParName("set"); + ParTail(drv->unit); + EaseUpdate(EURO2K_SET); ParFloat(&drv->setpoint, PAR_NAN); - - ParName("task"); ParAccess(usUser); ParList(NULL); ParSave(1); + + ParName("task"); + ParAccess(usUser); + ParList(NULL); + ParSave(1); ParStr(&drv->script, "0"); saveFile = ParSaveFile(); @@ -193,9 +230,9 @@ void Euro2kParDef(void *object) { if (par->adr > 0) { if (saveFile) { if (par->set) { - w="w "; + w = "w "; } else { - w=""; + w = ""; } if (par->type == modBusInt) { t = "int "; @@ -214,8 +251,8 @@ void Euro2kParDef(void *object) { } else { f = ""; } - fprintf(saveFile, " %s makepar %s %s%s%d \"%s\" \"%s\"\n", obj->name, par->name, - w, t, par->adr, u, f); + fprintf(saveFile, " %s makepar %s %s%s%d \"%s\" \"%s\"\n", + obj->name, par->name, w, t, par->adr, u, f); } ParName(par->name); if (par->unit) { @@ -234,8 +271,10 @@ void Euro2kParDef(void *object) { ParFloat(&par->par, PAR_NAN); } } - - ParName("makepar"); ParAccess(usUser); ParCmd(Euro2kMakePar, NULL); + + ParName("makepar"); + ParAccess(usUser); + ParCmd(Euro2kMakePar, NULL); EaseBasePar(drv); EaseDrivPar(drv, "%.5g", drv->unit); @@ -244,7 +283,7 @@ void Euro2kParDef(void *object) { if (ParActionIs(PAR_KILL)) { next = drv->pars; for (par = next; par != NULL; par = next) { - next= par->next; + next = par->next; if (par->name) { free(par->name); par->name = NULL; @@ -267,14 +306,16 @@ void Euro2kParDef(void *object) { } } -double getTime(void) { +double getTime(void) +{ struct timeval tv; gettimeofday(&tv, NULL); return tv.tv_sec + 1.0e-6 * tv.tv_usec; } /*----------------------------------------------------------------------------*/ -static long Euro2kRead(long pc, void *object) { +static long Euro2kRead(long pc, void *object) +{ Euro2k *drv = ParCast(&euro2kClass, object); EaseBase *eab = object; Euro2kPar *par, *par0; @@ -286,25 +327,31 @@ static long Euro2kRead(long pc, void *object) { Statistics *old; double now, delta; - switch (pc) { default: /* FSM BEGIN *******************************/ - if (drv->script && drv->script[0] != '\0' && 0 != strcmp(drv->script, "0")) { + switch (pc) { + default: /* FSM BEGIN ****************************** */ + if (drv->script && drv->script[0] != '\0' + && 0 != strcmp(drv->script, "0")) { pTcl = InterpGetTcl(pServ->pSics); old = StatisticsBegin(drv->stat); - iRet = Tcl_Eval(pTcl,drv->script); + iRet = Tcl_Eval(pTcl, drv->script); StatisticsEnd(old); if (iRet == TCL_OK) { - if (drv->warned > 0) drv->warned--; - } else if (drv->warned<3) { + if (drv->warned > 0) + drv->warned--; + } else if (drv->warned < 3) { drv->warned++; - ParPrintf(drv, eError, "ERROR: %s in %s.task '%s'", pTcl->result, eab->p.name, drv->script); + ParPrintf(drv, eError, "ERROR: %s in %s.task '%s'", pTcl->result, + eab->p.name, drv->script); } } - if (EaseGetUpdate(drv, EURO2K_MODE)) goto skipMode; - ModBusRequestValue(eab, 273, modBusInt); /* get manual or auto */ - return __LINE__; case __LINE__: /**********************************/ + if (EaseGetUpdate(drv, EURO2K_MODE)) + goto skipMode; + ModBusRequestValue(eab, 273, modBusInt); /* get manual or auto */ + return __LINE__; + case __LINE__: /**********************************/ if (!EaseGetUpdate(drv, EURO2K_MODE)) { m = ModBusGetValue(eab, modBusInt); - if (m != drv->mode) { /* mode changed manually -> change disp */ + if (m != drv->mode) { /* mode changed manually -> change disp */ drv->mode = m; EaseSetUpdate(drv, EURO2K_MODE, 1); } @@ -312,7 +359,8 @@ static long Euro2kRead(long pc, void *object) { skipMode: ModBusRequestValues(eab, 1, 9); - return __LINE__; case __LINE__: /**********************************/ + return __LINE__; + case __LINE__: /**********************************/ drv->value = ModBusGet(eab, 1, modBusFloat); if (!EaseGetUpdate(drv, EURO2K_SET)) { drv->setpoint = ModBusGet(eab, 2, modBusFloat); @@ -326,22 +374,28 @@ static long Euro2kRead(long pc, void *object) { now = getTime(); delta = now - drv->lastRd; drv->lastRd = now; - if (delta > 10) delta = 10; + if (delta > 10) + delta = 10; a = drv->output * delta / drv->range; if ((drv->position > 50.) == (drv->output > 0)) { drv->position += a * (1 - drv->asymmetry * 0.01); } else { drv->position += a * (1 + drv->asymmetry * 0.01); } - if (drv->position < 0) drv->position = 0; - if (drv->position > 100) drv->position = 100; + if (drv->position < 0) + drv->position = 0; + if (drv->position > 100) + drv->position = 100; - if (drv->pbPow <= 0.0) goto getPars; + if (drv->pbPow <= 0.0) + goto getPars; pb = drv->pbMin + pow(drv->value * drv->pbScl, drv->pbPow); - if (pb > 999.) pb=999.; + if (pb > 999.) + pb = 999.; ModBusPutValue(eab, 6, modBusFloat, pb); - - return __LINE__; case __LINE__: /**********************************/ + + return __LINE__; + case __LINE__: /**********************************/ getPars: par = drv->readPar; par0 = par; @@ -351,11 +405,13 @@ static long Euro2kRead(long pc, void *object) { } else { par = par->next; } - if (par == par0) goto skipPar; + if (par == par0) + goto skipPar; } while (par == NULL || par->adr <= 9 || par->set == to_set); ModBusRequestValue(eab, par->adr, par->type); drv->readPar = par; - return __LINE__; case __LINE__: /**********************************/ + return __LINE__; + case __LINE__: /**********************************/ par = drv->readPar; if (par->set != to_set) { par->par = ModBusGetValue(eab, par->type); @@ -363,15 +419,19 @@ static long Euro2kRead(long pc, void *object) { skipPar: if (eab->p.verbose >= 3) { eab->p.verbose--; - if (eab->p.verbose < 3) eab->p.verbose=0; + if (eab->p.verbose < 3) + eab->p.verbose = 0; } - + finish: ParLog(drv); - fsm_quit: return 0; } /* FSM END *********************************/ + fsm_quit:return 0; + } /* FSM END ******************************** */ } + /*----------------------------------------------------------------------------*/ -static long Euro2kSet(long pc, void *object) { +static long Euro2kSet(long pc, void *object) +{ Euro2k *drv = ParCast(&euro2kClass, object); EaseBase *eab = object; Euro2kPar *par; @@ -379,16 +439,19 @@ static long Euro2kSet(long pc, void *object) { int l; int upd; char buf[4]; - - switch (pc) { default: /* FSM BEGIN *******************************/ + + switch (pc) { + default: /* FSM BEGIN ****************************** */ loop: upd = EaseNextUpdate(drv); if (upd == EASE_RUN) { drv->setpoint = drv->d.targetValue; goto run; } - if (upd == EURO2K_MODE) goto mode; - if (upd == EURO2K_SET) goto run; + if (upd == EURO2K_MODE) + goto mode; + if (upd == EURO2K_SET) + goto run; for (par = drv->pars; par != NULL; par = par->next) { if (par->set == to_set) { ModBusPutValue(eab, par->adr, par->type, par->par); @@ -399,67 +462,87 @@ static long Euro2kSet(long pc, void *object) { goto fsm_quit; run: ModBusPutFloats(eab, 2, 1, &drv->setpoint); - return __LINE__; case __LINE__: /**********************************/ - if (drv->mode == 0) goto loop; + return __LINE__; + case __LINE__: /**********************************/ + if (drv->mode == 0) + goto loop; drv->mode = 0; mode: - if (drv->mode) drv->mode = 1; - ModBusPutValue(eab, 106, modBusInt, drv->mode*5); /* set display std or blank */ - return __LINE__; case __LINE__: /**********************************/ - ModBusPutValue(eab, 273, modBusInt, drv->mode); /* set manual to 0 */ + if (drv->mode) + drv->mode = 1; + ModBusPutValue(eab, 106, modBusInt, drv->mode * 5); /* set display std or blank */ + return __LINE__; + case __LINE__: /**********************************/ + ModBusPutValue(eab, 273, modBusInt, drv->mode); /* set manual to 0 */ setIt: - return __LINE__; case __LINE__: /**********************************/ + return __LINE__; + case __LINE__: /**********************************/ goto loop; - fsm_quit: return 0; } /* FSM END *********************************/ + fsm_quit:return 0; + } /* FSM END ******************************** */ } + /*----------------------------------------------------------------------------*/ -static long Euro2kStart(long pc, void *object) { +static long Euro2kStart(long pc, void *object) +{ Euro2k *drv = ParCast(&euro2kClass, object); EaseBase *eab = object; - - switch (pc) { default: /* FSM BEGIN *******************************/ + + switch (pc) { + default: /* FSM BEGIN ****************************** */ ModBusRequestValue(eab, 1, modBusFloat); - return __LINE__; case __LINE__: /**********************************/ + return __LINE__; + case __LINE__: /**********************************/ if (0 == ModBusGetValue(eab, modBusFloat)) { ParPrintf(drv, eError, "bad or no response on ModBus"); goto quit; } ParPrintf(drv, eLog, "connected to euro2k"); ModBusPutValue(eab, 111, modBusFloat, drv->d.upperLimit); - return __LINE__; case __LINE__: /**********************************/ + return __LINE__; + case __LINE__: /**********************************/ ModBusPutValue(eab, 112, modBusFloat, drv->d.lowerLimit); - return __LINE__; case __LINE__: /**********************************/ + return __LINE__; + case __LINE__: /**********************************/ FsmCall(Euro2kRead); - return __LINE__; case __LINE__: /**********************************/ - + return __LINE__; + case __LINE__: /**********************************/ + quit: - return 0; } /* FSM END ********************************************/ + return 0; + } /* FSM END ******************************************* */ } + /*----------------------------------------------------------------------------*/ -static int Euro2kInit(SConnection *con, int argc, char *argv[], int dynamic) { +static int Euro2kInit(SConnection * con, int argc, char *argv[], + int dynamic) +{ /* args: - MakeObject objectname euro2k - + MakeObject objectname euro2k + */ Euro2k *drv; char sn[64]; drv = EaseMakeDriv(con, &euro2kClass, argc, argv, dynamic, 7, - Euro2kParDef, ModBusHandler, Euro2kStart, NULL, Euro2kRead, - Euro2kSet); - if (drv == NULL) return 0; + Euro2kParDef, ModBusHandler, Euro2kStart, NULL, + Euro2kRead, Euro2kSet); + if (drv == NULL) + return 0; drv->pars = NULL; drv->readPar = NULL; snprintf(sn, sizeof sn, "%s task", argv[1]); drv->stat = StatisticsNew(sn); drv->lastRd = getTime(); - setRS232ReplyTerminator(drv->d.b.ser,""); - setRS232SendTerminator(drv->d.b.ser,""); + setRS232ReplyTerminator(drv->d.b.ser, ""); + setRS232SendTerminator(drv->d.b.ser, ""); return 1; } + /*----------------------------------------------------------------------------*/ -void Euro2kStartup(void) { +void Euro2kStartup(void) +{ ParMakeClass(&euro2kClass, EaseDrivClass()); - MakeDriver("EURO2K", Euro2kInit, 0, "Eurotherm 2xxx"); + MakeDriver("EURO2K", Euro2kInit, 0, "Eurotherm 2xxx"); } diff --git a/eurodriv.c b/eurodriv.c index 1bbbfdd..9b7a80b 100644 --- a/eurodriv.c +++ b/eurodriv.c @@ -26,368 +26,352 @@ #include "hardsup/el734_def.h" #include "hardsup/el734fix.h" #include "hardsup/serialsinq.h" -#include "eurodriv.h" +#include "eurodriv.h" -#define INVALIDANSWER -1005 -#define INVALIDNUMBER -1006 +#define INVALIDANSWER -1005 +#define INVALIDNUMBER -1006 #define ERRNAK -1007 #define NOSEND -1008 /*-----------------------------------------------------------------------*/ - typedef struct { - void *pData; - char *pHost; - int iPort; - int iChannel; - int iLastError; - } EuroDriv, *pEuroDriv; +typedef struct { + void *pData; + char *pHost; + int iPort; + int iChannel; + int iLastError; +} EuroDriv, *pEuroDriv; /*------------------------------------------------------------------------*/ - int EuroGetParameter(void **pData, char *pPar,int iLen, float *fVal) - { - char pCommand[20]; - char pReply[20]; - char *pStart = NULL, *pEnd = NULL; - int iRet,i; +int EuroGetParameter(void **pData, char *pPar, int iLen, float *fVal) +{ + char pCommand[20]; + char pReply[20]; + char *pStart = NULL, *pEnd = NULL; + int iRet, i; - /* configure the serial port */ - SerialATerm(pData,"1\x3"); /* ETX */ - pCommand[0] = '\x4'; /* EOT */ - pCommand[1] = '0'; /* GID*/ - pCommand[2] = '0'; /* GID*/ - pCommand[3] = '1'; /* UID*/ - pCommand[4] = '1'; /* UID*/ - pCommand[5] = '1'; /* CHAN */ - for(i = 0; i < iLen; i++) - { - pCommand[6+i] = pPar[i]; - } - pCommand[6+iLen] = '\x5'; /* ENQ*/ - pCommand[7+iLen] = '\0'; - - /* send */ - iRet = SerialWriteRead(pData,pCommand,pReply,19); - if(iRet != 1) - { - return iRet; - } + /* configure the serial port */ + SerialATerm(pData, "1\x3"); /* ETX */ + pCommand[0] = '\x4'; /* EOT */ + pCommand[1] = '0'; /* GID */ + pCommand[2] = '0'; /* GID */ + pCommand[3] = '1'; /* UID */ + pCommand[4] = '1'; /* UID */ + pCommand[5] = '1'; /* CHAN */ + for (i = 0; i < iLen; i++) { + pCommand[6 + i] = pPar[i]; + } + pCommand[6 + iLen] = '\x5'; /* ENQ */ + pCommand[7 + iLen] = '\0'; + + /* send */ + iRet = SerialWriteRead(pData, pCommand, pReply, 19); + if (iRet != 1) { + return iRet; + } + + /* decode reply */ + pStart = strstr(pReply, pPar); + if (!pStart) { + if (strstr(pReply, "?TMO")) { + return EL734__BAD_TMO; + } else { + return INVALIDANSWER; + } + } + iRet = sscanf(pStart + strlen(pPar), "%f", fVal); + if (iRet != 1) { + return INVALIDNUMBER; + } + return 1; +} - /* decode reply */ - pStart = strstr(pReply,pPar); - if(!pStart) - { - if(strstr(pReply,"?TMO")) - { - return EL734__BAD_TMO; - } - else - { - return INVALIDANSWER; - } - } - iRet = sscanf(pStart+strlen(pPar),"%f",fVal); - if(iRet != 1) - { - return INVALIDNUMBER; - } - return 1; - } /*------------------------------------------------------------------------*/ - int EuroSetParameter(void **pData, char *pPar,int iLen, - char *pFormat, float fVal) - { - char pCommand[30]; - char pNum[10]; - char *pPtr, *pPtr2; - char pReply[20]; - char bcc; - int iRet,i; - +int EuroSetParameter(void **pData, char *pPar, int iLen, + char *pFormat, float fVal) +{ + char pCommand[30]; + char pNum[10]; + char *pPtr, *pPtr2; + char pReply[20]; + char bcc; + int iRet, i; - /* configure the serial port */ - SerialATerm(pData,"1\x06\x15"); /* ACK,NAK */ - pCommand[0] = '\x04'; /* EOT */ - pCommand[1] = '0'; /* GID*/ - pCommand[2] = '0'; /* GID*/ - pCommand[3] = '1'; /* UID*/ - pCommand[4] = '1'; /* UID*/ - pCommand[5] = '\x02'; - pCommand[6] = '1'; /* CHAN */ - for(i = 0; i < iLen; i++) - { - pCommand[7+i] = pPar[i]; - } - pPtr = pCommand + 7 + iLen; - sprintf(pNum,pFormat,fVal); - strcpy(pPtr,pNum); - pPtr += strlen(pNum); - *pPtr = '\x03'; - pPtr++; - /* build the checksum */ - bcc = pCommand[6]; - pPtr2 = &pCommand[7]; - while(pPtr2 != pPtr) - { - bcc = bcc ^ *pPtr2; - pPtr2++; - } - *pPtr = bcc; - pPtr++; - *pPtr = '\0'; + /* configure the serial port */ + SerialATerm(pData, "1\x06\x15"); /* ACK,NAK */ + pCommand[0] = '\x04'; /* EOT */ + pCommand[1] = '0'; /* GID */ + pCommand[2] = '0'; /* GID */ + pCommand[3] = '1'; /* UID */ + pCommand[4] = '1'; /* UID */ + pCommand[5] = '\x02'; + pCommand[6] = '1'; /* CHAN */ + for (i = 0; i < iLen; i++) { + pCommand[7 + i] = pPar[i]; + } + pPtr = pCommand + 7 + iLen; + sprintf(pNum, pFormat, fVal); + strcpy(pPtr, pNum); + pPtr += strlen(pNum); + *pPtr = '\x03'; + pPtr++; - /* send */ - iRet = SerialSend(pData,pCommand); - if(iRet != 1) - { - return iRet; - } - iRet = SerialReceiveWithTerm(pData,pReply,19,&bcc); + /* build the checksum */ + bcc = pCommand[6]; + pPtr2 = &pCommand[7]; + while (pPtr2 != pPtr) { + bcc = bcc ^ *pPtr2; + pPtr2++; + } + *pPtr = bcc; + pPtr++; + *pPtr = '\0'; + + /* send */ + iRet = SerialSend(pData, pCommand); + if (iRet != 1) { + return iRet; + } + iRet = SerialReceiveWithTerm(pData, pReply, 19, &bcc); /* printf("%s\n",pReply); -*/ - if(iRet != 1) - { - return iRet; - } - if(bcc == '\x15') - { - return ERRNAK; - } - if(strstr(pReply,"?TMO")) - { - return EL734__BAD_TMO; - } +*/ + if (iRet != 1) { + return iRet; + } + if (bcc == '\x15') { + return ERRNAK; + } + if (strstr(pReply, "?TMO")) { + return EL734__BAD_TMO; + } + + return 1; +} - return 1; - } /*---------------------------------------------------------------------------*/ - static int GetEuroPos(pEVDriver self, float *fPos) - { - pEuroDriv pMe = NULL; - int iRet; - - assert(self); - pMe = (pEuroDriv)self->pPrivate; - assert(pMe); +static int GetEuroPos(pEVDriver self, float *fPos) +{ + pEuroDriv pMe = NULL; + int iRet; + + assert(self); + pMe = (pEuroDriv) self->pPrivate; + assert(pMe); + + iRet = EuroGetParameter(&(pMe->pData), "PV", 2, fPos); + if (iRet != 1) { + pMe->iLastError = iRet; + return 0; + } + return 1; +} - iRet = EuroGetParameter(&(pMe->pData),"PV",2,fPos); - if(iRet != 1) - { - pMe->iLastError = iRet; - return 0; - } - return 1; - } /*----------------------------------------------------------------------------*/ - static int EuroRun(pEVDriver self, float fVal) - { - pEuroDriv pMe = NULL; - int iRet; - - assert(self); - pMe = (pEuroDriv )self->pPrivate; - assert(pMe); +static int EuroRun(pEVDriver self, float fVal) +{ + pEuroDriv pMe = NULL; + int iRet; - iRet = EuroSetParameter(&(pMe->pData),"SL",2,"%4.1f",fVal); - if(iRet != 1) - { - pMe->iLastError = iRet; - return 0; - } - return 1; - } -/*--------------------------------------------------------------------------*/ - static int EuroError(pEVDriver self, int *iCode, char *error, int iErrLen) - { - pEuroDriv pMe = NULL; - - assert(self); - pMe = (pEuroDriv)self->pPrivate; - assert(pMe); + assert(self); + pMe = (pEuroDriv) self->pPrivate; + assert(pMe); - *iCode = pMe->iLastError; - switch(pMe->iLastError) - { - case INVALIDANSWER: - strncpy(error,"Unexpected reply from Eurotherm",iErrLen); - break; - case INVALIDNUMBER: - strncpy(error,"No number in Eurotherm answer",iErrLen); - break; - case ERRNAK: - strncpy(error,"Eurothem did NOT acknowledge command",iErrLen); - break; - case NOSEND: - strncpy(error, - "Eurotherm has a bizarre protocoll, sending things is very STUPID",iErrLen); - break; - default: - SerialError(pMe->iLastError,error,iErrLen); - break; - } - - return 1; + iRet = EuroSetParameter(&(pMe->pData), "SL", 2, "%4.1f", fVal); + if (iRet != 1) { + pMe->iLastError = iRet; + return 0; } -/*--------------------------------------------------------------------------*/ - static int EuroSend(pEVDriver self, char *pCommand, char *pReply, int iLen) - { - pEuroDriv pMe = NULL; - - assert(self); - pMe = (pEuroDriv)self->pPrivate; - assert(pMe); - - pMe->iLastError = NOSEND; - strncpy(pReply,"ERROR: Eurotherm does not support send functionality", - iLen); - return 0; - } -/*--------------------------------------------------------------------------*/ - static int EuroInit(pEVDriver self) - { - pEuroDriv pMe = NULL; - int iRet; - - assert(self); - pMe = (pEuroDriv )self->pPrivate; - assert(pMe); + return 1; +} - pMe->pData = NULL; - iRet = SerialOpen(&pMe->pData, pMe->pHost, pMe->iPort, pMe->iChannel); - if(iRet != 1) - { - pMe->iLastError = iRet; - return 0; - } - SerialSendTerm(&pMe->pData,""); - return 1; - } /*--------------------------------------------------------------------------*/ - static int EuroClose(pEVDriver self) - { - pEuroDriv pMe = NULL; - int iRet; - - assert(self); - pMe = (pEuroDriv )self->pPrivate; - assert(pMe); +static int EuroError(pEVDriver self, int *iCode, char *error, int iErrLen) +{ + pEuroDriv pMe = NULL; + + assert(self); + pMe = (pEuroDriv) self->pPrivate; + assert(pMe); + + *iCode = pMe->iLastError; + switch (pMe->iLastError) { + case INVALIDANSWER: + strncpy(error, "Unexpected reply from Eurotherm", iErrLen); + break; + case INVALIDNUMBER: + strncpy(error, "No number in Eurotherm answer", iErrLen); + break; + case ERRNAK: + strncpy(error, "Eurothem did NOT acknowledge command", iErrLen); + break; + case NOSEND: + strncpy(error, + "Eurotherm has a bizarre protocoll, sending things is very STUPID", + iErrLen); + break; + default: + SerialError(pMe->iLastError, error, iErrLen); + break; + } + + return 1; +} + +/*--------------------------------------------------------------------------*/ +static int EuroSend(pEVDriver self, char *pCommand, char *pReply, int iLen) +{ + pEuroDriv pMe = NULL; + + assert(self); + pMe = (pEuroDriv) self->pPrivate; + assert(pMe); + + pMe->iLastError = NOSEND; + strncpy(pReply, "ERROR: Eurotherm does not support send functionality", + iLen); + return 0; +} + +/*--------------------------------------------------------------------------*/ +static int EuroInit(pEVDriver self) +{ + pEuroDriv pMe = NULL; + int iRet; + + assert(self); + pMe = (pEuroDriv) self->pPrivate; + assert(pMe); + + pMe->pData = NULL; + iRet = SerialOpen(&pMe->pData, pMe->pHost, pMe->iPort, pMe->iChannel); + if (iRet != 1) { + pMe->iLastError = iRet; + return 0; + } + SerialSendTerm(&pMe->pData, ""); + return 1; +} + +/*--------------------------------------------------------------------------*/ +static int EuroClose(pEVDriver self) +{ + pEuroDriv pMe = NULL; + int iRet; + + assert(self); + pMe = (pEuroDriv) self->pPrivate; + assert(pMe); + + SerialClose(&pMe->pData); + return 1; +} - SerialClose(&pMe->pData); - return 1; - } /*---------------------------------------------------------------------------*/ - static int EuroFix(pEVDriver self, int iError) - { - pEuroDriv pMe = NULL; - int iRet; - - assert(self); - pMe = (pEuroDriv )self->pPrivate; - assert(pMe); +static int EuroFix(pEVDriver self, int iError) +{ + pEuroDriv pMe = NULL; + int iRet; - switch(iError) - { - /* network errors */ - case EL734__BAD_FLUSH: - case EL734__BAD_RECV: - case EL734__BAD_RECV_NET: - case EL734__BAD_RECV_UNKN: - case EL734__BAD_RECVLEN: - case EL734__BAD_RECV1: - case EL734__BAD_RECV1_PIPE: - case EL734__BAD_RNG: - case EL734__BAD_SEND: - case EL734__BAD_SEND_PIPE: - case EL734__BAD_SEND_NET: - case EL734__BAD_SEND_UNKN: - case EL734__BAD_SENDLEN: - EuroClose(self); - iRet = EuroInit(self); - if(iRet) - { - return DEVREDO; - } - else - { - return DEVFAULT; - } - break; - /* handable protocoll errors */ - case EL734__BAD_TMO: - return DEVREDO; - break; - case ERRNAK: - case NOSEND: - case INVALIDANSWER: - case INVALIDNUMBER: - return DEVFAULT; - default: - return DEVFAULT; - break; - } - return DEVFAULT; + assert(self); + pMe = (pEuroDriv) self->pPrivate; + assert(pMe); + + switch (iError) { + /* network errors */ + case EL734__BAD_FLUSH: + case EL734__BAD_RECV: + case EL734__BAD_RECV_NET: + case EL734__BAD_RECV_UNKN: + case EL734__BAD_RECVLEN: + case EL734__BAD_RECV1: + case EL734__BAD_RECV1_PIPE: + case EL734__BAD_RNG: + case EL734__BAD_SEND: + case EL734__BAD_SEND_PIPE: + case EL734__BAD_SEND_NET: + case EL734__BAD_SEND_UNKN: + case EL734__BAD_SENDLEN: + EuroClose(self); + iRet = EuroInit(self); + if (iRet) { + return DEVREDO; + } else { + return DEVFAULT; + } + break; + /* handable protocoll errors */ + case EL734__BAD_TMO: + return DEVREDO; + break; + case ERRNAK: + case NOSEND: + case INVALIDANSWER: + case INVALIDNUMBER: + return DEVFAULT; + default: + return DEVFAULT; + break; } - + return DEVFAULT; +} + /*--------------------------------------------------------------------------*/ - static int EuroHalt(pEVDriver *self) - { - assert(self); - - return 1; +static int EuroHalt(pEVDriver * self) +{ + assert(self); + + return 1; +} + +/*------------------------------------------------------------------------*/ +void KillEuro(void *pData) +{ + pEuroDriv pMe = NULL; + + pMe = (pEuroDriv) pData; + assert(pMe); + + if (pMe->pHost) { + free(pMe->pHost); } -/*------------------------------------------------------------------------*/ - void KillEuro(void *pData) - { - pEuroDriv pMe = NULL; - - pMe = (pEuroDriv)pData; - assert(pMe); - - if(pMe->pHost) - { - free(pMe->pHost); - } - free(pMe); - } -/*------------------------------------------------------------------------*/ - pEVDriver CreateEURODriv(int argc, char *argv[]) - { - pEVDriver pNew = NULL; - pEuroDriv pSim = NULL; - - /* check for arguments */ - if(argc < 3) - { - return NULL; - } - - pNew = CreateEVDriver(argc,argv); - pSim = (pEuroDriv)malloc(sizeof(EuroDriv)); - memset(pSim,0,sizeof(EuroDriv)); - if(!pNew || !pSim) - { - return NULL; - } - pNew->pPrivate = pSim; - pNew->KillPrivate = KillEuro; - - /* initalise pDILLUDriver */ - pSim->iLastError = 0; - pSim->pHost = strdup(argv[0]); - pSim->iPort = atoi(argv[1]); - pSim->iChannel = atoi(argv[2]); - - /* initialise function pointers */ - pNew->SetValue = EuroRun; - pNew->GetValue = GetEuroPos; - pNew->Send = EuroSend; - pNew->GetError = EuroError; - pNew->TryFixIt = EuroFix; - pNew->Init = EuroInit; - pNew->Close = EuroClose; - - return pNew; - } - + free(pMe); +} +/*------------------------------------------------------------------------*/ +pEVDriver CreateEURODriv(int argc, char *argv[]) +{ + pEVDriver pNew = NULL; + pEuroDriv pSim = NULL; + /* check for arguments */ + if (argc < 3) { + return NULL; + } + + pNew = CreateEVDriver(argc, argv); + pSim = (pEuroDriv) malloc(sizeof(EuroDriv)); + memset(pSim, 0, sizeof(EuroDriv)); + if (!pNew || !pSim) { + return NULL; + } + pNew->pPrivate = pSim; + pNew->KillPrivate = KillEuro; + + /* initalise pDILLUDriver */ + pSim->iLastError = 0; + pSim->pHost = strdup(argv[0]); + pSim->iPort = atoi(argv[1]); + pSim->iChannel = atoi(argv[2]); + + /* initialise function pointers */ + pNew->SetValue = EuroRun; + pNew->GetValue = GetEuroPos; + pNew->Send = EuroSend; + pNew->GetError = EuroError; + pNew->TryFixIt = EuroFix; + pNew->Init = EuroInit; + pNew->Close = EuroClose; + + return pNew; +} diff --git a/eurodriv.h b/eurodriv.h index 132856f..e220fb7 100644 --- a/eurodriv.h +++ b/eurodriv.h @@ -10,14 +10,14 @@ ---------------------------------------------------------------------------*/ #ifndef EURODRIV #define EURODRIV - pEVDriver CreateEURODriv(int argc, char *argv[]); +pEVDriver CreateEURODriv(int argc, char *argv[]); /* - these are hooks to implement further functionality which, - I'am sure, Joachim Kohlbrecher will request. - */ - int EuroGetParameter(void **pData, char *pPar, int iLen, float *fVal); - int EuroSetParameter(void **pData, char *pPar, int iLen, - char *pFormat, float fVal); - -#endif + these are hooks to implement further functionality which, + I'am sure, Joachim Kohlbrecher will request. + */ +int EuroGetParameter(void **pData, char *pPar, int iLen, float *fVal); +int EuroSetParameter(void **pData, char *pPar, int iLen, + char *pFormat, float fVal); + +#endif diff --git a/faverage.c b/faverage.c index 22f3a53..7620d75 100644 --- a/faverage.c +++ b/faverage.c @@ -32,450 +32,405 @@ #define DEB 1 */ /*-------------------------------------------------------------------------*/ - typedef struct __FocusAverager { - pObjectDescriptor pDes; - pHistMem pHistogram1; - pHistMem pHistogram2; - pHistMem pHistogram3; - } FocusAverager, *pFocusAverager; +typedef struct __FocusAverager { + pObjectDescriptor pDes; + pHistMem pHistogram1; + pHistMem pHistogram2; + pHistMem pHistogram3; +} FocusAverager, *pFocusAverager; /*------------------------------------------------------------------------*/ - HistInt *CheckBank(pFocusAverager self, SConnection *pCon, - int iLength, int iBank); +HistInt *CheckBank(pFocusAverager self, SConnection * pCon, + int iLength, int iBank); - static void KillFA(void *pData) - { - pFocusAverager self = NULL; - - self = (pFocusAverager)pData; - if(!self) - return; - - if(self->pDes) - DeleteDescriptor(self->pDes); - free(self); - } -/*-------------------------------------------------------------------------*/ - int FocusAverageDo(SConnection *pCon, SicsInterp *pSics, void *pData, - int argc, char *argv[]) - { - pFocusAverager self = NULL; - int *iData = NULL; - const float *fTimeBin = NULL; - float fVal; - int iLength, iStart, iEnd, iNum, i,ii, iTest, iBufLen, iRet, iVal; - char pBueffel[256]; - HistInt *hiData = NULL, *hiPtr; - time_t tStart, tEnd; - int iBank = MIDDLE; - pSicsVariable var1 = NULL; - pSicsVariable var2 = NULL; - pSicsVariable var3 = NULL; - int lbank, mbank, ubank; - - self = (pFocusAverager)pData; - assert(self); - assert(pCon); - assert(pSics); - - /* we need two parameters: start and end of averaging */ - if(argc < 3) - { - SCWrite(pCon, - "ERROR: insufficient number of parameters for FocusAverage", - eError); - return 0; - } - iRet = Tcl_GetInt(pSics->pTcl,argv[1],&iStart); - if(iRet != TCL_OK) - { - sprintf(pBueffel,"ERROR: cannot convert %s to integer",argv[1]); - SCWrite(pCon,pBueffel,eError); - return 0; - } - iRet = Tcl_GetInt(pSics->pTcl,argv[2],&iEnd); - if(iRet != TCL_OK) - { - sprintf(pBueffel,"ERROR: cannot convert %s to integer",argv[2]); - SCWrite(pCon,pBueffel,eError); - return 0; - } - - /* another parameter, if available describes the detector bank - */ - if(argc > 3) - { - iRet = Tcl_GetInt(pSics->pTcl,argv[3],&iBank); - if(iRet != TCL_OK) - { - sprintf(pBueffel,"ERROR: cannot convert %s to integer",argv[3]); - SCWrite(pCon,pBueffel,eError); - return 0; - } - } - - /* how much to do: correct parameters? */ - iNum = iEnd - iStart; - if(iNum < 0) - { - SCWrite(pCon,"ERROR: invalid parameters given to FocusAverage", - eError); - return 0; - } - /* may be only one histogram requested */ - if(iNum == 0) - iNum = 1; - if(iStart < 0) - { - SCWrite(pCon,"ERROR: invalid parameters given to FocusAverage", - eError); - return 0; - } - -#ifdef DEB - printf("Starting averaging ...\n"); - fflush(stdout); - tStart = time(NULL); -#endif - - /* do work! first retrieve time binning data */ - - var2 = FindVariable(pServ->pSics,"mbank"); - if(var2) - { - VarGetInt(var2,&mbank); - } else { - SCWrite(pCon,"ERROR: mbank value not found!",eError); - } - if(mbank==1) - { - fTimeBin = GetHistTimeBin(self->pHistogram2,&iLength); - } - else - { - var1 = FindVariable(pServ->pSics,"lbank"); - if(var1) - { - VarGetInt(var1,&lbank); - } else { - SCWrite(pCon,"ERROR: lbank value not found!",eError); - } - if(lbank==1) - { - fTimeBin = GetHistTimeBin(self->pHistogram1,&iLength); - } - else - { - fTimeBin = GetHistTimeBin(self->pHistogram3,&iLength); - } - } - assert(fTimeBin); - if(iLength <= 0) - { - SCWrite(pCon,"ERROR: histogram memory inproperly configured",eError); - return 0; - } - /* allocate result data */ - iBufLen = (iLength *2 +1)*sizeof(int); - iData = (int *)malloc(iBufLen); - memset(iData,0,iBufLen); - - /* get histogram length */ - i = getFMdim(iBank); - /* correct iEnd to maximum allowed */ - iTest = i; - if(iEnd > iTest -1) - { - iEnd = iTest - 1; - iNum = iEnd - iStart; - if(iNum <= 0) - iNum = 1; - } - -#ifdef DEB - printf("Getting histogram....\n"); - fflush(stdout); -#endif - - hiData = CheckBank(self,pCon,iLength,iBank); - -#ifdef DEB - tEnd = time(NULL); - printf("Histogram received in %d seconds\n", tStart - tEnd); - fflush(stdout); -#endif - - if(hiData == NULL) - { - SCWrite(pCon,"ERROR: BAD Configuration",eError); - free(iData); - return 0; - } - - /* first int: length of things to come */ - iData[0] = htonl(iLength); - /* sum up */ - for(i = iStart; i < iEnd; i++) - { - hiPtr = hiData + i*iLength; - for(ii = 0; ii < iLength; ii++) - { - iData[ii+1] += hiPtr[ii]; - } - } - /* average */ - for(i = 1; i < iLength + 1; i++) - { - fVal = (float)iData[i]/(float)iNum; - fVal *= 65536.; - iData[i] = htonl((int)fVal); - } - /* make time binning fixed point */ - for(i = 0; i < iLength; i++) - { - fVal = fTimeBin[i]/10.; - fVal *= 65536.; - iData[iLength+1+i] = htonl((int)fVal); - } -#ifdef DEB - printf("Sending averaged data....\n"); - fflush(stdout); -#endif - /* finally send out uuencoded */ - SCWriteUUencoded(pCon,"FocusAverage",iData,iBufLen); - if(iData) - free(iData); -#ifdef DEB - printf("Averaging finished\n"); - fflush(stdout); -#endif - return 1; - } - -/*-------------------------------------------------------------------------*/ - static int FocusRaw(SConnection *pCon, SicsInterp *pSics, void *pData, - int argc, char *argv[]) - { - pFocusAverager self = NULL; - int *iData = NULL; - int iLength, noTimebin, iRet, i; - char pBueffel[256]; - const float *timeBin; - HistInt *hiData = NULL, *hiPtr; - int iBank = MIDDLE; - pSicsVariable var1 = NULL; - pSicsVariable var2 = NULL; - pSicsVariable var3 = NULL; - int lbank, mbank, ubank; - - self = (pFocusAverager)pData; - assert(self); - assert(pCon); - assert(pSics); - - - /* we need one parameter, the bank to read */ - if(argc < 2) - { - SCWrite(pCon, - "ERROR: insufficient number of parameters for FocusRaw", - eError); - return 0; - } - iRet = Tcl_GetInt(pSics->pTcl,argv[1],&iBank); - if(iRet != TCL_OK) - { - sprintf(pBueffel,"ERROR: cannot convert %s to integer",argv[1]); - SCWrite(pCon,pBueffel,eError); - return 0; - } - var2 = FindVariable(pServ->pSics,"mbank"); - if(var2) - { - VarGetInt(var2,&mbank); - } else { - SCWrite(pCon,"ERROR: mbank value not found!",eError); - } - if(var2) - { - timeBin = GetHistTimeBin(self->pHistogram2,&iLength); - } - else - { - var1 = FindVariable(pServ->pSics,"lbank"); - if(var1) - { - VarGetInt(var1,&lbank); - } else { - SCWrite(pCon,"ERROR: lbank value not found!",eError); - } - if(var1) - { - timeBin = GetHistTimeBin(self->pHistogram1,&iLength); - } - else - { - timeBin = GetHistTimeBin(self->pHistogram3,&iLength); - } - } - assert(timeBin); - hiData = CheckBank(self, pCon, iLength, iBank); - - /* get histogram length */ - iLength = getFMdim(iBank); - noTimebin = getFMdim(TIMEBIN); - /* write dimension info*/ - sprintf(pBueffel,"focusrawdim = %d = %d", iLength, noTimebin); - SCWrite(pCon,pBueffel,eValue); - - /* allocate space */ - iData = (int *)malloc((iLength*noTimebin+1)*sizeof(int)); - if(iData == NULL) - { - SCWrite(pCon,"ERROR: out of memory in FocusRaw",eError); - return 0; - } - memset(iData,0,noTimebin*iLength*sizeof(int)); - - /* first int: length of things to come */ - iData[0] = htonl(iLength*noTimebin); - /* network byte order for everything */ - for(i = 0; i < noTimebin*iLength; i++) - { - iData[i+1] = htonl(hiData[i]); - } - /* send away, zipped */ - SCWriteZipped(pCon,"focusraw",iData,(iLength*noTimebin+1)*sizeof(int)); - - free(iData); - return 1; - } -/*-------------------------------------------------------------------------*/ - int MakeFA(SConnection *pCon, SicsInterp *pSics, void *pData, - int argc, char *argv[]) - { - pFocusAverager pNew = NULL; - CommandList *pCom = NULL; - pDummy pDum = NULL; - char pBueffel[256]; - int iRet; - pSicsVariable var1 = NULL; - pSicsVariable var2 = NULL; - pSicsVariable var3 = NULL; - int lbank, mbank, ubank; - - assert(pCon); - assert(pSics); - - /* we need two parameters: the name for the averager and the histogram - memory - */ - if(argc < 3) - { - SCWrite(pCon,"ERROR: Insufficient number of parameters to MakeFA", - eError); - return 0; - } - - /* find histogram memory */ - pCom = FindCommand(pSics,argv[2]); - if(!pCom) - { - sprintf(pBueffel,"ERROR: histogram memory %s NOT found!", argv[2]); - SCWrite(pCon,pBueffel,eError); - return 0; - } - pDum = (pDummy)pCom->pData; - if(!pDum) - { - sprintf(pBueffel,"ERROR: histogram memory %s INVALID!", argv[2]); - SCWrite(pCon,pBueffel,eError); - return 0; - } - if(strcmp(pDum->pDescriptor->name,"HMcontrol") != 0) - { - sprintf(pBueffel,"ERROR: %s is NO histogram control object!", argv[2]); - SCWrite(pCon,pBueffel,eError); - return 0; - } - - /* we got what we need: set things up */ - pNew = (pFocusAverager)malloc(sizeof(FocusAverager)); - if(!pNew) - { - SCWrite(pCon,"ERROR: out of memory in MakeFA",eError); - return 0; - } - memset(pNew,0,sizeof(FocusAverager)); - - pNew->pDes = CreateDescriptor("FocusAverager"); - if(!pNew->pDes) - { - SCWrite(pCon,"ERROR: out of memory in MakeFA",eError); - return 0; - } - var2 = FindVariable(pServ->pSics,"mbank"); - if(var2) - { - VarGetInt(var2,&mbank); - } else { - SCWrite(pCon,"ERROR: mbank value not found!",eError); - } - if(mbank==1) - { - pCom = FindCommand(pSics,"hm2"); - pDum = (pDummy)pCom->pData; - pNew->pHistogram2 = (pHistMem)pDum; - } - var1 = FindVariable(pServ->pSics,"lbank"); - if(var1) - { - VarGetInt(var1,&lbank); - } else { - SCWrite(pCon,"ERROR: lbank value not found!",eError); - } - if(lbank==1) - { - pCom = FindCommand(pSics,"hm1"); - pDum = (pDummy)pCom->pData; - pNew->pHistogram1 = (pHistMem)pDum; - } - var3 = FindVariable(pServ->pSics,"ubank"); - if(var3) - { - VarGetInt(var3,&ubank); - } else { - SCWrite(pCon,"ERROR: ubank value not found!",eError); - } - if(ubank==1) - { - pCom = FindCommand(pSics,"hm3"); - pDum = (pDummy)pCom->pData; - pNew->pHistogram3 = (pHistMem)pDum; - } - iRet = AddCommand(pSics,argv[1],FocusAverageDo, KillFA, pNew); - if(!iRet) - { - sprintf(pBueffel,"ERROR: duplicate command %s not created", argv[1]); - SCWrite(pCon,pBueffel,eError); - KillFA(pNew); - return 0; - } - iRet = AddCommand(pSics,"focusraw",FocusRaw, NULL, pNew); - if(!iRet) - { - sprintf(pBueffel,"ERROR: duplicate command focusraw not created"); - SCWrite(pCon,pBueffel,eError); - return 0; - } - return 1; - } -/*----------------------------------------------------------------------*/ -HistInt *CheckBank(pFocusAverager self, SConnection *pCon, - int iLength, int iBank) +static void KillFA(void *pData) { - + pFocusAverager self = NULL; + + self = (pFocusAverager) pData; + if (!self) + return; + + if (self->pDes) + DeleteDescriptor(self->pDes); + free(self); +} + +/*-------------------------------------------------------------------------*/ +int FocusAverageDo(SConnection * pCon, SicsInterp * pSics, void *pData, + int argc, char *argv[]) +{ + pFocusAverager self = NULL; + int *iData = NULL; + const float *fTimeBin = NULL; + float fVal; + int iLength, iStart, iEnd, iNum, i, ii, iTest, iBufLen, iRet, iVal; + char pBueffel[256]; + HistInt *hiData = NULL, *hiPtr; + time_t tStart, tEnd; + int iBank = MIDDLE; + pSicsVariable var1 = NULL; + pSicsVariable var2 = NULL; + pSicsVariable var3 = NULL; + int lbank, mbank, ubank; + + self = (pFocusAverager) pData; + assert(self); + assert(pCon); + assert(pSics); + + /* we need two parameters: start and end of averaging */ + if (argc < 3) { + SCWrite(pCon, + "ERROR: insufficient number of parameters for FocusAverage", + eError); + return 0; + } + iRet = Tcl_GetInt(pSics->pTcl, argv[1], &iStart); + if (iRet != TCL_OK) { + sprintf(pBueffel, "ERROR: cannot convert %s to integer", argv[1]); + SCWrite(pCon, pBueffel, eError); + return 0; + } + iRet = Tcl_GetInt(pSics->pTcl, argv[2], &iEnd); + if (iRet != TCL_OK) { + sprintf(pBueffel, "ERROR: cannot convert %s to integer", argv[2]); + SCWrite(pCon, pBueffel, eError); + return 0; + } + + /* another parameter, if available describes the detector bank + */ + if (argc > 3) { + iRet = Tcl_GetInt(pSics->pTcl, argv[3], &iBank); + if (iRet != TCL_OK) { + sprintf(pBueffel, "ERROR: cannot convert %s to integer", argv[3]); + SCWrite(pCon, pBueffel, eError); + return 0; + } + } + + /* how much to do: correct parameters? */ + iNum = iEnd - iStart; + if (iNum < 0) { + SCWrite(pCon, "ERROR: invalid parameters given to FocusAverage", + eError); + return 0; + } + /* may be only one histogram requested */ + if (iNum == 0) + iNum = 1; + if (iStart < 0) { + SCWrite(pCon, "ERROR: invalid parameters given to FocusAverage", + eError); + return 0; + } +#ifdef DEB + printf("Starting averaging ...\n"); + fflush(stdout); + tStart = time(NULL); +#endif + + /* do work! first retrieve time binning data */ + + var2 = FindVariable(pServ->pSics, "mbank"); + if (var2) { + VarGetInt(var2, &mbank); + } else { + SCWrite(pCon, "ERROR: mbank value not found!", eError); + } + if (mbank == 1) { + fTimeBin = GetHistTimeBin(self->pHistogram2, &iLength); + } else { + var1 = FindVariable(pServ->pSics, "lbank"); + if (var1) { + VarGetInt(var1, &lbank); + } else { + SCWrite(pCon, "ERROR: lbank value not found!", eError); + } + if (lbank == 1) { + fTimeBin = GetHistTimeBin(self->pHistogram1, &iLength); + } else { + fTimeBin = GetHistTimeBin(self->pHistogram3, &iLength); + } + } + assert(fTimeBin); + if (iLength <= 0) { + SCWrite(pCon, "ERROR: histogram memory inproperly configured", eError); + return 0; + } + /* allocate result data */ + iBufLen = (iLength * 2 + 1) * sizeof(int); + iData = (int *) malloc(iBufLen); + memset(iData, 0, iBufLen); + + /* get histogram length */ + i = getFMdim(iBank); + /* correct iEnd to maximum allowed */ + iTest = i; + if (iEnd > iTest - 1) { + iEnd = iTest - 1; + iNum = iEnd - iStart; + if (iNum <= 0) + iNum = 1; + } +#ifdef DEB + printf("Getting histogram....\n"); + fflush(stdout); +#endif + + hiData = CheckBank(self, pCon, iLength, iBank); + +#ifdef DEB + tEnd = time(NULL); + printf("Histogram received in %d seconds\n", tStart - tEnd); + fflush(stdout); +#endif + + if (hiData == NULL) { + SCWrite(pCon, "ERROR: BAD Configuration", eError); + free(iData); + return 0; + } + + /* first int: length of things to come */ + iData[0] = htonl(iLength); + /* sum up */ + for (i = iStart; i < iEnd; i++) { + hiPtr = hiData + i * iLength; + for (ii = 0; ii < iLength; ii++) { + iData[ii + 1] += hiPtr[ii]; + } + } + /* average */ + for (i = 1; i < iLength + 1; i++) { + fVal = (float) iData[i] / (float) iNum; + fVal *= 65536.; + iData[i] = htonl((int) fVal); + } + /* make time binning fixed point */ + for (i = 0; i < iLength; i++) { + fVal = fTimeBin[i] / 10.; + fVal *= 65536.; + iData[iLength + 1 + i] = htonl((int) fVal); + } +#ifdef DEB + printf("Sending averaged data....\n"); + fflush(stdout); +#endif + /* finally send out uuencoded */ + SCWriteUUencoded(pCon, "FocusAverage", iData, iBufLen); + if (iData) + free(iData); +#ifdef DEB + printf("Averaging finished\n"); + fflush(stdout); +#endif + return 1; +} + +/*-------------------------------------------------------------------------*/ +static int FocusRaw(SConnection * pCon, SicsInterp * pSics, void *pData, + int argc, char *argv[]) +{ + pFocusAverager self = NULL; + int *iData = NULL; + int iLength, noTimebin, iRet, i; + char pBueffel[256]; + const float *timeBin; + HistInt *hiData = NULL, *hiPtr; + int iBank = MIDDLE; + pSicsVariable var1 = NULL; + pSicsVariable var2 = NULL; + pSicsVariable var3 = NULL; + int lbank, mbank, ubank; + + self = (pFocusAverager) pData; + assert(self); + assert(pCon); + assert(pSics); + + + /* we need one parameter, the bank to read */ + if (argc < 2) { + SCWrite(pCon, + "ERROR: insufficient number of parameters for FocusRaw", + eError); + return 0; + } + iRet = Tcl_GetInt(pSics->pTcl, argv[1], &iBank); + if (iRet != TCL_OK) { + sprintf(pBueffel, "ERROR: cannot convert %s to integer", argv[1]); + SCWrite(pCon, pBueffel, eError); + return 0; + } + var2 = FindVariable(pServ->pSics, "mbank"); + if (var2) { + VarGetInt(var2, &mbank); + } else { + SCWrite(pCon, "ERROR: mbank value not found!", eError); + } + if (var2) { + timeBin = GetHistTimeBin(self->pHistogram2, &iLength); + } else { + var1 = FindVariable(pServ->pSics, "lbank"); + if (var1) { + VarGetInt(var1, &lbank); + } else { + SCWrite(pCon, "ERROR: lbank value not found!", eError); + } + if (var1) { + timeBin = GetHistTimeBin(self->pHistogram1, &iLength); + } else { + timeBin = GetHistTimeBin(self->pHistogram3, &iLength); + } + } + assert(timeBin); + hiData = CheckBank(self, pCon, iLength, iBank); + + /* get histogram length */ + iLength = getFMdim(iBank); + noTimebin = getFMdim(TIMEBIN); + /* write dimension info */ + sprintf(pBueffel, "focusrawdim = %d = %d", iLength, noTimebin); + SCWrite(pCon, pBueffel, eValue); + + /* allocate space */ + iData = (int *) malloc((iLength * noTimebin + 1) * sizeof(int)); + if (iData == NULL) { + SCWrite(pCon, "ERROR: out of memory in FocusRaw", eError); + return 0; + } + memset(iData, 0, noTimebin * iLength * sizeof(int)); + + /* first int: length of things to come */ + iData[0] = htonl(iLength * noTimebin); + /* network byte order for everything */ + for (i = 0; i < noTimebin * iLength; i++) { + iData[i + 1] = htonl(hiData[i]); + } + /* send away, zipped */ + SCWriteZipped(pCon, "focusraw", iData, + (iLength * noTimebin + 1) * sizeof(int)); + + free(iData); + return 1; +} + +/*-------------------------------------------------------------------------*/ +int MakeFA(SConnection * pCon, SicsInterp * pSics, void *pData, + int argc, char *argv[]) +{ + pFocusAverager pNew = NULL; + CommandList *pCom = NULL; + pDummy pDum = NULL; + char pBueffel[256]; + int iRet; + pSicsVariable var1 = NULL; + pSicsVariable var2 = NULL; + pSicsVariable var3 = NULL; + int lbank, mbank, ubank; + + assert(pCon); + assert(pSics); + + /* we need two parameters: the name for the averager and the histogram + memory + */ + if (argc < 3) { + SCWrite(pCon, "ERROR: Insufficient number of parameters to MakeFA", + eError); + return 0; + } + + /* find histogram memory */ + pCom = FindCommand(pSics, argv[2]); + if (!pCom) { + sprintf(pBueffel, "ERROR: histogram memory %s NOT found!", argv[2]); + SCWrite(pCon, pBueffel, eError); + return 0; + } + pDum = (pDummy) pCom->pData; + if (!pDum) { + sprintf(pBueffel, "ERROR: histogram memory %s INVALID!", argv[2]); + SCWrite(pCon, pBueffel, eError); + return 0; + } + if (strcmp(pDum->pDescriptor->name, "HMcontrol") != 0) { + sprintf(pBueffel, "ERROR: %s is NO histogram control object!", + argv[2]); + SCWrite(pCon, pBueffel, eError); + return 0; + } + + /* we got what we need: set things up */ + pNew = (pFocusAverager) malloc(sizeof(FocusAverager)); + if (!pNew) { + SCWrite(pCon, "ERROR: out of memory in MakeFA", eError); + return 0; + } + memset(pNew, 0, sizeof(FocusAverager)); + + pNew->pDes = CreateDescriptor("FocusAverager"); + if (!pNew->pDes) { + SCWrite(pCon, "ERROR: out of memory in MakeFA", eError); + return 0; + } + var2 = FindVariable(pServ->pSics, "mbank"); + if (var2) { + VarGetInt(var2, &mbank); + } else { + SCWrite(pCon, "ERROR: mbank value not found!", eError); + } + if (mbank == 1) { + pCom = FindCommand(pSics, "hm2"); + pDum = (pDummy) pCom->pData; + pNew->pHistogram2 = (pHistMem) pDum; + } + var1 = FindVariable(pServ->pSics, "lbank"); + if (var1) { + VarGetInt(var1, &lbank); + } else { + SCWrite(pCon, "ERROR: lbank value not found!", eError); + } + if (lbank == 1) { + pCom = FindCommand(pSics, "hm1"); + pDum = (pDummy) pCom->pData; + pNew->pHistogram1 = (pHistMem) pDum; + } + var3 = FindVariable(pServ->pSics, "ubank"); + if (var3) { + VarGetInt(var3, &ubank); + } else { + SCWrite(pCon, "ERROR: ubank value not found!", eError); + } + if (ubank == 1) { + pCom = FindCommand(pSics, "hm3"); + pDum = (pDummy) pCom->pData; + pNew->pHistogram3 = (pHistMem) pDum; + } + iRet = AddCommand(pSics, argv[1], FocusAverageDo, KillFA, pNew); + if (!iRet) { + sprintf(pBueffel, "ERROR: duplicate command %s not created", argv[1]); + SCWrite(pCon, pBueffel, eError); + KillFA(pNew); + return 0; + } + iRet = AddCommand(pSics, "focusraw", FocusRaw, NULL, pNew); + if (!iRet) { + sprintf(pBueffel, "ERROR: duplicate command focusraw not created"); + SCWrite(pCon, pBueffel, eError); + return 0; + } + return 1; +} + +/*----------------------------------------------------------------------*/ +HistInt *CheckBank(pFocusAverager self, SConnection * pCon, + int iLength, int iBank) +{ + pSicsVariable var1 = NULL; pSicsVariable var2 = NULL; pSicsVariable var3 = NULL; @@ -483,76 +438,63 @@ HistInt *CheckBank(pFocusAverager self, SConnection *pCon, HistInt *mData = NULL; HistInt *uData = NULL; HistInt *mergData = NULL; - int lbank, mbank, ubank; - - if (iBank==2) - { - var2 = FindVariable(pServ->pSics,"mbank"); - if(var2) - { - VarGetInt(var2,&mbank); - } else { - SCWrite(pCon,"ERROR: mbank value not found!",eError); - } - if(mbank==1) - { - mData = GetHistogramPointer(self->pHistogram2,pCon); - if(mData == NULL) - { - return NULL; - } - setFMDataPointer(mData, iLength,2); - mData = getFMBankPointer(2); - return mData; - } - } - if (iBank==3) - { - var1 = FindVariable(pServ->pSics,"lbank"); - if(var1) - { - VarGetInt(var1,&lbank); - } else { - SCWrite(pCon,"ERROR: lbank value not found!",eError); - } - if(lbank==1) - { - lData = GetHistogramPointer(self->pHistogram1,pCon); - if(lData == NULL) - { - return NULL; - } - setFMDataPointer(lData, iLength, 3); - lData = getFMBankPointer(3); - return lData; - } - } - if (iBank==1) - { - var3 = FindVariable(pServ->pSics,"ubank"); - if(var3) - { - VarGetInt(var3,&ubank); - } else { - SCWrite(pCon,"ERROR: ubank value not found!",eError); - } - if(ubank==1) - { - uData = GetHistogramPointer(self->pHistogram3,pCon); - if(uData == NULL) - { - return NULL; - } - setFMDataPointer(uData, iLength, 1); - uData = getFMBankPointer(1); - return uData; - } - } - if (iBank==4) - { - setFMDataPointer(mergData, iLength,4); - mergData = getFMBankPointer(4); - return mergData; + int lbank, mbank, ubank; + + if (iBank == 2) { + var2 = FindVariable(pServ->pSics, "mbank"); + if (var2) { + VarGetInt(var2, &mbank); + } else { + SCWrite(pCon, "ERROR: mbank value not found!", eError); } - return NULL; + if (mbank == 1) { + mData = GetHistogramPointer(self->pHistogram2, pCon); + if (mData == NULL) { + return NULL; + } + setFMDataPointer(mData, iLength, 2); + mData = getFMBankPointer(2); + return mData; + } + } + if (iBank == 3) { + var1 = FindVariable(pServ->pSics, "lbank"); + if (var1) { + VarGetInt(var1, &lbank); + } else { + SCWrite(pCon, "ERROR: lbank value not found!", eError); + } + if (lbank == 1) { + lData = GetHistogramPointer(self->pHistogram1, pCon); + if (lData == NULL) { + return NULL; + } + setFMDataPointer(lData, iLength, 3); + lData = getFMBankPointer(3); + return lData; + } + } + if (iBank == 1) { + var3 = FindVariable(pServ->pSics, "ubank"); + if (var3) { + VarGetInt(var3, &ubank); + } else { + SCWrite(pCon, "ERROR: ubank value not found!", eError); + } + if (ubank == 1) { + uData = GetHistogramPointer(self->pHistogram3, pCon); + if (uData == NULL) { + return NULL; + } + setFMDataPointer(uData, iLength, 1); + uData = getFMBankPointer(1); + return uData; + } + } + if (iBank == 4) { + setFMDataPointer(mergData, iLength, 4); + mergData = getFMBankPointer(4); + return mergData; + } + return NULL; } diff --git a/faverage.h b/faverage.h index eb0edc9..99aef5e 100644 --- a/faverage.h +++ b/faverage.h @@ -10,11 +10,11 @@ #ifndef FOCUSAVERAGE #define FOCUSAVERAGE - int MakeFA(SConnection *pCon, SicsInterp *pSics, void *pData, - int argc, char *argv[]); +int MakeFA(SConnection * pCon, SicsInterp * pSics, void *pData, + int argc, char *argv[]); - int FocusAverageDo(SConnection *pCon, SicsInterp *pSics, void *pData, - int argc, char *argv[]); +int FocusAverageDo(SConnection * pCon, SicsInterp * pSics, void *pData, + int argc, char *argv[]); #endif diff --git a/fowrite.c b/fowrite.c index 21188b8..98bfa5d 100644 --- a/fowrite.c +++ b/fowrite.c @@ -40,1150 +40,1037 @@ /* the name of the SICS chopper controller object */ -#define CHOPPERNAME "choco" +#define CHOPPERNAME "choco" /*--------- the internal data structure ------------------------------------*/ - typedef struct { - pObjectDescriptor pDes; - pHistMem pHistogram1, pHistogram2, pHistogram3; - int iNew; - time_t tUpdate; - int iInterval; - int iEnd; - SConnection *pCon; - pCounter pCount; - char *pFile; - char *pDictFile; - pFit pFitter; - float fElastic; - pICallBack pCall; - int iUpper, iMiddle, iLower; - /* detector availability flags */ - } FoWrite, *pFoWrite; +typedef struct { + pObjectDescriptor pDes; + pHistMem pHistogram1, pHistogram2, pHistogram3; + int iNew; + time_t tUpdate; + int iInterval; + int iEnd; + SConnection *pCon; + pCounter pCount; + char *pFile; + char *pDictFile; + pFit pFitter; + float fElastic; + pICallBack pCall; + int iUpper, iMiddle, iLower; + /* detector availability flags */ +} FoWrite, *pFoWrite; /* ------------------- forward declaration of task function --------------*/ - static int FoTask(void *pData); - static void FoUpdate(pFoWrite self, SConnection *pCon); +static int FoTask(void *pData); +static void FoUpdate(pFoWrite self, SConnection * pCon); /*------------------ The Countstart Callback Function ----------------------*/ - static int Countstartcallback(int iEvent, void *pEventData, void *pUser) - { - pFoWrite self = NULL; - - if(iEvent == COUNTSTART) - { - self = (pFoWrite)pUser; - assert(self); - self->iNew = 1; - self->iEnd = 0; - self->tUpdate = time(NULL); - self->pCon = (SConnection *)pEventData; - TaskRegister(pServ->pTasker,FoTask,NULL,NULL,self,1); - return 1; - } - return 1; - } -/*------------------ The Countend Callback Function ----------------------*/ - static int Countendcallback(int iEvent, void *pEventData, void *pUser) - { - pFoWrite self = NULL; - - if(iEvent == COUNTEND) - { - self = (pFoWrite)pUser; - assert(self); - self->tUpdate = time(NULL); - self->iEnd = 1; - /* - FoUpdate(self,self->pCon); - */ - return 1; - } - return 1; - } -/*-----------------------------------------------------------------------*/ - static void SNError(void *pData, char *text) - { - SConnection *pCon; - - assert(pData); - pCon = (SConnection *)pData; - SCWrite(pCon,text,eError); - } -/*------------------------------------------------------------------------*/ - static void WriteSelector(NXhandle pFile, NXdict pDict, SConnection *pCon) - { - pSicsSelector pSel = NULL; - char *pName = NULL; - CommandList *pCom = NULL; - pDummy pDum = NULL; - float fTh, fTTH, fB1, fB2; - int iRet; - - pCom = FindCommand(pServ->pSics,"mono"); - if(!pCom) - { - SCWrite(pCon,"ERROR: no monochromator found",eError); - return ; - } - pSel = (pSicsSelector)pCom->pData; - if(!pSel) - { - SCWrite(pCon,"ERROR: no monochromator found",eError); - return ; - } - pDum = (pDummy)pSel; - if(strcmp(pDum->pDescriptor->name,"CrystalSelector") != 0) - { - SCWrite(pCon,"ERROR: monochromator is invalid",eError); - return ; - } - - NXDputalias(pFile,pDict,"mname",MonoGetType(pSel)); - iRet = GetMonoPositions(pSel,pCon,&fTh, &fTTH, &fB1, &fB2); - if(!iRet) - { - SCWrite(pCon,"ERROR: Problem reading monochromator positions",eError); - SCWrite(pCon,"ERROR: monochromator data missing in file",eError); - return; - } - NXDputalias(pFile,pDict,"mtheta",&fTh); - NXDputalias(pFile,pDict,"mttheta",&fTTH); - SNXSPutDrivable(pServ->pSics,pCon, pFile,pDict,"lambda","mlambda"); - SNXSPutDrivable(pServ->pSics,pCon, pFile,pDict,"qi","menergy"); - } -/*----------------------------------------------------------------------*/ - static float CalculateElastic(pFoWrite self, SConnection *pCon) - { - pIDrivable pDriv; - pSicsVariable pVar; - CommandList *pCom = NULL; - float fLambda, fDist, fResult; +static int Countstartcallback(int iEvent, void *pEventData, void *pUser) +{ + pFoWrite self = NULL; - pCom = FindCommand(pServ->pSics,"lambda"); - if(!pCom) - return 0.; - pDriv = GetDrivableInterface(pCom->pData); - if(!pDriv) - return 0.; - fLambda = pDriv->GetValue(pCom->pData,pCon); - pVar = FindVariable(pServ->pSics,"sampledist"); - if(!pVar) - return 0.; - fDist = pVar->fVal; - pVar = FindVariable(pServ->pSics,"detectordist"); - if(!pVar) - return 0.; - fDist += pVar->fVal; - fResult = 252.78*fLambda*(fDist/1000.); - return fResult; + if (iEvent == COUNTSTART) { + self = (pFoWrite) pUser; + assert(self); + self->iNew = 1; + self->iEnd = 0; + self->tUpdate = time(NULL); + self->pCon = (SConnection *) pEventData; + TaskRegister(pServ->pTasker, FoTask, NULL, NULL, self, 1); + return 1; } + return 1; +} + +/*------------------ The Countend Callback Function ----------------------*/ +static int Countendcallback(int iEvent, void *pEventData, void *pUser) +{ + pFoWrite self = NULL; + + if (iEvent == COUNTEND) { + self = (pFoWrite) pUser; + assert(self); + self->tUpdate = time(NULL); + self->iEnd = 1; + /* + FoUpdate(self,self->pCon); + */ + return 1; + } + return 1; +} + +/*-----------------------------------------------------------------------*/ +static void SNError(void *pData, char *text) +{ + SConnection *pCon; + + assert(pData); + pCon = (SConnection *) pData; + SCWrite(pCon, text, eError); +} + +/*------------------------------------------------------------------------*/ +static void WriteSelector(NXhandle pFile, NXdict pDict, SConnection * pCon) +{ + pSicsSelector pSel = NULL; + char *pName = NULL; + CommandList *pCom = NULL; + pDummy pDum = NULL; + float fTh, fTTH, fB1, fB2; + int iRet; + + pCom = FindCommand(pServ->pSics, "mono"); + if (!pCom) { + SCWrite(pCon, "ERROR: no monochromator found", eError); + return; + } + pSel = (pSicsSelector) pCom->pData; + if (!pSel) { + SCWrite(pCon, "ERROR: no monochromator found", eError); + return; + } + pDum = (pDummy) pSel; + if (strcmp(pDum->pDescriptor->name, "CrystalSelector") != 0) { + SCWrite(pCon, "ERROR: monochromator is invalid", eError); + return; + } + + NXDputalias(pFile, pDict, "mname", MonoGetType(pSel)); + iRet = GetMonoPositions(pSel, pCon, &fTh, &fTTH, &fB1, &fB2); + if (!iRet) { + SCWrite(pCon, "ERROR: Problem reading monochromator positions", + eError); + SCWrite(pCon, "ERROR: monochromator data missing in file", eError); + return; + } + NXDputalias(pFile, pDict, "mtheta", &fTh); + NXDputalias(pFile, pDict, "mttheta", &fTTH); + SNXSPutDrivable(pServ->pSics, pCon, pFile, pDict, "lambda", "mlambda"); + SNXSPutDrivable(pServ->pSics, pCon, pFile, pDict, "qi", "menergy"); +} + +/*----------------------------------------------------------------------*/ +static float CalculateElastic(pFoWrite self, SConnection * pCon) +{ + pIDrivable pDriv; + pSicsVariable pVar; + CommandList *pCom = NULL; + float fLambda, fDist, fResult; + + pCom = FindCommand(pServ->pSics, "lambda"); + if (!pCom) + return 0.; + pDriv = GetDrivableInterface(pCom->pData); + if (!pDriv) + return 0.; + fLambda = pDriv->GetValue(pCom->pData, pCon); + pVar = FindVariable(pServ->pSics, "sampledist"); + if (!pVar) + return 0.; + fDist = pVar->fVal; + pVar = FindVariable(pServ->pSics, "detectordist"); + if (!pVar) + return 0.; + fDist += pVar->fVal; + fResult = 252.78 * fLambda * (fDist / 1000.); + return fResult; +} + /*------------------------------------------------------------------------- FoStart writes all the fixed data items, creates a new file etc. A complete file is obtained after FoStart plus a call to FoUpdate -*/ - static int FoStart(pFoWrite self, SConnection *pCon) - { - NXhandle pFile = NULL; - NXdict pDict = NULL; - pSicsVariable var1 = NULL; - pSicsVariable var2 = NULL; - int lbank, mbank; - int iStat, iLength, i; - char pBueffel[512]; - CounterMode eMode; - float fVal, *fArray; - const float *fTime; - float *fTime2 = NULL; - char pBuffer[50]; - - /* get a filename */ - if(self->pFile) - free(self->pFile); - - self->pFile = SNXMakeFileName(pServ->pSics,pCon); - if(!self->pFile) - { - SCWrite(pCon,"ERROR: Extra severe: failed to create data file name", - eError); - return 0; - } - - /* create a Nexus file */ - NXopen(self->pFile,NXACC_CREATE,&pFile); - if(!pFile) - { - SCWrite(pCon,"ERROR: cannot create data file ",eError); - return 0; - } - - /* tell Uwe User what we are doing */ - sprintf(pBueffel,"Writing %s ......",self->pFile); - SCWrite(pCon,pBueffel,eWarning); - - /* write globals */ - SNXSPutGlobals(pFile,self->pFile,"FOCUS",pCon); - - /* open nxdict and configure nxdict parameters */ - iStat = NXDinitfromfile(self->pDictFile,&pDict); - if(iStat != NX_OK) - { - sprintf(pBueffel,"ERROR: failed to open dictionary file %s", - self->pDictFile); - SCWrite(pCon,pBueffel,eError); - SCWrite(pCon,"ERROR: Aborting data file writing",eError); - SCWrite(pCon,"ERROR: This is a SERIOUS problem!",eError); - SCWrite(pCon,"ERROR: DATA NOT WRITTEN",eError); - NXclose(&pFile); - return 0; - } +*/ +static int FoStart(pFoWrite self, SConnection * pCon) +{ + NXhandle pFile = NULL; + NXdict pDict = NULL; + pSicsVariable var1 = NULL; + pSicsVariable var2 = NULL; + int lbank, mbank; + int iStat, iLength, i; + char pBueffel[512]; + CounterMode eMode; + float fVal, *fArray; + const float *fTime; + float *fTime2 = NULL; + char pBuffer[50]; - /* put permanent data */ - SNXSPutVariable(pServ->pSics,pCon,pFile,pDict,"etitle","title"); - SNXFormatTime(pBueffel,511); + /* get a filename */ + if (self->pFile) + free(self->pFile); - /* entry & instrument stuff */ - NXDputalias(pFile,pDict,"estart",pBueffel); - SNXSPutVariable(pServ->pSics,pCon,pFile,pDict,"iname","instrument"); - NXDputalias(pFile,pDict,"sname","SINQ, PSI, Switzerland"); - NXDputalias(pFile,pDict,"stype","continous spallation source"); + self->pFile = SNXMakeFileName(pServ->pSics, pCon); + if (!self->pFile) { + SCWrite(pCon, "ERROR: Extra severe: failed to create data file name", + eError); + return 0; + } - /* disk chopper */ - NXDputalias(pFile,pDict,"cname","Dornier disk chopper"); + /* create a Nexus file */ + NXopen(self->pFile, NXACC_CREATE, &pFile); + if (!pFile) { + SCWrite(pCon, "ERROR: cannot create data file ", eError); + return 0; + } - /* be-filter */ - NXDputalias(pFile,pDict,"bname","BE-filter"); - SNXSPutVariable(pServ->pSics,pCon,pFile,pDict,"bstatus","bestatus"); + /* tell Uwe User what we are doing */ + sprintf(pBueffel, "Writing %s ......", self->pFile); + SCWrite(pCon, pBueffel, eWarning); - /* flight path */ - SNXSPutVariable(pServ->pSics,pCon,pFile,pDict,"fltype","flightpath"); - SNXSPutVariable(pServ->pSics,pCon,pFile,pDict,"fllength","flightpathlength"); + /* write globals */ + SNXSPutGlobals(pFile, self->pFile, "FOCUS", pCon); - /* monochromator */ - WriteSelector(pFile,pDict,pCon); + /* open nxdict and configure nxdict parameters */ + iStat = NXDinitfromfile(self->pDictFile, &pDict); + if (iStat != NX_OK) { + sprintf(pBueffel, "ERROR: failed to open dictionary file %s", + self->pDictFile); + SCWrite(pCon, pBueffel, eError); + SCWrite(pCon, "ERROR: Aborting data file writing", eError); + SCWrite(pCon, "ERROR: This is a SERIOUS problem!", eError); + SCWrite(pCon, "ERROR: DATA NOT WRITTEN", eError); + NXclose(&pFile); + return 0; + } - /* fermi chupper */ - SNXSPutVariable(pServ->pSics,pCon,pFile,pDict,"fcname","ferminame"); - SNXSPutVariable(pServ->pSics,pCon,pFile,pDict,"fcdist","fermidist"); + /* put permanent data */ + SNXSPutVariable(pServ->pSics, pCon, pFile, pDict, "etitle", "title"); + SNXFormatTime(pBueffel, 511); - /* counting data */ + /* entry & instrument stuff */ + NXDputalias(pFile, pDict, "estart", pBueffel); + SNXSPutVariable(pServ->pSics, pCon, pFile, pDict, "iname", "instrument"); + NXDputalias(pFile, pDict, "sname", "SINQ, PSI, Switzerland"); + NXDputalias(pFile, pDict, "stype", "continous spallation source"); - var2 = FindVariable(pServ->pSics,"mbank"); - if(var2) - { - VarGetInt(var2,&mbank); - } else { - SCWrite(pCon,"ERROR: mbank value not found!",eError); - } - if(var2) - { - eMode = GetHistCountMode(self->pHistogram2); - fTime = GetHistTimeBin(self->pHistogram2,&iLength); - fVal = GetHistPreset(self->pHistogram2); - } - else - { - var1 = FindVariable(pServ->pSics,"lbank"); - if(var1) - { - VarGetInt(var1,&lbank); - } else { - SCWrite(pCon,"ERROR: lbank value not found!",eError); - } - if(var1) - { - eMode = GetHistCountMode(self->pHistogram1); - fTime = GetHistTimeBin(self->pHistogram1,&iLength); - fVal = GetHistPreset(self->pHistogram1); - } - else - { - eMode = GetHistCountMode(self->pHistogram3); - fTime = GetHistTimeBin(self->pHistogram3,&iLength); - fVal = GetHistPreset(self->pHistogram3); - } - } + /* disk chopper */ + NXDputalias(pFile, pDict, "cname", "Dornier disk chopper"); - if(eMode == eTimer) - { - strcpy(pBueffel,"timer"); - } - else - { - strcpy(pBueffel,"monitor"); - } - NXDputalias(pFile,pDict,"cnmode",pBueffel); - NXDputalias(pFile,pDict,"cnpreset",&fVal); - - /* detector banks */ - fTime2 = (float *)malloc(iLength*sizeof(float)); - if(fTime2) - { - for(i = 0; i < iLength; i++) - { - fTime2[i] = fTime[i]/10.; - } - sprintf(pBueffel,"%d",iLength); - NXDupdate(pDict,"timebin",pBueffel); - if(self->iMiddle) - { - NXDupdate(pDict,"bank","bank1"); - NXDputalias(pFile,pDict,"dtime",fTime2); - } - if(self->iUpper) - { - NXDupdate(pDict,"bank","upperbank"); - NXDputalias(pFile,pDict,"dtime",fTime2); - } - if(self->iLower) - { - NXDupdate(pDict,"bank","lowerbank"); - NXDputalias(pFile,pDict,"dtime",fTime2); - } - if( (self->iLower || self->iUpper) && self->iMiddle) - { - NXDupdate(pDict,"bank","merged"); - NXDputalias(pFile,pDict,"dtime",fTime2); - } - NXDupdate(pDict,"bank","bank1"); + /* be-filter */ + NXDputalias(pFile, pDict, "bname", "BE-filter"); + SNXSPutVariable(pServ->pSics, pCon, pFile, pDict, "bstatus", "bestatus"); + + /* flight path */ + SNXSPutVariable(pServ->pSics, pCon, pFile, pDict, "fltype", + "flightpath"); + SNXSPutVariable(pServ->pSics, pCon, pFile, pDict, "fllength", + "flightpathlength"); + + /* monochromator */ + WriteSelector(pFile, pDict, pCon); + + /* fermi chupper */ + SNXSPutVariable(pServ->pSics, pCon, pFile, pDict, "fcname", "ferminame"); + SNXSPutVariable(pServ->pSics, pCon, pFile, pDict, "fcdist", "fermidist"); + + /* counting data */ + + var2 = FindVariable(pServ->pSics, "mbank"); + if (var2) { + VarGetInt(var2, &mbank); + } else { + SCWrite(pCon, "ERROR: mbank value not found!", eError); + } + if (var2) { + eMode = GetHistCountMode(self->pHistogram2); + fTime = GetHistTimeBin(self->pHistogram2, &iLength); + fVal = GetHistPreset(self->pHistogram2); + } else { + var1 = FindVariable(pServ->pSics, "lbank"); + if (var1) { + VarGetInt(var1, &lbank); + } else { + SCWrite(pCon, "ERROR: lbank value not found!", eError); + } + if (var1) { + eMode = GetHistCountMode(self->pHistogram1); + fTime = GetHistTimeBin(self->pHistogram1, &iLength); + fVal = GetHistPreset(self->pHistogram1); + } else { + eMode = GetHistCountMode(self->pHistogram3); + fTime = GetHistTimeBin(self->pHistogram3, &iLength); + fVal = GetHistPreset(self->pHistogram3); + } + } + + if (eMode == eTimer) { + strcpy(pBueffel, "timer"); + } else { + strcpy(pBueffel, "monitor"); + } + NXDputalias(pFile, pDict, "cnmode", pBueffel); + NXDputalias(pFile, pDict, "cnpreset", &fVal); + + /* detector banks */ + fTime2 = (float *) malloc(iLength * sizeof(float)); + if (fTime2) { + for (i = 0; i < iLength; i++) { + fTime2[i] = fTime[i] / 10.; + } + sprintf(pBueffel, "%d", iLength); + NXDupdate(pDict, "timebin", pBueffel); + if (self->iMiddle) { + NXDupdate(pDict, "bank", "bank1"); + NXDputalias(pFile, pDict, "dtime", fTime2); + } + if (self->iUpper) { + NXDupdate(pDict, "bank", "upperbank"); + NXDputalias(pFile, pDict, "dtime", fTime2); + } + if (self->iLower) { + NXDupdate(pDict, "bank", "lowerbank"); + NXDputalias(pFile, pDict, "dtime", fTime2); + } + if ((self->iLower || self->iUpper) && self->iMiddle) { + NXDupdate(pDict, "bank", "merged"); + NXDputalias(pFile, pDict, "dtime", fTime2); + } + NXDupdate(pDict, "bank", "bank1"); - /* calculate theoretical position of elastic peak */ - fVal = CalculateElastic(self,pCon); - self->fElastic = (fVal - fTime2[0]) / (fTime2[1] - fTime2[0]); - free(fTime2); - fTime2 = NULL; - } - else - { - SCWrite(pCon,"ERROR: out of memory while writing time binning", - eError); - } + /* calculate theoretical position of elastic peak */ + fVal = CalculateElastic(self, pCon); + self->fElastic = (fVal - fTime2[0]) / (fTime2[1] - fTime2[0]); + free(fTime2); + fTime2 = NULL; + } else { + SCWrite(pCon, "ERROR: out of memory while writing time binning", + eError); + } - SNXSPutVariable(pServ->pSics,pCon,pFile,pDict,"ddist","detectordist"); + SNXSPutVariable(pServ->pSics, pCon, pFile, pDict, "ddist", + "detectordist"); - /* theta arrays */ - if(self->iMiddle) - { - NXDupdate(pDict,"bank","bank1"); - iLength = 150; - sprintf(pBuffer,"%d",iLength); - NXDupdate(pDict,"noofdetectors",pBuffer); - fArray = getFMBankTheta(MIDDLE); - NXDputalias(pFile,pDict,"dtheta",fArray); - } - if(self->iLower) - { - NXDupdate(pDict,"bank","lowerbank"); - iLength = 115; - sprintf(pBuffer,"%d",iLength); - NXDupdate(pDict,"noofdetectors",pBuffer); - fArray = getFMBankTheta(LOWER); - NXDputalias(pFile,pDict,"dtheta",fArray); - } - if(self->iUpper) - { - NXDupdate(pDict,"bank","upperbank"); - iLength = 110; - sprintf(pBuffer,"%d",iLength); - NXDupdate(pDict,"noofdetectors",pBuffer); - fArray = getFMBankTheta(UPPER); - NXDputalias(pFile,pDict,"dtheta",fArray); - } - if(self->iMiddle && ( self->iLower || self->iUpper) ) - { - NXDupdate(pDict,"bank","merged"); - iLength = 375; - sprintf(pBuffer,"%d",iLength); - NXDupdate(pDict,"noofdetectors",pBuffer); - fArray = getFMBankTheta(MERGED); - NXDputalias(pFile,pDict,"dtheta",fArray); - } + /* theta arrays */ + if (self->iMiddle) { + NXDupdate(pDict, "bank", "bank1"); + iLength = 150; + sprintf(pBuffer, "%d", iLength); + NXDupdate(pDict, "noofdetectors", pBuffer); + fArray = getFMBankTheta(MIDDLE); + NXDputalias(pFile, pDict, "dtheta", fArray); + } + if (self->iLower) { + NXDupdate(pDict, "bank", "lowerbank"); + iLength = 115; + sprintf(pBuffer, "%d", iLength); + NXDupdate(pDict, "noofdetectors", pBuffer); + fArray = getFMBankTheta(LOWER); + NXDputalias(pFile, pDict, "dtheta", fArray); + } + if (self->iUpper) { + NXDupdate(pDict, "bank", "upperbank"); + iLength = 110; + sprintf(pBuffer, "%d", iLength); + NXDupdate(pDict, "noofdetectors", pBuffer); + fArray = getFMBankTheta(UPPER); + NXDputalias(pFile, pDict, "dtheta", fArray); + } + if (self->iMiddle && (self->iLower || self->iUpper)) { + NXDupdate(pDict, "bank", "merged"); + iLength = 375; + sprintf(pBuffer, "%d", iLength); + NXDupdate(pDict, "noofdetectors", pBuffer); + fArray = getFMBankTheta(MERGED); + NXDputalias(pFile, pDict, "dtheta", fArray); + } + + NXDupdate(pDict, "bank", "bank1"); + SNXSPutVariable(pServ->pSics, pCon, pFile, pDict, "ddelay", "delay"); + + + /* sample info */ + SNXSPutVariable(pServ->pSics, pCon, pFile, pDict, "saname", "sample"); + SNXSPutVariable(pServ->pSics, pCon, pFile, pDict, "senvir", + "environment"); + SNXSPutVariable(pServ->pSics, pCon, pFile, pDict, "sdist", "sampledist"); + SNXSPutVariable(pServ->pSics, pCon, pFile, pDict, "saangle", + "sampleangle"); + + /* close everything */ + NXclose(&pFile); + NXDclose(pDict, NULL); + return 0; +} - NXDupdate(pDict,"bank","bank1"); - SNXSPutVariable(pServ->pSics,pCon,pFile,pDict,"ddelay","delay"); - - - /* sample info */ - SNXSPutVariable(pServ->pSics,pCon,pFile,pDict,"saname","sample"); - SNXSPutVariable(pServ->pSics,pCon,pFile,pDict,"senvir","environment"); - SNXSPutVariable(pServ->pSics,pCon,pFile,pDict,"sdist","sampledist"); - SNXSPutVariable(pServ->pSics,pCon,pFile,pDict,"saangle","sampleangle"); - - /* close everything */ - NXclose(&pFile); - NXDclose(pDict,NULL); - return 0; - } /*---------------------------------------------------------------------------*/ - static void FoUpdate(pFoWrite self, SConnection *pCon) - { - char pBueffel[512]; - int iInt, iStat, iTime, i,ii, j, iDet, iIndex; - pSicsVariable var1 = NULL; - pSicsVariable var2 = NULL; - pSicsVariable var3 = NULL; - int lbank, mbank, ubank; - long lVal; - float fVal; - const float *fTime; - NXhandle pFile = NULL; - NXdict pDict; - HistInt *lData = NULL; - HistInt *mData = NULL; - HistInt *uData = NULL; - int *iSum = NULL; - float *fAxis = NULL; - long *lSum = NULL; - float fCenter, fStdDev, fFWHM; - - /* open everything again */ - NXopen(self->pFile,NXACC_RDWR,&pFile); - if(!pFile) - { - SCWrite(pCon,"ERROR: cannot reopen data file ",eError); - return; - } - iStat = NXDinitfromfile(self->pDictFile,&pDict); - if(iStat != NX_OK) - { - sprintf(pBueffel,"ERROR: failed to open dictionary file %s", - self->pDictFile); - SCWrite(pCon,pBueffel,eError); - SCWrite(pCon,"ERROR: Aborting data file writing",eError); - SCWrite(pCon,"ERROR: This is a SERIOUS problem!",eError); - SCWrite(pCon,"ERROR: DATA NOT WRITTEN",eError); - NXclose(&pFile); - return; - } - - /* tell the user that something is happening */ - sprintf(pBueffel,"Updating %s",self->pFile); - SCWrite(pCon,pBueffel,eWarning); - - /* do the end time */ - SNXFormatTime(pBueffel,511); - NXDputalias(pFile,pDict,"eend",pBueffel); - - /* chopper speeds */ - SNXSPutDrivable(pServ->pSics,pCon,pFile,pDict,"diskspeed","crot"); - SNXSPutDrivable(pServ->pSics,pCon,pFile,pDict,"fermispeed","fcrot"); - SNXSPutDrivable(pServ->pSics,pCon,pFile,pDict,"phase","fcphase"); - SNXSPutDrivable(pServ->pSics,pCon,pFile,pDict,"ratio","cratio"); - - /* counter data */ - var2 = FindVariable(pServ->pSics,"mbank"); - if(var2) - { - VarGetInt(var2,&mbank); - } else { - SCWrite(pCon,"ERROR: mbank value not found!",eError); - } - if(var2) - { - fVal = GetHistCountTime(self->pHistogram2,pCon); - NXDputalias(pFile,pDict,"cntime",&fVal); - lVal = GetHistMonitor(self->pHistogram2,1,pCon); - NXDputalias(pFile,pDict,"cnmon1",&lVal); - lVal = GetHistMonitor(self->pHistogram2,0,pCon); - NXDputalias(pFile,pDict,"cnmon2",&lVal); - lVal = GetHistMonitor(self->pHistogram2,4,pCon); - NXDputalias(pFile,pDict,"cnmon3",&lVal); - fTime = GetHistTimeBin(self->pHistogram2,&iInt); - } - else - { - var1 = FindVariable(pServ->pSics,"lbank"); - if(var1) - { - VarGetInt(var1,&lbank); - } else { - SCWrite(pCon,"ERROR: lbank value not found!",eError); - } - if(var1) - { - fVal = GetHistCountTime(self->pHistogram1,pCon); - NXDputalias(pFile,pDict,"cntime",&fVal); - lVal = GetHistMonitor(self->pHistogram1,1,pCon); - NXDputalias(pFile,pDict,"cnmon1",&lVal); - lVal = GetHistMonitor(self->pHistogram1,0,pCon); - NXDputalias(pFile,pDict,"cnmon2",&lVal); - lVal = GetHistMonitor(self->pHistogram1,4,pCon); - NXDputalias(pFile,pDict,"cnmon3",&lVal); - fTime = GetHistTimeBin(self->pHistogram1,&iInt); - } - else - { - fVal = GetHistCountTime(self->pHistogram3,pCon); - NXDputalias(pFile,pDict,"cntime",&fVal); - lVal = GetHistMonitor(self->pHistogram3,1,pCon); - NXDputalias(pFile,pDict,"cnmon1",&lVal); - lVal = GetHistMonitor(self->pHistogram3,0,pCon); - NXDputalias(pFile,pDict,"cnmon2",&lVal); - lVal = GetHistMonitor(self->pHistogram3,4,pCon); - NXDputalias(pFile,pDict,"cnmon3",&lVal); - fTime = GetHistTimeBin(self->pHistogram3,&iInt); - } - } +static void FoUpdate(pFoWrite self, SConnection * pCon) +{ + char pBueffel[512]; + int iInt, iStat, iTime, i, ii, j, iDet, iIndex; + pSicsVariable var1 = NULL; + pSicsVariable var2 = NULL; + pSicsVariable var3 = NULL; + int lbank, mbank, ubank; + long lVal; + float fVal; + const float *fTime; + NXhandle pFile = NULL; + NXdict pDict; + HistInt *lData = NULL; + HistInt *mData = NULL; + HistInt *uData = NULL; + int *iSum = NULL; + float *fAxis = NULL; + long *lSum = NULL; + float fCenter, fStdDev, fFWHM; - /* histogram with three detector banks */ - iTime = iInt; - sprintf(pBueffel,"%d",iInt); - NXDupdate(pDict,"timebin",pBueffel); - var1 = FindVariable(pServ->pSics,"lbank"); - if(var1) - { - VarGetInt(var1,&lbank); - } else { - SCWrite(pCon,"ERROR: lbank value not found!",eError); - } - if (lbank == 1) - { - lData = GetHistogramPointer(self->pHistogram1,pCon); - if(!lData) - { - SCWrite(pCon,"ERROR: failed to find Histogram Memory Data (lower bank)",eError); - NXclose(&pFile); - NXDclose(pDict,NULL); - return; - } - } - if (mbank == 1) - { - mData = GetHistogramPointer(self->pHistogram2,pCon); - if(!mData) - { - SCWrite(pCon,"ERROR: failed to find Histogram Memory Data (middle bank)",eError); - NXclose(&pFile); - NXDclose(pDict,NULL); - return; + /* open everything again */ + NXopen(self->pFile, NXACC_RDWR, &pFile); + if (!pFile) { + SCWrite(pCon, "ERROR: cannot reopen data file ", eError); + return; + } + iStat = NXDinitfromfile(self->pDictFile, &pDict); + if (iStat != NX_OK) { + sprintf(pBueffel, "ERROR: failed to open dictionary file %s", + self->pDictFile); + SCWrite(pCon, pBueffel, eError); + SCWrite(pCon, "ERROR: Aborting data file writing", eError); + SCWrite(pCon, "ERROR: This is a SERIOUS problem!", eError); + SCWrite(pCon, "ERROR: DATA NOT WRITTEN", eError); + NXclose(&pFile); + return; + } + + /* tell the user that something is happening */ + sprintf(pBueffel, "Updating %s", self->pFile); + SCWrite(pCon, pBueffel, eWarning); + + /* do the end time */ + SNXFormatTime(pBueffel, 511); + NXDputalias(pFile, pDict, "eend", pBueffel); + + /* chopper speeds */ + SNXSPutDrivable(pServ->pSics, pCon, pFile, pDict, "diskspeed", "crot"); + SNXSPutDrivable(pServ->pSics, pCon, pFile, pDict, "fermispeed", "fcrot"); + SNXSPutDrivable(pServ->pSics, pCon, pFile, pDict, "phase", "fcphase"); + SNXSPutDrivable(pServ->pSics, pCon, pFile, pDict, "ratio", "cratio"); + + /* counter data */ + var2 = FindVariable(pServ->pSics, "mbank"); + if (var2) { + VarGetInt(var2, &mbank); + } else { + SCWrite(pCon, "ERROR: mbank value not found!", eError); + } + if (var2) { + fVal = GetHistCountTime(self->pHistogram2, pCon); + NXDputalias(pFile, pDict, "cntime", &fVal); + lVal = GetHistMonitor(self->pHistogram2, 1, pCon); + NXDputalias(pFile, pDict, "cnmon1", &lVal); + lVal = GetHistMonitor(self->pHistogram2, 0, pCon); + NXDputalias(pFile, pDict, "cnmon2", &lVal); + lVal = GetHistMonitor(self->pHistogram2, 4, pCon); + NXDputalias(pFile, pDict, "cnmon3", &lVal); + fTime = GetHistTimeBin(self->pHistogram2, &iInt); + } else { + var1 = FindVariable(pServ->pSics, "lbank"); + if (var1) { + VarGetInt(var1, &lbank); + } else { + SCWrite(pCon, "ERROR: lbank value not found!", eError); + } + if (var1) { + fVal = GetHistCountTime(self->pHistogram1, pCon); + NXDputalias(pFile, pDict, "cntime", &fVal); + lVal = GetHistMonitor(self->pHistogram1, 1, pCon); + NXDputalias(pFile, pDict, "cnmon1", &lVal); + lVal = GetHistMonitor(self->pHistogram1, 0, pCon); + NXDputalias(pFile, pDict, "cnmon2", &lVal); + lVal = GetHistMonitor(self->pHistogram1, 4, pCon); + NXDputalias(pFile, pDict, "cnmon3", &lVal); + fTime = GetHistTimeBin(self->pHistogram1, &iInt); + } else { + fVal = GetHistCountTime(self->pHistogram3, pCon); + NXDputalias(pFile, pDict, "cntime", &fVal); + lVal = GetHistMonitor(self->pHistogram3, 1, pCon); + NXDputalias(pFile, pDict, "cnmon1", &lVal); + lVal = GetHistMonitor(self->pHistogram3, 0, pCon); + NXDputalias(pFile, pDict, "cnmon2", &lVal); + lVal = GetHistMonitor(self->pHistogram3, 4, pCon); + NXDputalias(pFile, pDict, "cnmon3", &lVal); + fTime = GetHistTimeBin(self->pHistogram3, &iInt); + } + } + + /* histogram with three detector banks */ + iTime = iInt; + sprintf(pBueffel, "%d", iInt); + NXDupdate(pDict, "timebin", pBueffel); + var1 = FindVariable(pServ->pSics, "lbank"); + if (var1) { + VarGetInt(var1, &lbank); + } else { + SCWrite(pCon, "ERROR: lbank value not found!", eError); + } + if (lbank == 1) { + lData = GetHistogramPointer(self->pHistogram1, pCon); + if (!lData) { + SCWrite(pCon, + "ERROR: failed to find Histogram Memory Data (lower bank)", + eError); + NXclose(&pFile); + NXDclose(pDict, NULL); + return; + } + } + if (mbank == 1) { + mData = GetHistogramPointer(self->pHistogram2, pCon); + if (!mData) { + SCWrite(pCon, + "ERROR: failed to find Histogram Memory Data (middle bank)", + eError); + NXclose(&pFile); + NXDclose(pDict, NULL); + return; + } + } + var3 = FindVariable(pServ->pSics, "ubank"); + if (var3) { + VarGetInt(var3, &ubank); + } else { + SCWrite(pCon, "ERROR: ubank value not found!", eError); + } + if (ubank == 1) { + uData = GetHistogramPointer(self->pHistogram3, pCon); + if (!uData) { + SCWrite(pCon, + "ERROR: failed to find Histogram Memory Data (upper bank)", + eError); + NXclose(&pFile); + NXDclose(pDict, NULL); + return; + } + } + setFMDataPointer(lData, iTime, LOWER); + setFMDataPointer(mData, iTime, MIDDLE); + setFMDataPointer(uData, iTime, UPPER); + /* middle bank */ + if (self->iMiddle) { + NXDupdate(pDict, "bank", "bank1"); + iDet = 150; + sprintf(pBueffel, "%d", iDet); + NXDupdate(pDict, "noofdetectors", pBueffel); + mData = getFMBankPointer(MIDDLE); + NXDputalias(pFile, pDict, "dcounts", mData); + /* summed counts for each detector */ + iSum = (int *) malloc(iDet * sizeof(int)); + if (iSum) { + memset(iSum, 0, iDet * sizeof(int)); + for (i = 0; i < iDet; i++) { + iIndex = i * iTime; + for (j = 0; j < iTime; j++) { + iSum[i] += mData[iIndex + j]; } - } - var3 = FindVariable(pServ->pSics,"ubank"); - if(var3) - { - VarGetInt(var3,&ubank); - } else { - SCWrite(pCon,"ERROR: ubank value not found!",eError); - } - if (ubank == 1) - { - uData = GetHistogramPointer(self->pHistogram3,pCon); - if(!uData) - { - SCWrite(pCon,"ERROR: failed to find Histogram Memory Data (upper bank)",eError); - NXclose(&pFile); - NXDclose(pDict,NULL); - return; + } + NXDputalias(pFile, pDict, "dsums", iSum); + free(iSum); + } else { + SCWrite(pCon, "WARNING: out of memory, failed to do sums", eWarning); + } + } + if (self->iUpper) { + NXDupdate(pDict, "bank", "upperbank"); + iDet = 110; + sprintf(pBueffel, "%d", iDet); + NXDupdate(pDict, "noofdetectors", pBueffel); + uData = getFMBankPointer(UPPER); + NXDputalias(pFile, pDict, "dcounts", uData); + /* summed counts for each detector */ + iSum = (int *) malloc(iDet * sizeof(int)); + if (iSum) { + memset(iSum, 0, iDet * sizeof(int)); + for (i = 0; i < iDet; i++) { + iIndex = i * iTime; + for (j = 0; j < iTime; j++) { + iSum[i] += uData[iIndex + j]; } - } - setFMDataPointer(lData,iTime,LOWER); - setFMDataPointer(mData,iTime,MIDDLE); - setFMDataPointer(uData,iTime,UPPER); - /* middle bank */ - if(self->iMiddle) - { - NXDupdate(pDict,"bank","bank1"); - iDet = 150; - sprintf(pBueffel,"%d",iDet); - NXDupdate(pDict,"noofdetectors",pBueffel); - mData = getFMBankPointer(MIDDLE); - NXDputalias(pFile,pDict,"dcounts",mData); - /* summed counts for each detector */ - iSum = (int *)malloc(iDet*sizeof(int)); - if(iSum) - { - memset(iSum,0,iDet*sizeof(int)); - for(i = 0; i < iDet; i++) - { - iIndex = i * iTime; - for(j = 0; j < iTime; j++) - { - iSum[i] += mData[iIndex+j]; - } - } - NXDputalias(pFile,pDict,"dsums",iSum); - free(iSum); - } - else - { - SCWrite(pCon,"WARNING: out of memory, failed to do sums", - eWarning); - } - } - if(self->iUpper) - { - NXDupdate(pDict,"bank","upperbank"); - iDet = 110; - sprintf(pBueffel,"%d",iDet); - NXDupdate(pDict,"noofdetectors",pBueffel); - uData = getFMBankPointer(UPPER); - NXDputalias(pFile,pDict,"dcounts",uData); - /* summed counts for each detector */ - iSum = (int *)malloc(iDet*sizeof(int)); - if(iSum) - { - memset(iSum,0,iDet*sizeof(int)); - for(i = 0; i < iDet; i++) - { - iIndex = i * iTime; - for(j = 0; j < iTime; j++) - { - iSum[i] += uData[iIndex+j]; - } - } - NXDputalias(pFile,pDict,"dsums",iSum); - free(iSum); - } - else - { - SCWrite(pCon,"WARNING: out of memory, failed to do sums", - eWarning); - } - } - if(self->iLower) - { - NXDupdate(pDict,"bank","lowerbank"); - iDet = 115; - sprintf(pBueffel,"%d",iDet); - NXDupdate(pDict,"noofdetectors",pBueffel); - lData = getFMBankPointer(LOWER); - NXDputalias(pFile,pDict,"dcounts",lData); - /* summed counts for each detector */ - iSum = (int *)malloc(iDet*sizeof(int)); - if(iSum) - { - memset(iSum,0,iDet*sizeof(int)); - for(i = 0; i < iDet; i++) - { - iIndex = i * iTime; - for(j = 0; j < iTime; j++) - { - iSum[i] += lData[iIndex+j]; - } - } - NXDputalias(pFile,pDict,"dsums",iSum); - free(iSum); - } - else - { - SCWrite(pCon,"WARNING: out of memory, failed to do sums", - eWarning); - } - /* - now get and write tof_monitor - */ - - lData = (HistInt *)malloc(iTime*sizeof(HistInt)); - if(!lData) - { - SCWrite(pCon,"ERROR: out of memory while writing tof-monitor", - eError); - } - else - { - memset(lData,0,iTime*sizeof(HistInt)); - GetHistogramDirect(self->pHistogram1,pCon,0,115*iTime, - 116*iTime, lData, iTime*sizeof(HistInt)); - NXDputalias(pFile,pDict,"tofmon",lData); - } - } - /* merged data */ - if( (self->iUpper || self->iLower) && self->iMiddle) - { - NXDupdate(pDict,"bank","merged"); - iDet = 375; - sprintf(pBueffel,"%d",iDet); - NXDupdate(pDict,"noofdetectors",pBueffel); - lData = getFMBankPointer(MERGED); - NXDputalias(pFile,pDict,"dcounts",lData); - /* summed counts for each detector */ - iSum = (int *)malloc(iDet*sizeof(int)); - if(iSum) - { - memset(iSum,0,iDet*sizeof(int)); - for(i = 0; i < iDet; i++) - { - iIndex = i * iTime; - for(j = 0; j < iTime; j++) - { - iSum[i] += lData[iIndex+j]; - } - } - NXDputalias(pFile,pDict,"dsums",iSum); - free(iSum); - } - else - { - SCWrite(pCon,"WARNING: out of memory, failed to do sums", - eWarning); - } - } + } + NXDputalias(pFile, pDict, "dsums", iSum); + free(iSum); + } else { + SCWrite(pCon, "WARNING: out of memory, failed to do sums", eWarning); + } + } + if (self->iLower) { + NXDupdate(pDict, "bank", "lowerbank"); + iDet = 115; + sprintf(pBueffel, "%d", iDet); + NXDupdate(pDict, "noofdetectors", pBueffel); + lData = getFMBankPointer(LOWER); + NXDputalias(pFile, pDict, "dcounts", lData); + /* summed counts for each detector */ + iSum = (int *) malloc(iDet * sizeof(int)); + if (iSum) { + memset(iSum, 0, iDet * sizeof(int)); + for (i = 0; i < iDet; i++) { + iIndex = i * iTime; + for (j = 0; j < iTime; j++) { + iSum[i] += lData[iIndex + j]; + } + } + NXDputalias(pFile, pDict, "dsums", iSum); + free(iSum); + } else { + SCWrite(pCon, "WARNING: out of memory, failed to do sums", eWarning); + } + /* + now get and write tof_monitor + */ - - /* calculate elastic peak position */ - NXDupdate(pDict,"bank","bank1"); - mData = getFMBankPointer(MIDDLE); - iDet = getFMdim(MIDDLE); - if(mData) - { - lSum = (long *)malloc(iTime *sizeof(long)); - fAxis = (float *)malloc(iTime *sizeof(float)); - if( lSum && fAxis) - { - memset(lSum,0,iTime*sizeof(long)); - memset(fAxis,0,iTime*sizeof(float)); - for(i = 5; i < iDet - 5; i++) - { - iIndex = i * iTime; - for(j = 0; j < iTime; j++) - { - lSum[j] += mData[iIndex+j]; - } - } - for(i = 0; i < iTime; i++) - { - fAxis[i] = (float)i; - } - iStat = CalculateFitFromData(self->pFitter,fAxis,lSum,iTime); - GetFitResults(self->pFitter,&fCenter,&fStdDev,&fFWHM,&fVal); - fVal = fCenter - self->fElastic; - if(fVal < 0.) - fVal = - fVal; - /* bad value, leave at theoretical value */ - if(fVal < 10.) - { - self->fElastic = fCenter; - } - free(lSum); - free(fAxis); - } - else - { - SCWrite(pCon,"WARNING: out of memory, failed to do sums",eWarning); - } - } - sprintf(pBueffel,"Elastic peak found at detector: %f",self->fElastic); - SCWrite(pCon,pBueffel,eWarning); - NXDputalias(pFile,pDict,"delastic",&self->fElastic); + lData = (HistInt *) malloc(iTime * sizeof(HistInt)); + if (!lData) { + SCWrite(pCon, "ERROR: out of memory while writing tof-monitor", + eError); + } else { + memset(lData, 0, iTime * sizeof(HistInt)); + GetHistogramDirect(self->pHistogram1, pCon, 0, 115 * iTime, + 116 * iTime, lData, iTime * sizeof(HistInt)); + NXDputalias(pFile, pDict, "tofmon", lData); + } + } + /* merged data */ + if ((self->iUpper || self->iLower) && self->iMiddle) { + NXDupdate(pDict, "bank", "merged"); + iDet = 375; + sprintf(pBueffel, "%d", iDet); + NXDupdate(pDict, "noofdetectors", pBueffel); + lData = getFMBankPointer(MERGED); + NXDputalias(pFile, pDict, "dcounts", lData); + /* summed counts for each detector */ + iSum = (int *) malloc(iDet * sizeof(int)); + if (iSum) { + memset(iSum, 0, iDet * sizeof(int)); + for (i = 0; i < iDet; i++) { + iIndex = i * iTime; + for (j = 0; j < iTime; j++) { + iSum[i] += lData[iIndex + j]; + } + } + NXDputalias(pFile, pDict, "dsums", iSum); + free(iSum); + } else { + SCWrite(pCon, "WARNING: out of memory, failed to do sums", eWarning); + } + } - /* sample temperature */ - SNXSPutEVVar(pFile,pDict,"temperature",pCon,"stemp",NULL); - + /* calculate elastic peak position */ + NXDupdate(pDict, "bank", "bank1"); + mData = getFMBankPointer(MIDDLE); + iDet = getFMdim(MIDDLE); + if (mData) { + lSum = (long *) malloc(iTime * sizeof(long)); + fAxis = (float *) malloc(iTime * sizeof(float)); + if (lSum && fAxis) { + memset(lSum, 0, iTime * sizeof(long)); + memset(fAxis, 0, iTime * sizeof(float)); + for (i = 5; i < iDet - 5; i++) { + iIndex = i * iTime; + for (j = 0; j < iTime; j++) { + lSum[j] += mData[iIndex + j]; + } + } + for (i = 0; i < iTime; i++) { + fAxis[i] = (float) i; + } + iStat = CalculateFitFromData(self->pFitter, fAxis, lSum, iTime); + GetFitResults(self->pFitter, &fCenter, &fStdDev, &fFWHM, &fVal); + fVal = fCenter - self->fElastic; + if (fVal < 0.) + fVal = -fVal; + /* bad value, leave at theoretical value */ + if (fVal < 10.) { + self->fElastic = fCenter; + } + free(lSum); + free(fAxis); + } else { + SCWrite(pCon, "WARNING: out of memory, failed to do sums", eWarning); + } + } + sprintf(pBueffel, "Elastic peak found at detector: %f", self->fElastic); + SCWrite(pCon, pBueffel, eWarning); + NXDputalias(pFile, pDict, "delastic", &self->fElastic); + + + /* sample temperature */ + SNXSPutEVVar(pFile, pDict, "temperature", pCon, "stemp", NULL); + + + /* close everything */ + NXclose(&pFile); + NXDclose(pDict, NULL); + +} - /* close everything */ - NXclose(&pFile); - NXDclose(pDict,NULL); - - } /*------------------------------------------------------------------------- FoLink sets all the links for the NXdata vGroup. Had to be separate because at least one update is necessary before this can be done. */ - static void FoLink(pFoWrite self, SConnection *pCon) - { - NXhandle pFile; - NXdict pDict; - int iStat; - char pBueffel[512]; - - /* open everything again */ - NXopen(self->pFile,NXACC_RDWR,&pFile); - if(!pFile) - { - SCWrite(pCon,"ERROR: cannot reopen data file ",eError); - return; - } - iStat = NXDinitfromfile(self->pDictFile,&pDict); - if(iStat != NX_OK) - { - sprintf(pBueffel,"ERROR: failed to open dictionary file %s", - self->pDictFile); - SCWrite(pCon,pBueffel,eError); - SCWrite(pCon,"ERROR: Aborting data file writing",eError); - SCWrite(pCon,"ERROR: This is a SERIOUS problem!",eError); - SCWrite(pCon,"ERROR: DATA NOT WRITTEN",eError); - NXclose(&pFile); - return; - } +static void FoLink(pFoWrite self, SConnection * pCon) +{ + NXhandle pFile; + NXdict pDict; + int iStat; + char pBueffel[512]; - if( (self->iUpper || self->iLower) && self->iMiddle) - { - NXDupdate(pDict,"bank","merged"); - NXDaliaslink(pFile,pDict,"dana","dcounts"); - NXDaliaslink(pFile,pDict,"dana","dtime"); - NXDaliaslink(pFile,pDict,"dana","dtheta"); - NXDaliaslink(pFile,pDict,"dana","cnmon1"); - } - - if(self->iUpper) - { - NXDupdate(pDict,"bank","upperbank"); - NXDaliaslink(pFile,pDict,"dana","dcounts"); - NXDaliaslink(pFile,pDict,"dana","dtime"); - NXDaliaslink(pFile,pDict,"dana","dtheta"); - NXDaliaslink(pFile,pDict,"dana","cnmon1"); - } - if(self->iMiddle) - { - NXDupdate(pDict,"bank","bank1"); - NXDaliaslink(pFile,pDict,"dana","dcounts"); - NXDaliaslink(pFile,pDict,"dana","dtime"); - NXDaliaslink(pFile,pDict,"dana","dtheta"); - NXDaliaslink(pFile,pDict,"dana","cnmon1"); - } - if(self->iLower) - { - NXDupdate(pDict,"bank","lowerbank"); - NXDaliaslink(pFile,pDict,"dana","dcounts"); - NXDaliaslink(pFile,pDict,"dana","dtime"); - NXDaliaslink(pFile,pDict,"dana","dtheta"); - NXDaliaslink(pFile,pDict,"dana","cnmon1"); - } + /* open everything again */ + NXopen(self->pFile, NXACC_RDWR, &pFile); + if (!pFile) { + SCWrite(pCon, "ERROR: cannot reopen data file ", eError); + return; + } + iStat = NXDinitfromfile(self->pDictFile, &pDict); + if (iStat != NX_OK) { + sprintf(pBueffel, "ERROR: failed to open dictionary file %s", + self->pDictFile); + SCWrite(pCon, pBueffel, eError); + SCWrite(pCon, "ERROR: Aborting data file writing", eError); + SCWrite(pCon, "ERROR: This is a SERIOUS problem!", eError); + SCWrite(pCon, "ERROR: DATA NOT WRITTEN", eError); + NXclose(&pFile); + return; + } + + if ((self->iUpper || self->iLower) && self->iMiddle) { + NXDupdate(pDict, "bank", "merged"); + NXDaliaslink(pFile, pDict, "dana", "dcounts"); + NXDaliaslink(pFile, pDict, "dana", "dtime"); + NXDaliaslink(pFile, pDict, "dana", "dtheta"); + NXDaliaslink(pFile, pDict, "dana", "cnmon1"); + } + + if (self->iUpper) { + NXDupdate(pDict, "bank", "upperbank"); + NXDaliaslink(pFile, pDict, "dana", "dcounts"); + NXDaliaslink(pFile, pDict, "dana", "dtime"); + NXDaliaslink(pFile, pDict, "dana", "dtheta"); + NXDaliaslink(pFile, pDict, "dana", "cnmon1"); + } + if (self->iMiddle) { + NXDupdate(pDict, "bank", "bank1"); + NXDaliaslink(pFile, pDict, "dana", "dcounts"); + NXDaliaslink(pFile, pDict, "dana", "dtime"); + NXDaliaslink(pFile, pDict, "dana", "dtheta"); + NXDaliaslink(pFile, pDict, "dana", "cnmon1"); + } + if (self->iLower) { + NXDupdate(pDict, "bank", "lowerbank"); + NXDaliaslink(pFile, pDict, "dana", "dcounts"); + NXDaliaslink(pFile, pDict, "dana", "dtime"); + NXDaliaslink(pFile, pDict, "dana", "dtheta"); + NXDaliaslink(pFile, pDict, "dana", "cnmon1"); + } - /* close everything */ - NXclose(&pFile); - NXDclose(pDict,NULL); - self->iNew = 0; - } + /* close everything */ + NXclose(&pFile); + NXDclose(pDict, NULL); + self->iNew = 0; +} + /*--------------------------------------------------------------------------- This is the task function for updating the data file any now and then automatically */ - static int FoTask(void *pData) - { - pFoWrite self = NULL; - int iWrite, iRet; - - self = (pFoWrite)pData; - if(!self) - return 0; - - /* figure out if we need to write */ - iWrite = 0; - iRet = 1; - /* first case: update intervall */ - if(time(NULL) >= self->tUpdate) - { - self->tUpdate = time(NULL) + self->iInterval; - iWrite = 1; - iRet = 1; - } - if(self->iEnd) - { - self->tUpdate = 0; - iWrite = 0; - iRet = 0; - FoUpdate(self,self->pCon); - } - - if(iWrite) - { - if(self->iNew) - { - FoStart(self,self->pCon); - FoUpdate(self,self->pCon); - FoLink(self,self->pCon); - } - else - { - FoUpdate(self,self->pCon); - } - } - return iRet; - } -/*------------------------------------------------------------------------*/ - static void KillFoWrite(void *pData) - { - pFoWrite self = NULL; - - self = (pFoWrite)pData; - if(!self) - return; - - if(self->pDes) - DeleteDescriptor(self->pDes); - - if(self->pDictFile) - free(self->pDictFile); - - if(self->pFile) - free(self->pFile); +static int FoTask(void *pData) +{ + pFoWrite self = NULL; + int iWrite, iRet; - if(self->pFitter) - DeleteFitCenter(self->pFitter); - - /* free fomerge */ - killFM(); - - free(self); - } -/*-----------------------------------------------------------------------*/ - int FoInstall(SConnection *pCon, SicsInterp *pSics, void *pData, - int argc, char *argv[]) - { - CommandList *pCom = NULL; - char pBueffel[512]; - pFoWrite pNew = NULL; - pICallBack pCall = NULL; - pDummy pDum; - pHMcontrol pHMC = NULL; - commandContext comCon; - - /* check arguments */ - if(argc < 4 ) - { - SCWrite(pCon,"ERROR: Insufficient number of arguments to FoInstall", - eError); - return 0; - } - - /* allocate data structure */ - pNew = (pFoWrite)malloc(sizeof(FoWrite)); - if(!pNew) - { - SCWrite(pCon,"ERROR: out of memory in FoInstall",eError); - return 0; - } - memset(pNew,0,sizeof(FoWrite)); - pNew->pDes = CreateDescriptor("FocusWrite"); - pNew->pCall = CreateCallBackInterface(); - pNew->pFitter = CreateFitCenter(NULL); - if( (!pNew->pDes) || (!pNew->pFitter) ) - { - SCWrite(pCon,"ERROR: out of memory in FoInstall",eError); - free(pNew); - return 0; - } - pNew->pDictFile = strdup(argv[2]); - pNew->iInterval = 20*60; - - pHMC = FindCommandData(pSics,argv[1],"HMcontrol"); - if(!pHMC){ - SCWrite(pCon,"ERROR: no histogram memory control found!",eError); - free(pNew); - return 0; - } - - /* find things in interpreter */ - pCom = FindCommand(pSics,"hm1"); - if(!pCom) - { - SCWrite(pCon,"ERROR: Histogram memory for lower detector bank NOT found",eError); - pNew->pHistogram1 = NULL; - } else - { - pNew->pHistogram1 = (pHistMem)pCom->pData; - pNew->iLower =1; - } - - - pCom = FindCommand(pSics,HM2); - if(pCom) - { - pNew->pHistogram2 = (pHistMem)pCom->pData; - pNew->iMiddle =1; - } - else - { - SCWrite(pCon,"ERROR: Histogram memory for middle detector bank NOT found",eError); - pNew->pHistogram2 = NULL; - } - - pCom = FindCommand(pSics,HM3); - if(pCom) - { - pNew->pHistogram3 = (pHistMem)pCom->pData; - pNew->iUpper =1; - } - else - { - SCWrite(pCon,"ERROR: Histogram memory for upper detector bank NOT found",eError); - pNew->pHistogram3 = NULL; - } - - if(!initializeFM(argv[3])) - { - SCWrite(pCon,"ERROR: bad merge data file",eError); - return 0; - } - - pCom = FindCommand(pSics,"counter"); - if(pCom) - { - pNew->pCount = (pCounter)pCom->pData; - } - - comCon.transID = 0; - strncpy(comCon.deviceID,"internal",SCDEVIDLEN); - RegisterCallback(pHMC->pCall,COUNTSTART,Countstartcallback,pNew,NULL); - RegisterCallback(pHMC->pCall,COUNTEND,Countendcallback,pNew,NULL); - - /* install command */ - AddCommand(pSics,"StoreFocus",FoAction,KillFoWrite,pNew); - return 1; - } -/*-------------------------------------------------------------------------*/ - int FoAction(SConnection *pCon, SicsInterp *pSics, void *pData, - int argc, char *argv[]) - { - int iRet, iVal; - pFoWrite self = NULL; - char pBueffel[512]; - - if(argc < 1) - { - SCWrite(pCon,"ERROR: Insufficient number of arguments to StoreFocus", - eError); - return 0; - } - self = (pFoWrite)pData; - assert(self); - - strtolower(argv[1]); - if(strcmp(argv[1],"start") == 0) - { - FoStart(self,pCon); - FoUpdate(self,pCon); - FoLink(self,pCon); - return 1; - } - else if(strcmp(argv[1],"update") == 0) - { - if((self->iNew) || (!self->pFile)) - { - FoStart(self,pCon); - FoUpdate(self,pCon); - FoLink(self,pCon); - } - else - { - FoUpdate(self,pCon); - } - return 1; - } - else if(strcmp(argv[1],"getfile") == 0) - { - sprintf(pBueffel,"storefocus.file = %s",self->pFile); - SCWrite(pCon,pBueffel,eValue); - return 1; - } - else if(strcmp(argv[1],"interval") == 0) - { - if(argc > 2) /* set value */ - { - if(!SCMatchRights(pCon,usUser)) - { - return 0; - } - iRet = Tcl_GetInt(pSics->pTcl,argv[2],&iVal); - if(iRet != TCL_OK) - { - sprintf(pBueffel,"ERROR: cannot convert --> %s <-- to number ",argv[2]); - SCWrite(pCon,pBueffel,eError); - return 0; - } - self->iInterval = iVal*60; /* go to seconds from minutes*/ - SCSendOK(pCon); - return 1; - } - else /* read the value */ - { - sprintf(pBueffel,"storefocus.interval = %d",self->iInterval/60); - SCWrite(pCon,pBueffel,eValue); - return 1; - } - } - else if(strcmp(argv[1],"middle") == 0) - { - if(argc > 2) /* set value */ - { - if(!SCMatchRights(pCon,usMugger)) - { - return 0; - } - iRet = Tcl_GetInt(pSics->pTcl,argv[2],&iVal); - if(iRet != TCL_OK) - { - sprintf(pBueffel,"ERROR: cannot convert --> %s <-- to number ", - argv[2]); - SCWrite(pCon,pBueffel,eError); - return 0; - } - if(iVal < 0) iVal = 0; - self->iMiddle = iVal; - setFMconfiguration(self->iUpper,self->iMiddle,self->iLower); - SCSendOK(pCon); - return 1; - } - else /* read the value */ - { - sprintf(pBueffel,"storefocus.middle = %d",self->iMiddle); - SCWrite(pCon,pBueffel,eValue); - return 1; - } - } - else if(strcmp(argv[1],"lower") == 0) - { - if(argc > 2) /* set value */ - { - if(!SCMatchRights(pCon,usMugger)) - { - return 0; - } - iRet = Tcl_GetInt(pSics->pTcl,argv[2],&iVal); - if(iRet != TCL_OK) - { - sprintf(pBueffel,"ERROR: cannot convert --> %s <-- to number ", - argv[2]); - SCWrite(pCon,pBueffel,eError); - return 0; - } - if(iVal < 0) iVal = 0; - self->iLower = iVal; - setFMconfiguration(self->iUpper,self->iMiddle,self->iLower); - SCSendOK(pCon); - return 1; - } - else /* read the value */ - { - sprintf(pBueffel,"storefocus.lower = %d",self->iLower); - SCWrite(pCon,pBueffel,eValue); - return 1; - } - } - else if(strcmp(argv[1],"upper") == 0) - { - if(argc > 2) /* set value */ - { - if(!SCMatchRights(pCon,usMugger)) - { - return 0; - } - iRet = Tcl_GetInt(pSics->pTcl,argv[2],&iVal); - if(iRet != TCL_OK) - { - sprintf(pBueffel,"ERROR: cannot convert --> %s <-- to number ", - argv[2]); - SCWrite(pCon,pBueffel,eError); - return 0; - } - if(iVal < 0) iVal = 0; - self->iUpper = iVal; - setFMconfiguration(self->iUpper,self->iMiddle,self->iLower); - SCSendOK(pCon); - return 1; - } - else /* read the value */ - { - sprintf(pBueffel,"storefocus.upper = %d",self->iUpper); - SCWrite(pCon,pBueffel,eValue); - return 1; - } - } - SCWrite(pCon,"ERROR: subcommand to storefocus not recognized",eError); + self = (pFoWrite) pData; + if (!self) return 0; - } + + /* figure out if we need to write */ + iWrite = 0; + iRet = 1; + /* first case: update intervall */ + if (time(NULL) >= self->tUpdate) { + self->tUpdate = time(NULL) + self->iInterval; + iWrite = 1; + iRet = 1; + } + if (self->iEnd) { + self->tUpdate = 0; + iWrite = 0; + iRet = 0; + FoUpdate(self, self->pCon); + } + + if (iWrite) { + if (self->iNew) { + FoStart(self, self->pCon); + FoUpdate(self, self->pCon); + FoLink(self, self->pCon); + } else { + FoUpdate(self, self->pCon); + } + } + return iRet; +} + +/*------------------------------------------------------------------------*/ +static void KillFoWrite(void *pData) +{ + pFoWrite self = NULL; + + self = (pFoWrite) pData; + if (!self) + return; + + if (self->pDes) + DeleteDescriptor(self->pDes); + + if (self->pDictFile) + free(self->pDictFile); + + if (self->pFile) + free(self->pFile); + + if (self->pFitter) + DeleteFitCenter(self->pFitter); + + /* free fomerge */ + killFM(); + + free(self); +} + +/*-----------------------------------------------------------------------*/ +int FoInstall(SConnection * pCon, SicsInterp * pSics, void *pData, + int argc, char *argv[]) +{ + CommandList *pCom = NULL; + char pBueffel[512]; + pFoWrite pNew = NULL; + pICallBack pCall = NULL; + pDummy pDum; + pHMcontrol pHMC = NULL; + commandContext comCon; + + /* check arguments */ + if (argc < 4) { + SCWrite(pCon, "ERROR: Insufficient number of arguments to FoInstall", + eError); + return 0; + } + + /* allocate data structure */ + pNew = (pFoWrite) malloc(sizeof(FoWrite)); + if (!pNew) { + SCWrite(pCon, "ERROR: out of memory in FoInstall", eError); + return 0; + } + memset(pNew, 0, sizeof(FoWrite)); + pNew->pDes = CreateDescriptor("FocusWrite"); + pNew->pCall = CreateCallBackInterface(); + pNew->pFitter = CreateFitCenter(NULL); + if ((!pNew->pDes) || (!pNew->pFitter)) { + SCWrite(pCon, "ERROR: out of memory in FoInstall", eError); + free(pNew); + return 0; + } + pNew->pDictFile = strdup(argv[2]); + pNew->iInterval = 20 * 60; + + pHMC = FindCommandData(pSics, argv[1], "HMcontrol"); + if (!pHMC) { + SCWrite(pCon, "ERROR: no histogram memory control found!", eError); + free(pNew); + return 0; + } + + /* find things in interpreter */ + pCom = FindCommand(pSics, "hm1"); + if (!pCom) { + SCWrite(pCon, + "ERROR: Histogram memory for lower detector bank NOT found", + eError); + pNew->pHistogram1 = NULL; + } else { + pNew->pHistogram1 = (pHistMem) pCom->pData; + pNew->iLower = 1; + } + + + pCom = FindCommand(pSics, HM2); + if (pCom) { + pNew->pHistogram2 = (pHistMem) pCom->pData; + pNew->iMiddle = 1; + } else { + SCWrite(pCon, + "ERROR: Histogram memory for middle detector bank NOT found", + eError); + pNew->pHistogram2 = NULL; + } + + pCom = FindCommand(pSics, HM3); + if (pCom) { + pNew->pHistogram3 = (pHistMem) pCom->pData; + pNew->iUpper = 1; + } else { + SCWrite(pCon, + "ERROR: Histogram memory for upper detector bank NOT found", + eError); + pNew->pHistogram3 = NULL; + } + + if (!initializeFM(argv[3])) { + SCWrite(pCon, "ERROR: bad merge data file", eError); + return 0; + } + + pCom = FindCommand(pSics, "counter"); + if (pCom) { + pNew->pCount = (pCounter) pCom->pData; + } + + comCon.transID = 0; + strncpy(comCon.deviceID, "internal", SCDEVIDLEN); + RegisterCallback(pHMC->pCall, COUNTSTART, Countstartcallback, pNew, + NULL); + RegisterCallback(pHMC->pCall, COUNTEND, Countendcallback, pNew, NULL); + + /* install command */ + AddCommand(pSics, "StoreFocus", FoAction, KillFoWrite, pNew); + return 1; +} + +/*-------------------------------------------------------------------------*/ +int FoAction(SConnection * pCon, SicsInterp * pSics, void *pData, + int argc, char *argv[]) +{ + int iRet, iVal; + pFoWrite self = NULL; + char pBueffel[512]; + + if (argc < 1) { + SCWrite(pCon, "ERROR: Insufficient number of arguments to StoreFocus", + eError); + return 0; + } + self = (pFoWrite) pData; + assert(self); + + strtolower(argv[1]); + if (strcmp(argv[1], "start") == 0) { + FoStart(self, pCon); + FoUpdate(self, pCon); + FoLink(self, pCon); + return 1; + } else if (strcmp(argv[1], "update") == 0) { + if ((self->iNew) || (!self->pFile)) { + FoStart(self, pCon); + FoUpdate(self, pCon); + FoLink(self, pCon); + } else { + FoUpdate(self, pCon); + } + return 1; + } else if (strcmp(argv[1], "getfile") == 0) { + sprintf(pBueffel, "storefocus.file = %s", self->pFile); + SCWrite(pCon, pBueffel, eValue); + return 1; + } else if (strcmp(argv[1], "interval") == 0) { + if (argc > 2) { /* set value */ + if (!SCMatchRights(pCon, usUser)) { + return 0; + } + iRet = Tcl_GetInt(pSics->pTcl, argv[2], &iVal); + if (iRet != TCL_OK) { + sprintf(pBueffel, "ERROR: cannot convert --> %s <-- to number ", + argv[2]); + SCWrite(pCon, pBueffel, eError); + return 0; + } + self->iInterval = iVal * 60; /* go to seconds from minutes */ + SCSendOK(pCon); + return 1; + } else { /* read the value */ + + sprintf(pBueffel, "storefocus.interval = %d", self->iInterval / 60); + SCWrite(pCon, pBueffel, eValue); + return 1; + } + } else if (strcmp(argv[1], "middle") == 0) { + if (argc > 2) { /* set value */ + if (!SCMatchRights(pCon, usMugger)) { + return 0; + } + iRet = Tcl_GetInt(pSics->pTcl, argv[2], &iVal); + if (iRet != TCL_OK) { + sprintf(pBueffel, "ERROR: cannot convert --> %s <-- to number ", + argv[2]); + SCWrite(pCon, pBueffel, eError); + return 0; + } + if (iVal < 0) + iVal = 0; + self->iMiddle = iVal; + setFMconfiguration(self->iUpper, self->iMiddle, self->iLower); + SCSendOK(pCon); + return 1; + } else { /* read the value */ + + sprintf(pBueffel, "storefocus.middle = %d", self->iMiddle); + SCWrite(pCon, pBueffel, eValue); + return 1; + } + } else if (strcmp(argv[1], "lower") == 0) { + if (argc > 2) { /* set value */ + if (!SCMatchRights(pCon, usMugger)) { + return 0; + } + iRet = Tcl_GetInt(pSics->pTcl, argv[2], &iVal); + if (iRet != TCL_OK) { + sprintf(pBueffel, "ERROR: cannot convert --> %s <-- to number ", + argv[2]); + SCWrite(pCon, pBueffel, eError); + return 0; + } + if (iVal < 0) + iVal = 0; + self->iLower = iVal; + setFMconfiguration(self->iUpper, self->iMiddle, self->iLower); + SCSendOK(pCon); + return 1; + } else { /* read the value */ + + sprintf(pBueffel, "storefocus.lower = %d", self->iLower); + SCWrite(pCon, pBueffel, eValue); + return 1; + } + } else if (strcmp(argv[1], "upper") == 0) { + if (argc > 2) { /* set value */ + if (!SCMatchRights(pCon, usMugger)) { + return 0; + } + iRet = Tcl_GetInt(pSics->pTcl, argv[2], &iVal); + if (iRet != TCL_OK) { + sprintf(pBueffel, "ERROR: cannot convert --> %s <-- to number ", + argv[2]); + SCWrite(pCon, pBueffel, eError); + return 0; + } + if (iVal < 0) + iVal = 0; + self->iUpper = iVal; + setFMconfiguration(self->iUpper, self->iMiddle, self->iLower); + SCSendOK(pCon); + return 1; + } else { /* read the value */ + + sprintf(pBueffel, "storefocus.upper = %d", self->iUpper); + SCWrite(pCon, pBueffel, eValue); + return 1; + } + } + SCWrite(pCon, "ERROR: subcommand to storefocus not recognized", eError); + return 0; +} diff --git a/fowrite.h b/fowrite.h index 2c7d099..7e2afe8 100644 --- a/fowrite.h +++ b/fowrite.h @@ -10,12 +10,11 @@ #ifndef FOWRITE #define FOWRITE - int FoInstall(SConnection *pCon, SicsInterp *pSics, - void *pData, int argc, char *argv[]); - +int FoInstall(SConnection * pCon, SicsInterp * pSics, + void *pData, int argc, char *argv[]); + + +int FoAction(SConnection * pCon, SicsInterp * pSics, + void *pData, int argc, char *argv[]); - int FoAction(SConnection *pCon, SicsInterp *pSics, - void *pData, int argc, char *argv[]); - #endif - diff --git a/frame.c b/frame.c index 14665f3..055c6fa 100644 --- a/frame.c +++ b/frame.c @@ -24,7 +24,8 @@ #include "nxdict.h" #include "frame.h" /*======================================================================*/ -static int readHMFrame(SConnection *pCon, pHistMem pHM, int nFrame){ +static int readHMFrame(SConnection * pCon, pHistMem pHM, int nFrame) +{ HistInt *buffer = NULL; int iDim[MAXDIM], rank, length, status, i, noTimeBins; pSINQHM pHist; @@ -32,214 +33,225 @@ static int readHMFrame(SConnection *pCon, pHistMem pHM, int nFrame){ const float *timeBin; /* - find dimensions and allocate data - */ - GetHistDim(pHM,iDim,&rank); - timeBin = GetHistTimeBin(pHM,&noTimeBins); + find dimensions and allocate data + */ + GetHistDim(pHM, iDim, &rank); + timeBin = GetHistTimeBin(pHM, &noTimeBins); - if(rank < 2){ - SCWrite(pCon,"ERROR: no PSD data present, cannot send frame",eError); + if (rank < 2) { + SCWrite(pCon, "ERROR: no PSD data present, cannot send frame", eError); return 0; } - length = iDim[0]*iDim[1]; - buffer = (HistInt *)malloc((length + 2)*sizeof(HistInt)); - if(!buffer){ - SCWrite(pCon,"ERROR: out of memory in readHMFrame",eError); + length = iDim[0] * iDim[1]; + buffer = (HistInt *) malloc((length + 2) * sizeof(HistInt)); + if (!buffer) { + SCWrite(pCon, "ERROR: out of memory in readHMFrame", eError); return 0; } - memset(buffer,0,(length+2)*sizeof(HistInt)); + memset(buffer, 0, (length + 2) * sizeof(HistInt)); /* - first two values are dimensions - */ + first two values are dimensions + */ buffer[0] = htonl(iDim[0]); buffer[1] = htonl(iDim[1]); - if(isSINQHMDriv(pHM->pDriv) && noTimeBins > 2) { + if (isSINQHMDriv(pHM->pDriv) && noTimeBins > 2) { /* - read from HM. The 5 is PROJECT__FRAME in Sinqhm_def.h - Again: be friendly: fix out of range frames - */ - if(nFrame < 0){ + read from HM. The 5 is PROJECT__FRAME in Sinqhm_def.h + Again: be friendly: fix out of range frames + */ + if (nFrame < 0) { nFrame = 0; } - if(nFrame >= noTimeBins){ - nFrame = noTimeBins-1; + if (nFrame >= noTimeBins) { + nFrame = noTimeBins - 1; } - pTata = (SinqHMDriv *)pHM->pDriv->pPriv; - pHist = (pSINQHM)pTata->pMaster; + pTata = (SinqHMDriv *) pHM->pDriv->pPriv; + pHist = (pSINQHM) pTata->pMaster; status = SINQHMProject(pHist, 0x0005, 0, nFrame, - 0, iDim[1], buffer+2,length*sizeof(HistInt)); - if(status != 1){ - SCWrite(pCon,"ERROR: SINQHM refused to deliver frame",eError); + 0, iDim[1], buffer + 2, + length * sizeof(HistInt)); + if (status != 1) { + SCWrite(pCon, "ERROR: SINQHM refused to deliver frame", eError); free(buffer); return 0; } } else { /* - be friendly, just read the 2D data which is there - */ - status = GetHistogram(pHM,pCon,0,0,length,buffer+2,length*sizeof(HistInt)); - if(!status){ + be friendly, just read the 2D data which is there + */ + status = + GetHistogram(pHM, pCon, 0, 0, length, buffer + 2, + length * sizeof(HistInt)); + if (!status) { free(buffer); return status; } } /* - enforce network byte order - */ - for(i = 0; i < length; i++){ - buffer[i+2] = htonl(buffer[i+2]); + enforce network byte order + */ + for (i = 0; i < length; i++) { + buffer[i + 2] = htonl(buffer[i + 2]); } - SCWriteUUencoded(pCon,"framedata", buffer,(length+2)*sizeof(HistInt)); + SCWriteUUencoded(pCon, "framedata", buffer, + (length + 2) * sizeof(HistInt)); free(buffer); return 1; } + /*=======================================================================*/ -static int readFileFrame(SConnection *pCon, - char *file, char *dictFile, - char *alias, int nFrame){ +static int readFileFrame(SConnection * pCon, + char *file, char *dictFile, + char *alias, int nFrame) +{ int status, iDim[NX_MAXRANK], rank = 0, type = 0; int iStart[3], iSize[3], length, i; int *buffer = NULL; NXhandle fileHandle; - NXdict dictHandle; + NXdict dictHandle; char error[512]; - status = NXopen(file,NXACC_READ,&fileHandle); - if(status != NX_OK){ - sprintf(error,"ERROR: failed to open %s", file); - SCWrite(pCon,error,eError); + status = NXopen(file, NXACC_READ, &fileHandle); + if (status != NX_OK) { + sprintf(error, "ERROR: failed to open %s", file); + SCWrite(pCon, error, eError); return 0; } status = NXDinitfromfile(dictFile, &dictHandle); - if(status != NX_OK){ - sprintf(error,"ERROR: failed to open dictionary %s", dictFile); + if (status != NX_OK) { + sprintf(error, "ERROR: failed to open dictionary %s", dictFile); NXclose(&fileHandle); - SCWrite(pCon,error,eError); + SCWrite(pCon, error, eError); return 0; } - - status = NXDopenalias(fileHandle,dictHandle,alias); - if(status != NX_OK){ - sprintf(error,"ERROR: failed to open alias %s", alias); + + status = NXDopenalias(fileHandle, dictHandle, alias); + if (status != NX_OK) { + sprintf(error, "ERROR: failed to open alias %s", alias); NXclose(&fileHandle); - NXDclose(dictHandle,NULL); - SCWrite(pCon,error,eError); + NXDclose(dictHandle, NULL); + SCWrite(pCon, error, eError); return 0; } - - status = NXgetinfo(fileHandle,&rank,iDim,&type); - if(type != NX_INT32 && type != NX_UINT32)type = -1; - if(status != NX_OK || rank < 2 || type < 0 ){ - sprintf(error,"ERROR: Dataset does not match!"); + + status = NXgetinfo(fileHandle, &rank, iDim, &type); + if (type != NX_INT32 && type != NX_UINT32) + type = -1; + if (status != NX_OK || rank < 2 || type < 0) { + sprintf(error, "ERROR: Dataset does not match!"); NXclose(&fileHandle); - NXDclose(dictHandle,NULL); - SCWrite(pCon,error,eError); + NXDclose(dictHandle, NULL); + SCWrite(pCon, error, eError); return 0; } /* - allocate space - */ - length = iDim[0]*iDim[1]; - buffer = (int *)malloc((length+2)*sizeof(int)); - if(!buffer){ + allocate space + */ + length = iDim[0] * iDim[1]; + buffer = (int *) malloc((length + 2) * sizeof(int)); + if (!buffer) { NXclose(&fileHandle); - NXDclose(dictHandle,NULL); - SCWrite(pCon,"ERROR: out of memory in readFrameFromFile",eError); + NXDclose(dictHandle, NULL); + SCWrite(pCon, "ERROR: out of memory in readFrameFromFile", eError); return 0; } - memset(buffer,0,(length+2)*sizeof(int)); + memset(buffer, 0, (length + 2) * sizeof(int)); /* - first two values: dimensions - */ + first two values: dimensions + */ buffer[0] = htonl(iDim[0]); buffer[1] = htonl(iDim[1]); - if(rank == 2){ + if (rank == 2) { /* - be friendly - */ - status = NXgetdata(fileHandle,buffer+2); + be friendly + */ + status = NXgetdata(fileHandle, buffer + 2); } else { iStart[0] = iStart[1] = 0; - if(nFrame > iDim[2] - 2){ - nFrame = iDim[2] - 2; + if (nFrame > iDim[2] - 2) { + nFrame = iDim[2] - 2; } iStart[2] = nFrame; iSize[0] = iDim[0]; iSize[1] = iDim[1]; iSize[2] = 1; - status = NXgetslab(fileHandle,buffer+2,iStart,iSize); + status = NXgetslab(fileHandle, buffer + 2, iStart, iSize); } - if(status != NX_OK){ + if (status != NX_OK) { NXclose(&fileHandle); - NXDclose(dictHandle,NULL); + NXDclose(dictHandle, NULL); free(buffer); - SCWrite(pCon,"ERROR: failed to read data",eError); + SCWrite(pCon, "ERROR: failed to read data", eError); return 0; } /* - enforce network byte order - */ - for(i = 0; i < length; i++){ - buffer[2+i] = htonl(buffer[2+i]); + enforce network byte order + */ + for (i = 0; i < length; i++) { + buffer[2 + i] = htonl(buffer[2 + i]); } - SCWriteUUencoded(pCon,"framedata",buffer,(length+2)*sizeof(int)); + SCWriteUUencoded(pCon, "framedata", buffer, (length + 2) * sizeof(int)); NXclose(&fileHandle); - NXDclose(dictHandle,NULL); + NXDclose(dictHandle, NULL); free(buffer); return 1; } + /*=======================================================================*/ -int PSDFrameAction(SConnection *pCon, SicsInterp *pSics, void *pData, - int argc, char *argv[]){ +int PSDFrameAction(SConnection * pCon, SicsInterp * pSics, void *pData, + int argc, char *argv[]) +{ pHistMem pHM; int nFrame; - if(argc < 2){ - SCWrite(pCon,"ERROR: Insufficient number of arguments to PSDFrame", - eError); + if (argc < 2) { + SCWrite(pCon, "ERROR: Insufficient number of arguments to PSDFrame", + eError); return 0; } strtolower(argv[1]); - if(strcmp(argv[1],"hm") == 0){ - if(argc < 4){ - SCWrite(pCon,"ERROR: Insufficient number of arguments to PSDFrame", - eError); + if (strcmp(argv[1], "hm") == 0) { + if (argc < 4) { + SCWrite(pCon, "ERROR: Insufficient number of arguments to PSDFrame", + eError); return 0; } - pHM = (pHistMem)FindCommandData(pSics,argv[2],"HistMem"); - if(pHM == NULL){ - SCWrite(pCon,"ERROR: Did not find histogram memory",eError); + pHM = (pHistMem) FindCommandData(pSics, argv[2], "HistMem"); + if (pHM == NULL) { + SCWrite(pCon, "ERROR: Did not find histogram memory", eError); return 0; } - nFrame = atoi(argv[3]); - return readHMFrame(pCon,pHM,nFrame); - } else if(strcmp(argv[1],"file") == 0){ - if(argc < 6 ){ - SCWrite(pCon,"ERROR: Insufficient number of arguments to PSDframe file", - eError); + nFrame = atoi(argv[3]); + return readHMFrame(pCon, pHM, nFrame); + } else if (strcmp(argv[1], "file") == 0) { + if (argc < 6) { + SCWrite(pCon, + "ERROR: Insufficient number of arguments to PSDframe file", + eError); return 0; } nFrame = atoi(argv[5]); - return readFileFrame(pCon,argv[2],argv[3],argv[4],nFrame); + return readFileFrame(pCon, argv[2], argv[3], argv[4], nFrame); } else { - SCWrite(pCon,"ERROR: subcommand to PSDframe not recognised",eError); + SCWrite(pCon, "ERROR: subcommand to PSDframe not recognised", eError); return 0; } } -/*======================================================================*/ -int MakeFrameFunc(SConnection *pCon, SicsInterp *pSics, void *pData, - int argc, char *argv[]){ - return AddCommand(pSics,"PSDframe",PSDFrameAction,NULL,NULL); -} +/*======================================================================*/ +int MakeFrameFunc(SConnection * pCon, SicsInterp * pSics, void *pData, + int argc, char *argv[]) +{ + return AddCommand(pSics, "PSDframe", PSDFrameAction, NULL, NULL); +} diff --git a/frame.h b/frame.h index af5a1ef..6788f09 100644 --- a/frame.h +++ b/frame.h @@ -12,11 +12,11 @@ #ifndef SICSFRAME #define SICSFRAME -int MakeFrameFunc(SConnection *pCon, SicsInterp *pSics, void *pData, - int argc, char *argv[]); +int MakeFrameFunc(SConnection * pCon, SicsInterp * pSics, void *pData, + int argc, char *argv[]); -int PSDFrameAction(SConnection *pCon, SicsInterp *pSics, void *pData, - int argc, char *argv[]); +int PSDFrameAction(SConnection * pCon, SicsInterp * pSics, void *pData, + int argc, char *argv[]); #endif diff --git a/fsm.c b/fsm.c index d2ba96d..a68a283 100644 --- a/fsm.c +++ b/fsm.c @@ -36,37 +36,41 @@ struct Fsm { static Fsm *fsm = NULL; static FsmFunc callFunc = NULL; -void FsmWait(long delay) { +void FsmWait(long delay) +{ assert(fsm); fsm->till = time(NULL) + delay; } -void FsmSpeed(Fsm *task) { +void FsmSpeed(Fsm * task) +{ assert(task); - if (task->till != 0) task->till = time(NULL); + if (task->till != 0) + task->till = time(NULL); } -int FsmTaskHandler(Fsm *task) { +int FsmTaskHandler(Fsm * task) +{ long line; Statistics *old; - + old = StatisticsBegin(task->stat); if (task->pause) { task->handler(task->obj); StatisticsEnd(old); return 1; } - if (task->pc >= 0) { /* task->pc < 0 means stop current function */ + if (task->pc >= 0) { /* task->pc < 0 means stop current function */ if (task->till != 0) { if (time(NULL) < task->till) { StatisticsEnd(old); - return 1; /* wait */ + return 1; /* wait */ } task->till = 0; } if (task->handler(task->obj) == 0) { StatisticsEnd(old); - return 1; /* wait for answer */ + return 1; /* wait for answer */ } fsm = task; task->pc = task->func(task->pc, task->obj); @@ -85,7 +89,7 @@ int FsmTaskHandler(Fsm *task) { StatisticsEnd(old); if (task->pc <= 0) { if (task->sp == 0) { - return (task->obj != NULL); /* finish task only when explicitely stopped */ + return (task->obj != NULL); /* finish task only when explicitely stopped */ } if (task->sp > 0) { task->sp--; @@ -95,12 +99,14 @@ int FsmTaskHandler(Fsm *task) { } return 1; } - -void FsmKill(void *data) { + +void FsmKill(void *data) +{ free(data); } -void FsmRestartTask(Fsm *task, FsmFunc func) { +void FsmRestartTask(Fsm * task, FsmFunc func) +{ task->pc = 0; task->func = func; task->sp = 0; @@ -108,11 +114,12 @@ void FsmRestartTask(Fsm *task, FsmFunc func) { task->till = 0; } -Fsm *FsmStartTask(void *obj, FsmHandler handler, FsmFunc func, char *name) { +Fsm *FsmStartTask(void *obj, FsmHandler handler, FsmFunc func, char *name) +{ Fsm *task; char fsmName[80]; - - task=malloc(sizeof *task); + + task = malloc(sizeof *task); task->obj = obj; task->handler = handler; snprintf(fsmName, sizeof fsmName, "fsm %s", name); @@ -121,38 +128,45 @@ Fsm *FsmStartTask(void *obj, FsmHandler handler, FsmFunc func, char *name) { return task; } -int FsmStop(Fsm *task, FsmFunc func) { +int FsmStop(Fsm * task, FsmFunc func) +{ int i; - - if (task == NULL) task = fsm; - if (func == NULL) return 0; + + if (task == NULL) + task = fsm; + if (func == NULL) + return 0; assert(task); - for (i=0; i < task->sp; i++) { + for (i = 0; i < task->sp; i++) { if (func == task->stack[i].func) { break; } } - if (i == task->sp) { /* not found on stack */ - if (func != task->func) return 0; /* is also not running function */ + if (i == task->sp) { /* not found on stack */ + if (func != task->func) + return 0; /* is also not running function */ } else { - task->sp = i; /* unwind stack to level i */ + task->sp = i; /* unwind stack to level i */ } - task->pc = -1; /* leave function */ + task->pc = -1; /* leave function */ return 1; } -void FsmStopTask(Fsm *task) { +void FsmStopTask(Fsm * task) +{ assert(task); task->sp = 0; task->pc = -1; task->obj = NULL; } -void FsmPause(Fsm *task, int pause) { +void FsmPause(Fsm * task, int pause) +{ task->pause = pause; } -long FsmCallOld(long pc, FsmFunc func) { +long FsmCallOld(long pc, FsmFunc func) +{ assert(fsm); assert(fsm->sp < MAXSTACK); fsm->stack[fsm->sp].pc = pc; @@ -163,7 +177,8 @@ long FsmCallOld(long pc, FsmFunc func) { return fsm->func(fsm->pc, fsm->obj); } -void FsmCall(FsmFunc func) { +void FsmCall(FsmFunc func) +{ assert(fsm); callFunc = func; } diff --git a/fsm.h b/fsm.h index b59af5a..47e2249 100644 --- a/fsm.h +++ b/fsm.h @@ -11,7 +11,7 @@ M. Zolliker, Aug 2004 typedef struct Fsm Fsm; -typedef long (*FsmFunc)(long pc, void *obj); +typedef long (*FsmFunc) (long pc, void *obj); /* the prototype for a task function a task function body has the following form: @@ -41,31 +41,31 @@ typedef long (*FsmFunc)(long pc, void *obj); #define FSM_CALL(FUNC) return FsmCallOld(__LINE__, (FsmFunc)FUNC); case __LINE__: /* call a task subfunction */ -typedef int (*FsmHandler)(void *obj); +typedef int (*FsmHandler) (void *obj); /* the prototype for the handler. Should return 0 when waiting for an answer or 1 when result is o.k. */ Fsm *FsmStartTask(void *obj, FsmHandler handler, FsmFunc func, char *name); /* start a task and return a pointer to it */ -void FsmRestartTask(Fsm *task, FsmFunc func); +void FsmRestartTask(Fsm * task, FsmFunc func); /* restart a stopped task */ -int FsmTaskHandler(Fsm *task); +int FsmTaskHandler(Fsm * task); /* this is the task handler. the argument should be the pointer obtained from FsmStartTask returns 0 when finished, 1 when still running */ -int FsmStop(Fsm *task, FsmFunc func); +int FsmStop(Fsm * task, FsmFunc func); /* stop a function. returns to the caller next time */ -void FsmStopTask(Fsm *task); +void FsmStopTask(Fsm * task); /* stops the task, it will be killed after next execution */ void FsmKill(void *task); /* kill the task */ -void FsmPause(Fsm *task, int pause); +void FsmPause(Fsm * task, int pause); /* pause=1: pause task, pause=0: continue task */ long FsmCallOld(long pc, FsmFunc func); @@ -75,6 +75,6 @@ void FsmCall(FsmFunc func); void FsmWait(long delay); -void FsmSpeed(Fsm *task); +void FsmSpeed(Fsm * task); #endif diff --git a/haakedriv.c b/haakedriv.c index ec74e05..267dbc4 100644 --- a/haakedriv.c +++ b/haakedriv.c @@ -53,19 +53,21 @@ typedef struct { int sensor2alarm; int with2sensors; } Haake; - + static ParClass haakeClass = { "HAAKE", sizeof(Haake) }; /*----------------------------------------------------------------------------*/ -int HaakeHandler(void *object) { +int HaakeHandler(void *object) +{ int iret, l; Haake *drv = ParCast(&haakeClass, object); EaseBase *eab = EaseBaseCast(object); char *corr; - + assert(drv); - if (eab->state < EASE_idle) goto quit; + if (eab->state < EASE_idle) + goto quit; if (availableNetRS232(eab->ser) || availableRS232(eab->ser)) { eab->msg[0] = '\0'; l = sizeof(eab->ans); @@ -81,7 +83,7 @@ int HaakeHandler(void *object) { ParPrintf(eab, -2, "ans: %s", eab->ans); if (drv->errcnt < 10) { eab->state = EASE_read; - EaseWrite(eab, NULL); /* send the same command again */ + EaseWrite(eab, NULL); /* send the same command again */ drv->errcnt++; return 0; } @@ -89,7 +91,7 @@ int HaakeHandler(void *object) { eab->state = EASE_idle; goto error; } else { - drv->errcnt=0; + drv->errcnt = 0; } if (iret == 1) { ParPrintf(eab, -2, "ans: %s", eab->ans); @@ -99,8 +101,8 @@ int HaakeHandler(void *object) { if (strcmp(eab->ans, eab->version) == 0) { /* we are still connected with the same device */ } else if (*eab->version == '\0') { - strncat(eab->version, eab->ans, sizeof(eab->version)-1); - } else { /* version (and therefore device) changed */ + strncat(eab->version, eab->ans, sizeof(eab->version) - 1); + } else { /* version (and therefore device) changed */ eab->errCode = EASE_DEV_CHANGED; eab->state = EASE_idle; goto error; @@ -135,43 +137,66 @@ error: quit: return EaseHandler(eab); } + /*----------------------------------------------------------------------------*/ -static void HaakeParDef(void *object) { +static void HaakeParDef(void *object) +{ Haake *drv = ParCast(&haakeClass, object); EaseBase *eab = object; int reset = 0; - ParName(""); ParFmt("%.2f"); ParTail("K"); + ParName(""); + ParFmt("%.2f"); + ParTail("K"); ParFloat(&drv->t, PAR_NAN); - + ParName("t2"); - if (drv->with2sensors) { ParFmt("%.2f"); ParTail("K"); } + if (drv->with2sensors) { + ParFmt("%.2f"); + ParTail("K"); + } ParFloat(&drv->t2, PAR_NAN); - - ParName("set"); ParFmt("%.2f"); ParTail("K"); + + ParName("set"); + ParFmt("%.2f"); + ParTail("K"); ParFloat(&drv->set, PAR_NAN); - - ParName("running"); EaseUpdate(HAAKE_ON); + + ParName("running"); + EaseUpdate(HAAKE_ON); ParInt(&drv->running, 0); - ParName("extcontrol"); EaseUpdate(HAAKE_EXT); + ParName("extcontrol"); + EaseUpdate(HAAKE_EXT); ParInt(&drv->extcontrol, 0); - ParName("relais"); ParInt(&drv->relais, 0); - ParName("overtemp"); ParInt(&drv->overtemp, 0); - ParName("lowlevel"); ParInt(&drv->lowlevel, 0); - ParName("pumpalarm"); ParInt(&drv->pumpalarm, 0); - ParName("externalarm"); ParInt(&drv->externalarm, 0); - ParName("coolalarm"); ParInt(&drv->coolalarm, 0); - ParName("sensor1alarm"); ParInt(&drv->sensor1alarm, 0); - ParName("sensor2alarm"); ParInt(&drv->sensor2alarm, 0); + ParName("relais"); + ParInt(&drv->relais, 0); + ParName("overtemp"); + ParInt(&drv->overtemp, 0); + ParName("lowlevel"); + ParInt(&drv->lowlevel, 0); + ParName("pumpalarm"); + ParInt(&drv->pumpalarm, 0); + ParName("externalarm"); + ParInt(&drv->externalarm, 0); + ParName("coolalarm"); + ParInt(&drv->coolalarm, 0); + ParName("sensor1alarm"); + ParInt(&drv->sensor1alarm, 0); + ParName("sensor2alarm"); + ParInt(&drv->sensor2alarm, 0); - ParName("reset"); ParAccess(usUser); ParSave(0); + ParName("reset"); + ParAccess(usUser); + ParSave(0); ParInt(&reset, 0); if (ParActionIs(PAR_SET) > 0) { EaseSetUpdate(drv, HAAKE_RESET, 1); } - ParName("with2sensors"); ParAccess(usUser); ParInt(&drv->with2sensors, 0); + ParName("with2sensors"); + ParAccess(usUser); + ParInt(&drv->with2sensors, 0); EaseBasePar(drv); EaseSendPar(drv); @@ -179,86 +204,105 @@ static void HaakeParDef(void *object) { ParStdDef(); EaseMsgPar(drv); } + /*----------------------------------------------------------------------------*/ -static long HaakeRead(long pc, void *object) { +static long HaakeRead(long pc, void *object) +{ Haake *drv = ParCast(&haakeClass, object); EaseBase *eab = object; char alarms[128]; int status; - switch (pc) { default: /* FSM BEGIN *******************************/ + switch (pc) { + default: /* FSM BEGIN ****************************** */ EaseWrite(eab, "B"); - return __LINE__; case __LINE__: /**********************************/ + return __LINE__; + case __LINE__: /**********************************/ if (!EaseGetUpdate(drv, HAAKE_ON)) { - drv->running = (eab->ans[0]!='0'); + drv->running = (eab->ans[0] != '0'); } if (!EaseGetUpdate(drv, HAAKE_EXT)) { - drv->extcontrol = (eab->ans[1]!='0'); + drv->extcontrol = (eab->ans[1] != '0'); } - drv->relais = (eab->ans[2]!='0'); - drv->overtemp = (eab->ans[3]!='0'); - drv->lowlevel = (eab->ans[4]!='0'); - drv->pumpalarm = (eab->ans[5]!='0'); - drv->externalarm = (eab->ans[6]!='0'); - drv->coolalarm = (eab->ans[7]!='0'); - drv->sensor1alarm = (eab->ans[10]!='0'); - drv->sensor2alarm = (eab->ans[11]!='0'); - + drv->relais = (eab->ans[2] != '0'); + drv->overtemp = (eab->ans[3] != '0'); + drv->lowlevel = (eab->ans[4] != '0'); + drv->pumpalarm = (eab->ans[5] != '0'); + drv->externalarm = (eab->ans[6] != '0'); + drv->coolalarm = (eab->ans[7] != '0'); + drv->sensor1alarm = (eab->ans[10] != '0'); + drv->sensor2alarm = (eab->ans[11] != '0'); + EaseWrite(eab, "F1"); - return __LINE__; case __LINE__: /**********************************/ + return __LINE__; + case __LINE__: /**********************************/ drv->t = atof(eab->ans) + 273.15; - if (!drv->with2sensors) goto nof2; + if (!drv->with2sensors) + goto nof2; EaseWrite(eab, "F2"); - return __LINE__; case __LINE__: /**********************************/ + return __LINE__; + case __LINE__: /**********************************/ drv->t2 = atof(eab->ans) + 273.15; if (drv->t2 < -222) { drv->t2 = PAR_NAN; } nof2: EaseWrite(eab, "S"); - return __LINE__; case __LINE__: /**********************************/ + return __LINE__; + case __LINE__: /**********************************/ drv->set = atof(eab->ans) + 273.15; skipGetSet: ParLog(drv); - fsm_quit: return 0; } /* FSM END *********************************/ + fsm_quit:return 0; + } /* FSM END ******************************** */ } + /*----------------------------------------------------------------------------*/ -static long HaakeStart(long pc, void *object) { +static long HaakeStart(long pc, void *object) +{ Haake *drv = ParCast(&haakeClass, object); EaseBase *eab = object; - switch (pc) { default: /* FSM BEGIN *******************************/ + switch (pc) { + default: /* FSM BEGIN ****************************** */ EaseWrite(eab, "V"); - return __LINE__; case __LINE__: /**********************************/ + return __LINE__; + case __LINE__: /**********************************/ if (0 != strncmp(eab->version, "1P/H", 4)) { - snprintf(eab->msg, sizeof eab->msg, "unknown temperature controller version: %s", - eab->version); + snprintf(eab->msg, sizeof eab->msg, + "unknown temperature controller version: %s", eab->version); ParPrintf(drv, eError, "ERROR: %s", eab->msg); EaseStop(eab); goto quit; } ParPrintf(drv, eLog, "connected to haake thermostat %s", eab->version); EaseWrite(eab, "W TE K"); - return __LINE__; case __LINE__: /**********************************/ + return __LINE__; + case __LINE__: /**********************************/ FsmCall(HaakeRead); - return __LINE__; case __LINE__: /**********************************/ - + return __LINE__; + case __LINE__: /**********************************/ + quit: - return 0; } /* FSM END ********************************************/ + return 0; + } /* FSM END ******************************************* */ } + /*----------------------------------------------------------------------------*/ -static long HaakeSet(long pc, void *object) { +static long HaakeSet(long pc, void *object) +{ Haake *drv = ParCast(&haakeClass, object); EaseBase *eab = object; char cmd[32]; int upd; - - switch (pc) { default: /* FSM BEGIN *******************************/ + + switch (pc) { + default: /* FSM BEGIN ****************************** */ upd = EaseNextUpdate(drv); switch (upd) { - case EASE_RUN: - snprintf(cmd, sizeof cmd, "w sw %.5g", drv->d.targetValue-273.17); + case EASE_RUN: + snprintf(cmd, sizeof cmd, "w sw %.5g", drv->d.targetValue - 273.17); break; case HAAKE_ON: snprintf(cmd, sizeof cmd, "w ts%d", drv->running); @@ -286,27 +330,34 @@ static long HaakeSet(long pc, void *object) { } EaseWrite(eab, cmd); quit: - return 0; } /* FSM END ********************************************/ + return 0; + } /* FSM END ******************************************* */ } + /*----------------------------------------------------------------------------*/ -static int HaakeInit(SConnection *con, int argc, char *argv[], int dynamic) { +static int HaakeInit(SConnection * con, int argc, char *argv[], + int dynamic) +{ /* args: - MakeObject objectname haake - MakeObject objectname haake + MakeObject objectname haake + MakeObject objectname haake */ Haake *drv; - + drv = EaseMakeDriv(con, &haakeClass, argc, argv, dynamic, 7, - HaakeParDef, HaakeHandler, HaakeStart, NULL, HaakeRead, - HaakeSet); - if (drv == NULL) return 0; - setRS232ReplyTerminator(drv->d.b.ser,"\r"); - setRS232SendTerminator(drv->d.b.ser,"\r"); - drv->d.b.tmo=5; + HaakeParDef, HaakeHandler, HaakeStart, NULL, + HaakeRead, HaakeSet); + if (drv == NULL) + return 0; + setRS232ReplyTerminator(drv->d.b.ser, "\r"); + setRS232SendTerminator(drv->d.b.ser, "\r"); + drv->d.b.tmo = 5; return 1; } + /*----------------------------------------------------------------------------*/ -void HaakeStartup(void) { +void HaakeStartup(void) +{ ParMakeClass(&haakeClass, EaseDrivClass()); MakeDriver("HAAKE", HaakeInit, 0, "HAAKE Phoenix P1 thermostat"); } diff --git a/ighdriv.c b/ighdriv.c index e262ddc..9b5fdf9 100644 --- a/ighdriv.c +++ b/ighdriv.c @@ -41,20 +41,23 @@ Markus Zolliker, May 2005 #define VALVE_FLAGS 9 #define MAX_FLAG 32 -static char *valves[]={"V9", "V8", "V7", "V11A", "V13A", "V13B", "V11B", "V12B", - " He4", "V1", "V5", "V4", "V3", "V14", "V10", "V2", - " V2A", " V1A", " V5A", " V4A", " V3A", " Roots", " Aux", "He3", - NULL}; /* valves beginning with blank are not shown in list */ -typedef enum {V9,V8,V7,V11A,V13A,V13B,V11B,V12B, - HE4,V1,V5,V4,V3,V14,V10,V2, - V2A,V1A,V5A,V4A,V3A,ROOTS,AUX,HE3,n_VALVES} Valves; - -static char *motorValves[]={"V6", "V12A", "V1K", NULL}; -typedef enum {V6,V12A,V1K,n_MOTOR} MotorValves; -static char *motorCommands[]={"G", "H", "N"}; +static char *valves[] = + { "V9", "V8", "V7", "V11A", "V13A", "V13B", "V11B", "V12B", + " He4", "V1", "V5", "V4", "V3", "V14", "V10", "V2", + " V2A", " V1A", " V5A", " V4A", " V3A", " Roots", " Aux", "He3", + NULL +}; /* valves beginning with blank are not shown in list */ +typedef enum { V9, V8, V7, V11A, V13A, V13B, V11B, V12B, + HE4, V1, V5, V4, V3, V14, V10, V2, + V2A, V1A, V5A, V4A, V3A, ROOTS, AUX, HE3, n_VALVES +} Valves; -static char *gauges[]={"G1", "G2", "G3", "", "", "", "P1", "P2", NULL}; -typedef enum {G1,G2,G3,G4,G5,G6,P1,P2,n_PRESS} PressureGauges; +static char *motorValves[] = { "V6", "V12A", "V1K", NULL }; +typedef enum { V6, V12A, V1K, n_MOTOR } MotorValves; +static char *motorCommands[] = { "G", "H", "N" }; + +static char *gauges[] = { "G1", "G2", "G3", "", "", "", "P1", "P2", NULL }; +typedef enum { G1, G2, G3, G4, G5, G6, P1, P2, n_PRESS } PressureGauges; typedef struct { EaseDriv d; @@ -72,10 +75,10 @@ typedef struct { time_t v6time; int pdig; int v[n_VALVES]; - int e; /* heater range */ - int a; /* actual heater mode */ - int o; /* actual still/sorb mode */ - int s; /* moving valve state */ + int e; /* heater range */ + int a; /* actual heater mode */ + int o; /* actual still/sorb mode */ + int s; /* moving valve state */ int remote; } Igh; @@ -83,18 +86,23 @@ static ParClass ighClass = { "IGH", sizeof(Igh) }; static long IghSet(long pc, void *object); /*----------------------------------------------------------------------------*/ -static int IghPower2Range(float p) { +static int IghPower2Range(float p) +{ int e; - if (p <= 0) return 0; + if (p <= 0) + return 0; for (e = 1; e < 5; e++) { - if (p < 1.9994e-3) break; + if (p < 1.9994e-3) + break; p /= 10; } return e; } + /*----------------------------------------------------------------------------*/ -static float IghRange2Max(int e) { - static float elist[]={0,0.002,0.02,0.2,2.0,20.0}; +static float IghRange2Max(int e) +{ + static float elist[] = { 0, 0.002, 0.02, 0.2, 2.0, 20.0 }; if (e < 0) { e = 0; } else if (e > 5) { @@ -102,72 +110,94 @@ static float IghRange2Max(int e) { } return elist[e]; } + /*----------------------------------------------------------------------------*/ -static void IghParDef(void *object) { +static void IghParDef(void *object) +{ Igh *drv = ParCast(&ighClass, object); EaseBase *eab = object; int i, flag, l, changed; char *vPos, *val; char fmt[8], vList[80]; - static char *na=NULL; + static char *na = NULL; float maxP; - static char *heaterList[]={"off", "2uW", "20uW", "200uW", "2mW", "20mW", NULL}; - static char *closedOrOpen[]={"closed", "open", NULL}; - - ParName(""); ParTail("K"); ParFmt("%.4f"); + static char *heaterList[] = + { "off", "2uW", "20uW", "200uW", "2mW", "20mW", NULL }; + static char *closedOrOpen[] = { "closed", "open", NULL }; + + ParName(""); + ParTail("K"); + ParFmt("%.4f"); ParFloat(&drv->mixT, PAR_NAN); - - ParName("Tset"); ParTail("K"); ParFmt("%.4f"); + + ParName("Tset"); + ParTail("K"); + ParFmt("%.4f"); if (eab->syntax == OLDIGH) { ParList("all"); drv->setT = -1; ParFloat(&drv->setT, -1); } else { - if (drv->setT < 0) drv->setT = 0; + if (drv->setT < 0) + drv->setT = 0; ParFloat(&drv->setT, PAR_NAN); } ParName("TsorbSet"); - EaseUpdate(SORBS_FLAG); ParTail("K"); ParFmt("%.1f"); + EaseUpdate(SORBS_FLAG); + ParTail("K"); + ParFmt("%.1f"); ParFloat(&drv->sorbS, PAR_NAN); ParName("Tmix"); - ParTail("K"); ParFmt("%.4f"); + ParTail("K"); + ParFmt("%.4f"); ParFloat(&drv->mixT, PAR_NAN); ParName("T1K"); - ParTail("K"); ParFmt("%.4f"); + ParTail("K"); + ParFmt("%.4f"); ParFloat(&drv->onekT, PAR_NAN); ParName("Tsorb"); - ParTail("K"); ParFmt("%.1f"); + ParTail("K"); + ParFmt("%.1f"); ParFloat(&drv->sorbT, PAR_NAN); ParName("Pmix"); - EaseUpdate(MIXP_FLAG); ParTail("mW"); ParFmt("%.5g"); + EaseUpdate(MIXP_FLAG); + ParTail("mW"); + ParFmt("%.5g"); ParFloat(&drv->mixP, PAR_NAN); ParName("Pmax"); - ParTail("mW"); ParFmt("%.5g"); + ParTail("mW"); + ParFmt("%.5g"); maxP = IghRange2Max(drv->e); ParFloat(&maxP, PAR_NAN); ParName("HtrRange"); - EaseUpdate(MAXP_FLAG); ParEnum(heaterList); ParList(NULL); + EaseUpdate(MAXP_FLAG); + ParEnum(heaterList); + ParList(NULL); ParInt(&drv->e, PAR_NAN); if (ParActionIs(PAR_SET) > 0) { drv->mixP = 0; } ParName("Pstill"); - EaseUpdate(STILL_FLAG); ParTail("mW"); ParFmt("%.3f"); + EaseUpdate(STILL_FLAG); + ParTail("mW"); + ParFmt("%.3f"); ParFloat(&drv->stillP, PAR_NAN); ParName("Psorb"); - EaseUpdate(SORBP_FLAG); ParTail("W"); ParFmt("%.3f"); + EaseUpdate(SORBP_FLAG); + ParTail("W"); + ParFmt("%.3f"); ParFloat(&drv->sorbP, PAR_NAN); - for (i=0; ipdig); ParFmt(fmt); } else if (i == P2) { - ParFmt("%.3f"); ParList("all"); + ParFmt("%.3f"); + ParList("all"); } else if (i == G3) { - ParFmt("%.1f"); ParList("all"); + ParFmt("%.1f"); + ParList("all"); } else { - ParFmt("%.1f"); + ParFmt("%.1f"); } ParFloat(&drv->press[i], PAR_NAN); } } flag = MOT_FLAGS; - for (i=0; imv[i], PAR_NAN); } - ParName("v6pos"); ParFmt("%.1f"); ParTail("%"); + ParName("v6pos"); + ParFmt("%.1f"); + ParTail("%"); ParFloat(&drv->v6pos, PAR_NAN); assert(flag == VALVE_FLAGS); l = 0; - for (i=0; iv[i], PAR_LNAN); if (changed) { - if (drv->v[i] != 1) drv->v[i] = 0; /* allow only 1 or 0 */ + if (drv->v[i] != 1) + drv->v[i] = 0; /* allow only 1 or 0 */ } flag++; if (ParActionIs(PAR_LIST) && valves[i][0] != ' ') { @@ -219,7 +256,8 @@ static void IghParDef(void *object) { vPos = vList + l; l += strlen(valves[i]) + 1; if (l < sizeof vList) { - strcpy(vPos, " "); vPos++; + strcpy(vPos, " "); + vPos++; strcpy(vPos, valves[i]); vList[l] = '\0'; } else { @@ -228,7 +266,7 @@ static void IghParDef(void *object) { } } } - assert(MAX_FLAG == flag-1); + assert(MAX_FLAG == flag - 1); if (ParActionIs(PAR_LIST)) { vList[l] = '\0'; ParPrintf(NULL, eValue, "open valves:%s", vList); @@ -238,41 +276,42 @@ static void IghParDef(void *object) { ParStdDef(); EaseMsgPar(eab); } + /*----------------------------------------------------------------------------*/ -void IghStatus(Igh *drv) { +void IghStatus(Igh * drv) +{ char *ans; int *code; long mask, p; int i; - - if (drv->d.b.state != EASE_read) return; - ans=drv->d.b.ans; - code=&drv->d.b.errCode; + + if (drv->d.b.state != EASE_read) + return; + ans = drv->d.b.ans; + code = &drv->d.b.errCode; if (ans[0] != 'X' || ans[2] != 'A' || ans[4] != 'C' || ans[6] != 'P' || - ans[15] != 'S' || - ans[17] != 'O' || - ans[19] != 'E') { + ans[15] != 'S' || ans[17] != 'O' || ans[19] != 'E') { ParPrintf(drv, eError, "illegal status response: %s", ans); *code = EASE_FAULT; return; } - if (sscanf(ans+7, "%lx", &mask) <= 0) { + if (sscanf(ans + 7, "%lx", &mask) <= 0) { ParPrintf(drv, eError, "illegal valve status response"); *code = EASE_FAULT; return; } - p=1; - for (i=0; iv[i] = 1; } else { drv->v[i] = 0; } - p=p*2; + p = p * 2; } } drv->a = ans[3] - '0'; @@ -292,109 +331,145 @@ void IghStatus(Igh *drv) { return; } } + /*----------------------------------------------------------------------------*/ -static long IghRead(long pc, void *object) { +static long IghRead(long pc, void *object) +{ Igh *drv = ParCast(&ighClass, object); EaseBase *eab = object; char *p; int l; time_t now; float delta; - - switch (pc) { default: /* FSM BEGIN *******************************/ + + switch (pc) { + default: /* FSM BEGIN ****************************** */ EaseWrite(eab, "X"); - return __LINE__; case __LINE__: /**********************************/ + return __LINE__; + case __LINE__: /**********************************/ IghStatus(drv); - if (!drv->remote) goto skiprmt; + if (!drv->remote) + goto skiprmt; EaseWrite(eab, "C0"); drv->remote = 0; - return __LINE__; case __LINE__: /**********************************/ + return __LINE__; + case __LINE__: /**********************************/ skiprmt: - if (! EaseNextFullRead(eab)) goto fsm_quit; - - if (EaseCheckDoit(eab)) goto quit; + if (!EaseNextFullRead(eab)) + goto fsm_quit; - if (EaseGetUpdate(drv, SORBS_FLAG)) goto skip0; + if (EaseCheckDoit(eab)) + goto quit; + + if (EaseGetUpdate(drv, SORBS_FLAG)) + goto skip0; if (drv->o / 2 != 1) { drv->sorbS = 0; goto skip0; } EaseWrite(eab, "R0"); - return __LINE__; case __LINE__: /**********************************/ - if (EaseGetUpdate(drv, SORBS_FLAG)) goto skip0; + return __LINE__; + case __LINE__: /**********************************/ + if (EaseGetUpdate(drv, SORBS_FLAG)) + goto skip0; drv->sorbS = OxiGet(eab, 1, NULL, drv->sorbS); skip0: - - if (EaseCheckDoit(eab)) goto quit; + + if (EaseCheckDoit(eab)) + goto quit; if (eab->syntax == OLDIGH) { EaseWrite(eab, "R3"); } else { EaseWrite(eab, "R32"); } - return __LINE__; case __LINE__: /**********************************/ + return __LINE__; + case __LINE__: /**********************************/ if (eab->syntax == OLDIGH) { drv->mixT = OxiGet(eab, 3, NULL, drv->mixT); } else { drv->mixT = OxiGet(eab, 4, NULL, drv->mixT); - if (drv->mixT < 0) drv->mixT += 6.5536; /* correct a bug in firmware < 3.03 */ + if (drv->mixT < 0) + drv->mixT += 6.5536; /* correct a bug in firmware < 3.03 */ } - if (EaseCheckDoit(eab)) goto quit; + if (EaseCheckDoit(eab)) + goto quit; - if (eab->syntax == OLDIGH) goto noSetTemp; + if (eab->syntax == OLDIGH) + goto noSetTemp; EaseWrite(eab, "R33"); - return __LINE__; case __LINE__: /**********************************/ + return __LINE__; + case __LINE__: /**********************************/ drv->setT = OxiGet(eab, 4, NULL, drv->setT); - + noSetTemp: EaseWrite(eab, "R1"); - return __LINE__; case __LINE__: /**********************************/ + return __LINE__; + case __LINE__: /**********************************/ drv->sorbT = OxiGet(eab, 1, NULL, drv->sorbT); - - if (EaseCheckDoit(eab)) goto quit; + + if (EaseCheckDoit(eab)) + goto quit; EaseWrite(eab, "R2"); - return __LINE__; case __LINE__: /**********************************/ + return __LINE__; + case __LINE__: /**********************************/ drv->onekT = OxiGet(eab, 3, NULL, drv->onekT); - - if (EaseCheckDoit(eab)) goto quit; + + if (EaseCheckDoit(eab)) + goto quit; if (drv->e == 0) { drv->mixP = 0; goto skip4; } - if (EaseGetUpdate(drv, MIXP_FLAG) || EaseGetUpdate(drv, MAXP_FLAG)) goto skip4; + if (EaseGetUpdate(drv, MIXP_FLAG) || EaseGetUpdate(drv, MAXP_FLAG)) + goto skip4; EaseWrite(eab, "R4"); - return __LINE__; case __LINE__: /**********************************/ - if (EaseGetUpdate(drv, MIXP_FLAG) || EaseGetUpdate(drv, MAXP_FLAG)) goto skip4; - drv->mixP = OxiGet(eab, 5 - drv->e, NULL, drv->mixP*100) * 0.01; + return __LINE__; + case __LINE__: /**********************************/ + if (EaseGetUpdate(drv, MIXP_FLAG) || EaseGetUpdate(drv, MAXP_FLAG)) + goto skip4; + drv->mixP = OxiGet(eab, 5 - drv->e, NULL, drv->mixP * 100) * 0.01; skip4: - - if (EaseCheckDoit(eab)) goto quit; - if (EaseGetUpdate(drv, STILL_FLAG)) goto skip5; + if (EaseCheckDoit(eab)) + goto quit; + + if (EaseGetUpdate(drv, STILL_FLAG)) + goto skip5; EaseWrite(eab, "R5"); - return __LINE__; case __LINE__: /**********************************/ - if (EaseGetUpdate(drv, STILL_FLAG)) goto skip5; + return __LINE__; + case __LINE__: /**********************************/ + if (EaseGetUpdate(drv, STILL_FLAG)) + goto skip5; drv->stillP = OxiGet(eab, 1, NULL, drv->stillP); skip5: - - if (EaseCheckDoit(eab)) goto quit; - if (EaseGetUpdate(drv, SORBP_FLAG)) goto skip6; + if (EaseCheckDoit(eab)) + goto quit; + + if (EaseGetUpdate(drv, SORBP_FLAG)) + goto skip6; EaseWrite(eab, "R6"); - return __LINE__; case __LINE__: /**********************************/ - if (EaseGetUpdate(drv, SORBP_FLAG)) goto skip6; + return __LINE__; + case __LINE__: /**********************************/ + if (EaseGetUpdate(drv, SORBP_FLAG)) + goto skip6; drv->sorbP = OxiGet(eab, 3, NULL, drv->sorbP); skip6: - - if (EaseCheckDoit(eab)) goto quit; - if (EaseGetUpdate(drv, MOT_FLAGS+V6)) goto skip7; + if (EaseCheckDoit(eab)) + goto quit; + + if (EaseGetUpdate(drv, MOT_FLAGS + V6)) + goto skip7; EaseWrite(eab, "R7"); - return __LINE__; case __LINE__: /**********************************/ - if (EaseGetUpdate(drv, MOT_FLAGS+V6)) goto skip7; + return __LINE__; + case __LINE__: /**********************************/ + if (EaseGetUpdate(drv, MOT_FLAGS + V6)) + goto skip7; drv->mv[V6] = OxiGet(eab, 1, NULL, drv->mv[V6]); time(&now); delta = (now - drv->v6time) / 2.64; /* speed: 1/2.64 %/sec */ @@ -407,87 +482,115 @@ static long IghRead(long pc, void *object) { drv->v6pos = drv->mv[V6]; } skip7: - - if (EaseCheckDoit(eab)) goto quit; - if (EaseGetUpdate(drv, MOT_FLAGS+V12A)) goto skip8; + if (EaseCheckDoit(eab)) + goto quit; + + if (EaseGetUpdate(drv, MOT_FLAGS + V12A)) + goto skip8; EaseWrite(eab, "R8"); - return __LINE__; case __LINE__: /**********************************/ - if (EaseGetUpdate(drv, MOT_FLAGS+V12A)) goto skip8; + return __LINE__; + case __LINE__: /**********************************/ + if (EaseGetUpdate(drv, MOT_FLAGS + V12A)) + goto skip8; drv->mv[V12A] = OxiGet(eab, 1, NULL, drv->mv[V12A]); skip8: - - if (EaseCheckDoit(eab)) goto quit; - if (EaseGetUpdate(drv, MOT_FLAGS+V1K)) goto skip9; + if (EaseCheckDoit(eab)) + goto quit; + + if (EaseGetUpdate(drv, MOT_FLAGS + V1K)) + goto skip9; EaseWrite(eab, "R9"); - return __LINE__; case __LINE__: /**********************************/ - if (EaseGetUpdate(drv, MOT_FLAGS+V1K)) goto skip9; + return __LINE__; + case __LINE__: /**********************************/ + if (EaseGetUpdate(drv, MOT_FLAGS + V1K)) + goto skip9; drv->mv[V1K] = OxiGet(eab, 1, NULL, drv->mv[V1K]); skip9: - - if (EaseCheckDoit(eab)) goto quit; + + if (EaseCheckDoit(eab)) + goto quit; EaseWrite(eab, "R14"); - return __LINE__; case __LINE__: /**********************************/ + return __LINE__; + case __LINE__: /**********************************/ drv->press[G1] = OxiGet(eab, 1, NULL, drv->press[G1]); - - if (EaseCheckDoit(eab)) goto quit; + + if (EaseCheckDoit(eab)) + goto quit; EaseWrite(eab, "R15"); - return __LINE__; case __LINE__: /**********************************/ + return __LINE__; + case __LINE__: /**********************************/ drv->press[G2] = OxiGet(eab, 1, NULL, drv->press[G2]); - - if (EaseCheckDoit(eab)) goto quit; + + if (EaseCheckDoit(eab)) + goto quit; EaseWrite(eab, "R16"); - return __LINE__; case __LINE__: /**********************************/ + return __LINE__; + case __LINE__: /**********************************/ drv->press[G3] = OxiGet(eab, 1, NULL, drv->press[G3]); - - if (EaseCheckDoit(eab)) goto quit; + + if (EaseCheckDoit(eab)) + goto quit; EaseWrite(eab, "R20"); - return __LINE__; case __LINE__: /**********************************/ + return __LINE__; + case __LINE__: /**********************************/ drv->press[P1] = OxiGet(eab, drv->pdig, &drv->pdig, drv->press[P1]); - - if (EaseCheckDoit(eab)) goto quit; + + if (EaseCheckDoit(eab)) + goto quit; EaseWrite(eab, "R21"); - return __LINE__; case __LINE__: /**********************************/ + return __LINE__; + case __LINE__: /**********************************/ drv->press[P2] = OxiGet(eab, 1, NULL, drv->press[P2]); - + quit: ParLog(drv); - fsm_quit: return 0; } /* FSM END **********************************/ + fsm_quit:return 0; + } /* FSM END ********************************* */ } + /*----------------------------------------------------------------------------*/ -static long IghStart(long pc, void *object) { +static long IghStart(long pc, void *object) +{ Igh *drv = ParCast(&ighClass, object); EaseBase *eab = object; - - switch (pc) { default: /* FSM BEGIN *******************************/ + + switch (pc) { + default: /* FSM BEGIN ****************************** */ EaseWrite(eab, "V"); - return __LINE__; case __LINE__: /**********************************/ + return __LINE__; + case __LINE__: /**********************************/ if (0 != strncmp(eab->version, "IGH", 3)) { - snprintf(eab->msg, sizeof eab->msg, "unknown gas handling system version: %s", eab->version); + snprintf(eab->msg, sizeof eab->msg, + "unknown gas handling system version: %s", eab->version); ParPrintf(drv, eError, "ERROR: %s", eab->msg); EaseStop(eab); goto quit; } if (strstr(eab->version, "2.01") != NULL) { - eab->syntax = OLDIGH; /* includes communication error correction */ + eab->syntax = OLDIGH; /* includes communication error correction */ } else { eab->syntax = 0; } ParPrintf(drv, eLog, "connected to %s", eab->version); FsmCall(IghRead); - return __LINE__; case __LINE__: /**********************************/ - + return __LINE__; + case __LINE__: /**********************************/ + quit: - return 0; } /* FSM END ********************************************/ + return 0; + } /* FSM END ******************************************* */ } + /*----------------------------------------------------------------------------*/ -static long IghSet(long pc, void *object) { +static long IghSet(long pc, void *object) +{ Igh *drv = ParCast(&ighClass, object); EaseBase *eab = object; char buf[8]; @@ -495,169 +598,220 @@ static long IghSet(long pc, void *object) { int upd; int i; float mp; - - switch (pc) { default: /* FSM BEGIN *******************************/ + + switch (pc) { + default: /* FSM BEGIN ****************************** */ EaseWrite(eab, "C3"); - drv->remote=2; + drv->remote = 2; loop: - return __LINE__; case __LINE__: /**********************************/ + return __LINE__; + case __LINE__: /**********************************/ upd = EaseNextUpdate(drv); - if (upd >= VALVE_FLAGS) goto set_valve; - if (upd >= MOT_FLAGS) goto set_mot; - if (upd == EASE_RUN) goto set_temp; - if (upd == SORBS_FLAG) goto set_sorb_temp; - if (upd == MIXP_FLAG) goto set_mix_pow; - if (upd == MAXP_FLAG) goto set_max_pow; - if (upd == STILL_FLAG) goto set_still_pow; - if (upd == SORBP_FLAG) goto set_sorb_pow; + if (upd >= VALVE_FLAGS) + goto set_valve; + if (upd >= MOT_FLAGS) + goto set_mot; + if (upd == EASE_RUN) + goto set_temp; + if (upd == SORBS_FLAG) + goto set_sorb_temp; + if (upd == MIXP_FLAG) + goto set_mix_pow; + if (upd == MAXP_FLAG) + goto set_max_pow; + if (upd == STILL_FLAG) + goto set_still_pow; + if (upd == SORBP_FLAG) + goto set_sorb_pow; goto finish; - + set_sorb_temp: if (drv->sorbS == 0) { drv->sorbP = 0; goto set_sorb_pow; } OxiSet(eab, "K", drv->sorbS, 1); - return __LINE__; case __LINE__: /**********************************/ + return __LINE__; + case __LINE__: /**********************************/ EaseWrite(eab, "X"); - return __LINE__; case __LINE__: /**********************************/ + return __LINE__; + case __LINE__: /**********************************/ IghStatus(drv); - if (drv->o == 2 || drv->o == 3) goto loop; + if (drv->o == 2 || drv->o == 3) + goto loop; if (drv->o % 2) { EaseWrite(eab, "O3"); } else { EaseWrite(eab, "O2"); } - return __LINE__; case __LINE__: /**********************************/ + return __LINE__; + case __LINE__: /**********************************/ goto loop; - + set_sorb_pow: EaseWrite(eab, "X"); - return __LINE__; case __LINE__: /**********************************/ + return __LINE__; + case __LINE__: /**********************************/ IghStatus(drv); - if (drv->o <= 1) goto skipSetO; + if (drv->o <= 1) + goto skipSetO; if (drv->o % 2) { - EaseWrite(eab, "O1"); drv->o = 1; + EaseWrite(eab, "O1"); + drv->o = 1; } else { - EaseWrite(eab, "O0"); drv->o = 0; + EaseWrite(eab, "O0"); + drv->o = 0; } - return __LINE__; case __LINE__: /**********************************/ + return __LINE__; + case __LINE__: /**********************************/ skipSetO: OxiSet(eab, "B", drv->sorbP, 3); - return __LINE__; case __LINE__: /**********************************/ - if (drv->sorbP == 0.0 || drv->o >= 4) goto loop; + return __LINE__; + case __LINE__: /**********************************/ + if (drv->sorbP == 0.0 || drv->o >= 4) + goto loop; if (drv->o % 2) { EaseWrite(eab, "O5"); } else { EaseWrite(eab, "O4"); } - return __LINE__; case __LINE__: /**********************************/ + return __LINE__; + case __LINE__: /**********************************/ goto loop; - + set_still_pow: OxiSet(eab, "S", drv->stillP, 1); - return __LINE__; case __LINE__: /**********************************/ + return __LINE__; + case __LINE__: /**********************************/ EaseWrite(eab, "X"); - return __LINE__; case __LINE__: /**********************************/ + return __LINE__; + case __LINE__: /**********************************/ IghStatus(drv); snprintf(buf, sizeof buf, "O%d", drv->o | 1); EaseWrite(eab, buf); - return __LINE__; case __LINE__: /**********************************/ + return __LINE__; + case __LINE__: /**********************************/ goto loop; - + set_mix_pow: EaseWrite(eab, "A0"); - return __LINE__; case __LINE__: /**********************************/ - if (drv->e <= 1) goto skipe; + return __LINE__; + case __LINE__: /**********************************/ + if (drv->e <= 1) + goto skipe; EaseWrite(eab, "E1"); - return __LINE__; case __LINE__: /**********************************/ - + return __LINE__; + case __LINE__: /**********************************/ + skipe: if (drv->mixP > 0) { drv->e = IghPower2Range(drv->mixP); mp = drv->mixP / IghRange2Max(drv->e) * 2000; } else { - mp = 0; /* range unchanged for external heater signal */ + mp = 0; /* range unchanged for external heater signal */ } OxiSet(eab, "M", mp, 0); - return __LINE__; case __LINE__: /**********************************/ - if (drv->e == 0) goto seta0; + return __LINE__; + case __LINE__: /**********************************/ + if (drv->e == 0) + goto seta0; snprintf(buf, sizeof buf, "E%d", drv->e); EaseWrite(eab, buf); - return __LINE__; case __LINE__: /**********************************/ + return __LINE__; + case __LINE__: /**********************************/ EaseWrite(eab, "A1"); - return __LINE__; case __LINE__: /**********************************/ + return __LINE__; + case __LINE__: /**********************************/ goto loop; - + EaseWrite(eab, "A1"); - return __LINE__; case __LINE__: /**********************************/ + return __LINE__; + case __LINE__: /**********************************/ set_max_pow: - if (drv->e == 0) goto seta0; + if (drv->e == 0) + goto seta0; snprintf(buf, sizeof buf, "E%d", drv->e); EaseWrite(eab, buf); - return __LINE__; case __LINE__: /**********************************/ + return __LINE__; + case __LINE__: /**********************************/ EaseWrite(eab, "M0"); - return __LINE__; case __LINE__: /**********************************/ + return __LINE__; + case __LINE__: /**********************************/ EaseWrite(eab, "A1"); - return __LINE__; case __LINE__: /**********************************/ + return __LINE__; + case __LINE__: /**********************************/ goto loop; - + seta0: EaseWrite(eab, "A0"); - return __LINE__; case __LINE__: /**********************************/ + return __LINE__; + case __LINE__: /**********************************/ goto loop; - + set_temp: EaseWrite(eab, "A2"); - return __LINE__; case __LINE__: /**********************************/ - if (drv->d.targetValue < 0) drv->d.targetValue = 0; - if (drv->d.targetValue > 1.999) drv->d.targetValue = 1.999; + return __LINE__; + case __LINE__: /**********************************/ + if (drv->d.targetValue < 0) + drv->d.targetValue = 0; + if (drv->d.targetValue > 1.999) + drv->d.targetValue = 1.999; OxiSet(eab, "T", drv->d.targetValue, 4); - return __LINE__; case __LINE__: /**********************************/ + return __LINE__; + case __LINE__: /**********************************/ goto loop; - + set_valve: i = upd - VALVE_FLAGS; snprintf(buf, sizeof buf, "P%d", i * 2 + 3 - drv->v[i]); EaseWrite(eab, buf); - return __LINE__; case __LINE__: /**********************************/ + return __LINE__; + case __LINE__: /**********************************/ goto loop; - + set_mot: i = upd - MOT_FLAGS; if (drv->mv[i] > 99.9) { - drv->mv[i]=99.9; + drv->mv[i] = 99.9; } else if (drv->mv[i] < 0) { - drv->mv[i]=0; + drv->mv[i] = 0; } OxiSet(eab, motorCommands[i], drv->mv[i], 1); - return __LINE__; case __LINE__: /**********************************/ + return __LINE__; + case __LINE__: /**********************************/ goto loop; - + finish: EaseWrite(eab, "C0"); - return __LINE__; case __LINE__: /**********************************/ + return __LINE__; + case __LINE__: /**********************************/ drv->remote = 0; quit: - return 0; } /* FSM END ********************************************/ + return 0; + } /* FSM END ******************************************* */ } + /*----------------------------------------------------------------------------*/ -static int IghInit(SConnection *con, int argc, char *argv[], int dynamic) { +static int IghInit(SConnection * con, int argc, char *argv[], int dynamic) +{ /* args: - MakeObject objectname igh - MakeObject objectname igh + MakeObject objectname igh + MakeObject objectname igh */ Igh *drv; - + drv = EaseMakeDriv(con, &ighClass, argc, argv, dynamic, MAX_FLAG, - IghParDef, OxiHandler, IghStart, NULL, IghRead, - IghSet); - if (drv == NULL) return 0; + IghParDef, OxiHandler, IghStart, NULL, IghRead, + IghSet); + if (drv == NULL) + return 0; return 1; } + /*----------------------------------------------------------------------------*/ -void IghStartup(void) { +void IghStartup(void) +{ ParMakeClass(&ighClass, EaseDrivClass()); - MakeDriver("IGH", IghInit, 0, "OI Gas Handling System"); + MakeDriver("IGH", IghInit, 0, "OI Gas Handling System"); } diff --git a/ilmdriv.c b/ilmdriv.c index 9eb65d9..d5a732e 100644 --- a/ilmdriv.c +++ b/ilmdriv.c @@ -30,7 +30,8 @@ Markus Zolliker, April 2005 /* typedef enum { ALWAYSNEW, NEW, MEASURING, NOTYETREAD, OLD } ReadState; */ -typedef enum { UNUSED, N2, PULSED_HE, CONTINOUS_HE, CHANNEL_ERROR = 9 } Usage; +typedef enum { UNUSED, N2, PULSED_HE, CONTINOUS_HE, CHANNEL_ERROR = + 9 } Usage; typedef struct { EaseBase b; @@ -43,29 +44,34 @@ typedef struct { static ParClass ilmClass = { "ILM", sizeof(Ilm) }; -char *tails[10]={"unused", "% N2", "% He","% He","","","","","","error"}; +char *tails[10] = + { "unused", "% N2", "% He", "% He", "", "", "", "", "", "error" }; /*----------------------------------------------------------------------------*/ -static void IlmParDef(void *object) { +static void IlmParDef(void *object) +{ Ilm *drv = ParCast(&ilmClass, object); ParName(""); if (drv->usage[0]) { - ParFmt("%.1f"); ParTail(tails[drv->usage[0]]); + ParFmt("%.1f"); + ParTail(tails[drv->usage[0]]); } /* if (drv->readState[0] == NEW) ParLogReady(PAR_NOW_READY); */ ParFloat(&drv->lev[0], PAR_NAN); - + ParName("lev2"); if (drv->usage[1]) { - ParFmt("%.1f"); ParTail(tails[drv->usage[1]]); + ParFmt("%.1f"); + ParTail(tails[drv->usage[1]]); }; /* if (drv->readState[1] == NEW) ParLogReady(PAR_NOW_READY); */ ParFloat(&drv->lev[1], PAR_NAN); - + ParName("lev3"); if (drv->usage[2]) { - ParFmt("%.1f"); ParTail(tails[drv->usage[2]]); + ParFmt("%.1f"); + ParTail(tails[drv->usage[2]]); } /* if (drv->readState[2] == NEW) ParLogReady(PAR_NOW_READY); */ ParFloat(&drv->lev[2], PAR_NAN); @@ -74,137 +80,162 @@ static void IlmParDef(void *object) { ParStdDef(); EaseMsgPar(drv); } + /*----------------------------------------------------------------------------*/ -static void IlmStatus(Ilm *drv) { +static void IlmStatus(Ilm * drv) +{ char *ans; int *code; int i; int status; - - if (drv->b.state != EASE_read) return; - ans=drv->b.ans; - code=&drv->b.errCode; + + if (drv->b.state != EASE_read) + return; + ans = drv->b.ans; + code = &drv->b.errCode; if (ans[0] != 'X' || ans[4] != 'S' || ans[11] != 'R') { ParPrintf(drv, eError, "illegal status response"); *code = EASE_FAULT; return; } - for (i=0; i<3; i++) { - if (ans[i+1]<'0' || ans[i+1] > '9') { - ans[i+1]='9'; + for (i = 0; i < 3; i++) { + if (ans[i + 1] < '0' || ans[i + 1] > '9') { + ans[i + 1] = '9'; } - drv->usage[i] = ans[i+1] - '0'; + drv->usage[i] = ans[i + 1] - '0'; if (drv->usage[i] == PULSED_HE) { /* - sscanf(ans+6+2*i, "%1x", &status); - if (status & 1) { // measuring - drv->readState[i] = MEASURING; - } else if (drv->readState[i] == MEASURING) { // new value - drv->readState[i] = NOTYETREAD; - } - */ + sscanf(ans+6+2*i, "%1x", &status); + if (status & 1) { // measuring + drv->readState[i] = MEASURING; + } else if (drv->readState[i] == MEASURING) { // new value + drv->readState[i] = NOTYETREAD; + } + */ } else { /* - drv->readState[i] = ALWAYSNEW; - */ + drv->readState[i] = ALWAYSNEW; + */ } } return; } + /*----------------------------------------------------------------------------*/ -static long IlmRead(long pc, void *object) { +static long IlmRead(long pc, void *object) +{ Ilm *drv = ParCast(&ilmClass, object); EaseBase *eab = object; int i; - - switch (pc) { default: /* FSM BEGIN *******************************/ - EaseWrite(eab, "X"); - return __LINE__; case __LINE__: /**********************************/ - IlmStatus(drv); /* check for errors */ - EaseWrite(eab, "R1"); /* read sensor 1 */ - return __LINE__; case __LINE__: /**********************************/ - /* if (drv->readState[0] != MEASURING) */ - - drv->lev[0] = OxiGet(eab, 1, NULL, drv->lev[0]); - - /* - if (drv->readState[0] == NOTYETREAD) { - drv->readState[0] = NEW; - } - */ - if (drv->usage[1] == 0) goto skip2; - EaseWrite(eab, "R2"); /* read sensor 2 */ - return __LINE__; case __LINE__: /**********************************/ + switch (pc) { + default: /* FSM BEGIN ****************************** */ + EaseWrite(eab, "X"); + return __LINE__; + case __LINE__: /**********************************/ + IlmStatus(drv); /* check for errors */ + EaseWrite(eab, "R1"); /* read sensor 1 */ + return __LINE__; + case __LINE__: /**********************************/ + /* if (drv->readState[0] != MEASURING) */ + + drv->lev[0] = OxiGet(eab, 1, NULL, drv->lev[0]); + + /* + if (drv->readState[0] == NOTYETREAD) { + drv->readState[0] = NEW; + } + */ + + if (drv->usage[1] == 0) + goto skip2; + EaseWrite(eab, "R2"); /* read sensor 2 */ + return __LINE__; + case __LINE__: /**********************************/ drv->lev[1] = OxiGet(eab, 1, NULL, drv->lev[1]); /* - if (drv->readState[1] == NOTYETREAD) { - drv->readState[1] = NEW; - } - */ + if (drv->readState[1] == NOTYETREAD) { + drv->readState[1] = NEW; + } + */ skip2: - - if (drv->usage[2] == 0) goto skip3; - EaseWrite(eab, "R3"); /* read sensor 3 */ - return __LINE__; case __LINE__: /**********************************/ + + if (drv->usage[2] == 0) + goto skip3; + EaseWrite(eab, "R3"); /* read sensor 3 */ + return __LINE__; + case __LINE__: /**********************************/ drv->lev[2] = OxiGet(eab, 1, NULL, drv->lev[2]); /* - if (drv->readState[2] == NOTYETREAD) { - drv->readState[2] = NEW; - } - */ + if (drv->readState[2] == NOTYETREAD) { + drv->readState[2] = NEW; + } + */ skip3: - if (ParLog(drv) >= 0) { /* logging was done */ + if (ParLog(drv) >= 0) { /* logging was done */ /* - for (i=0; i<3; i++) { - if (drv->readState[i] == NEW) { - drv->readState[i] = OLD; - } - } - */ + for (i=0; i<3; i++) { + if (drv->readState[i] == NEW) { + drv->readState[i] = OLD; + } + } + */ } - return 0; } /* FSM END ********************************************/ + return 0; + } /* FSM END ******************************************* */ } + /*----------------------------------------------------------------------------*/ -static long IlmStart(long pc, void *object) { +static long IlmStart(long pc, void *object) +{ Ilm *drv = ParCast(&ilmClass, object); EaseBase *eab = object; - - switch (pc) { default: /* FSM BEGIN *******************************/ + + switch (pc) { + default: /* FSM BEGIN ****************************** */ EaseWrite(eab, "V"); - return __LINE__; case __LINE__: /**********************************/ + return __LINE__; + case __LINE__: /**********************************/ if (0 != strncmp(eab->version, "ILM", 3)) { - snprintf(eab->msg, sizeof eab->msg, "unknown level meter version: %s", eab->version); + snprintf(eab->msg, sizeof eab->msg, + "unknown level meter version: %s", eab->version); ParPrintf(drv, eError, "ERROR: %s", eab->msg); EaseStop(eab); goto quit; } ParPrintf(drv, eLog, "connected to %s", eab->version); - eab->msg[0]='\0'; /* o.k. */ + eab->msg[0] = '\0'; /* o.k. */ FsmCall(IlmRead); - return __LINE__; case __LINE__: /**********************************/ - + return __LINE__; + case __LINE__: /**********************************/ + quit: - return 0; } /* FSM END ********************************************/ + return 0; + } /* FSM END ******************************************* */ } + /*----------------------------------------------------------------------------*/ -static int IlmInit(SConnection *con, int argc, char *argv[], int dynamic) { +static int IlmInit(SConnection * con, int argc, char *argv[], int dynamic) +{ /* args: - MakeObject objectname ilm - + MakeObject objectname ilm + */ Ilm *drv; drv = EaseMakeBase(con, &ilmClass, argc, argv, dynamic, 0, - IlmParDef, OxiHandler, IlmStart, NULL, IlmRead); - if (drv == NULL) return 0; + IlmParDef, OxiHandler, IlmStart, NULL, IlmRead); + if (drv == NULL) + return 0; return 1; } + /*----------------------------------------------------------------------------*/ -void IlmStartup(void) { +void IlmStartup(void) +{ ParMakeClass(&ilmClass, EaseBaseClass()); - MakeDriver("ILM", IlmInit, 0, "OI Level Meter"); + MakeDriver("ILM", IlmInit, 0, "OI Level Meter"); } diff --git a/ipsdriv.c b/ipsdriv.c index 5e3716c..b818c7c 100644 --- a/ipsdriv.c +++ b/ipsdriv.c @@ -33,20 +33,20 @@ Markus Zolliker, May 2005 typedef struct { EaseDriv d; - float current; /* current (in Tesla) */ - float persfield; /* persistent field from IPS (in Tesla) */ - float lastfield; /* persistent field from last drive */ - float confirmfield; /* field confirmed in 1st step */ - float ramp; /* actual ramp rate (Tesla/min) */ - float maxlimit; /* hard field limit */ - int persmode; /* 0: leave switch on, 1: go to persistant mode */ - int perswitch; /* state of switch */ - int remote; /* 0: local, 1: remote, do not check, 2: remote, check */ - int nowait; /* 0: normal, 1: drive finishes immediately, ramp in background */ + float current; /* current (in Tesla) */ + float persfield; /* persistent field from IPS (in Tesla) */ + float lastfield; /* persistent field from last drive */ + float confirmfield; /* field confirmed in 1st step */ + float ramp; /* actual ramp rate (Tesla/min) */ + float maxlimit; /* hard field limit */ + int persmode; /* 0: leave switch on, 1: go to persistant mode */ + int perswitch; /* state of switch */ + int remote; /* 0: local, 1: remote, do not check, 2: remote, check */ + int nowait; /* 0: normal, 1: drive finishes immediately, ramp in background */ int heaterFault; - char *fmt; /* fmt for field */ - int force; /* force = 2: put heater switch even when stored field does not match */ - time_t swtim; /* time when last switching the heater */ + char *fmt; /* fmt for field */ + int force; /* force = 2: put heater switch even when stored field does not match */ + time_t swtim; /* time when last switching the heater */ time_t tim; } Ips; @@ -54,115 +54,154 @@ static ParClass ipsClass = { "IPS", sizeof(Ips) }; static char *onOff[] = { "off", "on", NULL }; /*----------------------------------------------------------------------------*/ -static int IpsOk(Ips *drv) { +static int IpsOk(Ips * drv) +{ float dif; - - if (drv->d.b.msg[0] != '\0') return 1; /* connection not yet confirmed */ - if (drv->perswitch) return 1; - if (fabs(drv->persfield - drv->lastfield) < 1e-5) return 1; - if (drv->force != 0) return 1; + + if (drv->d.b.msg[0] != '\0') + return 1; /* connection not yet confirmed */ + if (drv->perswitch) + return 1; + if (fabs(drv->persfield - drv->lastfield) < 1e-5) + return 1; + if (drv->force != 0) + return 1; ParPrintf(drv, eWarning, - "\nit is not sure which field is in the magnet\n" - "value stored in power supply: %f\n" - " in software: %f\n" - "use command\n \n %s confirm ...\n \n" - "to specify the persistent field\n \n" - , drv->persfield, drv->lastfield, drv->d.b.p.name); + "\nit is not sure which field is in the magnet\n" + "value stored in power supply: %f\n" + " in software: %f\n" + "use command\n \n %s confirm ...\n \n" + "to specify the persistent field\n \n", drv->persfield, + drv->lastfield, drv->d.b.p.name); drv->force = 0; return 0; } + /*----------------------------------------------------------------------------*/ -static int IpsConfirm(void *object, void *userarg, int argc, char *argv[]) +static int IpsConfirm(void *object, void *userarg, int argc, char *argv[]) { Ips *drv = ParCast(&ipsClass, object); float fld; - + assert(drv); if (argc > 0) { if (argc > 1) { ParPrintf(object, eError, "Too many arguments"); return 0; } - fld=atof(argv[0]); + fld = atof(argv[0]); if (fld > drv->d.upperLimit || fld < drv->d.lowerLimit) { ParPrintf(object, eError, "Field outside limit"); return 0; } if (drv->perswitch) { - ParPrintf(object, eWarning, "switch heater is on - field is %f", drv->current); + ParPrintf(object, eWarning, "switch heater is on - field is %f", + drv->current); return 0; } - if (fabs(fld - drv->persfield) > 1e-5 && fabs(fld - drv->lastfield) > 1e-5) { - ParPrintf(object, eWarning, "Be aware that this does neither match the field" - " stored in software\nnor the field stored in power supply."); + if (fabs(fld - drv->persfield) > 1e-5 + && fabs(fld - drv->lastfield) > 1e-5) { + ParPrintf(object, eWarning, + "Be aware that this does neither match the field" + " stored in software\nnor the field stored in power supply."); } - if (drv->force && fld != drv->confirmfield) drv->force = 0; + if (drv->force && fld != drv->confirmfield) + drv->force = 0; if (drv->force == 0) { - ParPrintf(object, eWarning, "Please repeat this command, to confirm again" - " the persistent field of\n %f Tesla.", fld); + ParPrintf(object, eWarning, + "Please repeat this command, to confirm again" + " the persistent field of\n %f Tesla.", fld); drv->confirmfield = fld; - drv->force=1; + drv->force = 1; } else { - drv->force=2; - drv->lastfield=fld; + drv->force = 2; + drv->lastfield = fld; EaseParHasChanged(); ParPrintf(object, eValue, "%s confirm = %f", drv->d.b.p.name, fld); } } else { - ParPrintf(object, eValue, "%s lastfield = %f", drv->d.b.p.name, drv->lastfield); + ParPrintf(object, eValue, "%s lastfield = %f", drv->d.b.p.name, + drv->lastfield); } return 1; } + /*----------------------------------------------------------------------------*/ -void IpsParDef(void *object) { +void IpsParDef(void *object) +{ Ips *drv = ParCast(&ipsClass, object); - ParName(""); ParFmt(drv->fmt); ParTail("Tesla"); + ParName(""); + ParFmt(drv->fmt); + ParTail("Tesla"); ParFloat(&drv->persfield, PAR_NAN); - - ParName("persmode"); ParAccess(usUser); ParEnum(onOff); ParList(0); + + ParName("persmode"); + ParAccess(usUser); + ParEnum(onOff); + ParList(0); ParInt(&drv->persmode, 1); - - ParName("perswitch"); ParEnum(onOff); ParList(0); + + ParName("perswitch"); + ParEnum(onOff); + ParList(0); ParInt(&drv->perswitch, PAR_NAN); - ParName("nowait"); ParAccess(usUser); ParEnum(onOff); ParList(0); + ParName("nowait"); + ParAccess(usUser); + ParEnum(onOff); + ParList(0); ParInt(&drv->nowait, 0); - - ParName("maxlimit"); ParSave(1); ParFloat(&drv->maxlimit, 0.0); - ParName("limit"); ParAccess(usUser); ParFmt(drv->fmt); ParTail("Tesla"); + ParName("maxlimit"); + ParSave(1); + ParFloat(&drv->maxlimit, 0.0); + + ParName("limit"); + ParAccess(usUser); + ParFmt(drv->fmt); + ParTail("Tesla"); ParFloat(&drv->d.upperLimit, 0.0); if (ParActionIs(PAR_SET) > 0) { - if (drv->maxlimit == 0) { /* first time: set maxlimit */ + if (drv->maxlimit == 0) { /* first time: set maxlimit */ drv->maxlimit = drv->d.upperLimit; } else if (drv->d.upperLimit > drv->maxlimit) { - drv->d.upperLimit= drv->maxlimit; - ParPrintf(drv, eWarning, "limit is too high, set back to %.5g\n", drv->maxlimit); + drv->d.upperLimit = drv->maxlimit; + ParPrintf(drv, eWarning, "limit is too high, set back to %.5g\n", + drv->maxlimit); } - drv->d.lowerLimit = - drv->d.upperLimit; + drv->d.lowerLimit = -drv->d.upperLimit; } - - ParName("ramp"); ParAccess(usUser); ParFmt(drv->fmt); ParTail("Tesla/min"); + + ParName("ramp"); + ParAccess(usUser); + ParFmt(drv->fmt); + ParTail("Tesla/min"); ParFloat(&drv->ramp, 1.0); - - ParName("current"); ParFmt(drv->fmt); ParTail("Tesla equivalent"); + + ParName("current"); + ParFmt(drv->fmt); + ParTail("Tesla equivalent"); ParFloat(&drv->current, PAR_NAN); - + ParName("lastfield"); ParSave(1); ParFloat(&drv->lastfield, 0); - - ParName("confirm"); ParCmd(IpsConfirm, NULL); - + + ParName("confirm"); + ParCmd(IpsConfirm, NULL); + EaseBasePar(drv); EaseSendPar(drv); ParStdDef(); - - ParName("targetValue"); ParFmt(drv->fmt); ParTail("Tesla"); + + ParName("targetValue"); + ParFmt(drv->fmt); + ParTail("Tesla"); ParFloat(&drv->d.targetValue, PAR_NAN); - - if (ParActionIs(PAR_LIST) || ParActionIs(PAR_SET) || ParActionIs(PAR_SHOW)) { + + if (ParActionIs(PAR_LIST) || ParActionIs(PAR_SET) + || ParActionIs(PAR_SHOW)) { IpsOk(drv); } if (ParActionIs(PAR_KILL)) { @@ -170,30 +209,43 @@ void IpsParDef(void *object) { } EaseMsgPar(drv); } + /*----------------------------------------------------------------------------*/ -static void IpsStatus(Ips *drv) { +static void IpsStatus(Ips * drv) +{ char *ans; int *code; int swi; - - if (drv->d.b.state != EASE_read) return; - ans=drv->d.b.ans; - code=&drv->d.b.errCode; + + if (drv->d.b.state != EASE_read) + return; + ans = drv->d.b.ans; + code = &drv->d.b.errCode; if (ans[0] != 'X' || - ans[3] != 'A' || - ans[5] != 'C' || - ans[7] != 'H' || - ans[9] != 'M') { + ans[3] != 'A' || ans[5] != 'C' || ans[7] != 'H' || ans[9] != 'M') { ParPrintf(drv, eError, "illegal status response"); *code = EASE_FAULT; return; } switch (ans[1]) { - case '0': break; - case '1': ParPrintf(drv, eError, "magnet quenched"); *code = EASE_FAULT; return; - case '2': ParPrintf(drv, eError, "IPS overheated"); *code = EASE_FAULT; return; - case '4': ParPrintf(drv, eError, "IPS warming up"); *code = EASE_FAULT; return; - case '8': ParPrintf(drv, eError, "IPS fault"); *code = EASE_FAULT; return; + case '0': + break; + case '1': + ParPrintf(drv, eError, "magnet quenched"); + *code = EASE_FAULT; + return; + case '2': + ParPrintf(drv, eError, "IPS overheated"); + *code = EASE_FAULT; + return; + case '4': + ParPrintf(drv, eError, "IPS warming up"); + *code = EASE_FAULT; + return; + case '8': + ParPrintf(drv, eError, "IPS fault"); + *code = EASE_FAULT; + return; default: ParPrintf(drv, eError, "illegal status response"); *code = EASE_FAULT; @@ -209,7 +261,7 @@ static void IpsStatus(Ips *drv) { if (drv->d.hwstate == HWBusy && drv->d.b.doit == NULL) { drv->d.hwstate = HWIdle; drv->d.stopped = 0; - } + } } if (ans[8] == '5') { drv->heaterFault = 1; @@ -226,8 +278,10 @@ static void IpsStatus(Ips *drv) { drv->perswitch = swi; } } + /*----------------------------------------------------------------------------*/ -static void IpsSetField(Ips *drv, float val) { +static void IpsSetField(Ips * drv, float val) +{ ParLog(drv); if (drv->perswitch) { drv->current = val; @@ -238,46 +292,58 @@ static void IpsSetField(Ips *drv, float val) { drv->persfield = val; } } + /*----------------------------------------------------------------------------*/ -static long IpsRead(long pc, void *object) { +static long IpsRead(long pc, void *object) +{ Ips *drv = ParCast(&ipsClass, object); EaseBase *eab = object; - switch (pc) { default: /* FSM BEGIN *******************************/ + switch (pc) { + default: /* FSM BEGIN ****************************** */ EaseWrite(eab, "X"); - return __LINE__; case __LINE__: /**********************************/ + return __LINE__; + case __LINE__: /**********************************/ IpsStatus(drv); rd: - EaseWrite(eab, "R7"); /* read current (in Tesla) */ - return __LINE__; case __LINE__: /**********************************/ + EaseWrite(eab, "R7"); /* read current (in Tesla) */ + return __LINE__; + case __LINE__: /**********************************/ drv->current = OxiGet(eab, 3, NULL, drv->current); if (drv->perswitch) { IpsSetField(drv, drv->current); goto quit; } - EaseWrite(eab, "R18"); /* read persistant field (in Tesla) */ - return __LINE__; case __LINE__: /**********************************/ + EaseWrite(eab, "R18"); /* read persistant field (in Tesla) */ + return __LINE__; + case __LINE__: /**********************************/ IpsSetField(drv, OxiGet(eab, 3, NULL, drv->persfield)); - + quit: ParLog(drv); - return 0; } /* FSM END ********************************************/ + return 0; + } /* FSM END ******************************************* */ } + /*----------------------------------------------------------------------------*/ -static long IpsStart(long pc, void *object) { +static long IpsStart(long pc, void *object) +{ Ips *drv = ParCast(&ipsClass, object); EaseBase *eab = object; - - switch (pc) { default: /* FSM BEGIN *******************************/ + + switch (pc) { + default: /* FSM BEGIN ****************************** */ EaseWrite(eab, "V"); - return __LINE__; case __LINE__: /**********************************/ + return __LINE__; + case __LINE__: /**********************************/ if (0 == strncmp(eab->version, "IPS120", 6)) { eab->syntax = 1; } else if (0 == strncmp(eab->version, "PS", 2)) { eab->syntax = 0; } else { - snprintf(eab->msg, sizeof eab->msg, "unknown power supply version: %s", eab->version); + snprintf(eab->msg, sizeof eab->msg, + "unknown power supply version: %s", eab->version); ParPrintf(drv, eError, "ERROR: %s", eab->msg); EaseStop(eab); goto quit; @@ -289,22 +355,27 @@ static long IpsStart(long pc, void *object) { drv->fmt = "%.3f"; } FsmCall(IpsRead); - return __LINE__; case __LINE__: /**********************************/ + return __LINE__; + case __LINE__: /**********************************/ quit: - return 0; } /* FSM END ********************************************/ + return 0; + } /* FSM END ******************************************* */ } + /*----------------------------------------------------------------------------*/ -static long IpsChangeField(long pc, void *object) { +static long IpsChangeField(long pc, void *object) +{ Ips *drv = ParCast(&ipsClass, object); EaseBase *eab = object; float fld; float step; float ramp; time_t delay; - - switch (pc) { default: /* FSM BEGIN *******************************/ + + switch (pc) { + default: /* FSM BEGIN ****************************** */ EaseSetUpdate(eab, EASE_RUN, 0); if (drv->nowait) { drv->d.hwstate = HWIdle; @@ -312,76 +383,97 @@ static long IpsChangeField(long pc, void *object) { } EaseWrite(eab, "C3"); drv->remote = 1; - return __LINE__; case __LINE__: /**********************************/ - EaseWrite(eab, "F7"); /* switch to tesla on display */ - return __LINE__; case __LINE__: /**********************************/ - EaseWrite(eab, "A0"); /* hold */ - return __LINE__; case __LINE__: /**********************************/ + return __LINE__; + case __LINE__: /**********************************/ + EaseWrite(eab, "F7"); /* switch to tesla on display */ + return __LINE__; + case __LINE__: /**********************************/ + EaseWrite(eab, "A0"); /* hold */ + return __LINE__; + case __LINE__: /**********************************/ FsmCall(IpsRead); - return __LINE__; case __LINE__: /**********************************/ + return __LINE__; + case __LINE__: /**********************************/ drv->remote = 2; - if (!IpsOk(drv)) goto finish; + if (!IpsOk(drv)) + goto finish; if (fabs(drv->d.targetValue - drv->lastfield) < 1e-5) { - ParPrintf(drv, -1, "IPS: we are already at field %f", drv->lastfield); + ParPrintf(drv, -1, "IPS: we are already at field %f", + drv->lastfield); if (drv->persmode) { - if (!drv->perswitch) goto finish; + if (!drv->perswitch) + goto finish; goto target_reached; } else { - if (drv->perswitch) goto finish; + if (drv->perswitch) + goto finish; } } if (fabs(drv->current - drv->lastfield) < 1e-5) { goto switch_on; } - OxiSet(eab, "J", drv->lastfield, 3); /* set point */ - return __LINE__; case __LINE__: /**********************************/ + OxiSet(eab, "J", drv->lastfield, 3); /* set point */ + return __LINE__; + case __LINE__: /**********************************/ EaseWrite(eab, "A1"); - ParPrintf(drv, -1, "IPS: ramp to current for %f Tesla", drv->lastfield); - return __LINE__; case __LINE__: /**********************************/ + ParPrintf(drv, -1, "IPS: ramp to current for %f Tesla", + drv->lastfield); + return __LINE__; + case __LINE__: /**********************************/ drv->tim = time(NULL); - + stab1: EaseWrite(eab, "X"); - return __LINE__; case __LINE__: /**********************************/ - IpsStatus(drv); /* just check for errors */ - EaseWrite(eab, "R7"); /* read current (in Tesla) */ - return __LINE__; case __LINE__: /**********************************/ + return __LINE__; + case __LINE__: /**********************************/ + IpsStatus(drv); /* just check for errors */ + EaseWrite(eab, "R7"); /* read current (in Tesla) */ + return __LINE__; + case __LINE__: /**********************************/ drv->current = OxiGet(eab, 3, NULL, drv->current); ParLog(drv); - if (fabs(drv->current - drv->lastfield) > 1e-5) goto stab1; - + if (fabs(drv->current - drv->lastfield) > 1e-5) + goto stab1; + stab2: FsmWait(1); - return __LINE__; case __LINE__: /**********************************/ + return __LINE__; + case __LINE__: /**********************************/ EaseWrite(eab, "X"); - return __LINE__; case __LINE__: /**********************************/ + return __LINE__; + case __LINE__: /**********************************/ IpsStatus(drv); - if (time(NULL) < drv->tim + 10) goto stab2; /* stabilize */ - + if (time(NULL) < drv->tim + 10) + goto stab2; /* stabilize */ + switch_on: - if (drv->perswitch) goto wait_open; + if (drv->perswitch) + goto wait_open; if (drv->force == 2) { EaseWrite(eab, "H2"); } else { EaseWrite(eab, "H1"); } drv->force = 0; - return __LINE__; case __LINE__: /**********************************/ + return __LINE__; + case __LINE__: /**********************************/ drv->perswitch = 1; drv->swtim = time(NULL); - + wait_open: delay = drv->swtim + 30 - time(NULL); if (delay > 0) ParPrintf(drv, -1, "IPS: wait %d sec to open switch", delay); - + start_ramp: ParLog(drv); FsmWait(1); - return __LINE__; case __LINE__: /**********************************/ + return __LINE__; + case __LINE__: /**********************************/ EaseWrite(eab, "X"); - return __LINE__; case __LINE__: /**********************************/ - IpsStatus(drv); /* check for errors */ + return __LINE__; + case __LINE__: /**********************************/ + IpsStatus(drv); /* check for errors */ if (drv->heaterFault) { if (time(NULL) > drv->swtim + 3) { ParPrintf(drv, eError, "IPS heater fault"); @@ -389,130 +481,162 @@ static long IpsChangeField(long pc, void *object) { goto off_finish; } } - if (time(NULL) < drv->swtim + 30) goto start_ramp; /* wait */ + if (time(NULL) < drv->swtim + 30) + goto start_ramp; /* wait */ OxiSet(eab, "T", drv->ramp, 3); - return __LINE__; case __LINE__: /**********************************/ - OxiSet(eab, "J", drv->current, 3); /* put set point to actual value */ - return __LINE__; case __LINE__: /**********************************/ - EaseWrite(eab, "A1"); /* go to setpoint (do not yet run) */ - return __LINE__; case __LINE__: /**********************************/ + return __LINE__; + case __LINE__: /**********************************/ + OxiSet(eab, "J", drv->current, 3); /* put set point to actual value */ + return __LINE__; + case __LINE__: /**********************************/ + EaseWrite(eab, "A1"); /* go to setpoint (do not yet run) */ + return __LINE__; + case __LINE__: /**********************************/ ParPrintf(drv, -1, "IPS: ramp to %f Tesla", drv->d.targetValue); - + ramping: ParLog(drv); FsmWait(1); - return __LINE__; case __LINE__: /**********************************/ - EaseWrite(eab, "R7"); /* read "current" in Tesla */ - return __LINE__; case __LINE__: /**********************************/ - IpsSetField(drv, OxiGet(eab, 3, NULL, drv->current)); /* set drv->current and callback */ + return __LINE__; + case __LINE__: /**********************************/ + EaseWrite(eab, "R7"); /* read "current" in Tesla */ + return __LINE__; + case __LINE__: /**********************************/ + IpsSetField(drv, OxiGet(eab, 3, NULL, drv->current)); /* set drv->current and callback */ EaseWrite(eab, "X"); - return __LINE__; case __LINE__: /**********************************/ - IpsStatus(drv); /* just check for errors */ - EaseWrite(eab, "R9"); /* read back ramp rate (may be sweep limited) */ - return __LINE__; case __LINE__: /**********************************/ - ramp=OxiGet(eab, 3, NULL, drv->ramp); - step=ramp/6; /* step = ramp * 10 sec */ - if (step < 0.001) step=0.001; + return __LINE__; + case __LINE__: /**********************************/ + IpsStatus(drv); /* just check for errors */ + EaseWrite(eab, "R9"); /* read back ramp rate (may be sweep limited) */ + return __LINE__; + case __LINE__: /**********************************/ + ramp = OxiGet(eab, 3, NULL, drv->ramp); + step = ramp / 6; /* step = ramp * 10 sec */ + if (step < 0.001) + step = 0.001; if (drv->d.targetValue > drv->current + step) { - fld=drv->current + step; + fld = drv->current + step; } else if (drv->d.targetValue < drv->current - step) { - fld=drv->current - step; + fld = drv->current - step; } else { - fld=drv->d.targetValue; - if (fabs(drv->current - drv->d.targetValue) < 1e-5) goto target_reached; + fld = drv->d.targetValue; + if (fabs(drv->current - drv->d.targetValue) < 1e-5) + goto target_reached; } OxiSet(eab, "J", fld, 3); - return __LINE__; case __LINE__: /**********************************/ + return __LINE__; + case __LINE__: /**********************************/ goto ramping; - + target_reached: drv->d.hwstate = HWIdle; - drv->d.eMode = EVMonitor; /* we are at field, drive has finished */ - if (!drv->persmode) goto hold_finish; + drv->d.eMode = EVMonitor; /* we are at field, drive has finished */ + if (!drv->persmode) + goto hold_finish; /* but we continue in the background */ drv->tim = time(NULL); stab3: ParLog(drv); FsmWait(1); - return __LINE__; case __LINE__: /**********************************/ + return __LINE__; + case __LINE__: /**********************************/ EaseWrite(eab, "X"); - return __LINE__; case __LINE__: /**********************************/ - IpsStatus(drv); /* just check for errors */ - if (time(NULL) < drv->tim + 10) goto stab3; /* stabilize */ - - EaseWrite(eab, "A0"); /* hold */ - return __LINE__; case __LINE__: /**********************************/ + return __LINE__; + case __LINE__: /**********************************/ + IpsStatus(drv); /* just check for errors */ + if (time(NULL) < drv->tim + 10) + goto stab3; /* stabilize */ + + EaseWrite(eab, "A0"); /* hold */ + return __LINE__; + case __LINE__: /**********************************/ EaseWrite(eab, "H0"); drv->perswitch = 0; drv->swtim = time(NULL); drv->lastfield = drv->current; EaseParHasChanged(); - return __LINE__; case __LINE__: /**********************************/ + return __LINE__; + case __LINE__: /**********************************/ ParPrintf(drv, -1, "IPS: wait 30 sec to close switch"); - + wait_closed: ParLog(drv); FsmWait(1); - return __LINE__; case __LINE__: /**********************************/ - EaseWrite(eab, "R18"); /* read persistent field in Tesla */ - return __LINE__; case __LINE__: /**********************************/ + return __LINE__; + case __LINE__: /**********************************/ + EaseWrite(eab, "R18"); /* read persistent field in Tesla */ + return __LINE__; + case __LINE__: /**********************************/ fld = OxiGet(eab, 3, NULL, drv->current); if (fld != drv->lastfield) { - IpsSetField(drv, fld); /* set drv->current and callback */ + IpsSetField(drv, fld); /* set drv->current and callback */ drv->lastfield = fld; EaseParHasChanged(); } EaseWrite(eab, "X"); - return __LINE__; case __LINE__: /**********************************/ + return __LINE__; + case __LINE__: /**********************************/ IpsStatus(drv); - if (time(NULL) < drv->swtim + 30) goto wait_closed; /* wait */ - - if (drv->current == 0) goto finish; - EaseWrite(eab, "A2"); /* goto zero */ + if (time(NULL) < drv->swtim + 30) + goto wait_closed; /* wait */ + + if (drv->current == 0) + goto finish; + EaseWrite(eab, "A2"); /* goto zero */ ParPrintf(drv, -1, "IPS: ramp current to 0"); - return __LINE__; case __LINE__: /**********************************/ + return __LINE__; + case __LINE__: /**********************************/ goto finish; hold_finish: EaseWrite(eab, "A0"); - return __LINE__; case __LINE__: /**********************************/ + return __LINE__; + case __LINE__: /**********************************/ goto finish; - + off_finish: if (drv->perswitch) { drv->lastfield = drv->current; drv->swtim = time(NULL); } EaseWrite(eab, "H0"); - return __LINE__; case __LINE__: /**********************************/ - + return __LINE__; + case __LINE__: /**********************************/ + finish: EaseWrite(eab, "C0"); drv->remote = 0; drv->d.hwstate = HWIdle; - return __LINE__; case __LINE__: /**********************************/ - - return 0; } /* FSM END ********************************************/ + return __LINE__; + case __LINE__: /**********************************/ + + return 0; + } /* FSM END ******************************************* */ } + /*----------------------------------------------------------------------------*/ -static int IpsInit(SConnection *con, int argc, char *argv[], int dynamic) { +static int IpsInit(SConnection * con, int argc, char *argv[], int dynamic) +{ /* args: - MakeObject objectname ips - + MakeObject objectname ips + */ Ips *drv; drv = EaseMakeDriv(con, &ipsClass, argc, argv, dynamic, 7, - IpsParDef, OxiHandler, IpsStart, NULL, IpsRead, - IpsChangeField); - if (drv == NULL) return 0; + IpsParDef, OxiHandler, IpsStart, NULL, IpsRead, + IpsChangeField); + if (drv == NULL) + return 0; drv->d.maxwait = 999999; drv->d.tolerance = 0.001; return 1; } + /*----------------------------------------------------------------------------*/ -void IpsStartup(void) { +void IpsStartup(void) +{ ParMakeClass(&ipsClass, EaseDrivClass()); - MakeDriver("IPS", IpsInit, 0, "OI Power Supply"); + MakeDriver("IPS", IpsInit, 0, "OI Power Supply"); } diff --git a/itc4.c b/itc4.c index ae983c1..31e393c 100644 --- a/itc4.c +++ b/itc4.c @@ -53,229 +53,192 @@ #include "itc4.h" /*---------------------------------------------------------------------------*/ - int ITC4SetPar(pEVControl self, char *name, float fNew, SConnection *pCon) - { - int iRet; - - /* check authorsisation */ - if(!SCMatchRights(pCon,usUser)) - { - SCWrite(pCon,"ERROR: you are not authorised to change this parameter", - eError); - return 0; - } - - /* just catch those three names which we understand */ - if(strcmp(name,"sensor") == 0) - { - iRet = SetSensorITC4(self->pDriv,(int)fNew); - if(!iRet) - { - SCWrite(pCon,"ERROR: value out of range",eError); - return 0; - } - iRet = ConfigITC4(self->pDriv); - if(iRet != 1) - { - SCWrite(pCon,"ERROR: ITC4 configuration failed! ",eError); - SCWrite(pCon,"INFO: Probably comm problem, Retry!",eError); - return 0; - } - SCSendOK(pCon); - return 1; - } - else if(strcmp(name,"control") == 0) - { - iRet = SetControlITC4(self->pDriv,(int)fNew); - if(!iRet) - { - SCWrite(pCon,"ERROR: value out of range",eError); - return 0; - } - iRet = ConfigITC4(self->pDriv); - if(iRet != 1) - { - SCWrite(pCon,"ERROR: ITC4 configuration failed! ",eError); - SCWrite(pCon,"INFO: Probably comm problem, Retry!",eError); - return 0; - } - SCSendOK(pCon); - return 1; - } - else if(strcmp(name,"timeout") == 0) - { - iRet = SetTMOITC4(self->pDriv,(int)fNew); - if(!iRet) - { - SCWrite(pCon,"ERROR: value out of range",eError); - return 0; - } - iRet = ConfigITC4(self->pDriv); - if(iRet != 1) - { - SCWrite(pCon,"ERROR: ITC4 configuration failed! ",eError); - SCWrite(pCon,"INFO: Probably comm problem, Retry!",eError); - return 0; - } - SCSendOK(pCon); - return 1; - } - else if(strcmp(name,"divisor") == 0) - { - iRet = SetDivisorITC4(self->pDriv,fNew); - if(!iRet) - { - SCWrite(pCon,"ERROR: value out of range",eError); - return 0; - } - iRet = ConfigITC4(self->pDriv); - if(iRet != 1) - { - SCWrite(pCon,"ERROR: ITC4 configuration failed! ",eError); - SCWrite(pCon,"INFO: Probably comm problem, Retry!",eError); - return 0; - } - SCSendOK(pCon); - return 1; - } - else if(strcmp(name,"multiplicator") == 0) - { - iRet = SetMultITC4(self->pDriv,fNew); - if(!iRet) - { - SCWrite(pCon,"ERROR: value out of range",eError); - return 0; - } - iRet = ConfigITC4(self->pDriv); - if(iRet != 1) - { - SCWrite(pCon,"ERROR: ITC4 configuration failed! ",eError); - SCWrite(pCon,"INFO: Probably comm problem, Retry!",eError); - return 0; - } - SCSendOK(pCon); - return 1; - } - else - return EVCSetPar(self,name,fNew,pCon); +int ITC4SetPar(pEVControl self, char *name, float fNew, SConnection * pCon) +{ + int iRet; + + /* check authorsisation */ + if (!SCMatchRights(pCon, usUser)) { + SCWrite(pCon, "ERROR: you are not authorised to change this parameter", + eError); + return 0; } + + /* just catch those three names which we understand */ + if (strcmp(name, "sensor") == 0) { + iRet = SetSensorITC4(self->pDriv, (int) fNew); + if (!iRet) { + SCWrite(pCon, "ERROR: value out of range", eError); + return 0; + } + iRet = ConfigITC4(self->pDriv); + if (iRet != 1) { + SCWrite(pCon, "ERROR: ITC4 configuration failed! ", eError); + SCWrite(pCon, "INFO: Probably comm problem, Retry!", eError); + return 0; + } + SCSendOK(pCon); + return 1; + } else if (strcmp(name, "control") == 0) { + iRet = SetControlITC4(self->pDriv, (int) fNew); + if (!iRet) { + SCWrite(pCon, "ERROR: value out of range", eError); + return 0; + } + iRet = ConfigITC4(self->pDriv); + if (iRet != 1) { + SCWrite(pCon, "ERROR: ITC4 configuration failed! ", eError); + SCWrite(pCon, "INFO: Probably comm problem, Retry!", eError); + return 0; + } + SCSendOK(pCon); + return 1; + } else if (strcmp(name, "timeout") == 0) { + iRet = SetTMOITC4(self->pDriv, (int) fNew); + if (!iRet) { + SCWrite(pCon, "ERROR: value out of range", eError); + return 0; + } + iRet = ConfigITC4(self->pDriv); + if (iRet != 1) { + SCWrite(pCon, "ERROR: ITC4 configuration failed! ", eError); + SCWrite(pCon, "INFO: Probably comm problem, Retry!", eError); + return 0; + } + SCSendOK(pCon); + return 1; + } else if (strcmp(name, "divisor") == 0) { + iRet = SetDivisorITC4(self->pDriv, fNew); + if (!iRet) { + SCWrite(pCon, "ERROR: value out of range", eError); + return 0; + } + iRet = ConfigITC4(self->pDriv); + if (iRet != 1) { + SCWrite(pCon, "ERROR: ITC4 configuration failed! ", eError); + SCWrite(pCon, "INFO: Probably comm problem, Retry!", eError); + return 0; + } + SCSendOK(pCon); + return 1; + } else if (strcmp(name, "multiplicator") == 0) { + iRet = SetMultITC4(self->pDriv, fNew); + if (!iRet) { + SCWrite(pCon, "ERROR: value out of range", eError); + return 0; + } + iRet = ConfigITC4(self->pDriv); + if (iRet != 1) { + SCWrite(pCon, "ERROR: ITC4 configuration failed! ", eError); + SCWrite(pCon, "INFO: Probably comm problem, Retry!", eError); + return 0; + } + SCSendOK(pCon); + return 1; + } else + return EVCSetPar(self, name, fNew, pCon); +} + /*--------------------------------------------------------------------------*/ - int ITC4GetPar(pEVControl self, char *name, float *fNew) - { - int iRet; - float fDiv; - - /* just catch those two names which we understand */ - if(strcmp(name,"sensor") == 0) - { - iRet = GetSensorITC4(self->pDriv); - *fNew = (float)iRet; - return 1; - } - else if(strcmp(name,"control") == 0) - { - iRet = GetControlITC4(self->pDriv); - *fNew = (float)iRet; - return 1; - } - else if(strcmp(name,"timeout") == 0) - { - iRet = GetTMOITC4(self->pDriv); - *fNew = (float)iRet; - return 1; - } - else if(strcmp(name,"divisor") == 0) - { - fDiv = GetDivisorITC4(self->pDriv); - *fNew = fDiv; - return 1; - } - else if(strcmp(name,"multiplicator") == 0) - { - fDiv = GetMultITC4(self->pDriv); - *fNew = fDiv; - return 1; - } - else - return EVCGetPar(self,name,fNew); - } +int ITC4GetPar(pEVControl self, char *name, float *fNew) +{ + int iRet; + float fDiv; + + /* just catch those two names which we understand */ + if (strcmp(name, "sensor") == 0) { + iRet = GetSensorITC4(self->pDriv); + *fNew = (float) iRet; + return 1; + } else if (strcmp(name, "control") == 0) { + iRet = GetControlITC4(self->pDriv); + *fNew = (float) iRet; + return 1; + } else if (strcmp(name, "timeout") == 0) { + iRet = GetTMOITC4(self->pDriv); + *fNew = (float) iRet; + return 1; + } else if (strcmp(name, "divisor") == 0) { + fDiv = GetDivisorITC4(self->pDriv); + *fNew = fDiv; + return 1; + } else if (strcmp(name, "multiplicator") == 0) { + fDiv = GetMultITC4(self->pDriv); + *fNew = fDiv; + return 1; + } else + return EVCGetPar(self, name, fNew); +} + /*---------------------------------------------------------------------------*/ - int ITCList(pEVControl self, SConnection *pCon) - { - char pBueffel[132]; - int iRet; - - iRet = EVCList(self,pCon); - sprintf(pBueffel,"%s.sensor = %d\n",self->pName, - GetSensorITC4(self->pDriv)); - SCWrite(pCon,pBueffel,eValue); - sprintf(pBueffel,"%s.control = %d\n",self->pName, - GetControlITC4(self->pDriv)); - SCWrite(pCon,pBueffel,eValue); - sprintf(pBueffel,"%s.timeout = %d\n",self->pName, - GetTMOITC4(self->pDriv)); - SCWrite(pCon,pBueffel,eValue); - sprintf(pBueffel,"%s.divisor = %f\n",self->pName, - GetDivisorITC4(self->pDriv)); - SCWrite(pCon,pBueffel,eValue); - sprintf(pBueffel,"%s.multiplicator = %f\n",self->pName, - GetMultITC4(self->pDriv)); - SCWrite(pCon,pBueffel,eValue); - return iRet; - } +int ITCList(pEVControl self, SConnection * pCon) +{ + char pBueffel[132]; + int iRet; + + iRet = EVCList(self, pCon); + sprintf(pBueffel, "%s.sensor = %d\n", self->pName, + GetSensorITC4(self->pDriv)); + SCWrite(pCon, pBueffel, eValue); + sprintf(pBueffel, "%s.control = %d\n", self->pName, + GetControlITC4(self->pDriv)); + SCWrite(pCon, pBueffel, eValue); + sprintf(pBueffel, "%s.timeout = %d\n", self->pName, + GetTMOITC4(self->pDriv)); + SCWrite(pCon, pBueffel, eValue); + sprintf(pBueffel, "%s.divisor = %f\n", self->pName, + GetDivisorITC4(self->pDriv)); + SCWrite(pCon, pBueffel, eValue); + sprintf(pBueffel, "%s.multiplicator = %f\n", self->pName, + GetMultITC4(self->pDriv)); + SCWrite(pCon, pBueffel, eValue); + return iRet; +} + /*-------------------------------------------------------------------------*/ - int ITC4Wrapper(SConnection *pCon, SicsInterp *pSics, void *pData, - int argc, char *argv[]) - { - pEVControl self = NULL; - char pBueffel[256]; - int iRet; - double fNum; - float fVal; - - self = (pEVControl)pData; - assert(self); - assert(pCon); - assert(pSics); - - if(argc < 2) - { - return EVControlWrapper(pCon,pSics,pData,argc,argv); +int ITC4Wrapper(SConnection * pCon, SicsInterp * pSics, void *pData, + int argc, char *argv[]) +{ + pEVControl self = NULL; + char pBueffel[256]; + int iRet; + double fNum; + float fVal; + + self = (pEVControl) pData; + assert(self); + assert(pCon); + assert(pSics); + + if (argc < 2) { + return EVControlWrapper(pCon, pSics, pData, argc, argv); + } + + strtolower(argv[1]); + if ((strcmp(argv[1], "sensor") == 0) || (strcmp(argv[1], "control") == 0) + || (strcmp(argv[1], "timeout") == 0) + || (strcmp(argv[1], "divisor") == 0) + || (strcmp(argv[1], "multiplicator") == 0)) { + if (argc > 2) { /* set case */ + iRet = Tcl_GetDouble(pSics->pTcl, argv[2], &fNum); + if (iRet != TCL_OK) { + sprintf(pBueffel, "ERROR: expected number, got %s", argv[2]); + SCWrite(pCon, pBueffel, eError); + return 0; + } + return ITC4SetPar(self, argv[1], (float) fNum, pCon); + } else { /* get case */ + + iRet = ITC4GetPar(self, argv[1], &fVal); + sprintf(pBueffel, "%s.%s = %f\n", self->pName, argv[1], fVal); + SCWrite(pCon, pBueffel, eValue); + return 1; } - - strtolower(argv[1]); - if((strcmp(argv[1],"sensor") == 0) || (strcmp(argv[1],"control") == 0) || - (strcmp(argv[1],"timeout") == 0) || (strcmp(argv[1],"divisor") == 0) || - (strcmp(argv[1],"multiplicator") == 0) ) - { - if(argc > 2) /* set case */ - { - iRet = Tcl_GetDouble(pSics->pTcl,argv[2],&fNum); - if(iRet != TCL_OK) - { - sprintf(pBueffel,"ERROR: expected number, got %s",argv[2]); - SCWrite(pCon,pBueffel,eError); - return 0; - } - return ITC4SetPar(self,argv[1],(float)fNum,pCon); - } - else /* get case */ - { - iRet = ITC4GetPar(self,argv[1],&fVal); - sprintf(pBueffel,"%s.%s = %f\n",self->pName, - argv[1],fVal); - SCWrite(pCon,pBueffel,eValue); - return 1; - } - } - else if(strcmp(argv[1],"list") == 0) - { - return ITCList(self,pCon); - } - else - { - return EVControlWrapper(pCon,pSics,pData,argc,argv); - } - /* not reached */ - return 0; - } + } else if (strcmp(argv[1], "list") == 0) { + return ITCList(self, pCon); + } else { + return EVControlWrapper(pCon, pSics, pData, argc, argv); + } + /* not reached */ + return 0; +} diff --git a/itc4.h b/itc4.h index 1068ef3..0f15a5a 100644 --- a/itc4.h +++ b/itc4.h @@ -15,29 +15,28 @@ #define SICSITC4 /*------------------------- The Driver ------------------------------------*/ - pEVDriver CreateITC4Driver(int argc, char *argv[]); - int ConfigITC4(pEVDriver self); - int SetSensorITC4(pEVDriver self, int iSensor); - int SetControlITC4(pEVDriver self, int iSensor); - int GetSensorITC4(pEVDriver self); - int GetControlITC4(pEVDriver self); - int SetDivisorITC4(pEVDriver self, float iSensor); - float GetDivisorITC4(pEVDriver self); - int SetMultITC4(pEVDriver self, float iSensor); - float GetMultITC4(pEVDriver self); - int SetTMOITC4(pEVDriver self, int iSensor); - int GetTMOITC4(pEVDriver self); +pEVDriver CreateITC4Driver(int argc, char *argv[]); +int ConfigITC4(pEVDriver self); +int SetSensorITC4(pEVDriver self, int iSensor); +int SetControlITC4(pEVDriver self, int iSensor); +int GetSensorITC4(pEVDriver self); +int GetControlITC4(pEVDriver self); +int SetDivisorITC4(pEVDriver self, float iSensor); +float GetDivisorITC4(pEVDriver self); +int SetMultITC4(pEVDriver self, float iSensor); +float GetMultITC4(pEVDriver self); +int SetTMOITC4(pEVDriver self, int iSensor); +int GetTMOITC4(pEVDriver self); /*------------------------- The ITC4 object ------------------------------*/ - int ITC4Wrapper(SConnection *pCon, SicsInterp *pSics, void *pData, - int argc, char *argv[]); - int ITC4SetPar(pEVControl self, char *name, float fNew, - SConnection *pCon); - int ITC4GetPar(pEVControl self, char *name, float *fVal); - int ITCList(pEVControl self, SConnection *pCon); +int ITC4Wrapper(SConnection * pCon, SicsInterp * pSics, void *pData, + int argc, char *argv[]); +int ITC4SetPar(pEVControl self, char *name, float fNew, + SConnection * pCon); +int ITC4GetPar(pEVControl self, char *name, float *fVal); +int ITCList(pEVControl self, SConnection * pCon); -#endif - +#endif diff --git a/itc4driv.c b/itc4driv.c index ff275ed..e4a4c14 100644 --- a/itc4driv.c +++ b/itc4driv.c @@ -54,415 +54,412 @@ #define SHITTYVALUE -777 /*------------------------- The Driver ------------------------------------*/ - pEVDriver CreateITC4Driver(int argc, char *argv[]); - int ConfigITC4(pEVDriver self); - - +pEVDriver CreateITC4Driver(int argc, char *argv[]); +int ConfigITC4(pEVDriver self); + + /*-----------------------------------------------------------------------*/ - typedef struct { - pITC4 pData; - char *pHost; - int iPort; - int iChannel; - int iControl; - float fDiv; - float fMult; - int iRead; - int iTmo; - int iLastError; - } ITC4Driv, *pITC4Driv; +typedef struct { + pITC4 pData; + char *pHost; + int iPort; + int iChannel; + int iControl; + float fDiv; + float fMult; + int iRead; + int iTmo; + int iLastError; +} ITC4Driv, *pITC4Driv; /*----------------------------------------------------------------------------*/ - static int GetITC4Pos(pEVDriver self, float *fPos) - { - pITC4Driv pMe = NULL; - int iRet; - - assert(self); - pMe = (pITC4Driv)self->pPrivate; - assert(pMe); - - iRet = ITC4_Read(&pMe->pData,fPos); - if(iRet != 1 ) - { - pMe->iLastError = iRet; - return 0; - } - if( (*fPos < 0) || (*fPos > 10000) ) - { - *fPos = -999.; - pMe->iLastError = SHITTYVALUE; - return 0; - } - return 1; - } -/*----------------------------------------------------------------------------*/ - static int ITC4Run(pEVDriver self, float fVal) - { - pITC4Driv pMe = NULL; - int iRet; - - assert(self); - pMe = (pITC4Driv )self->pPrivate; - assert(pMe); +static int GetITC4Pos(pEVDriver self, float *fPos) +{ + pITC4Driv pMe = NULL; + int iRet; - iRet = ITC4_Set(&pMe->pData,fVal); - if(iRet != 1) - { - pMe->iLastError = iRet; - return 0; - } - return 1; - } -/*--------------------------------------------------------------------------*/ - static int ITC4Error(pEVDriver self, int *iCode, char *error, int iErrLen) - { - pITC4Driv pMe = NULL; - - assert(self); - pMe = (pITC4Driv)self->pPrivate; - assert(pMe); + assert(self); + pMe = (pITC4Driv) self->pPrivate; + assert(pMe); - *iCode = pMe->iLastError; - if(pMe->iLastError == SHITTYVALUE) - { - strncpy(error,"Invalid temperature returned form ITC4, check sensor",iErrLen); - } - else - { - ITC4_ErrorTxt(&pMe->pData,pMe->iLastError,error,iErrLen); - } - return 1; + iRet = ITC4_Read(&pMe->pData, fPos); + if (iRet != 1) { + pMe->iLastError = iRet; + return 0; } + if ((*fPos < 0) || (*fPos > 10000)) { + *fPos = -999.; + pMe->iLastError = SHITTYVALUE; + return 0; + } + return 1; +} + +/*----------------------------------------------------------------------------*/ +static int ITC4Run(pEVDriver self, float fVal) +{ + pITC4Driv pMe = NULL; + int iRet; + + assert(self); + pMe = (pITC4Driv) self->pPrivate; + assert(pMe); + + iRet = ITC4_Set(&pMe->pData, fVal); + if (iRet != 1) { + pMe->iLastError = iRet; + return 0; + } + return 1; +} + /*--------------------------------------------------------------------------*/ - static int ITC4Send(pEVDriver self, char *pCommand, char *pReply, int iLen) - { - pITC4Driv pMe = NULL; - int iRet; - - assert(self); - pMe = (pITC4Driv )self->pPrivate; - assert(pMe); +static int ITC4Error(pEVDriver self, int *iCode, char *error, int iErrLen) +{ + pITC4Driv pMe = NULL; - iRet = ITC4_Send(&pMe->pData,pCommand, pReply,iLen); - if(iRet != 1) - { - pMe->iLastError = iRet; - return 0; - } - return 1; + assert(self); + pMe = (pITC4Driv) self->pPrivate; + assert(pMe); + + *iCode = pMe->iLastError; + if (pMe->iLastError == SHITTYVALUE) { + strncpy(error, "Invalid temperature returned form ITC4, check sensor", + iErrLen); + } else { + ITC4_ErrorTxt(&pMe->pData, pMe->iLastError, error, iErrLen); + } + return 1; +} - } /*--------------------------------------------------------------------------*/ - static int ITC4Init(pEVDriver self) - { - pITC4Driv pMe = NULL; - int iRet; - - assert(self); - pMe = (pITC4Driv )self->pPrivate; - assert(pMe); +static int ITC4Send(pEVDriver self, char *pCommand, char *pReply, int iLen) +{ + pITC4Driv pMe = NULL; + int iRet; + + assert(self); + pMe = (pITC4Driv) self->pPrivate; + assert(pMe); + + iRet = ITC4_Send(&pMe->pData, pCommand, pReply, iLen); + if (iRet != 1) { + pMe->iLastError = iRet; + return 0; + } + return 1; + +} - pMe->pData = NULL; - iRet = ITC4_Open(&pMe->pData, pMe->pHost, pMe->iPort, pMe->iChannel,0); - if(iRet != 1) - { - if(iRet == ITC4__NOITC) - { - return -1; - } - else - { - pMe->iLastError = iRet; - return 0; - } - } - return 1; - } /*--------------------------------------------------------------------------*/ - static int ITC4Close(pEVDriver self) - { - pITC4Driv pMe = NULL; - int iRet; - - assert(self); - pMe = (pITC4Driv )self->pPrivate; - assert(pMe); +static int ITC4Init(pEVDriver self) +{ + pITC4Driv pMe = NULL; + int iRet; + + assert(self); + pMe = (pITC4Driv) self->pPrivate; + assert(pMe); + + pMe->pData = NULL; + iRet = ITC4_Open(&pMe->pData, pMe->pHost, pMe->iPort, pMe->iChannel, 0); + if (iRet != 1) { + if (iRet == ITC4__NOITC) { + return -1; + } else { + pMe->iLastError = iRet; + return 0; + } + } + return 1; +} + +/*--------------------------------------------------------------------------*/ +static int ITC4Close(pEVDriver self) +{ + pITC4Driv pMe = NULL; + int iRet; + + assert(self); + pMe = (pITC4Driv) self->pPrivate; + assert(pMe); + + ITC4_Close(&pMe->pData); + return 1; +} - ITC4_Close(&pMe->pData); - return 1; - } /*---------------------------------------------------------------------------*/ - static int ITC4Fix(pEVDriver self, int iError) - { - pITC4Driv pMe = NULL; - int iRet; - - assert(self); - pMe = (pITC4Driv )self->pPrivate; - assert(pMe); +static int ITC4Fix(pEVDriver self, int iError) +{ + pITC4Driv pMe = NULL; + int iRet; - switch(iError) - { - /* network errors */ - case EL734__BAD_FLUSH: - case EL734__BAD_RECV: - case EL734__BAD_RECV_NET: - case EL734__BAD_RECV_UNKN: - case EL734__BAD_RECVLEN: - case EL734__BAD_RECV1: - case EL734__BAD_RECV1_PIPE: - case EL734__BAD_RNG: - case EL734__BAD_SEND: - case EL734__BAD_SEND_PIPE: - case EL734__BAD_SEND_NET: - case EL734__BAD_SEND_UNKN: - case EL734__BAD_SENDLEN: - ITC4Close(self); - iRet = ITC4Init(self); - if(iRet) - { - return DEVREDO; - } - else - { - return DEVFAULT; - } - break; - /* handable protocoll errors */ - case EL734__BAD_TMO: - return DEVREDO; - break; - case -501: /* Bad_COM */ - return DEVREDO; - case -504: /* Badly formatted */ - return DEVREDO; - default: - return DEVFAULT; - break; - } - return DEVFAULT; + assert(self); + pMe = (pITC4Driv) self->pPrivate; + assert(pMe); + + switch (iError) { + /* network errors */ + case EL734__BAD_FLUSH: + case EL734__BAD_RECV: + case EL734__BAD_RECV_NET: + case EL734__BAD_RECV_UNKN: + case EL734__BAD_RECVLEN: + case EL734__BAD_RECV1: + case EL734__BAD_RECV1_PIPE: + case EL734__BAD_RNG: + case EL734__BAD_SEND: + case EL734__BAD_SEND_PIPE: + case EL734__BAD_SEND_NET: + case EL734__BAD_SEND_UNKN: + case EL734__BAD_SENDLEN: + ITC4Close(self); + iRet = ITC4Init(self); + if (iRet) { + return DEVREDO; + } else { + return DEVFAULT; + } + break; + /* handable protocoll errors */ + case EL734__BAD_TMO: + return DEVREDO; + break; + case -501: /* Bad_COM */ + return DEVREDO; + case -504: /* Badly formatted */ + return DEVREDO; + default: + return DEVFAULT; + break; } - + return DEVFAULT; +} + /*--------------------------------------------------------------------------*/ - static int ITC4Halt(pEVDriver *self) - { - assert(self); - - return 1; - } +static int ITC4Halt(pEVDriver * self) +{ + assert(self); + + return 1; +} + /*------------------------------------------------------------------------*/ - void KillITC4(void *pData) - { - pITC4Driv pMe = NULL; - - pMe = (pITC4Driv)pData; - assert(pMe); - - if(pMe->pHost) - { - free(pMe->pHost); - } - free(pMe); - } +void KillITC4(void *pData) +{ + pITC4Driv pMe = NULL; + + pMe = (pITC4Driv) pData; + assert(pMe); + + if (pMe->pHost) { + free(pMe->pHost); + } + free(pMe); +} + /*------------------------------------------------------------------------*/ - pEVDriver CreateITC4Driver(int argc, char *argv[]) - { - pEVDriver pNew = NULL; - pITC4Driv pSim = NULL; - - /* check for arguments */ - if(argc < 3) - { - return NULL; - } - - pNew = CreateEVDriver(argc,argv); - pSim = (pITC4Driv)malloc(sizeof(ITC4Driv)); - memset(pSim,0,sizeof(ITC4Driv)); - if(!pNew || !pSim) - { - return NULL; - } - pNew->pPrivate = pSim; - pNew->KillPrivate = KillITC4; - - /* initalise pITC4Driver */ - pSim->iControl = 1; - pSim->iRead = 1; - pSim->iLastError = 0; - pSim->iTmo = 10; - pSim->fDiv = 10.; - pSim->fMult = 10; - pSim->pHost = strdup(argv[0]); - pSim->iPort = atoi(argv[1]); - pSim->iChannel = atoi(argv[2]); - - - /* initialise function pointers */ - pNew->SetValue = ITC4Run; - pNew->GetValue = GetITC4Pos; - pNew->Send = ITC4Send; - pNew->GetError = ITC4Error; - pNew->TryFixIt = ITC4Fix; - pNew->Init = ITC4Init; - pNew->Close = ITC4Close; - - return pNew; - } +pEVDriver CreateITC4Driver(int argc, char *argv[]) +{ + pEVDriver pNew = NULL; + pITC4Driv pSim = NULL; + + /* check for arguments */ + if (argc < 3) { + return NULL; + } + + pNew = CreateEVDriver(argc, argv); + pSim = (pITC4Driv) malloc(sizeof(ITC4Driv)); + memset(pSim, 0, sizeof(ITC4Driv)); + if (!pNew || !pSim) { + return NULL; + } + pNew->pPrivate = pSim; + pNew->KillPrivate = KillITC4; + + /* initalise pITC4Driver */ + pSim->iControl = 1; + pSim->iRead = 1; + pSim->iLastError = 0; + pSim->iTmo = 10; + pSim->fDiv = 10.; + pSim->fMult = 10; + pSim->pHost = strdup(argv[0]); + pSim->iPort = atoi(argv[1]); + pSim->iChannel = atoi(argv[2]); + + + /* initialise function pointers */ + pNew->SetValue = ITC4Run; + pNew->GetValue = GetITC4Pos; + pNew->Send = ITC4Send; + pNew->GetError = ITC4Error; + pNew->TryFixIt = ITC4Fix; + pNew->Init = ITC4Init; + pNew->Close = ITC4Close; + + return pNew; +} + /*--------------------------------------------------------------------------*/ - int ConfigITC4(pEVDriver self) - { - pITC4Driv pMe = NULL; - int iRet; - - assert(self); - pMe = (pITC4Driv )self->pPrivate; - assert(pMe); +int ConfigITC4(pEVDriver self) +{ + pITC4Driv pMe = NULL; + int iRet; - iRet = ITC4_Config(&pMe->pData, pMe->iTmo, pMe->iRead, - pMe->iControl,pMe->fDiv,pMe->fMult); - if(iRet < 0) - { - pMe->iLastError = iRet; - return 0; - } - return 1; + assert(self); + pMe = (pITC4Driv) self->pPrivate; + assert(pMe); + + iRet = ITC4_Config(&pMe->pData, pMe->iTmo, pMe->iRead, + pMe->iControl, pMe->fDiv, pMe->fMult); + if (iRet < 0) { + pMe->iLastError = iRet; + return 0; } + return 1; +} + /*-------------------------------------------------------------------------*/ - int SetSensorITC4(pEVDriver self, int iSensor) - { - pITC4Driv pMe = NULL; - int iRet; - - assert(self); - pMe = (pITC4Driv )self->pPrivate; - assert(pMe); +int SetSensorITC4(pEVDriver self, int iSensor) +{ + pITC4Driv pMe = NULL; + int iRet; - if( (iSensor < 1) || (iSensor > 4) ) - { - return 0; - } - pMe->iRead = iSensor; - return 1; + assert(self); + pMe = (pITC4Driv) self->pPrivate; + assert(pMe); + + if ((iSensor < 1) || (iSensor > 4)) { + return 0; } + pMe->iRead = iSensor; + return 1; +} + /*-------------------------------------------------------------------------*/ - int SetControlITC4(pEVDriver self, int iSensor) - { - pITC4Driv pMe = NULL; - int iRet; - - assert(self); - pMe = (pITC4Driv )self->pPrivate; - assert(pMe); +int SetControlITC4(pEVDriver self, int iSensor) +{ + pITC4Driv pMe = NULL; + int iRet; - if( (iSensor < 1) || (iSensor > 4) ) - { - return 0; - } - pMe->iControl = iSensor; - return 1; + assert(self); + pMe = (pITC4Driv) self->pPrivate; + assert(pMe); + + if ((iSensor < 1) || (iSensor > 4)) { + return 0; } + pMe->iControl = iSensor; + return 1; +} + /*-------------------------------------------------------------------------*/ - int SetTMOITC4(pEVDriver self, int iSensor) - { - pITC4Driv pMe = NULL; - int iRet; - - assert(self); - pMe = (pITC4Driv )self->pPrivate; - assert(pMe); +int SetTMOITC4(pEVDriver self, int iSensor) +{ + pITC4Driv pMe = NULL; + int iRet; - if(iSensor < 10) - { - return 0; - } - pMe->iTmo = iSensor; - return 1; + assert(self); + pMe = (pITC4Driv) self->pPrivate; + assert(pMe); + + if (iSensor < 10) { + return 0; } + pMe->iTmo = iSensor; + return 1; +} + /*-------------------------------------------------------------------------*/ - int GetControlITC4(pEVDriver self) - { - pITC4Driv pMe = NULL; - int iRet; - - assert(self); - pMe = (pITC4Driv )self->pPrivate; - assert(pMe); +int GetControlITC4(pEVDriver self) +{ + pITC4Driv pMe = NULL; + int iRet; + + assert(self); + pMe = (pITC4Driv) self->pPrivate; + assert(pMe); + + return pMe->iControl; +} - return pMe->iControl; - } /*-------------------------------------------------------------------------*/ - int GetSensorITC4(pEVDriver self) - { - pITC4Driv pMe = NULL; - int iRet; - - assert(self); - pMe = (pITC4Driv )self->pPrivate; - assert(pMe); +int GetSensorITC4(pEVDriver self) +{ + pITC4Driv pMe = NULL; + int iRet; + + assert(self); + pMe = (pITC4Driv) self->pPrivate; + assert(pMe); + + return pMe->iRead; +} - return pMe->iRead; - } /*-------------------------------------------------------------------------*/ - int GetTMOITC4(pEVDriver self) - { - pITC4Driv pMe = NULL; - int iRet; - - assert(self); - pMe = (pITC4Driv )self->pPrivate; - assert(pMe); +int GetTMOITC4(pEVDriver self) +{ + pITC4Driv pMe = NULL; + int iRet; + + assert(self); + pMe = (pITC4Driv) self->pPrivate; + assert(pMe); + + return pMe->iTmo; +} - return pMe->iTmo; - } /*-------------------------------------------------------------------------*/ - float GetDivisorITC4(pEVDriver self) - { - pITC4Driv pMe = NULL; - int iRet; - - assert(self); - pMe = (pITC4Driv )self->pPrivate; - assert(pMe); +float GetDivisorITC4(pEVDriver self) +{ + pITC4Driv pMe = NULL; + int iRet; + + assert(self); + pMe = (pITC4Driv) self->pPrivate; + assert(pMe); + + return pMe->fDiv; +} - return pMe->fDiv; - } /*--------------------------------------------------------------------------*/ - int SetDivisorITC4(pEVDriver self, float fDiv) - { - pITC4Driv pMe = NULL; - int iRet; - - assert(self); - pMe = (pITC4Driv )self->pPrivate; - assert(pMe); +int SetDivisorITC4(pEVDriver self, float fDiv) +{ + pITC4Driv pMe = NULL; + int iRet; + + assert(self); + pMe = (pITC4Driv) self->pPrivate; + assert(pMe); + + pMe->fDiv = fDiv; + return 1; +} - pMe->fDiv = fDiv; - return 1; - } /*-------------------------------------------------------------------------*/ - float GetMultITC4(pEVDriver self) - { - pITC4Driv pMe = NULL; - int iRet; - - assert(self); - pMe = (pITC4Driv )self->pPrivate; - assert(pMe); +float GetMultITC4(pEVDriver self) +{ + pITC4Driv pMe = NULL; + int iRet; + + assert(self); + pMe = (pITC4Driv) self->pPrivate; + assert(pMe); + + return pMe->fMult; +} - return pMe->fMult; - } /*--------------------------------------------------------------------------*/ - int SetMultITC4(pEVDriver self, float fDiv) - { - pITC4Driv pMe = NULL; - int iRet; - - assert(self); - pMe = (pITC4Driv )self->pPrivate; - assert(pMe); +int SetMultITC4(pEVDriver self, float fDiv) +{ + pITC4Driv pMe = NULL; + int iRet; - pMe->fMult = fDiv; - return 1; - } - + assert(self); + pMe = (pITC4Driv) self->pPrivate; + assert(pMe); + + pMe->fMult = fDiv; + return 1; +} diff --git a/itcdriv.c b/itcdriv.c index 522c505..9275d34 100644 --- a/itcdriv.c +++ b/itcdriv.c @@ -42,19 +42,19 @@ Markus Zolliker, May 2005 typedef struct { EaseDriv d; - float t[4]; /* temperatures (0 is set point) */ - int dig[4]; /* format for these */ + float t[4]; /* temperatures (0 is set point) */ + int dig[4]; /* format for these */ float htr; float gas; float autoGasLimit; float setGas; - float travelTime; /* travel time for needle valve [sec/100%] */ - /* control parameters: for ITC / for TESLATRON */ - float prop; /* proportional value / for slow loop [mbar/K] */ - float integ; /* integration time / for slow loop [sec] */ - float deriv; /* deriv. time / int. for pressure [sec] */ - float prop2; /* TESLATRON only: prop. for pressure [%/mbar] */ - float lambdaTarget; /* TESLATRON only: lambda stage target temperature */ + float travelTime; /* travel time for needle valve [sec/100%] */ + /* control parameters: for ITC / for TESLATRON */ + float prop; /* proportional value / for slow loop [mbar/K] */ + float integ; /* integration time / for slow loop [sec] */ + float deriv; /* deriv. time / int. for pressure [sec] */ + float prop2; /* TESLATRON only: prop. for pressure [%/mbar] */ + float lambdaTarget; /* TESLATRON only: lambda stage target temperature */ float power; float resist; float htrVolt; @@ -68,8 +68,8 @@ typedef struct { int gasMode; int htrMode; int remote; - int h; /* actual heater channel */ - int a; /* actual auto mode */ + int h; /* actual heater channel */ + int a; /* actual auto mode */ time_t lastCtrl; float lastTdiff, lastPdiff; } Itc; @@ -77,26 +77,28 @@ typedef struct { static ParClass itcClass = { "ITC", sizeof(Itc) }; /*----------------------------------------------------------------------------*/ -static void ItcParDef(void *object) { +static void ItcParDef(void *object) +{ Itc *drv = ParCast(&itcClass, object); EaseBase *eab = object; - char fmt[8]=""; + char fmt[8] = ""; int i; - static char *ti[4] = {"setp","t1","t2","t3"}; - static char *modeList[]={"off", "manual", "auto", NULL }; - static char *progressList[]={"off", "cooling", "ok", NULL }; - static char *pidList[]={"default", "manual", "auto", NULL }; - + static char *ti[4] = { "setp", "t1", "t2", "t3" }; + static char *modeList[] = { "off", "manual", "auto", NULL }; + static char *progressList[] = { "off", "cooling", "ok", NULL }; + static char *pidList[] = { "default", "manual", "auto", NULL }; + ParName("sampleChan"); - if (eab->syntax != TESLATRON) ParAccess(usUser); + if (eab->syntax != TESLATRON) + ParAccess(usUser); ParInt(&drv->sampleChan, 1); if (ParActionIs(PAR_SET) > 0) { if (drv->sampleChan < 1 || drv->sampleChan > 3) { drv->sampleChan = 1; } } - + if (eab->syntax != TESLATRON) { ParName("controlChan"); ParAccess(usUser); @@ -107,7 +109,7 @@ static void ItcParDef(void *object) { } } } - + ParName(""); if (eab->syntax == TESLATRON) { ParTail("mbar"); @@ -122,11 +124,20 @@ static void ItcParDef(void *object) { } ParFmt(fmt); ParFloat(&drv->t[drv->sampleChan], PAR_NAN); - - ParName("dig1"); ParAccess(usUser); ParLogAs(NULL); ParInt(&drv->dig[1], -1); - ParName("dig2"); ParAccess(usUser); ParLogAs(NULL); ParInt(&drv->dig[2], -1); - ParName("dig3"); ParAccess(usUser); ParLogAs(NULL); ParInt(&drv->dig[3], -1); - + + ParName("dig1"); + ParAccess(usUser); + ParLogAs(NULL); + ParInt(&drv->dig[1], -1); + ParName("dig2"); + ParAccess(usUser); + ParLogAs(NULL); + ParInt(&drv->dig[2], -1); + ParName("dig3"); + ParAccess(usUser); + ParLogAs(NULL); + ParInt(&drv->dig[3], -1); + if (eab->syntax != TESLATRON) { ParName(ti[0]); if (drv->controlChan != 0) { @@ -141,9 +152,9 @@ static void ItcParDef(void *object) { ParTail("K"); ParFloat(&drv->t[0], PAR_NAN); } - - for (i=1; i<=3; i++) { - + + for (i = 1; i <= 3; i++) { + ParName(ti[i]); if (drv->dig[i] >= 0 && drv->sampleChan != i) { snprintf(fmt, sizeof fmt, "%%.%df", drv->dig[i]); @@ -153,7 +164,7 @@ static void ItcParDef(void *object) { ParList(""); } ParFloat(&drv->t[i], PAR_NAN); - + } if (eab->syntax != TESLATRON) { @@ -161,17 +172,20 @@ static void ItcParDef(void *object) { if (drv->controlChan == 0 && drv->htr == 0) { ParList(""); } - ParEnum(modeList); ParSave(1); + ParEnum(modeList); + ParSave(1); ParInt(&drv->htrMode, 2); - + ParName("htr"); - ParFmt("%.1f"); ParTail("%"); + ParFmt("%.1f"); + ParTail("%"); ParSave(1); EaseUpdate(ITC_SETHTR); ParFloat(&drv->htr, PAR_NAN); ParName("gasMode"); - ParAccess(usUser); ParEnum(modeList); + ParAccess(usUser); + ParEnum(modeList); ParList(NULL); ParInt(&drv->gasMode, 1); @@ -180,61 +194,86 @@ static void ItcParDef(void *object) { } else { ParName("progress"); - ParAccess(usUser); ParEnum(progressList); - ParList(NULL); ParSave(1); + ParAccess(usUser); + ParEnum(progressList); + ParList(NULL); + ParSave(1); ParInt(&drv->gasMode, 0); } - + ParName("gas"); - ParFmt("%.1f"); ParTail("%"); + ParFmt("%.1f"); + ParTail("%"); if (drv->gasMode < 1) { ParList(""); } ParFloat(&drv->gas, PAR_NAN); - + ParName("setGas"); - ParFmt("%.1f"); ParTail("%"); + ParFmt("%.1f"); + ParTail("%"); if (drv->gasMode < 1) { ParList(""); } - EaseUpdate(ITC_SETGAS); ParSave(1); - if (drv->setGas > 99.9) drv->setGas = 99.9; - if (drv->setGas < 0) drv->setGas = 0; + EaseUpdate(ITC_SETGAS); + ParSave(1); + if (drv->setGas > 99.9) + drv->setGas = 99.9; + if (drv->setGas < 0) + drv->setGas = 0; ParFloat(&drv->setGas, 20.0); - - ParName("travelTime"); ParFmt("%.0f"); ParTail("sec"); + + ParName("travelTime"); + ParFmt("%.0f"); + ParTail("sec"); ParList(""); - ParAccess(usUser); ParSave(1); + ParAccess(usUser); + ParSave(1); ParFloat(&drv->travelTime, 100.0); if (eab->syntax != TESLATRON) { ParName("autoGasLimit"); - ParAccess(usUser); ParFmt("%.1f"); ParTail("K"); ParSave(1); - if (drv->gasMode != 2) ParList(""); + ParAccess(usUser); + ParFmt("%.1f"); + ParTail("K"); + ParSave(1); + if (drv->gasMode != 2) + ParList(""); ParFloat(&drv->autoGasLimit, 3.0); - + ParName("pidMode"); ParEnum(pidList); - EaseUpdate(ITC_PIDMODE); ParSave(1); + EaseUpdate(ITC_PIDMODE); + ParSave(1); ParInt(&drv->pidMode, 0); - - ParName("prop"); ParFmt("%.3f"); ParTail("K"); - if (drv->pidMode == 1) ParList(""); + + ParName("prop"); + ParFmt("%.3f"); + ParTail("K"); + if (drv->pidMode == 1) + ParList(""); EaseUpdate(ITC_PROP); ParFloat(&drv->prop, PAR_NAN); - ParName("int"); ParFmt("%.1f"); ParTail("min"); - if (drv->pidMode == 1) ParList(""); + ParName("int"); + ParFmt("%.1f"); + ParTail("min"); + if (drv->pidMode == 1) + ParList(""); EaseUpdate(ITC_INTEG); ParFloat(&drv->integ, PAR_NAN); - ParName("deriv"); ParFmt("%.2f"); ParTail("min"); - if (drv->pidMode == 1) ParList(""); + ParName("deriv"); + ParFmt("%.2f"); + ParTail("min"); + if (drv->pidMode == 1) + ParList(""); EaseUpdate(ITC_DERIV); ParFloat(&drv->deriv, PAR_NAN); ParName("maxPower"); - ParFmt("%.4g"); ParTail("W"); + ParFmt("%.4g"); + ParTail("W"); EaseUpdate(ITC_MAXVOLT); ParFloat(&drv->maxPower, PAR_NAN); if (ParActionIs(PAR_SET) > 0) { @@ -246,7 +285,7 @@ static void ItcParDef(void *object) { drv->readMaxVolt = 0; if (drv->resist < 0) { drv->resist = 0; - } + } drv->maxVolt = sqrt(drv->maxPower * drv->resist); if (drv->maxVolt > 47.9) { drv->maxVolt = 47.9; @@ -255,42 +294,61 @@ static void ItcParDef(void *object) { } ParName("resist"); - ParFmt("%g"); ParAccess(usUser); - ParTail("Ohm"); ParList(""); + ParFmt("%g"); + ParAccess(usUser); + ParTail("Ohm"); + ParList(""); ParFloat(&drv->resist, 80.0); ParName("power"); - ParFmt("%g"); ParTail("W"); + ParFmt("%g"); + ParTail("W"); ParFloat(&drv->power, PAR_NAN); } else { - ParName("lambdaTarget"); ParFmt("%.2f"); ParTail("K"); - if (drv->gasMode == 0) ParList(""); - ParAccess(usUser); ParSave(1); + ParName("lambdaTarget"); + ParFmt("%.2f"); + ParTail("K"); + if (drv->gasMode == 0) + ParList(""); + ParAccess(usUser); + ParSave(1); ParFloat(&drv->lambdaTarget, 2.2); - ParName("prop"); ParFmt("%.1f"); ParTail("mbar/K"); + ParName("prop"); + ParFmt("%.1f"); + ParTail("mbar/K"); ParList(""); - ParAccess(usUser); ParSave(1); + ParAccess(usUser); + ParSave(1); ParFloat(&drv->prop, 300); - ParName("int"); ParFmt("%.1f"); ParTail("mbar/K/min"); + ParName("int"); + ParFmt("%.1f"); + ParTail("mbar/K/min"); ParList(""); - ParAccess(usUser); ParSave(1); + ParAccess(usUser); + ParSave(1); ParFloat(&drv->integ, 3.0); - ParName("prop2"); ParFmt("%.1f"); ParTail("%/mbar"); + ParName("prop2"); + ParFmt("%.1f"); + ParTail("%/mbar"); ParList(""); - ParAccess(usUser); ParSave(1); + ParAccess(usUser); + ParSave(1); ParFloat(&drv->prop2, 1.0); - ParName("int2"); ParFmt("%.1f"); ParTail("%/mbar/min"); + ParName("int2"); + ParFmt("%.1f"); + ParTail("%/mbar/min"); ParList(""); - ParAccess(usUser); ParSave(1); + ParAccess(usUser); + ParSave(1); ParFloat(&drv->deriv, 2.0); } - + if (drv->controlChan == 0) { i = drv->dig[drv->sampleChan]; } else { @@ -299,7 +357,8 @@ static void ItcParDef(void *object) { if (i < 0) { snprintf(fmt, sizeof fmt, "%s", "%.3f"); } else { - if (eab->syntax == TESLATRON) i+=2; + if (eab->syntax == TESLATRON) + i += 2; snprintf(fmt, sizeof fmt, "%s.%df", "%", i); } @@ -313,24 +372,26 @@ static void ItcParDef(void *object) { ParStdDef(); EaseMsgPar(drv); } + /*----------------------------------------------------------------------------*/ -static void ItcLcParDef(void *object) { +static void ItcLcParDef(void *object) +{ EaseBase *eab = object; eab->syntax = TESLATRON; ItcParDef(object); } + /*----------------------------------------------------------------------------*/ -void ItcStatus(Itc *drv) { +void ItcStatus(Itc * drv) +{ char *ans; int *code; - - if (drv->d.b.state != EASE_read) return; - ans=drv->d.b.ans; - code=&drv->d.b.errCode; - if (ans[0] != 'X' || - ans[2] != 'A' || - ans[4] != 'C' || - ans[6] != 'S') { + + if (drv->d.b.state != EASE_read) + return; + ans = drv->d.b.ans; + code = &drv->d.b.errCode; + if (ans[0] != 'X' || ans[2] != 'A' || ans[4] != 'C' || ans[6] != 'S') { ParPrintf(drv, eError, "illegal status response"); *code = EASE_FAULT; return; @@ -338,7 +399,8 @@ void ItcStatus(Itc *drv) { drv->a = ans[3] - '0'; if (ans[9] == 'H') { drv->h = ans[10] - '0'; - if (ans[11] == 'L' && drv->pidMode != 0 && ! EaseGetUpdate(drv, ITC_PIDMODE)) { + if (ans[11] == 'L' && drv->pidMode != 0 + && !EaseGetUpdate(drv, ITC_PIDMODE)) { drv->pidMode == ans[12] - '0' + 1; } } else { @@ -351,17 +413,18 @@ void ItcStatus(Itc *drv) { return; } } + /*----------------------------------------------------------------------------*/ -float controlPropInt( - float diff, /* input (soll-ist for negative loop, ist-soll for positive) */ - float prop, /* prop (gain) units: [out]/[inp] */ - float intd, /* int*delta (reset) units: [out]/[inp] */ - float bandP, /* prop deadband units: [inp] */ - float bandi, /* integral deadband units: [inp] */ - float *buffer) /* a buffer to store last diff */ { +float controlPropInt(float diff, /* input (soll-ist for negative loop, ist-soll for positive) */ + float prop, /* prop (gain) units: [out]/[inp] */ + float intd, /* int*delta (reset) units: [out]/[inp] */ + float bandP, /* prop deadband units: [inp] */ + float bandi, /* integral deadband units: [inp] */ + float *buffer) +{ /* a buffer to store last diff */ float d, d0; - + bandP = bandP * 0.5; d0 = *buffer; if (fabs(diff) < bandi * 1.01) { @@ -377,16 +440,20 @@ float controlPropInt( *buffer = d; return prop * (d - d0) + intd * diff; } + /*----------------------------------------------------------------------------*/ -void controlLimits(float *inp, float min, float max) { +void controlLimits(float *inp, float min, float max) +{ if (*inp > max) { *inp = max; } else if (*inp < min) { *inp = min; } } + /*----------------------------------------------------------------------------*/ -static long ItcRead(long pc, void *object) { +static long ItcRead(long pc, void *object) +{ Itc *drv = ParCast(&itcClass, object); EaseBase *eab = object; char *p; @@ -394,52 +461,61 @@ static long ItcRead(long pc, void *object) { time_t now, delta; char buf[4]; float gas, band, v1, v2, h; - - switch (pc) { default: /* FSM BEGIN *******************************/ - EaseWrite(eab, "X"); - return __LINE__; case __LINE__: /**********************************/ - ItcStatus(drv); /* check for errors */ - if (drv->dig[1] < 0) goto skip1; - EaseWrite(eab, "R1"); /* read sensor 1 */ - return __LINE__; case __LINE__: /**********************************/ + switch (pc) { + default: /* FSM BEGIN ****************************** */ + EaseWrite(eab, "X"); + return __LINE__; + case __LINE__: /**********************************/ + ItcStatus(drv); /* check for errors */ + + if (drv->dig[1] < 0) + goto skip1; + EaseWrite(eab, "R1"); /* read sensor 1 */ + return __LINE__; + case __LINE__: /**********************************/ drv->t[1] = OxiGet(eab, drv->dig[1], &drv->dig[1], drv->t[1]); - + skip1: - if (drv->dig[2] < 0) goto skip2; - EaseWrite(eab, "R2"); /* read sensor 2 */ - return __LINE__; case __LINE__: /**********************************/ + if (drv->dig[2] < 0) + goto skip2; + EaseWrite(eab, "R2"); /* read sensor 2 */ + return __LINE__; + case __LINE__: /**********************************/ drv->t[2] = OxiGet(eab, drv->dig[2], &drv->dig[2], drv->t[2]); - + skip2: - if (drv->dig[3] < 0) goto skip3; - EaseWrite(eab, "R3"); /* read sensor 3 */ - return __LINE__; case __LINE__: /**********************************/ + if (drv->dig[3] < 0) + goto skip3; + EaseWrite(eab, "R3"); /* read sensor 3 */ + return __LINE__; + case __LINE__: /**********************************/ drv->t[3] = OxiGet(eab, drv->dig[3], &drv->dig[3], drv->t[3]); - + skip3: if (drv->controlChan == 0 || drv->a == 0) { drv->t[0] = drv->d.targetValue; goto skip0; } - EaseWrite(eab, "R0"); /* read control T */ - return __LINE__; case __LINE__: /**********************************/ + EaseWrite(eab, "R0"); /* read control T */ + return __LINE__; + case __LINE__: /**********************************/ drv->t[0] = OxiGet(eab, drv->dig[drv->controlChan], NULL, drv->t[0]); if (drv->gasMode == 2 && eab->syntax != TESLATRON) { if (drv->t[drv->controlChan] > drv->autoGasLimit + 1.0) { if (drv->a < 2) { - drv->a |= 2; /* switch gas to auto */ + drv->a |= 2; /* switch gas to auto */ ParPrintf(drv, eWarning, - "needle valve switched to ITC control (AutoGas)"); + "needle valve switched to ITC control (AutoGas)"); } else { goto skip0; } } else { if (drv->a >= 2) { if (drv->t[drv->controlChan] < drv->autoGasLimit) { - drv->a &= 1; /* switch gas to manual */ + drv->a &= 1; /* switch gas to manual */ ParPrintf(drv, eWarning, - "needle valve switched to software control"); + "needle valve switched to software control"); } else { goto skip0; } @@ -456,19 +532,22 @@ static long ItcRead(long pc, void *object) { } else if (drv->a < 2) { goto skip0; } else { - drv->a &= 1; /* switch gas to manual */ + drv->a &= 1; /* switch gas to manual */ } EaseWrite(eab, "C3"); - return __LINE__; case __LINE__: /**********************************/ + return __LINE__; + case __LINE__: /**********************************/ drv->remote = 2; - snprintf(buf, sizeof buf, "A%d", drv->a); + snprintf(buf, sizeof buf, "A%d", drv->a); EaseWrite(eab, buf); - return __LINE__; case __LINE__: /**********************************/ + return __LINE__; + case __LINE__: /**********************************/ skip0: - EaseWrite(eab, "R7"); /* read gas flow */ - return __LINE__; case __LINE__: /**********************************/ + EaseWrite(eab, "R7"); /* read gas flow */ + return __LINE__; + case __LINE__: /**********************************/ gas = OxiGet(eab, 1, NULL, drv->gas); time(&now); @@ -478,19 +557,24 @@ static long ItcRead(long pc, void *object) { if (drv->gas == PAR_NAN) { drv->gas = gas; } else { - if (drv->travelTime < 1) drv->travelTime = 1; + if (drv->travelTime < 1) + drv->travelTime = 1; if (drv->gas < gas) { drv->gas += delta * 100.0 / drv->travelTime; - if (drv->gas > gas) drv->gas = gas; + if (drv->gas > gas) + drv->gas = gas; } else { drv->gas -= delta * 100.0 / drv->travelTime; - if (drv->gas < gas) drv->gas = gas; + if (drv->gas < gas) + drv->gas = gas; } } - - if (eab->syntax != TESLATRON || drv->gasMode <= 0) goto skipFlow; - if (delta > 10) delta=10; - + + if (eab->syntax != TESLATRON || drv->gasMode <= 0) + goto skipFlow; + if (delta > 10) + delta = 10; + if (drv->prop <= 0) { band = 0.1; } else { @@ -507,58 +591,71 @@ static long ItcRead(long pc, void *object) { } } else { drv->d.targetValue += - controlPropInt(drv->t[2] - drv->lambdaTarget, - drv->prop, drv->integ*delta/60.0, 0.01, 0.01, &drv->lastTdiff); + controlPropInt(drv->t[2] - drv->lambdaTarget, + drv->prop, drv->integ * delta / 60.0, 0.01, 0.01, + &drv->lastTdiff); band = 0.01 * drv->prop; controlLimits(&drv->d.targetValue, drv->d.lowerLimit - band, drv->d.upperLimit + band); } - + drv->setGas += - controlPropInt(drv->d.targetValue - drv->t[1], - drv->prop2, drv->deriv*delta/60.0, drv->d.tolerance, 0.1, &drv->lastPdiff); + controlPropInt(drv->d.targetValue - drv->t[1], + drv->prop2, drv->deriv * delta / 60.0, + drv->d.tolerance, 0.1, &drv->lastPdiff); controlLimits(&drv->setGas, 0.0, 99.9); - - if (fabsf(drv->setGas - gas) < 0.1) goto skipFlow; + + if (fabsf(drv->setGas - gas) < 0.1) + goto skipFlow; EaseParHasChanged(); - - if (drv->remote == 2) goto skipActive; + + if (drv->remote == 2) + goto skipActive; EaseWrite(eab, "C3"); - return __LINE__; case __LINE__: /**********************************/ + return __LINE__; + case __LINE__: /**********************************/ drv->remote = 2; skipActive: - - OxiSet(eab, "G", drv->setGas, 1); /* cold valve setting */ - return __LINE__; case __LINE__: /**********************************/ + + OxiSet(eab, "G", drv->setGas, 1); /* cold valve setting */ + return __LINE__; + case __LINE__: /**********************************/ skipFlow: - - if (!drv->remote || eab->syntax == TESLATRON) goto skiprmt; + + if (!drv->remote || eab->syntax == TESLATRON) + goto skiprmt; EaseWrite(eab, "C0"); drv->remote = 0; - return __LINE__; case __LINE__: /**********************************/ + return __LINE__; + case __LINE__: /**********************************/ skiprmt: - - if (eab->syntax == TESLATRON) goto skipctrl; - - if (EaseGetUpdate(drv, ITC_MAXVOLT)) goto skiphtr; - EaseWrite(eab, "R5"); /* read heater percent */ - return __LINE__; case __LINE__: /**********************************/ - if (EaseGetUpdate(drv, ITC_MAXVOLT)) goto skiphtr; + + if (eab->syntax == TESLATRON) + goto skipctrl; + + if (EaseGetUpdate(drv, ITC_MAXVOLT)) + goto skiphtr; + EaseWrite(eab, "R5"); /* read heater percent */ + return __LINE__; + case __LINE__: /**********************************/ + if (EaseGetUpdate(drv, ITC_MAXVOLT)) + goto skiphtr; drv->htr = OxiGet(eab, 1, NULL, drv->htr); if (drv->readMaxVolt == 0) { drv->htrVolt = drv->htr * 0.01 * drv->maxVolt; goto skiphtr; } - EaseWrite(eab, "R6"); /* read heater voltage */ - return __LINE__; case __LINE__: /**********************************/ + EaseWrite(eab, "R6"); /* read heater voltage */ + return __LINE__; + case __LINE__: /**********************************/ drv->htrVolt = OxiGet(eab, 1, NULL, drv->htrVolt); if (drv->readMaxVolt) { h = drv->htr; if (h > 1.0) { - v1 = 0.1 * (int)(drv->htrVolt * 1000 / (h + 0.099) - 0.5); - v2 = 0.1 * (int)(drv->htrVolt * 1000 / (h - 0.05) + 0.99); + v1 = 0.1 * (int) (drv->htrVolt * 1000 / (h + 0.099) - 0.5); + v2 = 0.1 * (int) (drv->htrVolt * 1000 / (h - 0.05) + 0.99); if (drv->maxVolt > v2) { drv->cntVolt++; if (drv->cntVolt > drv->readMaxVolt) { @@ -582,8 +679,9 @@ static long ItcRead(long pc, void *object) { drv->htrVolt = h * 0.01 * drv->maxVolt; } - skiphtr: - if (drv->resist <= 1) drv->resist = 80.0; + skiphtr: + if (drv->resist <= 1) + drv->resist = 80.0; if (drv->maxVolt != PAR_NAN) { drv->maxPower = drv->maxVolt * drv->maxVolt / drv->resist; } @@ -591,43 +689,57 @@ static long ItcRead(long pc, void *object) { drv->power = drv->htrVolt * drv->htrVolt / drv->resist; } - if (EaseGetUpdate(drv, ITC_PROP)) goto skipprop; - EaseWrite(eab, "R8"); /* read prop */ - return __LINE__; case __LINE__: /**********************************/ - if (EaseGetUpdate(drv, ITC_PROP)) goto skipprop; + if (EaseGetUpdate(drv, ITC_PROP)) + goto skipprop; + EaseWrite(eab, "R8"); /* read prop */ + return __LINE__; + case __LINE__: /**********************************/ + if (EaseGetUpdate(drv, ITC_PROP)) + goto skipprop; drv->prop = OxiGet(eab, 1, NULL, drv->prop); skipprop: - if (EaseGetUpdate(drv, ITC_INTEG)) goto skipint; - EaseWrite(eab, "R9"); /* read int */ - return __LINE__; case __LINE__: /**********************************/ - if (EaseGetUpdate(drv, ITC_INTEG)) goto skipint; + if (EaseGetUpdate(drv, ITC_INTEG)) + goto skipint; + EaseWrite(eab, "R9"); /* read int */ + return __LINE__; + case __LINE__: /**********************************/ + if (EaseGetUpdate(drv, ITC_INTEG)) + goto skipint; drv->integ = OxiGet(eab, 1, NULL, drv->integ); skipint: - if (EaseGetUpdate(drv, ITC_DERIV)) goto skipderiv; - EaseWrite(eab, "R10"); /* read deriv */ - return __LINE__; case __LINE__: /**********************************/ - if (EaseGetUpdate(drv, ITC_DERIV)) goto skipderiv; + if (EaseGetUpdate(drv, ITC_DERIV)) + goto skipderiv; + EaseWrite(eab, "R10"); /* read deriv */ + return __LINE__; + case __LINE__: /**********************************/ + if (EaseGetUpdate(drv, ITC_DERIV)) + goto skipderiv; drv->deriv = OxiGet(eab, 1, NULL, drv->deriv); skipderiv: - + skipctrl: ParLog(drv); - fsm_quit: return 0; } /* FSM END *********************************/ + fsm_quit:return 0; + } /* FSM END ******************************** */ } + /*----------------------------------------------------------------------------*/ -static long ItcStart(long pc, void *object) { +static long ItcStart(long pc, void *object) +{ Itc *drv = ParCast(&itcClass, object); EaseBase *eab = object; - - switch (pc) { default: /* FSM BEGIN *******************************/ + + switch (pc) { + default: /* FSM BEGIN ****************************** */ EaseWrite(eab, "V"); - return __LINE__; case __LINE__: /**********************************/ + return __LINE__; + case __LINE__: /**********************************/ if (eab->syntax == TESLATRON) { if (0 != strncmp(eab->version, "TESLATRON", 9)) { - snprintf(eab->msg, sizeof eab->msg, "unknown teslatron version: %s", - eab->version); + snprintf(eab->msg, sizeof eab->msg, + "unknown teslatron version: %s", eab->version); ParPrintf(drv, eError, "ERROR: %s", eab->msg); EaseStop(eab); goto quit; @@ -638,7 +750,8 @@ static long ItcStart(long pc, void *object) { } else if (0 == strncmp(eab->version, "ITC4", 4)) { eab->syntax = 0; } else { - snprintf(eab->msg, sizeof eab->msg, "unknown temperature controller version: %s", + snprintf(eab->msg, sizeof eab->msg, + "unknown temperature controller version: %s", eab->version); ParPrintf(drv, eError, "ERROR: %s", eab->msg); EaseStop(eab); @@ -647,45 +760,57 @@ static long ItcStart(long pc, void *object) { } ParPrintf(drv, eLog, "connected to %s", eab->version); FsmCall(ItcRead); - return __LINE__; case __LINE__: /**********************************/ + return __LINE__; + case __LINE__: /**********************************/ if (drv->controlChan == 0 && drv->h >= 1 && drv->h <= 3) { drv->controlChan = drv->h; } drv->d.targetValue = drv->t[0]; - + quit: - return 0; } /* FSM END ********************************************/ + return 0; + } /* FSM END ******************************************* */ } + /*----------------------------------------------------------------------------*/ -static long ItcSetTemp(long pc, void *object) { +static long ItcSetTemp(long pc, void *object) +{ Itc *drv = ParCast(&itcClass, object); EaseBase *eab = object; char buf[4]; int a; - - switch (pc) { default: /* FSM BEGIN *******************************/ + + switch (pc) { + default: /* FSM BEGIN ****************************** */ if (drv->controlChan == 0) { ParPrintf(drv, eError, "no control channel selected"); goto quit; } - if (drv->h == drv->controlChan) goto skiph; - EaseWrite(eab, "A0"); /* heater off */ - return __LINE__; case __LINE__: /**********************************/ + if (drv->h == drv->controlChan) + goto skiph; + EaseWrite(eab, "A0"); /* heater off */ + return __LINE__; + case __LINE__: /**********************************/ snprintf(buf, sizeof buf, "H%d", drv->controlChan); - EaseWrite(eab, buf); /* set heater to channel */ - return __LINE__; case __LINE__: /**********************************/ - + EaseWrite(eab, buf); /* set heater to channel */ + return __LINE__; + case __LINE__: /**********************************/ + skiph: - OxiSet(eab, "T", drv->d.targetValue, drv->dig[drv->controlChan]); /* set point */ - return __LINE__; case __LINE__: /**********************************/ - - if (drv->pidMode != 0) goto skipPidMode; - EaseWrite(eab, "L1"); /* 'auto' pid on */ - return __LINE__; case __LINE__: /**********************************/ + OxiSet(eab, "T", drv->d.targetValue, drv->dig[drv->controlChan]); /* set point */ + return __LINE__; + case __LINE__: /**********************************/ + + if (drv->pidMode != 0) + goto skipPidMode; + EaseWrite(eab, "L1"); /* 'auto' pid on */ + return __LINE__; + case __LINE__: /**********************************/ skipPidMode: - - a = 1; /* auto heater */ - if (drv->a >= 2) a = 3; /* auto gas & heater */ + + a = 1; /* auto heater */ + if (drv->a >= 2) + a = 3; /* auto gas & heater */ if (drv->d.targetValue == 0.0) { drv->htrMode = 0; a = 0; @@ -693,29 +818,37 @@ static long ItcSetTemp(long pc, void *object) { EaseSetUpdate(drv, ITC_SETGAS, 1); } } else { - drv->htrMode = 2; /* heater auto */ + drv->htrMode = 2; /* heater auto */ } - if (drv->h == drv->controlChan && drv->a == a) goto skipa; + if (drv->h == drv->controlChan && drv->a == a) + goto skipa; snprintf(buf, sizeof buf, "A%d", a); drv->a = a; EaseWrite(eab, buf); - return __LINE__; case __LINE__: /**********************************/ + return __LINE__; + case __LINE__: /**********************************/ skipa: - - if (drv->a != 0) goto quit; - EaseWrite(eab, "O0"); /* switch off heater */ - return __LINE__; case __LINE__: /**********************************/ - + + if (drv->a != 0) + goto quit; + EaseWrite(eab, "O0"); /* switch off heater */ + return __LINE__; + case __LINE__: /**********************************/ + quit: - return 0; } /* FSM END ********************************************/ + return 0; + } /* FSM END ******************************************* */ } + /*----------------------------------------------------------------------------*/ -static long ItcSetGas(long pc, void *object) { +static long ItcSetGas(long pc, void *object) +{ Itc *drv = ParCast(&itcClass, object); EaseBase *eab = object; char buf[4]; - - switch (pc) { default: /* FSM BEGIN *******************************/ + + switch (pc) { + default: /* FSM BEGIN ****************************** */ if (drv->gasMode != 1 && drv->gasMode != 2) { ParPrintf(drv, eError, "gasMode must be set to manual or auto"); goto quit; @@ -727,93 +860,133 @@ static long ItcSetGas(long pc, void *object) { } else { goto skipmode; } - return __LINE__; case __LINE__: /**********************************/ + return __LINE__; + case __LINE__: /**********************************/ skipmode: - OxiSet(eab, "G", drv->setGas, 1); /* cold valve setting */ - return __LINE__; case __LINE__: /**********************************/ - EaseWrite(eab, "R7"); /* read gas flow */ - return __LINE__; case __LINE__: /**********************************/ - if (! EaseGetUpdate(drv, ITC_SETGAS)) { + OxiSet(eab, "G", drv->setGas, 1); /* cold valve setting */ + return __LINE__; + case __LINE__: /**********************************/ + EaseWrite(eab, "R7"); /* read gas flow */ + return __LINE__; + case __LINE__: /**********************************/ + if (!EaseGetUpdate(drv, ITC_SETGAS)) { drv->setGas = OxiGet(eab, 1, NULL, drv->setGas); } - if (drv->a < 2) goto quit; - snprintf(buf, sizeof buf, "A%d", drv->a); + if (drv->a < 2) + goto quit; + snprintf(buf, sizeof buf, "A%d", drv->a); EaseWrite(eab, buf); - return __LINE__; case __LINE__: /**********************************/ + return __LINE__; + case __LINE__: /**********************************/ quit: - return 0; } /* FSM END ********************************************/ + return 0; + } /* FSM END ******************************************* */ } + /*----------------------------------------------------------------------------*/ -static long ItcSetHtr(long pc, void *object) { +static long ItcSetHtr(long pc, void *object) +{ Itc *drv = ParCast(&itcClass, object); EaseBase *eab = object; char buf[4]; - - switch (pc) { default: /* FSM BEGIN *******************************/ - if (drv->a == 0) goto skipmode; + + switch (pc) { + default: /* FSM BEGIN ****************************** */ + if (drv->a == 0) + goto skipmode; EaseWrite(eab, "A0"); - return __LINE__; case __LINE__: /**********************************/ + return __LINE__; + case __LINE__: /**********************************/ skipmode: - OxiSet(eab, "O", drv->htr, 1); /* manual heater setting */ - return __LINE__; case __LINE__: /**********************************/ - if (drv->a == 0) goto quit; - snprintf(buf, sizeof buf, "A%d", drv->a); + OxiSet(eab, "O", drv->htr, 1); /* manual heater setting */ + return __LINE__; + case __LINE__: /**********************************/ + if (drv->a == 0) + goto quit; + snprintf(buf, sizeof buf, "A%d", drv->a); EaseWrite(eab, buf); - return __LINE__; case __LINE__: /**********************************/ + return __LINE__; + case __LINE__: /**********************************/ quit: - return 0; } /* FSM END ********************************************/ + return 0; + } /* FSM END ******************************************* */ } + /*----------------------------------------------------------------------------*/ -static long ItcSet(long pc, void *object) { +static long ItcSet(long pc, void *object) +{ Itc *drv = ParCast(&itcClass, object); EaseBase *eab = object; int upd; - - switch (pc) { default: /* FSM BEGIN *******************************/ + + switch (pc) { + default: /* FSM BEGIN ****************************** */ EaseWrite(eab, "C3"); loop: - return __LINE__; case __LINE__: /**********************************/ + return __LINE__; + case __LINE__: /**********************************/ drv->remote = 2; upd = EaseNextUpdate(drv); if (eab->syntax != TESLATRON) { switch (upd) { - case EASE_RUN: FsmCall(ItcSetTemp); goto loop; - case ITC_SETHTR: FsmCall(ItcSetHtr); goto loop; - case ITC_SETGAS: FsmCall(ItcSetGas); goto loop; + case EASE_RUN: + FsmCall(ItcSetTemp); + goto loop; + case ITC_SETHTR: + FsmCall(ItcSetHtr); + goto loop; + case ITC_SETGAS: + FsmCall(ItcSetGas); + goto loop; case ITC_PIDMODE: - if (drv->pidMode == 1) { - EaseWrite(eab, "L0"); - } else { - EaseWrite(eab, "L1"); - drv->pidMode = 2; - } - goto loop; - case ITC_PROP: OxiSet(eab, "P", drv->prop, 1); goto loop; - case ITC_INTEG: OxiSet(eab, "I", drv->integ, 1); goto loop; - case ITC_DERIV: OxiSet(eab, "D", drv->deriv, 1); goto loop; - case ITC_MAXVOLT:OxiSet(eab, "M", drv->maxVolt, 1); goto loop; - default: break; + if (drv->pidMode == 1) { + EaseWrite(eab, "L0"); + } else { + EaseWrite(eab, "L1"); + drv->pidMode = 2; + } + goto loop; + case ITC_PROP: + OxiSet(eab, "P", drv->prop, 1); + goto loop; + case ITC_INTEG: + OxiSet(eab, "I", drv->integ, 1); + goto loop; + case ITC_DERIV: + OxiSet(eab, "D", drv->deriv, 1); + goto loop; + case ITC_MAXVOLT: + OxiSet(eab, "M", drv->maxVolt, 1); + goto loop; + default: + break; } } - if (eab->syntax == TESLATRON && drv->gasMode > 0) goto quit; + if (eab->syntax == TESLATRON && drv->gasMode > 0) + goto quit; EaseWrite(eab, "C0"); - return __LINE__; case __LINE__: /**********************************/ + return __LINE__; + case __LINE__: /**********************************/ drv->remote = 0; quit: - return 0; } /* FSM END ********************************************/ + return 0; + } /* FSM END ******************************************* */ } + /*----------------------------------------------------------------------------*/ -static int ItcInit(SConnection *con, int argc, char *argv[], int dynamic) { +static int ItcInit(SConnection * con, int argc, char *argv[], int dynamic) +{ /* args: - MakeObject objectname itc - MakeObject objectname itc + MakeObject objectname itc + MakeObject objectname itc */ Itc *drv; - + drv = EaseMakeDriv(con, &itcClass, argc, argv, dynamic, 7, - ItcParDef, OxiHandler, ItcStart, NULL, ItcRead, - ItcSet); - if (drv == NULL) return 0; + ItcParDef, OxiHandler, ItcStart, NULL, ItcRead, + ItcSet); + if (drv == NULL) + return 0; drv->d.b.syntax = 0; drv->cntVolt = 0; drv->maxVolt = PAR_NAN; @@ -821,27 +994,33 @@ static int ItcInit(SConnection *con, int argc, char *argv[], int dynamic) { drv->readMaxVolt = 1; return 1; } + /*----------------------------------------------------------------------------*/ -static int ItcInitLc(SConnection *con, int argc, char *argv[], int dynamic) { +static int ItcInitLc(SConnection * con, int argc, char *argv[], + int dynamic) +{ /* args: - MakeObject objectname lc - MakeObject objectname lc + MakeObject objectname lc + MakeObject objectname lc */ Itc *drv; - + drv = EaseMakeDriv(con, &itcClass, argc, argv, dynamic, 7, - ItcLcParDef, OxiHandler, ItcStart, NULL, ItcRead, - ItcSet); - if (drv == NULL) return 0; + ItcLcParDef, OxiHandler, ItcStart, NULL, ItcRead, + ItcSet); + if (drv == NULL) + return 0; drv->d.b.syntax = TESLATRON; drv->lastCtrl = 0; drv->lastTdiff = 0; drv->lastPdiff = 0; return 1; } + /*----------------------------------------------------------------------------*/ -void ItcStartup(void) { +void ItcStartup(void) +{ ParMakeClass(&itcClass, EaseDrivClass()); - MakeDriver("ITC", ItcInit, 0, "OI Temperature Controller"); - MakeDriver("LC", ItcInitLc, 0, "OI Lambda Controller"); + MakeDriver("ITC", ItcInit, 0, "OI Temperature Controller"); + MakeDriver("LC", ItcInitLc, 0, "OI Lambda Controller"); } diff --git a/julcho.c b/julcho.c index 6048353..9bf8ffd 100644 --- a/julcho.c +++ b/julcho.c @@ -20,7 +20,7 @@ #include #define CHOCOINTERNAL #include -#include +#include #include #include #include @@ -52,1269 +52,1334 @@ #define CH5N "five" /*=============== Juelich chopper private data structure ================== */ typedef struct { - prs232 controller; - pHdb parNode; - int errorCode; - time_t lastUpdate; - int updateIntervall; - int speedUpdate; - int halt; -}JulCho, *pJulCho; + prs232 controller; + pHdb parNode; + int errorCode; + time_t lastUpdate; + int updateIntervall; + int speedUpdate; + int halt; +} JulCho, *pJulCho; /*------------------------------------------------------------------------*/ typedef struct { - char prefix[10]; - char postfix[10]; - char comCode[10]; - pJulCho pDriv; + char prefix[10]; + char postfix[10]; + char comCode[10]; + pJulCho pDriv; } julCBData, *pJulCBData; /*================= internal support functions ============================*/ -static int calculateJulCheckSum(char *realCommand){ - int i, checkSum = 0; - - for(i = 1; i < strlen(realCommand); i++){ - checkSum += (int)realCommand[i]; - } - return checkSum; +static int calculateJulCheckSum(char *realCommand) +{ + int i, checkSum = 0; + + for (i = 1; i < strlen(realCommand); i++) { + checkSum += (int) realCommand[i]; + } + return checkSum; } + /*------------------------------------------------------------------------*/ -static int testJulError(char *reply){ - char *pPtr = NULL, *pEnd = NULL; - int code, status; - - if(strstr(reply,"ERR") == NULL){ - return 1; - } - pPtr = &reply[9]; /* #ERR:CCC: */ - pEnd = strchr(pPtr,'{'); - if(pEnd == NULL){ - return BADERR; - } - *pEnd = '\0'; - code = atoi(pPtr); - switch(code){ - case 1: - status = FRAMEERROR; - break; - case 2: - status = CKERROR; - break; - case 3: - status = BADCOMMAND; - break; - case 4: - status = WRONGNOPAR; - break; - case 5: - status = ILLPAR; - break; - case 6: - status = PARRANGE; - break; - default: - status = BADERR; - break; - } - return status; +static int testJulError(char *reply) +{ + char *pPtr = NULL, *pEnd = NULL; + int code, status; + + if (strstr(reply, "ERR") == NULL) { + return 1; + } + pPtr = &reply[9]; /* #ERR:CCC: */ + pEnd = strchr(pPtr, '{'); + if (pEnd == NULL) { + return BADERR; + } + *pEnd = '\0'; + code = atoi(pPtr); + switch (code) { + case 1: + status = FRAMEERROR; + break; + case 2: + status = CKERROR; + break; + case 3: + status = BADCOMMAND; + break; + case 4: + status = WRONGNOPAR; + break; + case 5: + status = ILLPAR; + break; + case 6: + status = PARRANGE; + break; + default: + status = BADERR; + break; + } + return status; } + /*------------------------------------------------------------------------*/ -static void readClean(prs232 controller){ - char buffer[1024]; - int count = 0, bufSize; - - while(availableRS232(controller) == 1 && count < 20){ - bufSize = 1024; - readRS232(controller,buffer, &bufSize); - } +static void readClean(prs232 controller) +{ + char buffer[1024]; + int count = 0, bufSize; + + while (availableRS232(controller) == 1 && count < 20) { + bufSize = 1024; + readRS232(controller, buffer, &bufSize); + } } + /*-------------------------------------------------------------------------*/ -static int JulChoTransact(pJulCho self, char *command, - char *reply, int replyLen){ - int status, length, checkSum; - char realCommand[1024], checkString[30]; - - strcpy(realCommand,"#"); - strcat(realCommand,command); - - checkSum = calculateJulCheckSum(realCommand); - snprintf(checkString,30,"{%d}$", checkSum); - strcat(realCommand,checkString); - - /* - * clean the socket: If someone whacked the keyboard and the - * controller did not repsond, the line might be full of shit - */ - readClean(self->controller); - - status = transactRS232(self->controller, realCommand,strlen(realCommand), - (void *)reply, replyLen); - if(status <= 0){ - return status; - } +static int JulChoTransact(pJulCho self, char *command, + char *reply, int replyLen) +{ + int status, length, checkSum; + char realCommand[1024], checkString[30]; - status = testJulError(reply); - + strcpy(realCommand, "#"); + strcat(realCommand, command); + + checkSum = calculateJulCheckSum(realCommand); + snprintf(checkString, 30, "{%d}$", checkSum); + strcat(realCommand, checkString); + + /* + * clean the socket: If someone whacked the keyboard and the + * controller did not repsond, the line might be full of shit + */ + readClean(self->controller); + + status = + transactRS232(self->controller, realCommand, strlen(realCommand), + (void *) reply, replyLen); + if (status <= 0) { return status; -} + } + + status = testJulError(reply); + + return status; +} + /*---------------------------------------------------------------------------*/ -static hdbCallbackReturn JulChoSetCallback(pHdb node, void *userData, - pHdbMessage message){ - pJulCBData cbData = NULL; - char command[256], reply[256]; - pHdbDataMessage mm = NULL; - int status; - - cbData = (pJulCBData)userData; - if(cbData == NULL){ - return hdbContinue; - } - - /* - * Is this for us? - */ - mm = GetHdbSetMessage(message); - if(mm == NULL){ - return hdbContinue; - } - - - if(mm->v->dataType == HIPINT){ - snprintf(command,255,"%s %s%d%s",cbData->comCode, cbData->prefix, - (int)mm->v->v.intValue,cbData->postfix); - } else if(mm->v->dataType == HIPFLOAT){ - snprintf(command,255,"%s %s%f%s",cbData->comCode, cbData->prefix, - (float)mm->v->v.doubleValue,cbData->postfix); - } else { - assert(0); /* this is a programming error */ - } - - cbData->pDriv->halt = 0; - status = JulChoTransact(cbData->pDriv, command, reply, 255); - if(status < 0) { - cbData->pDriv->errorCode = status; - return hdbAbort; - } +static hdbCallbackReturn JulChoSetCallback(pHdb node, void *userData, + pHdbMessage message) +{ + pJulCBData cbData = NULL; + char command[256], reply[256]; + pHdbDataMessage mm = NULL; + int status; + + cbData = (pJulCBData) userData; + if (cbData == NULL) { return hdbContinue; + } + + /* + * Is this for us? + */ + mm = GetHdbSetMessage(message); + if (mm == NULL) { + return hdbContinue; + } + + + if (mm->v->dataType == HIPINT) { + snprintf(command, 255, "%s %s%d%s", cbData->comCode, cbData->prefix, + (int) mm->v->v.intValue, cbData->postfix); + } else if (mm->v->dataType == HIPFLOAT) { + snprintf(command, 255, "%s %s%f%s", cbData->comCode, cbData->prefix, + (float) mm->v->v.doubleValue, cbData->postfix); + } else { + assert(0); /* this is a programming error */ + } + + cbData->pDriv->halt = 0; + status = JulChoTransact(cbData->pDriv, command, reply, 255); + if (status < 0) { + cbData->pDriv->errorCode = status; + return hdbAbort; + } + return hdbContinue; } + /*------------------------------------------------------------------------------*/ -static pHdbCallback MakeJulChoSetCallback(pJulCho driv, char *command, - char *prefix, char *postfix){ - pJulCBData cbData = NULL; - pHdbCallback hdbCB = NULL; - - hdbCB = malloc(sizeof(hdbCallback)); - cbData = malloc(sizeof(julCBData)); - if(cbData == NULL || hdbCB == NULL){ - return NULL; - } - cbData->pDriv = driv; - strncpy(cbData->comCode,command,9); - strncpy(cbData->prefix,prefix,9); - strncpy(cbData->postfix,postfix,9); - hdbCB->next = NULL; - hdbCB->previous = NULL; - hdbCB->killFunc = free; - hdbCB->userCallback = JulChoSetCallback; - hdbCB->userData = cbData; - return hdbCB; +static pHdbCallback MakeJulChoSetCallback(pJulCho driv, char *command, + char *prefix, char *postfix) +{ + pJulCBData cbData = NULL; + pHdbCallback hdbCB = NULL; + + hdbCB = malloc(sizeof(hdbCallback)); + cbData = malloc(sizeof(julCBData)); + if (cbData == NULL || hdbCB == NULL) { + return NULL; + } + cbData->pDriv = driv; + strncpy(cbData->comCode, command, 9); + strncpy(cbData->prefix, prefix, 9); + strncpy(cbData->postfix, postfix, 9); + hdbCB->next = NULL; + hdbCB->previous = NULL; + hdbCB->killFunc = free; + hdbCB->userCallback = JulChoSetCallback; + hdbCB->userData = cbData; + return hdbCB; } + /*--------------------------------------------------------------------------*/ -static int splitJulChoInt(char *reply, int data[5]){ - char number[10]; - char *pPtr = NULL; - int count = 0; - - pPtr = stptok(reply,number,10,":"); - pPtr = stptok(pPtr,number,10,":"); - while(pPtr != NULL && count < 5){ - data[count] = atoi(number); - count++; - pPtr = stptok(pPtr,number,10,":"); - } - if(count < 4){ - return 0; - } - return 1; +static int splitJulChoInt(char *reply, int data[5]) +{ + char number[10]; + char *pPtr = NULL; + int count = 0; + + pPtr = stptok(reply, number, 10, ":"); + pPtr = stptok(pPtr, number, 10, ":"); + while (pPtr != NULL && count < 5) { + data[count] = atoi(number); + count++; + pPtr = stptok(pPtr, number, 10, ":"); + } + if (count < 4) { + return 0; + } + return 1; } + /*--------------------------------------------------------------------------*/ -static int splitJulChoDouble(char *reply, double data[5]){ - char number[10]; - char *pPtr = NULL; - int count = 0; - - pPtr = stptok(reply,number,10,":"); - pPtr = stptok(pPtr,number,10,":"); - while(pPtr != NULL && count < 5){ - data[count] = (double)atof(number); - count++; - pPtr = stptok(pPtr,number,10,":"); - } - if(count < 4){ - return 0; - } - return 1; +static int splitJulChoDouble(char *reply, double data[5]) +{ + char number[10]; + char *pPtr = NULL; + int count = 0; + + pPtr = stptok(reply, number, 10, ":"); + pPtr = stptok(pPtr, number, 10, ":"); + while (pPtr != NULL && count < 5) { + data[count] = (double) atof(number); + count++; + pPtr = stptok(pPtr, number, 10, ":"); + } + if (count < 4) { + return 0; + } + return 1; } + /*--------------------------------------------------------------------------*/ -static int setJulChoIntPar(pHdb root, char *par, int data[5]){ - char path[256]; - hdbValue v; - pHdb node = NULL; - - memset(&v,0,sizeof(hdbValue)); - v.dataType = HIPINT; - - snprintf(path,255,"%s/%s",CH1N,par); - node = GetHipadabaNode(root,path); - assert(node != NULL); - v.v.intValue = (long)data[0]; - UpdateHipadabaPar(node,v,NULL); +static int setJulChoIntPar(pHdb root, char *par, int data[5]) +{ + char path[256]; + hdbValue v; + pHdb node = NULL; - snprintf(path,255,"%s/%s",CH2N,par); - node = GetHipadabaNode(root,path); - assert(node != NULL); - v.v.intValue = (long)data[1]; - UpdateHipadabaPar(node,v,NULL); + memset(&v, 0, sizeof(hdbValue)); + v.dataType = HIPINT; - snprintf(path,255,"%s/%s",CH3N,par); - node = GetHipadabaNode(root,path); - assert(node != NULL); - v.v.intValue = (long)data[2]; - UpdateHipadabaPar(node,v,NULL); + snprintf(path, 255, "%s/%s", CH1N, par); + node = GetHipadabaNode(root, path); + assert(node != NULL); + v.v.intValue = (long) data[0]; + UpdateHipadabaPar(node, v, NULL); - snprintf(path,255,"%s/%s",CH4N,par); - node = GetHipadabaNode(root,path); - assert(node != NULL); - v.v.intValue = (long)data[3]; - UpdateHipadabaPar(node,v,NULL); + snprintf(path, 255, "%s/%s", CH2N, par); + node = GetHipadabaNode(root, path); + assert(node != NULL); + v.v.intValue = (long) data[1]; + UpdateHipadabaPar(node, v, NULL); - snprintf(path,255,"%s/%s",CH5N,par); - node = GetHipadabaNode(root,path); - assert(node != NULL); - v.v.intValue = (long)data[4]; - UpdateHipadabaPar(node,v,NULL); - - return 1; + snprintf(path, 255, "%s/%s", CH3N, par); + node = GetHipadabaNode(root, path); + assert(node != NULL); + v.v.intValue = (long) data[2]; + UpdateHipadabaPar(node, v, NULL); + + snprintf(path, 255, "%s/%s", CH4N, par); + node = GetHipadabaNode(root, path); + assert(node != NULL); + v.v.intValue = (long) data[3]; + UpdateHipadabaPar(node, v, NULL); + + snprintf(path, 255, "%s/%s", CH5N, par); + node = GetHipadabaNode(root, path); + assert(node != NULL); + v.v.intValue = (long) data[4]; + UpdateHipadabaPar(node, v, NULL); + + return 1; } + /*--------------------------------------------------------------------------*/ -static int setJulChoDoublePar(pHdb root, char *par, double data[5]){ - char path[256]; - hdbValue v; - pHdb node = NULL; - - memset(&v,0,sizeof(hdbValue)); - v.dataType = HIPFLOAT; - - snprintf(path,255,"%s/%s",CH1N,par); - node = GetHipadabaNode(root,path); - assert(node != NULL); - v.v.doubleValue = data[0]; - UpdateHipadabaPar(node,v,NULL); +static int setJulChoDoublePar(pHdb root, char *par, double data[5]) +{ + char path[256]; + hdbValue v; + pHdb node = NULL; - snprintf(path,255,"%s/%s",CH2N,par); - node = GetHipadabaNode(root,path); - assert(node != NULL); - v.v.doubleValue = data[1]; - UpdateHipadabaPar(node,v,NULL); + memset(&v, 0, sizeof(hdbValue)); + v.dataType = HIPFLOAT; - snprintf(path,255,"%s/%s",CH3N,par); - node = GetHipadabaNode(root,path); - assert(node != NULL); - v.v.doubleValue = data[2]; - UpdateHipadabaPar(node,v,NULL); + snprintf(path, 255, "%s/%s", CH1N, par); + node = GetHipadabaNode(root, path); + assert(node != NULL); + v.v.doubleValue = data[0]; + UpdateHipadabaPar(node, v, NULL); - snprintf(path,255,"%s/%s",CH4N,par); - node = GetHipadabaNode(root,path); - assert(node != NULL); - v.v.doubleValue = data[3]; - UpdateHipadabaPar(node,v,NULL); + snprintf(path, 255, "%s/%s", CH2N, par); + node = GetHipadabaNode(root, path); + assert(node != NULL); + v.v.doubleValue = data[1]; + UpdateHipadabaPar(node, v, NULL); - snprintf(path,255,"%s/%s",CH5N,par); - node = GetHipadabaNode(root,path); - assert(node != NULL); - v.v.doubleValue = data[4]; - UpdateHipadabaPar(node,v,NULL); - - return 1; + snprintf(path, 255, "%s/%s", CH3N, par); + node = GetHipadabaNode(root, path); + assert(node != NULL); + v.v.doubleValue = data[2]; + UpdateHipadabaPar(node, v, NULL); + + snprintf(path, 255, "%s/%s", CH4N, par); + node = GetHipadabaNode(root, path); + assert(node != NULL); + v.v.doubleValue = data[3]; + UpdateHipadabaPar(node, v, NULL); + + snprintf(path, 255, "%s/%s", CH5N, par); + node = GetHipadabaNode(root, path); + assert(node != NULL); + v.v.doubleValue = data[4]; + UpdateHipadabaPar(node, v, NULL); + + return 1; } + /*--------------------------------------------------------------------------*/ static void updateJulChoFlag(pHdb node, char *choppername, char *parname, - int code, int mask){ - char path[256]; - hdbValue v; - pHdb target = NULL; - - v.dataType = HIPINT; - snprintf(path,255,"%s/%s",choppername,parname); - if((mask & code) > 0) { - v.v.intValue = 1; - } else { - v.v.intValue = 0; - } - target = GetHipadabaNode(node,path); - assert(target != NULL); - UpdateHipadabaPar(target,v,NULL); + int code, int mask) +{ + char path[256]; + hdbValue v; + pHdb target = NULL; + + v.dataType = HIPINT; + snprintf(path, 255, "%s/%s", choppername, parname); + if ((mask & code) > 0) { + v.v.intValue = 1; + } else { + v.v.intValue = 0; + } + target = GetHipadabaNode(node, path); + assert(target != NULL); + UpdateHipadabaPar(target, v, NULL); } + /*---------------------------------------------------------------------------*/ -static int setJulChoFlags(pHdb node, int intData[5]){ - char *chNames[] = {CH1N, - CH2N, - CH3N, - CH4N, - CH5N, - NULL}; - char path[256]; - int i, code; - hdbValue v; - - memset(&v,0,sizeof(hdbValue)); - v.dataType = HIPINT; - for(i = 0; i < 5; i++){ - code = intData[i]; - updateJulChoFlag(node,chNames[i],"microok",code,1); - updateJulChoFlag(node,chNames[i],"atspeed",code,2); - updateJulChoFlag(node,chNames[i],"atphase",code,4); - updateJulChoFlag(node,chNames[i],"magneton",code,8); - updateJulChoFlag(node,chNames[i],"dcon",code,16); - updateJulChoFlag(node,chNames[i],"driveon",code,32); - updateJulChoFlag(node,chNames[i],"currentdc",code,64); - updateJulChoFlag(node,chNames[i],"lockopen",code,128); - updateJulChoFlag(node,chNames[i],"diskopen",code,256); - updateJulChoFlag(node,chNames[i],"diskclosed",code,512); - updateJulChoFlag(node,chNames[i],"speedoverflow",code,1024); - updateJulChoFlag(node,chNames[i],"bearingfailed",code,2048); - updateJulChoFlag(node,chNames[i],"voltagetohigh",code,4096); - } - - return 1; +static int setJulChoFlags(pHdb node, int intData[5]) +{ + char *chNames[] = { CH1N, + CH2N, + CH3N, + CH4N, + CH5N, + NULL + }; + char path[256]; + int i, code; + hdbValue v; + + memset(&v, 0, sizeof(hdbValue)); + v.dataType = HIPINT; + for (i = 0; i < 5; i++) { + code = intData[i]; + updateJulChoFlag(node, chNames[i], "microok", code, 1); + updateJulChoFlag(node, chNames[i], "atspeed", code, 2); + updateJulChoFlag(node, chNames[i], "atphase", code, 4); + updateJulChoFlag(node, chNames[i], "magneton", code, 8); + updateJulChoFlag(node, chNames[i], "dcon", code, 16); + updateJulChoFlag(node, chNames[i], "driveon", code, 32); + updateJulChoFlag(node, chNames[i], "currentdc", code, 64); + updateJulChoFlag(node, chNames[i], "lockopen", code, 128); + updateJulChoFlag(node, chNames[i], "diskopen", code, 256); + updateJulChoFlag(node, chNames[i], "diskclosed", code, 512); + updateJulChoFlag(node, chNames[i], "speedoverflow", code, 1024); + updateJulChoFlag(node, chNames[i], "bearingfailed", code, 2048); + updateJulChoFlag(node, chNames[i], "voltagetohigh", code, 4096); + } + + return 1; } + /*--------------------------------------------------------------------------*/ -static int ReadJulChoFlags(pJulCho self){ - int status, intData[5]; - char reply[256]; - - status = JulChoTransact(self,"RSC",reply,255); +static int ReadJulChoFlags(pJulCho self) +{ + int status, intData[5]; + char reply[256]; + + status = JulChoTransact(self, "RSC", reply, 255); /* fprintf(stdout,"Chopper flags = %s\n", reply);*/ - if(status < 0){ - self->errorCode = status; - return 0; - } - if(!splitJulChoInt(reply,intData)){ - self->errorCode = BADREPLY; - } - setJulChoFlags(self->parNode, intData); - return 1; + if (status < 0) { + self->errorCode = status; + return 0; + } + if (!splitJulChoInt(reply, intData)) { + self->errorCode = BADREPLY; + } + setJulChoFlags(self->parNode, intData); + return 1; } + /*---------------------------------------------------------------------------*/ -static int UpdateJulChoParameters(pJulCho self, int what){ - int status, intData[5]; - double doubleData[5]; - char reply[255]; - - assert(what == ALL || what == SPEED); - - if(what == SPEED){ - if(time(NULL) < self->speedUpdate + self->updateIntervall){ - return 1; - } - } else{ - if(time(NULL) < self->lastUpdate + self->updateIntervall){ - return 1; - } - } - - status = JulChoTransact(self,"RAS",reply,255); - if(status < 0){ - self->errorCode = status; - return 0; - } - if(!splitJulChoInt(reply,intData)){ - self->errorCode = BADREPLY; - } - setJulChoIntPar(self->parNode,"actspeed",intData); +static int UpdateJulChoParameters(pJulCho self, int what) +{ + int status, intData[5]; + double doubleData[5]; + char reply[255]; - status = JulChoTransact(self,"RAP",reply,255); - if(status < 0){ - self->errorCode = status; - return 0; - } - if(!splitJulChoDouble(reply,doubleData)){ - self->errorCode = BADREPLY; - } - setJulChoDoublePar(self->parNode,"actphase",doubleData); + assert(what == ALL || what == SPEED); - if(what != ALL){ - self->speedUpdate = time(NULL); - return 1; + if (what == SPEED) { + if (time(NULL) < self->speedUpdate + self->updateIntervall) { + return 1; } - - status = JulChoTransact(self,"RNS",reply,255); - if(status < 0){ - self->errorCode = status; - return 0; + } else { + if (time(NULL) < self->lastUpdate + self->updateIntervall) { + return 1; } - if(!splitJulChoInt(reply,intData)){ - self->errorCode = BADREPLY; - } - setJulChoIntPar(self->parNode,"nomspeed",intData); - - - status = JulChoTransact(self,"RNP",reply,255); - if(status < 0){ - self->errorCode = status; - return 0; - } - if(!splitJulChoDouble(reply,doubleData)){ - self->errorCode = BADREPLY; - } - setJulChoDoublePar(self->parNode,"nomphase",doubleData); - - - status = JulChoTransact(self,"RGW",reply,255); - if(status < 0){ - self->errorCode = status; - return 0; - } - if(!splitJulChoDouble(reply,doubleData)){ - self->errorCode = BADREPLY; - } - setJulChoDoublePar(self->parNode,"gatewidth",doubleData); - - status = JulChoTransact(self,"RNC",reply,255); - if(status < 0){ - self->errorCode = status; - return 0; - } - if(!splitJulChoDouble(reply,doubleData)){ - self->errorCode = BADREPLY; - } - setJulChoDoublePar(self->parNode,"nomcurrent",doubleData); - - - status = JulChoTransact(self,"RAC",reply,255); - if(status < 0){ - self->errorCode = status; - return 0; - } - if(!splitJulChoDouble(reply,doubleData)){ - self->errorCode = BADREPLY; - } - setJulChoDoublePar(self->parNode,"actcurrent",doubleData); - - status = JulChoTransact(self,"RAV",reply,255); - if(status < 0){ - self->errorCode = status; - return 0; - } - if(!splitJulChoDouble(reply,doubleData)){ - self->errorCode = BADREPLY; - } - setJulChoDoublePar(self->parNode,"voltage",doubleData); - - status = JulChoTransact(self,"RIT",reply,255); - if(status < 0){ - self->errorCode = status; - return 0; - } - if(!splitJulChoDouble(reply,doubleData)){ - self->errorCode = BADREPLY; - } - setJulChoDoublePar(self->parNode,"inverter_temperature",doubleData); + } - status = JulChoTransact(self,"RST",reply,255); - if(status < 0){ - self->errorCode = status; - return 0; - } - if(!splitJulChoDouble(reply,doubleData)){ - self->errorCode = BADREPLY; - } - setJulChoDoublePar(self->parNode,"stator_temperature",doubleData); + status = JulChoTransact(self, "RAS", reply, 255); + if (status < 0) { + self->errorCode = status; + return 0; + } + if (!splitJulChoInt(reply, intData)) { + self->errorCode = BADREPLY; + } + setJulChoIntPar(self->parNode, "actspeed", intData); - status = ReadJulChoFlags(self); - - self->lastUpdate = time(NULL); + status = JulChoTransact(self, "RAP", reply, 255); + if (status < 0) { + self->errorCode = status; + return 0; + } + if (!splitJulChoDouble(reply, doubleData)) { + self->errorCode = BADREPLY; + } + setJulChoDoublePar(self->parNode, "actphase", doubleData); + + if (what != ALL) { self->speedUpdate = time(NULL); - return status; + return 1; + } + + status = JulChoTransact(self, "RNS", reply, 255); + if (status < 0) { + self->errorCode = status; + return 0; + } + if (!splitJulChoInt(reply, intData)) { + self->errorCode = BADREPLY; + } + setJulChoIntPar(self->parNode, "nomspeed", intData); + + + status = JulChoTransact(self, "RNP", reply, 255); + if (status < 0) { + self->errorCode = status; + return 0; + } + if (!splitJulChoDouble(reply, doubleData)) { + self->errorCode = BADREPLY; + } + setJulChoDoublePar(self->parNode, "nomphase", doubleData); + + + status = JulChoTransact(self, "RGW", reply, 255); + if (status < 0) { + self->errorCode = status; + return 0; + } + if (!splitJulChoDouble(reply, doubleData)) { + self->errorCode = BADREPLY; + } + setJulChoDoublePar(self->parNode, "gatewidth", doubleData); + + status = JulChoTransact(self, "RNC", reply, 255); + if (status < 0) { + self->errorCode = status; + return 0; + } + if (!splitJulChoDouble(reply, doubleData)) { + self->errorCode = BADREPLY; + } + setJulChoDoublePar(self->parNode, "nomcurrent", doubleData); + + + status = JulChoTransact(self, "RAC", reply, 255); + if (status < 0) { + self->errorCode = status; + return 0; + } + if (!splitJulChoDouble(reply, doubleData)) { + self->errorCode = BADREPLY; + } + setJulChoDoublePar(self->parNode, "actcurrent", doubleData); + + status = JulChoTransact(self, "RAV", reply, 255); + if (status < 0) { + self->errorCode = status; + return 0; + } + if (!splitJulChoDouble(reply, doubleData)) { + self->errorCode = BADREPLY; + } + setJulChoDoublePar(self->parNode, "voltage", doubleData); + + status = JulChoTransact(self, "RIT", reply, 255); + if (status < 0) { + self->errorCode = status; + return 0; + } + if (!splitJulChoDouble(reply, doubleData)) { + self->errorCode = BADREPLY; + } + setJulChoDoublePar(self->parNode, "inverter_temperature", doubleData); + + status = JulChoTransact(self, "RST", reply, 255); + if (status < 0) { + self->errorCode = status; + return 0; + } + if (!splitJulChoDouble(reply, doubleData)) { + self->errorCode = BADREPLY; + } + setJulChoDoublePar(self->parNode, "stator_temperature", doubleData); + + status = ReadJulChoFlags(self); + + self->lastUpdate = time(NULL); + self->speedUpdate = time(NULL); + return status; } + /*------------------------------------------------------------------------*/ -static void JulChoErrorcodeToString(int code, char *pError, int iLen){ - switch(code){ - case FRAMEERROR: - strncpy(pError,"Frame error",iLen); - break; - case CKERROR: - strncpy(pError,"Checksum error",iLen); - break; - case BADCOMMAND: - strncpy(pError,"Bad Command",iLen); - break; - case WRONGNOPAR: - strncpy(pError,"Wrong number of parameters",iLen); - break; - case ILLPAR: - strncpy(pError,"Illegal parameter",iLen); - break; - case PARRANGE: - strncpy(pError,"Parameter out of range",iLen); - break; - case BADERR: - strncpy(pError,"Controller error not recognised",iLen); - break; - case BADREPLY: - strncpy(pError,"Unexpected reply",iLen); - break; - case NOTPAR: - strncpy(pError,"Unsupported parameter",iLen); - break; - case BADTEXT: - strncpy(pError,"Failed to convert text to number",iLen); - break; - case ROPAR: - strncpy(pError,"Read only Parameter",iLen); - break; - case NOMEM: - strncpy(pError,"Out of memory formatting parameter",iLen); - break; - case HALT: - strncpy(pError,"User requested HALT; choppers status undefined ",iLen); - break; - case SICSCBRANGE: - strncpy(pError,"Parameter value out of range",iLen); - break; - case SICSCBRO: - strncpy(pError,"Parameter is READ-ONLY",iLen); - break; - default: - getRS232Error(code, pError, iLen); - break; - } +static void JulChoErrorcodeToString(int code, char *pError, int iLen) +{ + switch (code) { + case FRAMEERROR: + strncpy(pError, "Frame error", iLen); + break; + case CKERROR: + strncpy(pError, "Checksum error", iLen); + break; + case BADCOMMAND: + strncpy(pError, "Bad Command", iLen); + break; + case WRONGNOPAR: + strncpy(pError, "Wrong number of parameters", iLen); + break; + case ILLPAR: + strncpy(pError, "Illegal parameter", iLen); + break; + case PARRANGE: + strncpy(pError, "Parameter out of range", iLen); + break; + case BADERR: + strncpy(pError, "Controller error not recognised", iLen); + break; + case BADREPLY: + strncpy(pError, "Unexpected reply", iLen); + break; + case NOTPAR: + strncpy(pError, "Unsupported parameter", iLen); + break; + case BADTEXT: + strncpy(pError, "Failed to convert text to number", iLen); + break; + case ROPAR: + strncpy(pError, "Read only Parameter", iLen); + break; + case NOMEM: + strncpy(pError, "Out of memory formatting parameter", iLen); + break; + case HALT: + strncpy(pError, "User requested HALT; choppers status undefined ", + iLen); + break; + case SICSCBRANGE: + strncpy(pError, "Parameter value out of range", iLen); + break; + case SICSCBRO: + strncpy(pError, "Parameter is READ-ONLY", iLen); + break; + default: + getRS232Error(code, pError, iLen); + break; + } } + /*------------------------------------------------------------------------*/ -static int testParGroup(char *name){ - if(strstr(name,"actspeed") != NULL || - strstr(name,"actphase") != NULL){ - return SPEED; - } else { - return ALL; - } +static int testParGroup(char *name) +{ + if (strstr(name, "actspeed") != NULL || strstr(name, "actphase") != NULL) { + return SPEED; + } else { + return ALL; + } } + /*-------------------------------------------------------------------------*/ -static hdbCallbackReturn JulChoGetCallback(pHdb currentNode, - void *userData, pHdbMessage message){ - pJulCho self = NULL; - SConnection *pCon = NULL; - int status; - char error[128], buffer[256]; - pHdbDataMessage mm = NULL; - - self = (pJulCho)userData; - assert(self != NULL); - - mm = GetHdbGetMessage(message); - if(mm == NULL){ - return hdbContinue; - } - pCon = (SConnection *)mm->callData; - - status = UpdateJulChoParameters(self,testParGroup(currentNode->name)); - if(status != 1 && pCon != NULL){ - JulChoErrorcodeToString(self->errorCode, error,127); - snprintf(buffer,255,"ERROR: %s occurred reading par",error); - SCWrite(pCon,buffer,eError); - } +static hdbCallbackReturn JulChoGetCallback(pHdb currentNode, + void *userData, + pHdbMessage message) +{ + pJulCho self = NULL; + SConnection *pCon = NULL; + int status; + char error[128], buffer[256]; + pHdbDataMessage mm = NULL; + + self = (pJulCho) userData; + assert(self != NULL); + + mm = GetHdbGetMessage(message); + if (mm == NULL) { return hdbContinue; + } + pCon = (SConnection *) mm->callData; + + status = UpdateJulChoParameters(self, testParGroup(currentNode->name)); + if (status != 1 && pCon != NULL) { + JulChoErrorcodeToString(self->errorCode, error, 127); + snprintf(buffer, 255, "ERROR: %s occurred reading par", error); + SCWrite(pCon, buffer, eError); + } + return hdbContinue; } + /*--------------------------------------------------------------------------*/ -static int AppendJulChoROPar(pHdb parent, char *name, int type){ - pHdb child = NULL; - child = AddSICSHdbROPar(parent,name,makeHdbValue(type,1)); - if(child != NULL){ - return 1; - } else { - return 0; - } +static int AppendJulChoROPar(pHdb parent, char *name, int type) +{ + pHdb child = NULL; + child = AddSICSHdbROPar(parent, name, makeHdbValue(type, 1)); + if (child != NULL) { + return 1; + } else { + return 0; + } } + /*---------------------------------------------------------------------------*/ -static int ConfigureSingleJulCho(pHdb parent, pJulCho driv, - char *prefix, char *postfix){ - pHdb child = NULL; - pHdbCallback pCb = NULL; - - /* - * write parameters - */ - - child = MakeHipadabaNode("nomphase",HIPFLOAT,0); - if(child == NULL){ - return 0; - } - pCb = MakeCheckPermissionCallback(usUser); - if(pCb == NULL){ - return 0; - } - AppendHipadabaCallback(child,pCb); - pCb = MakeFloatRangeCallback(5.0, 355.); - if(pCb == NULL){ - return 0; - } - AppendHipadabaCallback(child,pCb); - pCb = MakeJulChoSetCallback(driv,"SPH", prefix,postfix); - if(pCb == NULL){ - return 0; - } - AppendHipadabaCallback(child,pCb); - AddHipadabaChild(parent,child,NULL); - - child = MakeHipadabaNode("gatewidth",HIPFLOAT,0); - if(child == NULL){ - return 0; - } - pCb = MakeCheckPermissionCallback(usUser); - if(pCb == NULL){ - return 0; - } - AppendHipadabaCallback(child,pCb); - pCb = MakeJulChoSetCallback(driv,"SGW", prefix,postfix); - if(pCb == NULL){ - return 0; - } - AppendHipadabaCallback(child,pCb); - AddHipadabaChild(parent,child,NULL); - - if(!AppendJulChoROPar(parent,"nomspeed",HIPINT)){ - return 0; - } - - if(!AppendJulChoROPar(parent,"actspeed",HIPINT)){ - return 0; - } - - if(!AppendJulChoROPar(parent,"actphase",HIPFLOAT)){ - return 0; - } - - if(!AppendJulChoROPar(parent,"nomcurrent",HIPFLOAT)){ - return 0; - } - - if(!AppendJulChoROPar(parent,"actcurrent",HIPFLOAT)){ - return 0; - } - - if(!AppendJulChoROPar(parent,"voltage",HIPFLOAT)){ - return 0; - } - - if(!AppendJulChoROPar(parent,"inverter_temperature",HIPFLOAT)){ - return 0; - } +static int ConfigureSingleJulCho(pHdb parent, pJulCho driv, + char *prefix, char *postfix) +{ + pHdb child = NULL; + pHdbCallback pCb = NULL; - if(!AppendJulChoROPar(parent,"stator_temperature",HIPFLOAT)){ - return 0; - } - - if(!AppendJulChoROPar(parent,"microok",HIPINT)){ - return 0; - } - - if(!AppendJulChoROPar(parent,"atspeed",HIPINT)){ - return 0; - } - - if(!AppendJulChoROPar(parent,"atphase",HIPINT)){ - return 0; - } - - if(!AppendJulChoROPar(parent,"magneton",HIPINT)){ - return 0; - } + /* + * write parameters + */ - if(!AppendJulChoROPar(parent,"dcon",HIPINT)){ - return 0; - } - - if(!AppendJulChoROPar(parent,"driveon",HIPINT)){ - return 0; - } - - if(!AppendJulChoROPar(parent,"currentdc",HIPINT)){ - return 0; - } - - if(!AppendJulChoROPar(parent,"lockopen",HIPINT)){ - return 0; - } - - if(!AppendJulChoROPar(parent,"diskopen",HIPINT)){ - return 0; - } - - if(!AppendJulChoROPar(parent,"diskclosed",HIPINT)){ - return 0; - } - - if(!AppendJulChoROPar(parent,"speedoverflow",HIPINT)){ - return 0; - } - - if(!AppendJulChoROPar(parent,"bearingfailed",HIPINT)){ - return 0; - } - - if(!AppendJulChoROPar(parent,"voltagetohigh",HIPINT)){ - return 0; - } - - /* - * append get callbacks - */ - child = parent->child; - while(child != NULL){ - AppendHipadabaCallback(child, - MakeHipadabaCallback(JulChoGetCallback,driv,NULL)); - child = child->next; - } - return 1; + child = MakeHipadabaNode("nomphase", HIPFLOAT, 0); + if (child == NULL) { + return 0; + } + pCb = MakeCheckPermissionCallback(usUser); + if (pCb == NULL) { + return 0; + } + AppendHipadabaCallback(child, pCb); + pCb = MakeFloatRangeCallback(5.0, 355.); + if (pCb == NULL) { + return 0; + } + AppendHipadabaCallback(child, pCb); + pCb = MakeJulChoSetCallback(driv, "SPH", prefix, postfix); + if (pCb == NULL) { + return 0; + } + AppendHipadabaCallback(child, pCb); + AddHipadabaChild(parent, child, NULL); + + child = MakeHipadabaNode("gatewidth", HIPFLOAT, 0); + if (child == NULL) { + return 0; + } + pCb = MakeCheckPermissionCallback(usUser); + if (pCb == NULL) { + return 0; + } + AppendHipadabaCallback(child, pCb); + pCb = MakeJulChoSetCallback(driv, "SGW", prefix, postfix); + if (pCb == NULL) { + return 0; + } + AppendHipadabaCallback(child, pCb); + AddHipadabaChild(parent, child, NULL); + + if (!AppendJulChoROPar(parent, "nomspeed", HIPINT)) { + return 0; + } + + if (!AppendJulChoROPar(parent, "actspeed", HIPINT)) { + return 0; + } + + if (!AppendJulChoROPar(parent, "actphase", HIPFLOAT)) { + return 0; + } + + if (!AppendJulChoROPar(parent, "nomcurrent", HIPFLOAT)) { + return 0; + } + + if (!AppendJulChoROPar(parent, "actcurrent", HIPFLOAT)) { + return 0; + } + + if (!AppendJulChoROPar(parent, "voltage", HIPFLOAT)) { + return 0; + } + + if (!AppendJulChoROPar(parent, "inverter_temperature", HIPFLOAT)) { + return 0; + } + + if (!AppendJulChoROPar(parent, "stator_temperature", HIPFLOAT)) { + return 0; + } + + if (!AppendJulChoROPar(parent, "microok", HIPINT)) { + return 0; + } + + if (!AppendJulChoROPar(parent, "atspeed", HIPINT)) { + return 0; + } + + if (!AppendJulChoROPar(parent, "atphase", HIPINT)) { + return 0; + } + + if (!AppendJulChoROPar(parent, "magneton", HIPINT)) { + return 0; + } + + if (!AppendJulChoROPar(parent, "dcon", HIPINT)) { + return 0; + } + + if (!AppendJulChoROPar(parent, "driveon", HIPINT)) { + return 0; + } + + if (!AppendJulChoROPar(parent, "currentdc", HIPINT)) { + return 0; + } + + if (!AppendJulChoROPar(parent, "lockopen", HIPINT)) { + return 0; + } + + if (!AppendJulChoROPar(parent, "diskopen", HIPINT)) { + return 0; + } + + if (!AppendJulChoROPar(parent, "diskclosed", HIPINT)) { + return 0; + } + + if (!AppendJulChoROPar(parent, "speedoverflow", HIPINT)) { + return 0; + } + + if (!AppendJulChoROPar(parent, "bearingfailed", HIPINT)) { + return 0; + } + + if (!AppendJulChoROPar(parent, "voltagetohigh", HIPINT)) { + return 0; + } + + /* + * append get callbacks + */ + child = parent->child; + while (child != NULL) { + AppendHipadabaCallback(child, + MakeHipadabaCallback(JulChoGetCallback, driv, + NULL)); + child = child->next; + } + return 1; } -/*--------------------------------------------------------------------------*/ -static int InitJulChoPar(pJulCho driv){ - pHdb child = NULL, parChild = NULL; - pHdbCallback pCb = NULL; - - - child = MakeHipadabaNode(CH1N,HIPNONE,0); - if(child == NULL){ - return 0; - } - if(!ConfigureSingleJulCho(child,driv,"","::::")){ - return 0; - } - AddHipadabaChild(driv->parNode,child,NULL); - child = MakeHipadabaNode(CH2N,HIPNONE,0); - if(child == NULL){ - return 0; - } - if(!ConfigureSingleJulCho(child,driv,":",":::")){ - return 0; - } +/*--------------------------------------------------------------------------*/ +static int InitJulChoPar(pJulCho driv) +{ + pHdb child = NULL, parChild = NULL; + pHdbCallback pCb = NULL; + + + child = MakeHipadabaNode(CH1N, HIPNONE, 0); + if (child == NULL) { + return 0; + } + if (!ConfigureSingleJulCho(child, driv, "", "::::")) { + return 0; + } + AddHipadabaChild(driv->parNode, child, NULL); + + child = MakeHipadabaNode(CH2N, HIPNONE, 0); + if (child == NULL) { + return 0; + } + if (!ConfigureSingleJulCho(child, driv, ":", ":::")) { + return 0; + } /** * the master speed can be set, the slaves not, thus remove the read only * set callback and replace by a speed setting callback */ - parChild = GetHipadabaNode(child,"nomspeed"); - assert(parChild != NULL); - /* - * delete the callback cahin in order to remove the - * read only callback - */ - DeleteCallbackChain(parChild); - parChild->callBackChain = NULL; + parChild = GetHipadabaNode(child, "nomspeed"); + assert(parChild != NULL); + /* + * delete the callback cahin in order to remove the + * read only callback + */ + DeleteCallbackChain(parChild); + parChild->callBackChain = NULL; - pCb = MakeCheckPermissionCallback(usUser); - if(pCb == NULL){ - return 0; - } - AppendHipadabaCallback(parChild,pCb); - pCb = MakeJulChoSetCallback(driv,"SMS","",""); - if(pCb == NULL){ - return 0; - } - AppendHipadabaCallback(parChild,pCb); - AppendHipadabaCallback(parChild, - MakeHipadabaCallback(JulChoGetCallback,driv,NULL)); - - - AddHipadabaChild(driv->parNode,child,NULL); - - child = MakeHipadabaNode(CH3N,HIPNONE,0); - if(child == NULL){ - return 0; - } - if(!ConfigureSingleJulCho(child,driv,"::","::")){ - return 0; - } - AddHipadabaChild(driv->parNode,child,NULL); + pCb = MakeCheckPermissionCallback(usUser); + if (pCb == NULL) { + return 0; + } + AppendHipadabaCallback(parChild, pCb); + pCb = MakeJulChoSetCallback(driv, "SMS", "", ""); + if (pCb == NULL) { + return 0; + } + AppendHipadabaCallback(parChild, pCb); + AppendHipadabaCallback(parChild, + MakeHipadabaCallback(JulChoGetCallback, driv, + NULL)); - child = MakeHipadabaNode(CH4N,HIPNONE,0); - if(child == NULL){ - return 0; - } - if(!ConfigureSingleJulCho(child,driv,":::",":")){ - return 0; - } - AddHipadabaChild(driv->parNode,child,NULL); - child = MakeHipadabaNode(CH5N,HIPNONE,0); - if(child == NULL){ - return 0; - } - if(!ConfigureSingleJulCho(child,driv,"::::","")){ - return 0; - } - AddHipadabaChild(driv->parNode,child,NULL); - - return 1; + AddHipadabaChild(driv->parNode, child, NULL); + + child = MakeHipadabaNode(CH3N, HIPNONE, 0); + if (child == NULL) { + return 0; + } + if (!ConfigureSingleJulCho(child, driv, "::", "::")) { + return 0; + } + AddHipadabaChild(driv->parNode, child, NULL); + + child = MakeHipadabaNode(CH4N, HIPNONE, 0); + if (child == NULL) { + return 0; + } + if (!ConfigureSingleJulCho(child, driv, ":::", ":")) { + return 0; + } + AddHipadabaChild(driv->parNode, child, NULL); + + child = MakeHipadabaNode(CH5N, HIPNONE, 0); + if (child == NULL) { + return 0; + } + if (!ConfigureSingleJulCho(child, driv, "::::", "")) { + return 0; + } + AddHipadabaChild(driv->parNode, child, NULL); + + return 1; } + /*================= actual interface functions ==============================*/ -static int JulChoInit(pCodri pDriv){ - pJulCho self = NULL; - int status; - - self = (pJulCho)pDriv->pPrivate; - status = initRS232(self->controller); - if(status < 1){ - self->errorCode = status; - } - setRS232SendTerminator(self->controller,"$"); - setRS232ReplyTerminator(self->controller,"$"); - setRS232Timeout(self->controller,2000); - return 1; -} -/*---------------------------------------------------------------------------*/ -static int JulChoClose(pCodri pDriv){ - pJulCho self = NULL; - - self = (pJulCho)pDriv->pPrivate; - closeRS232(self->controller); - return 1; -} -/*---------------------------------------------------------------------------*/ -static int JulChoKill(pCodri pDriv){ - pJulCho self = NULL; +static int JulChoInit(pCodri pDriv) +{ + pJulCho self = NULL; + int status; - if(pDriv == NULL){ - return 1; - } - self = (pJulCho)pDriv->pPrivate; - JulChoClose(pDriv); - if(self->controller != NULL){ - KillRS232(self->controller); - self->controller = NULL; - } - free(self); - return 1; + self = (pJulCho) pDriv->pPrivate; + status = initRS232(self->controller); + if (status < 1) { + self->errorCode = status; + } + setRS232SendTerminator(self->controller, "$"); + setRS232ReplyTerminator(self->controller, "$"); + setRS232Timeout(self->controller, 2000); + return 1; } + +/*---------------------------------------------------------------------------*/ +static int JulChoClose(pCodri pDriv) +{ + pJulCho self = NULL; + + self = (pJulCho) pDriv->pPrivate; + closeRS232(self->controller); + return 1; +} + +/*---------------------------------------------------------------------------*/ +static int JulChoKill(pCodri pDriv) +{ + pJulCho self = NULL; + + if (pDriv == NULL) { + return 1; + } + self = (pJulCho) pDriv->pPrivate; + JulChoClose(pDriv); + if (self->controller != NULL) { + KillRS232(self->controller); + self->controller = NULL; + } + free(self); + return 1; +} + /*--------------------------------------------------------------------------- * The set and get routines introduce phase and speed values which map to * nomspeed when setting and actspeed when reading. This ugly hack saves me * to introduce another drive adapter which set one parameter and reads * another *---------------------------------------------------------------------------*/ -static int JulChoSetPar2(pCodri pDriv, char *parname, char *pValue){ - pJulCho self = NULL; - pHdb target = NULL; - hdbValue v; - char error[64], *pPtr = NULL; - int status; - - if(strcmp(parname,"master/speed") == 0){ - status = JulChoSetPar2(pDriv,"master/nomspeed", pValue); - if(status == 1) { - SicsWait(10); - } - return status; - } else if(strcmp(parname,"master/phase") == 0){ - return JulChoSetPar2(pDriv,"master/nomphase", pValue); - } else if(strcmp(parname,"snail/phase") == 0){ - return JulChoSetPar2(pDriv,"snail/nomphase", pValue); - } else if(strcmp(parname,"rabbit/phase") == 0){ - return JulChoSetPar2(pDriv,"rabbit/nomphase", pValue); - } else if(strcmp(parname, "four/phase") == 0){ - return JulChoSetPar2(pDriv,"four/nomphase", pValue); - } else if(strcmp(parname,"five/phase") == 0){ - return JulChoSetPar2(pDriv,"five/nomphase", pValue); +static int JulChoSetPar2(pCodri pDriv, char *parname, char *pValue) +{ + pJulCho self = NULL; + pHdb target = NULL; + hdbValue v; + char error[64], *pPtr = NULL; + int status; + + if (strcmp(parname, "master/speed") == 0) { + status = JulChoSetPar2(pDriv, "master/nomspeed", pValue); + if (status == 1) { + SicsWait(10); } - - self = (pJulCho)pDriv->pPrivate; - target = GetHipadabaNode(self->parNode,parname); - if(target == NULL){ - self->errorCode = NOTPAR; - return 0; - } - v.dataType = target->value.dataType; - if(!readHdbValue(&v,pValue,error,63)){ - self->errorCode = BADTEXT; - return 0; - } - self->errorCode = 0; - status = SetHipadabaPar(target,v,NULL); - if(status == 0 && self->errorCode == 0){ - self->errorCode = status; - return 0; - } - /* - * The SicsWait is here to allow the chopper to update his status flags. - * There were occurrences where the chopper was still driving but the - * status flag did not reflect this. - */ - SicsWait(STWAIT); - self->lastUpdate = 0; return status; + } else if (strcmp(parname, "master/phase") == 0) { + return JulChoSetPar2(pDriv, "master/nomphase", pValue); + } else if (strcmp(parname, "snail/phase") == 0) { + return JulChoSetPar2(pDriv, "snail/nomphase", pValue); + } else if (strcmp(parname, "rabbit/phase") == 0) { + return JulChoSetPar2(pDriv, "rabbit/nomphase", pValue); + } else if (strcmp(parname, "four/phase") == 0) { + return JulChoSetPar2(pDriv, "four/nomphase", pValue); + } else if (strcmp(parname, "five/phase") == 0) { + return JulChoSetPar2(pDriv, "five/nomphase", pValue); + } + + self = (pJulCho) pDriv->pPrivate; + target = GetHipadabaNode(self->parNode, parname); + if (target == NULL) { + self->errorCode = NOTPAR; + return 0; + } + v.dataType = target->value.dataType; + if (!readHdbValue(&v, pValue, error, 63)) { + self->errorCode = BADTEXT; + return 0; + } + self->errorCode = 0; + status = SetHipadabaPar(target, v, NULL); + if (status == 0 && self->errorCode == 0) { + self->errorCode = status; + return 0; + } + /* + * The SicsWait is here to allow the chopper to update his status flags. + * There were occurrences where the chopper was still driving but the + * status flag did not reflect this. + */ + SicsWait(STWAIT); + self->lastUpdate = 0; + return status; } + /*-------------------------------------------------------------------------------*/ -static int JulChoSetPar(pCodri pDriv, char *parname, float fValue){ - pJulCho self = NULL; - pHdb target = NULL; - hdbValue v; - char error[64]; - int status; - - if(strcmp(parname,"master/speed") == 0){ - status = JulChoSetPar(pDriv,"master/nomspeed", fValue); - if(status == 1) { - SicsWait(10); - } - return status; - } else if(strcmp(parname,"master/phase") == 0){ - return JulChoSetPar(pDriv,"master/nomphase", fValue); - } else if(strcmp(parname,"snail/phase") == 0){ - return JulChoSetPar(pDriv,"snail/nomphase", fValue); - } else if(strcmp(parname,"rabbit/phase") == 0){ - return JulChoSetPar(pDriv,"rabbit/nomphase", fValue); - } else if(strcmp(parname, "four/phase") == 0){ - return JulChoSetPar(pDriv,"four/nomphase", fValue); - } else if(strcmp(parname,"five/phase") == 0){ - return JulChoSetPar(pDriv,"five/nomphase", fValue); +static int JulChoSetPar(pCodri pDriv, char *parname, float fValue) +{ + pJulCho self = NULL; + pHdb target = NULL; + hdbValue v; + char error[64]; + int status; + + if (strcmp(parname, "master/speed") == 0) { + status = JulChoSetPar(pDriv, "master/nomspeed", fValue); + if (status == 1) { + SicsWait(10); } - - self = (pJulCho)pDriv->pPrivate; - target = GetHipadabaNode(self->parNode,parname); - if(target == NULL){ - self->errorCode = NOTPAR; - return 0; - } - v.dataType = target->value.dataType; - if(v.dataType == HIPINT){ - v.v.intValue = (int)fValue; - } else { - v.v.doubleValue = (double)fValue; - } - self->errorCode = 0; - status = SetHipadabaPar(target,v,NULL); - if(status == 0 && self->errorCode == 0){ - self->errorCode = status; - return 0; - } - /* - * The SicsWait is here to allow the chopper to update his status flags. - * There were occurrences where the chopper was still driving but the - * status flag did not reflect this. - */ - SicsWait(STWAIT); - self->lastUpdate = 0; return status; + } else if (strcmp(parname, "master/phase") == 0) { + return JulChoSetPar(pDriv, "master/nomphase", fValue); + } else if (strcmp(parname, "snail/phase") == 0) { + return JulChoSetPar(pDriv, "snail/nomphase", fValue); + } else if (strcmp(parname, "rabbit/phase") == 0) { + return JulChoSetPar(pDriv, "rabbit/nomphase", fValue); + } else if (strcmp(parname, "four/phase") == 0) { + return JulChoSetPar(pDriv, "four/nomphase", fValue); + } else if (strcmp(parname, "five/phase") == 0) { + return JulChoSetPar(pDriv, "five/nomphase", fValue); + } + + self = (pJulCho) pDriv->pPrivate; + target = GetHipadabaNode(self->parNode, parname); + if (target == NULL) { + self->errorCode = NOTPAR; + return 0; + } + v.dataType = target->value.dataType; + if (v.dataType == HIPINT) { + v.v.intValue = (int) fValue; + } else { + v.v.doubleValue = (double) fValue; + } + self->errorCode = 0; + status = SetHipadabaPar(target, v, NULL); + if (status == 0 && self->errorCode == 0) { + self->errorCode = status; + return 0; + } + /* + * The SicsWait is here to allow the chopper to update his status flags. + * There were occurrences where the chopper was still driving but the + * status flag did not reflect this. + */ + SicsWait(STWAIT); + self->lastUpdate = 0; + return status; } + /*---------------------------------------------------------------------------*/ -static int JulChoHalt(pCodri pDriv){ - pJulCho self = NULL; - - self = (pJulCho)pDriv->pPrivate; - self->halt = 1; - /* - * empty function on Philips request - */ - return 1; +static int JulChoHalt(pCodri pDriv) +{ + pJulCho self = NULL; + + self = (pJulCho) pDriv->pPrivate; + self->halt = 1; + /* + * empty function on Philips request + */ + return 1; } + /*--------------------------------------------------------------------------*/ -static int JulChoGetPar(pCodri pDriv, char *parname, - char *pBuffer, int iBufLen){ - pJulCho self = NULL; - pHdb target = NULL; - pDynString val = NULL; +static int JulChoGetPar(pCodri pDriv, char *parname, + char *pBuffer, int iBufLen) +{ + pJulCho self = NULL; + pHdb target = NULL; + pDynString val = NULL; - if(strcmp(parname,"master/speed") == 0){ - return JulChoGetPar(pDriv,"master/actspeed", pBuffer,iBufLen); - } else if(strcmp(parname,"master/phase") == 0){ - return JulChoGetPar(pDriv,"master/actphase", pBuffer,iBufLen); - } else if(strcmp(parname,"snail/phase") == 0){ - return JulChoGetPar(pDriv,"snail/actphase", pBuffer,iBufLen); - } else if(strcmp(parname,"rabbit/phase") == 0){ - return JulChoGetPar(pDriv,"rabbit/actphase", pBuffer,iBufLen); - } else if(strcmp(parname, "four/phase") == 0){ - return JulChoGetPar(pDriv,"four/actphase", pBuffer,iBufLen); - } else if(strcmp(parname,"five/phase") == 0){ - return JulChoGetPar(pDriv,"five/actphase", pBuffer,iBufLen); - } + if (strcmp(parname, "master/speed") == 0) { + return JulChoGetPar(pDriv, "master/actspeed", pBuffer, iBufLen); + } else if (strcmp(parname, "master/phase") == 0) { + return JulChoGetPar(pDriv, "master/actphase", pBuffer, iBufLen); + } else if (strcmp(parname, "snail/phase") == 0) { + return JulChoGetPar(pDriv, "snail/actphase", pBuffer, iBufLen); + } else if (strcmp(parname, "rabbit/phase") == 0) { + return JulChoGetPar(pDriv, "rabbit/actphase", pBuffer, iBufLen); + } else if (strcmp(parname, "four/phase") == 0) { + return JulChoGetPar(pDriv, "four/actphase", pBuffer, iBufLen); + } else if (strcmp(parname, "five/phase") == 0) { + return JulChoGetPar(pDriv, "five/actphase", pBuffer, iBufLen); + } - - self = (pJulCho)pDriv->pPrivate; - target = GetHipadabaNode(self->parNode,parname); - if(target == NULL){ - self->errorCode = NOTPAR; - return 0; - } - if(!UpdateJulChoParameters(self,testParGroup(parname))){ - return 0; - } - val = formatValue(target->value, target); - if(val == NULL){ - self->errorCode = NOMEM; - return 0; - } - strncpy(pBuffer,GetCharArray(val), iBufLen); - DeleteDynString(val); - return 1; + + self = (pJulCho) pDriv->pPrivate; + target = GetHipadabaNode(self->parNode, parname); + if (target == NULL) { + self->errorCode = NOTPAR; + return 0; + } + if (!UpdateJulChoParameters(self, testParGroup(parname))) { + return 0; + } + val = formatValue(target->value, target); + if (val == NULL) { + self->errorCode = NOMEM; + return 0; + } + strncpy(pBuffer, GetCharArray(val), iBufLen); + DeleteDynString(val); + return 1; } -/*---------------------------------------------------------------------------*/ -static int JulChoCheckPar(pCodri pDriv, char *parname){ - pJulCho self = NULL; - int i, status; - char path[256], reply[256]; - pHdb target = NULL; - char *chNames[] = {CH1N, - CH2N, - CH3N, - CH4N, - CH5N, - NULL}; - self = (pJulCho)pDriv->pPrivate; - - if(self->halt == 1){ - self->errorCode = HALT; - return HWFault; +/*---------------------------------------------------------------------------*/ +static int JulChoCheckPar(pCodri pDriv, char *parname) +{ + pJulCho self = NULL; + int i, status; + char path[256], reply[256]; + pHdb target = NULL; + char *chNames[] = { CH1N, + CH2N, + CH3N, + CH4N, + CH5N, + NULL + }; + + self = (pJulCho) pDriv->pPrivate; + + if (self->halt == 1) { + self->errorCode = HALT; + return HWFault; + } + /* + * For the Juelich chopper this means checking the atspeed, atphase + * flags + */ + if (!ReadJulChoFlags(self)) { + return HWFault; + } + for (i = 0; i < 5; i++) { + snprintf(path, 255, "%s/atspeed", chNames[i]); + target = GetHipadabaNode(self->parNode, path); + assert(target != NULL); + if (target->value.v.intValue == 0) { + return HWBusy; } - /* - * For the Juelich chopper this means checking the atspeed, atphase - * flags - */ - if(!ReadJulChoFlags(self)){ - return HWFault; - } - for(i = 0; i < 5; i++){ - snprintf(path,255,"%s/atspeed", chNames[i]); - target = GetHipadabaNode(self->parNode,path); - assert(target != NULL); - if(target->value.v.intValue == 0){ - return HWBusy; - } - snprintf(path,255,"%s/atphase",chNames[i]); - target = GetHipadabaNode(self->parNode,path); - assert(target != NULL); - if(target->value.v.intValue == 0){ - return HWBusy; - } - } - status = JulChoTransact(self,"RSC",reply,255); - if(status < 0){ - self->errorCode = status; - return HWFault; + snprintf(path, 255, "%s/atphase", chNames[i]); + target = GetHipadabaNode(self->parNode, path); + assert(target != NULL); + if (target->value.v.intValue == 0) { + return HWBusy; } + } + status = JulChoTransact(self, "RSC", reply, 255); + if (status < 0) { + self->errorCode = status; + return HWFault; + } /* fprintf(stdout,"Chopper Flags at finish: %s\n", reply);*/ - return HWIdle; + return HWIdle; } + /*---------------------------------------------------------------------------*/ -static int JulChoError(pCodri pDriv, int *iCode, char *pError, int iLen){ - pJulCho self = NULL; +static int JulChoError(pCodri pDriv, int *iCode, char *pError, int iLen) +{ + pJulCho self = NULL; - self = (pJulCho)pDriv->pPrivate; + self = (pJulCho) pDriv->pPrivate; - *iCode = self->errorCode; - JulChoErrorcodeToString(self->errorCode, pError, iLen); - return 1; + *iCode = self->errorCode; + JulChoErrorcodeToString(self->errorCode, pError, iLen); + return 1; } + /*---------------------------------------------------------------------------*/ -static int JulChoFix(pCodri pDriv, int code){ - pJulCho self = NULL; +static int JulChoFix(pCodri pDriv, int code) +{ + pJulCho self = NULL; - self = (pJulCho)pDriv->pPrivate; - - switch(code){ - case TIMEOUT: - case CKERROR: - case BADERR: - case BADREPLY: - return CHREDO; - break; - case NOTCONNECTED: - if(initRS232(self->controller) == 1){ - return CHREDO; - } else { - return CHFAIL; - } - break; - case INCOMPLETE: - case BADSEND: - case BADREAD: - closeRS232(self->controller); - if(initRS232(self->controller) == 1){ - return CHREDO; - } else { - return CHFAIL; - } - break; - default: - return CHFAIL; - break; + self = (pJulCho) pDriv->pPrivate; + + switch (code) { + case TIMEOUT: + case CKERROR: + case BADERR: + case BADREPLY: + return CHREDO; + break; + case NOTCONNECTED: + if (initRS232(self->controller) == 1) { + return CHREDO; + } else { + return CHFAIL; } + break; + case INCOMPLETE: + case BADSEND: + case BADREAD: + closeRS232(self->controller); + if (initRS232(self->controller) == 1) { + return CHREDO; + } else { + return CHFAIL; + } + break; + default: + return CHFAIL; + break; + } } + /*---------------------------------------------------------------------------*/ -static pCodri MakeJulChoDriver(char *pHost, int port, pHdb parNode){ - pCodri pDriv = NULL; - pJulCho self = NULL; - int i; - pDynString names = NULL; - char *chNames[] = {CH1N, - CH2N, - CH3N, - CH4N, - CH5N, - NULL}; - char path[256], *par = NULL; - - pDriv = malloc(sizeof(Codri)); - self = malloc(sizeof(JulCho)); - names = CreateDynString(256,256); - - if(pDriv == NULL && self == NULL && names == NULL){ - return NULL; - } - memset(pDriv,0,sizeof(Codri)); - memset(self,0,sizeof(JulCho)); - - self->parNode = parNode; - self->controller = createRS232(pHost,port); - if(self->controller == NULL){ - free(self); - free(pDriv); - return NULL; - } - self->updateIntervall = 10; - if(!InitJulChoPar(self)){ - free(self); - free(pDriv); - return NULL; - } - - pDriv->pPrivate = self; - - pDriv->Init = JulChoInit; - pDriv->Close = JulChoClose; - pDriv->Delete = JulChoKill; - pDriv->SetPar = JulChoSetPar; - pDriv->SetPar2 = JulChoSetPar2; - pDriv->GetPar = JulChoGetPar; - pDriv->CheckPar = JulChoCheckPar; - pDriv->GetError = JulChoError; - pDriv->TryFixIt = JulChoFix; - pDriv->Halt = JulChoHalt; - - for(i = 0; i < 5; i++){ - snprintf(path,255,"%s/nomspeed,",chNames[i]); - DynStringConcat(names,path); - snprintf(path,255,"%s/actspeed,",chNames[i]); - DynStringConcat(names,path); - snprintf(path,255,"%s/nomphase,",chNames[i]); - DynStringConcat(names,path); - snprintf(path,255,"%s/actphase,",chNames[i]); - DynStringConcat(names,path); - snprintf(path,255,"%s/gatewidth,",chNames[i]); - DynStringConcat(names,path); - snprintf(path,255,"%s/nomcurrent,",chNames[i]); - DynStringConcat(names,path); - snprintf(path,255,"%s/actcurrent,",chNames[i]); - DynStringConcat(names,path); - snprintf(path,255,"%s/voltage,",chNames[i]); - DynStringConcat(names,path); - snprintf(path,255,"%s/inverter_temperature,",chNames[i]); - DynStringConcat(names,path); - snprintf(path,255,"%s/stator_temperature,",chNames[i]); - DynStringConcat(names,path); - snprintf(path,255,"%s/microok,",chNames[i]); - DynStringConcat(names,path); - snprintf(path,255,"%s/atspeed,",chNames[i]); - DynStringConcat(names,path); - snprintf(path,255,"%s/atphase,",chNames[i]); - DynStringConcat(names,path); - snprintf(path,255,"%s/magneton,",chNames[i]); - DynStringConcat(names,path); - snprintf(path,255,"%s/dcon,",chNames[i]); - DynStringConcat(names,path); - snprintf(path,255,"%s/driveon,",chNames[i]); - DynStringConcat(names,path); - snprintf(path,255,"%s/currentdc,",chNames[i]); - DynStringConcat(names,path); - snprintf(path,255,"%s/lockopen,",chNames[i]); - DynStringConcat(names,path); - snprintf(path,255,"%s/diskopen,",chNames[i]); - DynStringConcat(names,path); - snprintf(path,255,"%s/diskclosed,",chNames[i]); - DynStringConcat(names,path); - snprintf(path,255,"%s/speedoverflow,",chNames[i]); - DynStringConcat(names,path); - snprintf(path,255,"%s/bearingfailed,",chNames[i]); - DynStringConcat(names,path); - snprintf(path,255,"%s/voltagetohigh,",chNames[i]); - DynStringConcat(names,path); - } - par = GetCharArray(names); - par[strlen(par) -1] = '\0'; - pDriv->pParList = strdup(par); - DeleteDynString(names); - if(pDriv->pParList == NULL){ - JulChoKill(pDriv); - free(pDriv); - return NULL; - } +static pCodri MakeJulChoDriver(char *pHost, int port, pHdb parNode) +{ + pCodri pDriv = NULL; + pJulCho self = NULL; + int i; + pDynString names = NULL; + char *chNames[] = { CH1N, + CH2N, + CH3N, + CH4N, + CH5N, + NULL + }; + char path[256], *par = NULL; - return pDriv; + pDriv = malloc(sizeof(Codri)); + self = malloc(sizeof(JulCho)); + names = CreateDynString(256, 256); + + if (pDriv == NULL && self == NULL && names == NULL) { + return NULL; + } + memset(pDriv, 0, sizeof(Codri)); + memset(self, 0, sizeof(JulCho)); + + self->parNode = parNode; + self->controller = createRS232(pHost, port); + if (self->controller == NULL) { + free(self); + free(pDriv); + return NULL; + } + self->updateIntervall = 10; + if (!InitJulChoPar(self)) { + free(self); + free(pDriv); + return NULL; + } + + pDriv->pPrivate = self; + + pDriv->Init = JulChoInit; + pDriv->Close = JulChoClose; + pDriv->Delete = JulChoKill; + pDriv->SetPar = JulChoSetPar; + pDriv->SetPar2 = JulChoSetPar2; + pDriv->GetPar = JulChoGetPar; + pDriv->CheckPar = JulChoCheckPar; + pDriv->GetError = JulChoError; + pDriv->TryFixIt = JulChoFix; + pDriv->Halt = JulChoHalt; + + for (i = 0; i < 5; i++) { + snprintf(path, 255, "%s/nomspeed,", chNames[i]); + DynStringConcat(names, path); + snprintf(path, 255, "%s/actspeed,", chNames[i]); + DynStringConcat(names, path); + snprintf(path, 255, "%s/nomphase,", chNames[i]); + DynStringConcat(names, path); + snprintf(path, 255, "%s/actphase,", chNames[i]); + DynStringConcat(names, path); + snprintf(path, 255, "%s/gatewidth,", chNames[i]); + DynStringConcat(names, path); + snprintf(path, 255, "%s/nomcurrent,", chNames[i]); + DynStringConcat(names, path); + snprintf(path, 255, "%s/actcurrent,", chNames[i]); + DynStringConcat(names, path); + snprintf(path, 255, "%s/voltage,", chNames[i]); + DynStringConcat(names, path); + snprintf(path, 255, "%s/inverter_temperature,", chNames[i]); + DynStringConcat(names, path); + snprintf(path, 255, "%s/stator_temperature,", chNames[i]); + DynStringConcat(names, path); + snprintf(path, 255, "%s/microok,", chNames[i]); + DynStringConcat(names, path); + snprintf(path, 255, "%s/atspeed,", chNames[i]); + DynStringConcat(names, path); + snprintf(path, 255, "%s/atphase,", chNames[i]); + DynStringConcat(names, path); + snprintf(path, 255, "%s/magneton,", chNames[i]); + DynStringConcat(names, path); + snprintf(path, 255, "%s/dcon,", chNames[i]); + DynStringConcat(names, path); + snprintf(path, 255, "%s/driveon,", chNames[i]); + DynStringConcat(names, path); + snprintf(path, 255, "%s/currentdc,", chNames[i]); + DynStringConcat(names, path); + snprintf(path, 255, "%s/lockopen,", chNames[i]); + DynStringConcat(names, path); + snprintf(path, 255, "%s/diskopen,", chNames[i]); + DynStringConcat(names, path); + snprintf(path, 255, "%s/diskclosed,", chNames[i]); + DynStringConcat(names, path); + snprintf(path, 255, "%s/speedoverflow,", chNames[i]); + DynStringConcat(names, path); + snprintf(path, 255, "%s/bearingfailed,", chNames[i]); + DynStringConcat(names, path); + snprintf(path, 255, "%s/voltagetohigh,", chNames[i]); + DynStringConcat(names, path); + } + par = GetCharArray(names); + par[strlen(par) - 1] = '\0'; + pDriv->pParList = strdup(par); + DeleteDynString(names); + if (pDriv->pParList == NULL) { + JulChoKill(pDriv); + free(pDriv); + return NULL; + } + + return pDriv; } + /*--------------------------------------------------------------------------*/ -int JulChoFactory(SConnection *pCon, SicsInterp *pSics, void *pData, - int argc, char *argv[]){ - pChoco pNew = NULL; - pCodri pDriv = NULL; - pObjectDescriptor pDes = NULL; - char pBueffel[132]; - int iRet, iPort, iChannel; - int iSingle = 0; +int JulChoFactory(SConnection * pCon, SicsInterp * pSics, void *pData, + int argc, char *argv[]) +{ + pChoco pNew = NULL; + pCodri pDriv = NULL; + pObjectDescriptor pDes = NULL; + char pBueffel[132]; + int iRet, iPort, iChannel; + int iSingle = 0; - if(argc < 4) - { - SCWrite(pCon, + if (argc < 4) { + SCWrite(pCon, "ERROR: Insufficient number of arguments to MakeJulCho", - eError); - return 0; - } - + eError); + return 0; + } - /* first try to get everything done */ - pNew = (pChoco)malloc(sizeof(Choco)); - pDes = CreateDescriptor("Chopper"); - pDes->parNode = MakeHipadabaNode(argv[1], HIPNONE,0); - /* do driver */ - - pDriv = MakeJulChoDriver(argv[2],atoi(argv[3]),pDes->parNode); - if(pDriv == NULL){ - sprintf(pBueffel,"ERROR: Failed to initialize JulCho Driver"); - SCWrite(pCon,pBueffel,eError); - return 0; - } - if( (pNew == NULL) || (pDes == NULL) || (pDriv == NULL) ) - { - SCWrite(pCon,"ERROR: No memory left to create controller",eError); - return 0; - } - pNew->pDes = pDes; - pNew->pDriv = pDriv; - /* initialize driver */ - iRet = pDriv->Init(pDriv); - if(!iRet){ - SCWrite(pCon,"ERROR: Failed to initialize driver",eError); - KillChoco(pNew); - return 0; - } + /* first try to get everything done */ + pNew = (pChoco) malloc(sizeof(Choco)); + pDes = CreateDescriptor("Chopper"); + pDes->parNode = MakeHipadabaNode(argv[1], HIPNONE, 0); + /* do driver */ - /* install as command */ - iRet = AddCommand(pSics, argv[1],ChocoAction,KillChoco,pNew); - if(!iRet){ - sprintf(pBueffel,"ERROR: duplicate command %s NOT created", - argv[1]); - SCWrite(pCon,pBueffel,eError); - return 0; - } - return 1; + pDriv = MakeJulChoDriver(argv[2], atoi(argv[3]), pDes->parNode); + if (pDriv == NULL) { + sprintf(pBueffel, "ERROR: Failed to initialize JulCho Driver"); + SCWrite(pCon, pBueffel, eError); + return 0; + } + if ((pNew == NULL) || (pDes == NULL) || (pDriv == NULL)) { + SCWrite(pCon, "ERROR: No memory left to create controller", eError); + return 0; + } + pNew->pDes = pDes; + pNew->pDriv = pDriv; + + /* initialize driver */ + iRet = pDriv->Init(pDriv); + if (!iRet) { + SCWrite(pCon, "ERROR: Failed to initialize driver", eError); + KillChoco(pNew); + return 0; + } + + /* install as command */ + iRet = AddCommand(pSics, argv[1], ChocoAction, KillChoco, pNew); + if (!iRet) { + sprintf(pBueffel, "ERROR: duplicate command %s NOT created", argv[1]); + SCWrite(pCon, pBueffel, eError); + return 0; + } + return 1; } - - diff --git a/julprot.c b/julprot.c index b9ce244..0ca8ac9 100644 --- a/julprot.c +++ b/julprot.c @@ -14,70 +14,75 @@ #include #include -static int calculateJulCheckSum(char *realCommand){ - int i, checkSum = 0; - - for(i = 1; i < strlen(realCommand); i++){ - checkSum += (int)realCommand[i]; - } - return checkSum; +static int calculateJulCheckSum(char *realCommand) +{ + int i, checkSum = 0; + + for (i = 1; i < strlen(realCommand); i++) { + checkSum += (int) realCommand[i]; + } + return checkSum; } + /*---------------------------------------------------------------------------*/ -int JulchoHandler(Ascon *a){ - char *data = NULL; - int checkSum, ret; - char checkBuffer[30], chr; - - switch(a->state){ - case AsconWriteStart: - data = GetCharArray(a->wrBuffer); - checkSum = calculateJulCheckSum(data); - snprintf(checkBuffer,30,"{%d}$", checkSum); - DynStringConcat(a->wrBuffer,checkBuffer); - a->state = AsconWriting; - a->wrPos = 0; - break; - case AsconReading: - ret = AsconReadChar(a->fd, &chr); - if(ret < 0){ - /* EINTR means we must retry */ - if(errno != EINTR && errno != EAGAIN){ - AsconError(a, "AsconReadChar failed:", errno); - } - return 1; - } else if (ret > 0) { - a->start = DoubleTime(); - if(chr == '$'){ - DynStringConcatChar(a->rdBuffer, '\0'); - a->state = AsconReadDone; - break; - } else { - if (DynStringConcatChar(a->rdBuffer, chr) == 0) { - AsconError(a, "DynStringConcatChar failed:", ENOMEM); - break; - } - } - } else if(ret == 0){ - if (a->timeout > 0) { - if (DoubleTime() - a->start > a->timeout) { - AsconError(a, "read timeout", 0); - a->state = AsconTimeout; - } - } - } - break; - default: - return AsconStdHandler(a); - } - return 1; +int JulchoHandler(Ascon * a) +{ + char *data = NULL; + int checkSum, ret; + char checkBuffer[30], chr; + + switch (a->state) { + case AsconWriteStart: + data = GetCharArray(a->wrBuffer); + checkSum = calculateJulCheckSum(data); + snprintf(checkBuffer, 30, "{%d}$", checkSum); + DynStringConcat(a->wrBuffer, checkBuffer); + a->state = AsconWriting; + a->wrPos = 0; + break; + case AsconReading: + ret = AsconReadChar(a->fd, &chr); + if (ret < 0) { + /* EINTR means we must retry */ + if (errno != EINTR && errno != EAGAIN) { + AsconError(a, "AsconReadChar failed:", errno); + } + return 1; + } else if (ret > 0) { + a->start = DoubleTime(); + if (chr == '$') { + DynStringConcatChar(a->rdBuffer, '\0'); + a->state = AsconReadDone; + break; + } else { + if (DynStringConcatChar(a->rdBuffer, chr) == 0) { + AsconError(a, "DynStringConcatChar failed:", ENOMEM); + break; + } + } + } else if (ret == 0) { + if (a->timeout > 0) { + if (DoubleTime() - a->start > a->timeout) { + AsconError(a, "read timeout", 0); + a->state = AsconTimeout; + } + } + } + break; + default: + return AsconStdHandler(a); + } + return 1; } + /*-------------------------------------------------------------------------*/ -void AddJulChoProtocoll(){ - AsconProtocol *prot = NULL; - - prot = calloc(sizeof(AsconProtocol), 1); - prot->name = strdup("julcho"); - prot->init = AsconStdInit; - prot->handler = JulchoHandler; - AsconInsertProtocol(prot); +void AddJulChoProtocoll() +{ + AsconProtocol *prot = NULL; + + prot = calloc(sizeof(AsconProtocol), 1); + prot->name = strdup("julcho"); + prot->init = AsconStdInit; + prot->handler = JulchoHandler; + AsconInsertProtocol(prot); } diff --git a/lcdriv.c b/lcdriv.c index e6ff677..abf461c 100644 --- a/lcdriv.c +++ b/lcdriv.c @@ -30,8 +30,8 @@ Markus Zolliker, Sept 2004 typedef struct { Eve eve; - float t[4]; /* set t. & 3 temperatures */ - int dig[4]; /* format for these */ + float t[4]; /* set t. & 3 temperatures */ + int dig[4]; /* format for these */ float gas; int remote; int hot; @@ -44,37 +44,40 @@ static long LcSetGas(long pc, void *obj); #define L EVE_LOGPAR #define S EVE_SAVEPAR -void LcPars(LcDriv *me, EveParArg *arg) { +void LcPars(LcDriv * me, EveParArg * arg) +{ char fmt[80]; - + sprintf(fmt, "%%.%df\tK", me->dig[2]); - EveFloatPar(arg, "t2", &me->t[2], fmt, usInternal, (me->dig[2] >= 0) * A + L); + EveFloatPar(arg, "t2", &me->t[2], fmt, usInternal, + (me->dig[2] >= 0) * A + L); sprintf(fmt, "%%.%df\tK", me->dig[3]); - EveFloatPar(arg, "t3", &me->t[3], fmt, usInternal, (me->dig[3] >= 0) * A + L); + EveFloatPar(arg, "t3", &me->t[3], fmt, usInternal, + (me->dig[3] >= 0) * A + L); EveFloatCmd(arg, "gas", &me->gas, "%.1f\t%%", LcSetGas, usUser, A + L); EveIntPar(arg, "dig1", &me->dig[1], usUser, S); EveIntPar(arg, "dig2", &me->dig[2], usUser, S); EveIntPar(arg, "dig3", &me->dig[3], usUser, S); - + sprintf(fmt, "%%.%df\tmbar", me->dig[1]); EveStdParEnd(arg, fmt, 0); } + /*----------------------------------------------------------------------------*/ -void LcStatus(LcDriv *me) { +void LcStatus(LcDriv * me) +{ char *ans; int *code; - Eve *eve=&me->eve; - - if (eve->state != readState) return; - ans=eve->ans; - code=&eve->errCode; - if (ans[0] != 'X' || - ans[2] != 'A' || - ans[4] != 'C' || - ans[6] != 'S') { + Eve *eve = &me->eve; + + if (eve->state != readState) + return; + ans = eve->ans; + code = &eve->errCode; + if (ans[0] != 'X' || ans[2] != 'A' || ans[4] != 'C' || ans[6] != 'S') { EvePrintf(eve, eError, "illegal status response"); *code = EVE_FAULT; return; @@ -86,119 +89,120 @@ void LcStatus(LcDriv *me) { return; } } + /*----------------------------------------------------------------------------*/ -static int LcRead(long pc, LcDriv *me) { - Eve *eve=&me->eve; +static int LcRead(long pc, LcDriv * me) +{ + Eve *eve = &me->eve; char *p; int l; - - FSM_BEGIN - EveWrite(eve, "X"); - FSM_NEXT - LcStatus(me); /* check for errors */ + + FSM_BEGIN EveWrite(eve, "X"); + FSM_NEXT LcStatus(me); /* check for errors */ /* if (!me->remote) goto skiprmt; EveWrite(eve, "C0"); me->remote = 0; FSM_NEXT -*/ - skiprmt: - if (me->dig[1] < 0) goto skip1; - EveWrite(eve, "R1"); /* read sensor 1 */ - FSM_NEXT - me->t[1] = OiGetFlt(eve, me->dig[1], NULL); - me->eve.value = me->t[1]; - skip1: - if (me->dig[2] < 0) goto skip2; - EveWrite(eve, "R2"); /* read sensor 2 */ - FSM_NEXT - me->t[2] = OiGetFlt(eve, me->dig[2], NULL); - skip2: - if (me->dig[3] < 0) goto skip3; - EveWrite(eve, "R3"); /* read sensor 3 */ - FSM_NEXT - me->t[3] = OiGetFlt(eve, me->dig[3], NULL); - skip3: - FSM_END -} +*/ +skiprmt: + if (me->dig[1] < 0) + goto skip1; + EveWrite(eve, "R1"); /* read sensor 1 */ + FSM_NEXT me->t[1] = OiGetFlt(eve, me->dig[1], NULL); + me->eve.value = me->t[1]; +skip1: + if (me->dig[2] < 0) + goto skip2; + EveWrite(eve, "R2"); /* read sensor 2 */ + FSM_NEXT me->t[2] = OiGetFlt(eve, me->dig[2], NULL); +skip2: + if (me->dig[3] < 0) + goto skip3; + EveWrite(eve, "R3"); /* read sensor 3 */ + FSM_NEXT me->t[3] = OiGetFlt(eve, me->dig[3], NULL); +skip3: +FSM_END} + /*----------------------------------------------------------------------------*/ -static long LcSetGas(long pc, void *obj) { +static long LcSetGas(long pc, void *obj) +{ LcDriv *me = obj; - Eve *eve=&me->eve; - pEVControl evc=eve->evc; + Eve *eve = &me->eve; + pEVControl evc = eve->evc; float fld; float step; float ramp; char buf[4]; SConnection *pCon; int a; - - FSM_BEGIN - if (me->remote) goto skipremote; - EveWrite(eve, "C1"); - FSM_NEXT - skipremote: - OiSet(eve, "G", me->gas, 1); /* cold valve setting */ - FSM_NEXT - quit: - FSM_END -} + + FSM_BEGIN if (me->remote) + goto skipremote; + EveWrite(eve, "C1"); +FSM_NEXT skipremote: + OiSet(eve, "G", me->gas, 1); /* cold valve setting */ +FSM_NEXT quit: +FSM_END} + /*----------------------------------------------------------------------------*/ -static int LcStart(long pc, LcDriv *me) { - Eve *eve=&me->eve; - - FSM_BEGIN - EveWrite(eve, "V"); - FSM_NEXT - if (0 == strncmp(eve->version, "TESLATRON", 9)) { - me->eve.syntax = 0; - me->dig[1] = 1; - me->dig[2] = 2; - me->dig[3] = 1; - } else { - EvePrintf(eve, eError, "unknown lambda controller version: %s", eve->version); - goto quit; - } - EvePrintf(eve, eLog, "connected to %s", eve->version); +static int LcStart(long pc, LcDriv * me) +{ + Eve *eve = &me->eve; + + FSM_BEGIN EveWrite(eve, "V"); + FSM_NEXT if (0 == strncmp(eve->version, "TESLATRON", 9)) { + me->eve.syntax = 0; + me->dig[1] = 1; + me->dig[2] = 2; + me->dig[3] = 1; + } else { + EvePrintf(eve, eError, "unknown lambda controller version: %s", + eve->version); + goto quit; + } + EvePrintf(eve, eLog, "connected to %s", eve->version); FSM_CALL(LcRead); - - quit: - FSM_END -} + +quit: +FSM_END} + /*----------------------------------------------------------------------------*/ -static int LcSetTemp(long pc, LcDriv *me) { - Eve *eve=&me->eve; - pEVControl evc=eve->evc; +static int LcSetTemp(long pc, LcDriv * me) +{ + Eve *eve = &me->eve; + pEVControl evc = eve->evc; float fld; float step; float ramp; char buf[4]; SConnection *pCon; - - FSM_BEGIN - FSM_END -} + +FSM_BEGIN FSM_END} + /*------------------------------------------------------------------------*/ -pEVControl LcMakeEVC(SConnection *pCon, int argc, char *argv[]) { +pEVControl LcMakeEVC(SConnection * pCon, int argc, char *argv[]) +{ /* args: lc - + */ Eve *eve; pEVControl evc; LcDriv *me = NULL; - - evc = MakeEveEVC(argc, argv, calloc(1, sizeof *me), pCon); - if (!evc) return NULL; - - me = evc->pDriv->pPrivate; - eve=&me->eve; - eve->run = (FsmFunc)LcSetTemp; - eve->read = (FsmFunc)LcRead; - eve->pardef = (EveParDef)LcPars; - eve->todo = (FsmFunc)LcStart; - eve->task = FsmStartTask(me, (FsmHandler)OiHandler, (FsmFunc)EveIdle); - + evc = MakeEveEVC(argc, argv, calloc(1, sizeof *me), pCon); + if (!evc) + return NULL; + + me = evc->pDriv->pPrivate; + eve = &me->eve; + + eve->run = (FsmFunc) LcSetTemp; + eve->read = (FsmFunc) LcRead; + eve->pardef = (EveParDef) LcPars; + eve->todo = (FsmFunc) LcStart; + eve->task = FsmStartTask(me, (FsmHandler) OiHandler, (FsmFunc) EveIdle); + return evc; } diff --git a/linadriv.c b/linadriv.c index bee566a..275e1d0 100644 --- a/linadriv.c +++ b/linadriv.c @@ -38,12 +38,14 @@ typedef struct { static ParClass linaClass = { "LINA", sizeof(Lina) }; /*----------------------------------------------------------------------------*/ -int LinaHandler(void *object) { +int LinaHandler(void *object) +{ int iret, l; EaseBase *eab = EaseBaseCast(object); char *corr; - - if (eab->state < EASE_idle) goto quit; + + if (eab->state < EASE_idle) + goto quit; if (availableNetRS232(eab->ser) || availableRS232(eab->ser)) { eab->msg[0] = '\0'; l = sizeof(eab->ans); @@ -58,12 +60,12 @@ int LinaHandler(void *object) { ParPrintf(eab, -2, "ans: %s", eab->ans); if (eab->state == EASE_lost) { goto quit; - } else if (strncmp(eab->cmd,"ID",2) == 0) { + } else if (strncmp(eab->cmd, "ID", 2) == 0) { if (strcmp(eab->ans, eab->version) == 0) { /* we are still connected with the same device */ } else if (*eab->version == '\0') { - strncat(eab->version, eab->ans, sizeof(eab->version)-1); - } else { /* version (and therefore device) changed */ + strncat(eab->version, eab->ans, sizeof(eab->version) - 1); + } else { /* version (and therefore device) changed */ eab->errCode = EASE_DEV_CHANGED; eab->state = EASE_idle; goto error; @@ -98,18 +100,23 @@ error: quit: return EaseHandler(eab); } + /*----------------------------------------------------------------------------*/ -static void LinaParDef(void *object) { +static void LinaParDef(void *object) +{ Lina *drv = ParCast(&linaClass, object); EaseBase *eab = object; - ParName(""); ParTail("units"); + ParName(""); + ParTail("units"); ParFloat(&drv->x, PAR_NAN); - - ParName("x"); ParTail(""); + + ParName("x"); + ParTail(""); ParFloat(&drv->x, PAR_NAN); - - ParName("y"); ParTail(""); + + ParName("y"); + ParTail(""); ParFloat(&drv->y, PAR_NAN); EaseBasePar(drv); @@ -120,82 +127,103 @@ static void LinaParDef(void *object) { ParStdDef(); EaseMsgPar(drv); } + /*----------------------------------------------------------------------------*/ -static long LinaRead(long pc, void *object) { +static long LinaRead(long pc, void *object) +{ Lina *drv = ParCast(&linaClass, object); EaseBase *eab = object; char *p; - - switch (pc) { default: /* FSM BEGIN *******************************/ + + switch (pc) { + default: /* FSM BEGIN ****************************** */ EaseWrite(eab, "XY."); - return __LINE__; case __LINE__: /**********************************/ + return __LINE__; + case __LINE__: /**********************************/ p = strchr(eab->ans, ','); if (p) { - *p='\0'; + *p = '\0'; p++; drv->x = atof(eab->ans); drv->y = atof(p); } ParLog(drv); - fsm_quit: return 0; } /* FSM END *********************************/ + fsm_quit:return 0; + } /* FSM END ******************************** */ } + /*----------------------------------------------------------------------------*/ -static long LinaStart(long pc, void *object) { +static long LinaStart(long pc, void *object) +{ Lina *drv = ParCast(&linaClass, object); EaseBase *eab = object; - - switch (pc) { default: /* FSM BEGIN *******************************/ + + switch (pc) { + default: /* FSM BEGIN ****************************** */ EaseWrite(eab, "ID"); - return __LINE__; case __LINE__: /**********************************/ + return __LINE__; + case __LINE__: /**********************************/ if (0 != strncmp(eab->version, "7265", 4)) { - snprintf(eab->msg, sizeof eab->msg, "unknown lock in amplifier version: %s", - eab->version); + snprintf(eab->msg, sizeof eab->msg, + "unknown lock in amplifier version: %s", eab->version); ParPrintf(drv, eError, "ERROR: %s", eab->msg); EaseStop(eab); goto quit; } ParPrintf(drv, eLog, "connected to %s", eab->version); FsmCall(LinaRead); - return __LINE__; case __LINE__: /**********************************/ - + return __LINE__; + case __LINE__: /**********************************/ + quit: - return 0; } /* FSM END ********************************************/ + return 0; + } /* FSM END ******************************************* */ } + /*----------------------------------------------------------------------------*/ -static long LinaSet(long pc, void *object) { +static long LinaSet(long pc, void *object) +{ Lina *drv = ParCast(&linaClass, object); EaseBase *eab = object; char cmd[32]; int upd; - - switch (pc) { default: /* FSM BEGIN *******************************/ - /* - snprintf(cmd, sizeof cmd, "SETP %.5g;SETP?", drv->d.targetValue); - EaseWrite(eab, cmd); - */ + + switch (pc) { + default: /* FSM BEGIN ****************************** */ + /* + snprintf(cmd, sizeof cmd, "SETP %.5g;SETP?", drv->d.targetValue); + EaseWrite(eab, cmd); + */ quit: - return 0; } /* FSM END ********************************************/ + return 0; + } /* FSM END ******************************************* */ } + /*----------------------------------------------------------------------------*/ -static int LinaInit(SConnection *con, int argc, char *argv[], int dynamic) { +static int LinaInit(SConnection * con, int argc, char *argv[], int dynamic) +{ /* args: - MakeObject objectname lina - MakeObject objectname lina + MakeObject objectname lina + MakeObject objectname lina */ Lina *drv; - + drv = EaseMakeDriv(con, &linaClass, argc, argv, dynamic, 7, - LinaParDef, LinaHandler, LinaStart, NULL, LinaRead, - LinaSet); - if (drv == NULL) return 0; + LinaParDef, LinaHandler, LinaStart, NULL, LinaRead, + LinaSet); + if (drv == NULL) + return 0; /* setRS232ReplyTerminator(drv->d.b.ser,"\n"); setRS232SendTerminator(drv->d.b.ser,"\n"); */ return 1; } + /*----------------------------------------------------------------------------*/ -void LinaStartup(void) { +void LinaStartup(void) +{ ParMakeClass(&linaClass, EaseDrivClass()); - MakeDriver("LINA", LinaInit, 0, "Lock in amplifier SIGNAL RECOVERY Model 7265"); + MakeDriver("LINA", LinaInit, 0, + "Lock in amplifier SIGNAL RECOVERY Model 7265"); } diff --git a/lmd200.c b/lmd200.c index 344ae8e..6928118 100644 --- a/lmd200.c +++ b/lmd200.c @@ -14,13 +14,13 @@ * * Mark Koennecke, October 2007 */ - #include - #include - #include - #include - #include - #include - #include +#include +#include +#include +#include +#include +#include +#include /* * possible states */ @@ -29,222 +29,235 @@ #define WAITDATA2 2 /* * private data structure - */ + */ #define BUFLEN 1024 - typedef struct { - int state; - char host[256]; - int port; - mkChannel *pSock; - pNWContext watchContext; - char lineBuffer[BUFLEN]; - } LMD200, *pLMD200; +typedef struct { + int state; + char host[256]; + int port; + mkChannel *pSock; + pNWContext watchContext; + char lineBuffer[BUFLEN]; +} LMD200, *pLMD200; /*----------------------------------------------------------------------------*/ - static void killLMD200(void *data){ - pLMD200 priv = (pLMD200)data; - if(priv == NULL){ - return; - } - if(priv->watchContext != NULL){ - NetWatchRemoveCallback(priv->watchContext); - } - if(priv->pSock != NULL){ - NETClosePort(priv->pSock); - free(priv->pSock); - } - free(priv); - } +static void killLMD200(void *data) +{ + pLMD200 priv = (pLMD200) data; + if (priv == NULL) { + return; + } + if (priv->watchContext != NULL) { + NetWatchRemoveCallback(priv->watchContext); + } + if (priv->pSock != NULL) { + NETClosePort(priv->pSock); + free(priv->pSock); + } + free(priv); +} + /*-------------------------------------------------------------------------*/ -static void setAlarm(pSICSOBJ self, char *text){ - hdbValue alarmVal; - pHdb node = NULL; - - alarmVal = MakeHdbText(text); - node = GetHipadabaNode(self->objectNode,"alarm"); - assert(node != NULL); - UpdateHipadabaPar(node,alarmVal, NULL); +static void setAlarm(pSICSOBJ self, char *text) +{ + hdbValue alarmVal; + pHdb node = NULL; + + alarmVal = MakeHdbText(text); + node = GetHipadabaNode(self->objectNode, "alarm"); + assert(node != NULL); + UpdateHipadabaPar(node, alarmVal, NULL); } + /*--------------------------------------------------------------------------*/ -static void doAlarm(pSICSOBJ self, char *lineBuffer){ - - setAlarm(self,lineBuffer); - WriteToCommandLog("CERCA>> ", lineBuffer); - ServerWriteGlobal(lineBuffer,eError); +static void doAlarm(pSICSOBJ self, char *lineBuffer) +{ + + setAlarm(self, lineBuffer); + WriteToCommandLog("CERCA>> ", lineBuffer); + ServerWriteGlobal(lineBuffer, eError); } + /*--------------------------------------------------------------------------*/ extern char *trim(char *); -static void storeData(pSICSOBJ self, int start, char *lineBuffer){ - pHdb node = NULL; - char number[80], *pPtr = NULL, *pKomma; +static void storeData(pSICSOBJ self, int start, char *lineBuffer) +{ + pHdb node = NULL; + char number[80], *pPtr = NULL, *pKomma; - node = GetHipadabaNode(self->objectNode,"data"); - assert(node != NULL); - /* - * throw first away - */ - pPtr = stptok(lineBuffer,number,80," "); - pPtr = trim(pPtr); - pPtr = stptok(pPtr,number,80," "); - while(pPtr != NULL){ - if(strstr(number,"noinp") != NULL){ - node->value.v.floatArray[start] = -9999.99; - start++; - } else { - pKomma = strchr(number,','); - if(pKomma != NULL){ - *pKomma = '.'; - } - pKomma = strchr(number,'('); - if(pKomma != NULL){ - *pKomma = ' '; - } - pKomma = strchr(number,')'); - if(pKomma != NULL){ - *pKomma = ' '; - } - node->value.v.floatArray[start] = atof(trim(number)); - start++; - } - pPtr = trim(pPtr); - pPtr = stptok(pPtr,number,80," "); - } - } -/*--------------------------------------------------------------------------*/ -static int countTokens(char *lineBuffer){ - int count = 0; - char myBuffer[BUFLEN], token[60]; - char *pPtr = NULL; - - - memset(myBuffer,0,BUFLEN); - strcpy(myBuffer, lineBuffer); - pPtr = myBuffer; - pPtr = stptok(pPtr,token, 60," \r\n"); - while(pPtr != NULL){ - count++; - pPtr = trim(pPtr); - pPtr = stptok(pPtr,token,60," \r\n"); + node = GetHipadabaNode(self->objectNode, "data"); + assert(node != NULL); + /* + * throw first away + */ + pPtr = stptok(lineBuffer, number, 80, " "); + pPtr = trim(pPtr); + pPtr = stptok(pPtr, number, 80, " "); + while (pPtr != NULL) { + if (strstr(number, "noinp") != NULL) { + node->value.v.floatArray[start] = -9999.99; + start++; + } else { + pKomma = strchr(number, ','); + if (pKomma != NULL) { + *pKomma = '.'; + } + pKomma = strchr(number, '('); + if (pKomma != NULL) { + *pKomma = ' '; + } + pKomma = strchr(number, ')'); + if (pKomma != NULL) { + *pKomma = ' '; + } + node->value.v.floatArray[start] = atof(trim(number)); + start++; } - return count; + pPtr = trim(pPtr); + pPtr = stptok(pPtr, number, 80, " "); + } } + /*--------------------------------------------------------------------------*/ -static void interpretLine(pSICSOBJ self, pLMD200 priv){ +static int countTokens(char *lineBuffer) +{ + int count = 0; + char myBuffer[BUFLEN], token[60]; + char *pPtr = NULL; + + + memset(myBuffer, 0, BUFLEN); + strcpy(myBuffer, lineBuffer); + pPtr = myBuffer; + pPtr = stptok(pPtr, token, 60, " \r\n"); + while (pPtr != NULL) { + count++; + pPtr = trim(pPtr); + pPtr = stptok(pPtr, token, 60, " \r\n"); + } + return count; +} + +/*--------------------------------------------------------------------------*/ +static void interpretLine(pSICSOBJ self, pLMD200 priv) +{ pHdb node = NULL; - switch(priv->state){ - case IDLE: - if(strstr(priv->lineBuffer, "Alarm") != NULL){ - doAlarm(self, priv->lineBuffer); - return; - } else if(strstr(priv->lineBuffer,"Pre") != NULL){ - setAlarm(self,priv->lineBuffer); - } else { - priv->state = WAITDATA1; - setAlarm(self,"I do not feel very alarmed"); - return; - } - break; - case WAITDATA1: - if(strstr(priv->lineBuffer,"...0") == NULL){ - /* this data is out of order, recover...*/ - priv->state == IDLE; - return; - } - storeData(self, 0, priv->lineBuffer); - priv->state = WAITDATA2; - break; - case WAITDATA2: - if(strstr(priv->lineBuffer,"...0") == NULL){ - /* this data is out of order, recover...*/ - priv->state == IDLE; - return; - } - storeData(self, 8, priv->lineBuffer); - priv->state = IDLE; - node = GetHipadabaNode(self->objectNode,"data"); - assert(node != NULL); - NotifyHipadabaPar(node,NULL); - break; + switch (priv->state) { + case IDLE: + if (strstr(priv->lineBuffer, "Alarm") != NULL) { + doAlarm(self, priv->lineBuffer); + return; + } else if (strstr(priv->lineBuffer, "Pre") != NULL) { + setAlarm(self, priv->lineBuffer); + } else { + priv->state = WAITDATA1; + setAlarm(self, "I do not feel very alarmed"); + return; } + break; + case WAITDATA1: + if (strstr(priv->lineBuffer, "...0") == NULL) { + /* this data is out of order, recover... */ + priv->state == IDLE; + return; + } + storeData(self, 0, priv->lineBuffer); + priv->state = WAITDATA2; + break; + case WAITDATA2: + if (strstr(priv->lineBuffer, "...0") == NULL) { + /* this data is out of order, recover... */ + priv->state == IDLE; + return; + } + storeData(self, 8, priv->lineBuffer); + priv->state = IDLE; + node = GetHipadabaNode(self->objectNode, "data"); + assert(node != NULL); + NotifyHipadabaPar(node, NULL); + break; + } } + /*--------------------------------------------------------------------------- * This handles the terminator discovery and causes the evaluation of complete * lines. * --------------------------------------------------------------------------*/ -static int LMD200Callback(void *context, int mode){ - pSICSOBJ self = (pSICSOBJ)context; - pLMD200 priv = NULL; - char buffer[512], *pPtr = NULL, line[132]; +static int LMD200Callback(void *context, int mode) +{ + pSICSOBJ self = (pSICSOBJ) context; + pLMD200 priv = NULL; + char buffer[512], *pPtr = NULL, line[132]; - assert(self != NULL); - priv = (pLMD200)self->pPrivate; - if(mode == nwatch_read){ - memset(buffer,0,512); - memset(line,0,132); - NETRead(priv->pSock, buffer, 512, 0); - pPtr = stptok(buffer,line,132,"\r"); - while(pPtr != NULL){ - if(strlen(line) > 3){ - strncpy(priv->lineBuffer,line,BUFLEN); - interpretLine(self, priv); - priv->lineBuffer[0] = '\0'; - } - pPtr = stptok(pPtr,line,132,"\r"); - } + assert(self != NULL); + priv = (pLMD200) self->pPrivate; + if (mode == nwatch_read) { + memset(buffer, 0, 512); + memset(line, 0, 132); + NETRead(priv->pSock, buffer, 512, 0); + pPtr = stptok(buffer, line, 132, "\r"); + while (pPtr != NULL) { + if (strlen(line) > 3) { + strncpy(priv->lineBuffer, line, BUFLEN); + interpretLine(self, priv); + priv->lineBuffer[0] = '\0'; + } + pPtr = stptok(pPtr, line, 132, "\r"); } - return 1; + } + return 1; } + /*---------------------------------------------------------------------------*/ -int MakeLMD200(SConnection *pCon, SicsInterp *pSics, void *pData, - int argc, char *argv[]){ - pSICSOBJ self = NULL; - pLMD200 priv = NULL; - hdbValue dataValue, textValue; - int status; +int MakeLMD200(SConnection * pCon, SicsInterp * pSics, void *pData, + int argc, char *argv[]) +{ + pSICSOBJ self = NULL; + pLMD200 priv = NULL; + hdbValue dataValue, textValue; + int status; - if(argc < 4){ - SCWrite(pCon, - "ERROR: require name host and port parameters for initialization", - eError); - return 0; - } - priv = (pLMD200)malloc(sizeof(LMD200)); - memset(priv,0,sizeof(LMD200)); - strncpy(priv->host,argv[2], 256); - priv->port = atoi(argv[3]); - priv->pSock = NETConnect(priv->host,priv->port); - if(priv->pSock == NULL){ - SCWrite(pCon,"ERROR: failed to connect to LMD200",eError); - killLMD200(priv); - return 0; - } + if (argc < 4) { + SCWrite(pCon, + "ERROR: require name host and port parameters for initialization", + eError); + return 0; + } + priv = (pLMD200) malloc(sizeof(LMD200)); + memset(priv, 0, sizeof(LMD200)); + strncpy(priv->host, argv[2], 256); + priv->port = atoi(argv[3]); + priv->pSock = NETConnect(priv->host, priv->port); + if (priv->pSock == NULL) { + SCWrite(pCon, "ERROR: failed to connect to LMD200", eError); + killLMD200(priv); + return 0; + } - self = MakeSICSOBJv(argv[1],"LMD400",HIPNONE, 0); - if(self == NULL || priv == NULL){ - return 0; - } - textValue = MakeHdbText("I do not feel very alarmed"); - dataValue = makeHdbValue(HIPFLOATAR,16); - AddSICSHdbPar(self->objectNode,"alarm", usInternal,textValue); - AddSICSHdbPar(self->objectNode,"data", usInternal,dataValue); - self->pPrivate = priv; - self->KillPrivate = killLMD200; - ReleaseHdbValue(&dataValue); - NetWatchRegisterCallback(&priv->watchContext, priv->pSock->sockid, - LMD200Callback, self); + self = MakeSICSOBJv(argv[1], "LMD400", HIPNONE, 0); + if (self == NULL || priv == NULL) { + return 0; + } + textValue = MakeHdbText("I do not feel very alarmed"); + dataValue = makeHdbValue(HIPFLOATAR, 16); + AddSICSHdbPar(self->objectNode, "alarm", usInternal, textValue); + AddSICSHdbPar(self->objectNode, "data", usInternal, dataValue); + self->pPrivate = priv; + self->KillPrivate = killLMD200; + ReleaseHdbValue(&dataValue); + NetWatchRegisterCallback(&priv->watchContext, priv->pSock->sockid, + LMD200Callback, self); - status = AddCommand(pSics, - argv[1], - InterInvokeSICSOBJ, - KillSICSOBJ, - self); - if(status != 1){ - KillSICSOBJ(self); - SCPrintf(pCon,eError,"ERROR: failed create duplicate command %s", argv[1]); - return 0; - } + status = AddCommand(pSics, + argv[1], InterInvokeSICSOBJ, KillSICSOBJ, self); + if (status != 1) { + KillSICSOBJ(self); + SCPrintf(pCon, eError, "ERROR: failed create duplicate command %s", + argv[1]); + return 0; + } - - return 1; -} + + return 1; +} diff --git a/lsc370driv.c b/lsc370driv.c index 5b4ccdf..1f5e9ff 100644 --- a/lsc370driv.c +++ b/lsc370driv.c @@ -44,10 +44,10 @@ typedef struct { float prop; float integ; float deriv; - float resist; /* Ohm */ + float resist; /* Ohm */ float temp[MAX_CHAN]; int channel[MAX_CHAN]; - int ighHeater; /* IGH heater range (-1 if output is direct) */ + int ighHeater; /* IGH heater range (-1 if output is direct) */ int htrRange; int currentEx; int voltageEx; @@ -59,17 +59,19 @@ typedef struct { static ParClass lsc370Class = { "LSC370", sizeof(Lsc370) }; /*----------------------------------------------------------------------------*/ -static float Lsc370Power(Lsc370 *drv, float percent) { - float power; /* mW */ - float current; /* A */ - float voltage; /* V */ - +static float Lsc370Power(Lsc370 * drv, float percent) +{ + float power; /* mW */ + float current; /* A */ + float voltage; /* V */ + if (drv->htrRange == 0 || drv->ighHeater == 0) { power = 0; } else if (drv->ighHeater > 0) { current = pow(10, drv->htrRange * 0.5 - 5) * percent / 100; voltage = current * 500; - if (voltage > 10) voltage = 10; + if (voltage > 10) + voltage = 10; power = pow(10, drv->ighHeater) * 0.0002 * voltage / 10; } else { current = pow(10, drv->htrRange * 0.5 - 5) * percent / 100; @@ -84,77 +86,99 @@ static float Lsc370Power(Lsc370 *drv, float percent) { } /*----------------------------------------------------------------------------*/ -static void Lsc370ParDef(void *object) { +static void Lsc370ParDef(void *object) +{ Lsc370 *drv = ParCast(&lsc370Class, object); EaseBase *eab = object; float power, maxPower; int iRng; int i; - - static char *heaterList[]={"off", + + static char *heaterList[] = { "off", "30uA", "100uA", "300uA", - "1mA", "3mA", "10mA", "30mA", "100mA", NULL }; - static char *currentList[]={"off", + "1mA", "3mA", "10mA", "30mA", "100mA", NULL + }; + static char *currentList[] = { "off", "1pA", "3pA", "10pA", "30pA", "100pA", "300pA", "1nA", "3nA", "10nA", "30nA", "100nA", "300nA", "1uA", "3uA", "10uA", "30uA", "100uA", "300uA", - "1mA", "3mA", "10mA", "30mA", NULL }; - static char *voltageList[]={"off", + "1mA", "3mA", "10mA", "30mA", NULL + }; + static char *voltageList[] = { "off", "2uV", "6uV", "20uV", "60uV", "200uV", "600uV", "2mV", "6mV", "20mV", "60mV", "200mV", "600mV", - NULL }; - static char *rangeList[]={"auto", + NULL + }; + static char *rangeList[] = { "auto", "2mOhm", "6mOhm", "20mOhm", "60mOhm", "200mOhm", "600mOhm", - "2Ohm", "6Ohm", "20Ohm", "60Ohm", "200Ohm", " 600Ohm", + "2Ohm", "6Ohm", "20Ohm", "60Ohm", "200Ohm", " 600Ohm", "2kOhm", "6kOhm", "20kOhm", "60kOhm", "200kOhm", "600kOhm", - "2MegaOhm", "6MegaOhm", "20MegaOhm", "60MegaOhm", NULL }; - static char *offOn[]={"off", "on", NULL}; - - static char *tNames[]={"tsample", "tstill", "tmix"}; - static char *cNames[]={"csample", "cstill", "cmix"}; + "2MegaOhm", "6MegaOhm", "20MegaOhm", "60MegaOhm", NULL + }; + static char *offOn[] = { "off", "on", NULL }; - ParName(""); ParTail("K"); + static char *tNames[] = { "tsample", "tstill", "tmix" }; + static char *cNames[] = { "csample", "cstill", "cmix" }; + + ParName(""); + ParTail("K"); ParFloat(&drv->temp[0], PAR_NAN); - - ParName("set"); ParTail("K"); + + ParName("set"); + ParTail("K"); ParFloat(&drv->set, PAR_NAN); - - ParName("htr"); ParTail("%"); + + ParName("htr"); + ParTail("%"); ParFloat(&drv->htr, PAR_NAN); for (i = 0; i < MAX_CHAN; i++) { if (drv->channel[i] > 0 && i > 0) { - ParName(tNames[i]); ParTail("K"); + ParName(tNames[i]); + ParTail("K"); ParFloat(&drv->temp[i], PAR_NAN); } - ParName(cNames[i]); ParAccess(usUser); + ParName(cNames[i]); + ParAccess(usUser); ParInt(&drv->channel[i], 0); } - ParName("res"); ParTail("Ohm"); + ParName("res"); + ParTail("Ohm"); ParFloat(&drv->res, PAR_NAN); - ParName("prop"); ParTail("(gain)"); - EaseUpdate(PID_FLAG); ParFmt("%.3f"); + ParName("prop"); + ParTail("(gain)"); + EaseUpdate(PID_FLAG); + ParFmt("%.3f"); ParFloat(&drv->prop, PAR_NAN); - ParName("integ"); ParTail("sec"); - EaseUpdate(PID_FLAG); ParFmt("%.0f"); + ParName("integ"); + ParTail("sec"); + EaseUpdate(PID_FLAG); + ParFmt("%.0f"); ParFloat(&drv->integ, PAR_NAN); - ParName("deriv"); ParTail("sec"); - EaseUpdate(PID_FLAG); ParFmt("%.0f"); + ParName("deriv"); + ParTail("sec"); + EaseUpdate(PID_FLAG); + ParFmt("%.0f"); ParFloat(&drv->deriv, PAR_NAN); - ParName("resist"); ParTail("Ohm"); ParAccess(usUser); + ParName("resist"); + ParTail("Ohm"); + ParAccess(usUser); ParFloat(&drv->resist, 500.0); - - ParName("ighHeater"); ParAccess(usUser); + + ParName("ighHeater"); + ParAccess(usUser); ParInt(&drv->ighHeater, -1); ParName("currentEx"); - EaseUpdate(RDGRNG_FLAG); ParEnum(currentList); - if (drv->currentEx > 0) ParList(NULL); + EaseUpdate(RDGRNG_FLAG); + ParEnum(currentList); + if (drv->currentEx > 0) + ParList(NULL); ParInt(&drv->currentEx, PAR_NAN); if (ParActionIs(PAR_SET) > 0) { if (drv->currentEx > 22) { @@ -165,10 +189,12 @@ static void Lsc370ParDef(void *object) { drv->voltageEx = 0; } } - + ParName("voltageEx"); - EaseUpdate(RDGRNG_FLAG); ParEnum(voltageList); - if (drv->voltageEx > 0) ParList(NULL); + EaseUpdate(RDGRNG_FLAG); + ParEnum(voltageList); + if (drv->voltageEx > 0) + ParList(NULL); ParInt(&drv->voltageEx, PAR_NAN); if (ParActionIs(PAR_SET) > 0) { if (drv->voltageEx > 12) { @@ -179,10 +205,12 @@ static void Lsc370ParDef(void *object) { drv->currentEx = 0; } } - + ParName("range"); - EaseUpdate(RDGRNG_FLAG); ParEnum(rangeList); - if (drv->autoRange == 0) ParList(NULL); + EaseUpdate(RDGRNG_FLAG); + ParEnum(rangeList); + if (drv->autoRange == 0) + ParList(NULL); ParInt(&drv->range, PAR_NAN); if (ParActionIs(PAR_SET) > 0) { if (drv->range > 22) { @@ -193,9 +221,10 @@ static void Lsc370ParDef(void *object) { drv->range = 0; } } - + ParName("autoRange"); - EaseUpdate(RDGRNG_FLAG); ParEnum(offOn); + EaseUpdate(RDGRNG_FLAG); + ParEnum(offOn); ParList(NULL); ParInt(&drv->autoRange, PAR_NAN); if (ParActionIs(PAR_SET) > 0) { @@ -203,96 +232,119 @@ static void Lsc370ParDef(void *object) { drv->autoRange = 1; } } - + ParName("htrRange"); - EaseUpdate(HTRRNG_FLAG); ParEnum(heaterList); ParList(NULL); + EaseUpdate(HTRRNG_FLAG); + ParEnum(heaterList); + ParList(NULL); ParInt(&drv->htrRange, PAR_NAN); if (ParActionIs(PAR_SET) > 0) { if (drv->htrRange > 8) { drv->htrRange = 8; - } else if (drv->htrRange <= 0) { + } else if (drv->htrRange <= 0) { drv->htrRange = 0; } } - - ParName("maxPower"); ParTail("mW"); + + ParName("maxPower"); + ParTail("mW"); power = Lsc370Power(drv, 100.0); ParFloat(&power, 0.0); - - ParName("power"); ParTail("mW"); + + ParName("power"); + ParTail("mW"); power = Lsc370Power(drv, drv->htr); ParFloat(&power, 0.0); - + EaseBasePar(drv); EaseSendPar(drv); EaseDrivPar(drv, "%.5g", "K"); ParStdDef(); EaseMsgPar(drv); } + /*----------------------------------------------------------------------------*/ -static long Lsc370Read(long pc, void *object) { +static long Lsc370Read(long pc, void *object) +{ Lsc370 *drv = ParCast(&lsc370Class, object); EaseBase *eab = object; int mode, exi, rng, autoR, eoff; float x, y, z; char buf[16]; - - switch (pc) { default: /* FSM BEGIN *******************************/ + + switch (pc) { + default: /* FSM BEGIN ****************************** */ drv->index = 0; chanLoop: snprintf(buf, sizeof buf, "RDGK?%d", drv->channel[drv->index]); EaseWrite(eab, buf); - return __LINE__; case __LINE__: /**********************************/ - + return __LINE__; + case __LINE__: /**********************************/ + if (1 == sscanf(eab->ans, "%f", &x)) { drv->temp[drv->index] = x; } drv->index++; - if (drv->index < MAX_CHAN) goto chanLoop; + if (drv->index < MAX_CHAN) + goto chanLoop; EaseWrite(eab, "RDGR?1"); - return __LINE__; case __LINE__: /**********************************/ + return __LINE__; + case __LINE__: /**********************************/ if (1 == sscanf(eab->ans, "%f", &x)) { drv->res = x; } EaseWrite(eab, "HTR?"); - return __LINE__; case __LINE__: /**********************************/ + return __LINE__; + case __LINE__: /**********************************/ if (1 == sscanf(eab->ans, "%f", &x)) { drv->htr = x; } EaseWrite(eab, "SETP?"); - return __LINE__; case __LINE__: /**********************************/ + return __LINE__; + case __LINE__: /**********************************/ if (1 == sscanf(eab->ans, "%f", &x)) { if (drv->set != x && !EaseGetUpdate(drv, EASE_RUN)) { drv->d.targetValue = x; } drv->set = x; } - if (EaseGetUpdate(drv, PID_FLAG)) goto skipPid; + if (EaseGetUpdate(drv, PID_FLAG)) + goto skipPid; EaseWrite(eab, "PID?"); - return __LINE__; case __LINE__: /**********************************/ - if (EaseGetUpdate(drv, PID_FLAG)) goto skipPid; + return __LINE__; + case __LINE__: /**********************************/ + if (EaseGetUpdate(drv, PID_FLAG)) + goto skipPid; if (3 == sscanf(eab->ans, "%f,%f,%f", &x, &y, &z)) { drv->prop = x; drv->integ = y; drv->deriv = z; } skipPid: - - if (EaseGetUpdate(drv, HTRRNG_FLAG)) goto skipHtrRng; + + if (EaseGetUpdate(drv, HTRRNG_FLAG)) + goto skipHtrRng; EaseWrite(eab, "HTRRNG?"); - return __LINE__; case __LINE__: /**********************************/ - if (EaseGetUpdate(drv, HTRRNG_FLAG)) goto skipHtrRng; + return __LINE__; + case __LINE__: /**********************************/ + if (EaseGetUpdate(drv, HTRRNG_FLAG)) + goto skipHtrRng; if (1 == sscanf(eab->ans, "%d", &rng)) { drv->htrRange = rng; } skipHtrRng: - - if (EaseGetUpdate(drv, RDGRNG_FLAG)) goto skipRdgRng; + + if (EaseGetUpdate(drv, RDGRNG_FLAG)) + goto skipRdgRng; EaseWrite(eab, "RDGRNG?1"); - return __LINE__; case __LINE__: /**********************************/ - if (EaseGetUpdate(drv, RDGRNG_FLAG)) goto skipRdgRng; - if (5 == sscanf(eab->ans, "%d,%d,%d,%d,%d", &mode, &exi, &rng, &autoR, &eoff)) { + return __LINE__; + case __LINE__: /**********************************/ + if (EaseGetUpdate(drv, RDGRNG_FLAG)) + goto skipRdgRng; + if (5 == + sscanf(eab->ans, "%d,%d,%d,%d,%d", &mode, &exi, &rng, &autoR, + &eoff)) { if (eoff) { drv->currentEx = 0; drv->voltageEx = 0; @@ -305,73 +357,93 @@ static long Lsc370Read(long pc, void *object) { } drv->range = rng; drv->autoRange = autoR; - } + } skipRdgRng: - - + + ParLog(drv); - fsm_quit: return 0; } /* FSM END *********************************/ + fsm_quit:return 0; + } /* FSM END ******************************** */ } + /*----------------------------------------------------------------------------*/ -static long Lsc370Start(long pc, void *object) { +static long Lsc370Start(long pc, void *object) +{ Lsc370 *drv = ParCast(&lsc370Class, object); EaseBase *eab = object; - - switch (pc) { default: /* FSM BEGIN *******************************/ + + switch (pc) { + default: /* FSM BEGIN ****************************** */ EaseWrite(eab, "*IDN?"); - return __LINE__; case __LINE__: /**********************************/ + return __LINE__; + case __LINE__: /**********************************/ if (0 != strncmp(eab->version, "LSCI,MODEL370", 13)) { - snprintf(eab->msg, sizeof eab->msg, "unknown temperature controller version: %s", - eab->version); + snprintf(eab->msg, sizeof eab->msg, + "unknown temperature controller version: %s", eab->version); ParPrintf(drv, eError, "ERROR: %s", eab->msg); EaseStop(eab); goto quit; } ParPrintf(drv, eLog, "connected to %s", eab->version); FsmCall(Lsc370Read); - return __LINE__; case __LINE__: /**********************************/ - + return __LINE__; + case __LINE__: /**********************************/ + quit: - return 0; } /* FSM END ********************************************/ + return 0; + } /* FSM END ******************************************* */ } + /*----------------------------------------------------------------------------*/ -static long Lsc370Set(long pc, void *object) { +static long Lsc370Set(long pc, void *object) +{ Lsc370 *drv = ParCast(&lsc370Class, object); EaseBase *eab = object; char cmd[128]; int upd, mode, exi, eoff; - - switch (pc) { default: /* FSM BEGIN *******************************/ - EaseWrite(eab, "MODE 1;MODE?"); /* remote mode */ - return __LINE__; case __LINE__: /**********************************/ + + switch (pc) { + default: /* FSM BEGIN ****************************** */ + EaseWrite(eab, "MODE 1;MODE?"); /* remote mode */ + return __LINE__; + case __LINE__: /**********************************/ loop: upd = EaseNextUpdate(drv); - if (upd == EASE_RUN) goto run; - if (upd == HTRRNG_FLAG) goto htrrng; - if (upd == PID_FLAG) goto pid; - if (upd == RDGRNG_FLAG) goto rdgrng; + if (upd == EASE_RUN) + goto run; + if (upd == HTRRNG_FLAG) + goto htrrng; + if (upd == PID_FLAG) + goto pid; + if (upd == RDGRNG_FLAG) + goto rdgrng; goto finish; - + run: snprintf(cmd, sizeof cmd, "SETP %.5g;SETP?", drv->d.targetValue); EaseWrite(eab, cmd); - return __LINE__; case __LINE__: /**********************************/ + return __LINE__; + case __LINE__: /**********************************/ /* fall through */ htrrng: snprintf(cmd, sizeof cmd, "CSET 1,1,1,1,1,8,%g;CSET?", drv->resist); EaseWrite(eab, cmd); - return __LINE__; case __LINE__: /**********************************/ + return __LINE__; + case __LINE__: /**********************************/ snprintf(cmd, sizeof cmd, "HTRRNG %d;HTRRNG?", drv->htrRange); EaseWrite(eab, cmd); - return __LINE__; case __LINE__: /**********************************/ + return __LINE__; + case __LINE__: /**********************************/ goto loop; - + pid: - snprintf(cmd, sizeof cmd, "PID %.5g,%.5g,%.5g;PID?", drv->prop, drv->integ, drv->deriv); + snprintf(cmd, sizeof cmd, "PID %.5g,%.5g,%.5g;PID?", drv->prop, + drv->integ, drv->deriv); EaseWrite(eab, cmd); - return __LINE__; case __LINE__: /**********************************/ + return __LINE__; + case __LINE__: /**********************************/ goto loop; rdgrng: @@ -397,38 +469,49 @@ static long Lsc370Set(long pc, void *object) { drv->range = 1; } } - if (drv->autoRange) drv->autoRange = 1; + if (drv->autoRange) + drv->autoRange = 1; snprintf(cmd, sizeof cmd, "RDGRNG 1,%d,%d,%d,%d,%d;RDGRNG?1", - mode, exi, drv->range, drv->autoRange, eoff); + mode, exi, drv->range, drv->autoRange, eoff); EaseWrite(eab, cmd); - return __LINE__; case __LINE__: /**********************************/ + return __LINE__; + case __LINE__: /**********************************/ goto loop; - - finish: - EaseWrite(eab, "MODE 0;MODE?"); /* local mode */ - return __LINE__; case __LINE__: /**********************************/ - - return 0; } /* FSM END ********************************************/ + + finish: + EaseWrite(eab, "MODE 0;MODE?"); /* local mode */ + return __LINE__; + case __LINE__: /**********************************/ + + return 0; + } /* FSM END ******************************************* */ } + /*----------------------------------------------------------------------------*/ -static int Lsc370Init(SConnection *con, int argc, char *argv[], int dynamic) { +static int Lsc370Init(SConnection * con, int argc, char *argv[], + int dynamic) +{ /* args: - MakeObject objectname lsc370 - MakeObject objectname lsc370 + MakeObject objectname lsc370 + MakeObject objectname lsc370 */ Lsc370 *drv; - + drv = EaseMakeDriv(con, &lsc370Class, argc, argv, dynamic, 7, - Lsc370ParDef, LscHandler, Lsc370Start, NULL, Lsc370Read, - Lsc370Set); - if (drv == NULL) return 0; + Lsc370ParDef, LscHandler, Lsc370Start, NULL, + Lsc370Read, Lsc370Set); + if (drv == NULL) + return 0; drv->htrRange = 0; - setRS232ReplyTerminator(drv->d.b.ser,"\n"); - setRS232SendTerminator(drv->d.b.ser,"\n"); + setRS232ReplyTerminator(drv->d.b.ser, "\n"); + setRS232SendTerminator(drv->d.b.ser, "\n"); return 1; } + /*----------------------------------------------------------------------------*/ -void Lsc370Startup(void) { +void Lsc370Startup(void) +{ ParMakeClass(&lsc370Class, EaseDrivClass()); - MakeDriver("LSC370", Lsc370Init, 0, "LakeShore 370 AC Resistance Bridge"); + MakeDriver("LSC370", Lsc370Init, 0, + "LakeShore 370 AC Resistance Bridge"); } diff --git a/lscsupport.c b/lscsupport.c index 5b165ce..33182f7 100644 --- a/lscsupport.c +++ b/lscsupport.c @@ -19,12 +19,14 @@ is not changed, i.e. an existing errCode is not overwritten. #include "oxinst.h" /*----------------------------------------------------------------------------*/ -int LscHandler(void *object) { +int LscHandler(void *object) +{ int iret, l; EaseBase *eab = EaseBaseCast(object); char *corr; - - if (eab->state < EASE_idle) goto quit; + + if (eab->state < EASE_idle) + goto quit; if (availableNetRS232(eab->ser) || availableRS232(eab->ser)) { eab->msg[0] = '\0'; l = sizeof(eab->ans); @@ -37,17 +39,17 @@ int LscHandler(void *object) { } if (iret == 1) { ParPrintf(eab, -2, "ans: %s", eab->ans); - if (strncmp(eab->ans, "0,123",5) == 0 && eab->state == EASE_lost) { /* response to LOCK? */ + if (strncmp(eab->ans, "0,123", 5) == 0 && eab->state == EASE_lost) { /* response to LOCK? */ EaseWrite(eab, "*IDN?"); goto quit; } else if (eab->state == EASE_lost) { goto quit; - } else if (strncmp(eab->cmd,"*IDN?",5) == 0) { + } else if (strncmp(eab->cmd, "*IDN?", 5) == 0) { if (strcmp(eab->ans, eab->version) == 0) { /* we are still connected with the same device */ } else if (*eab->version == '\0') { - strncat(eab->version, eab->ans, sizeof(eab->version)-1); - } else { /* version (and therefore device) changed */ + strncat(eab->version, eab->ans, sizeof(eab->version) - 1); + } else { /* version (and therefore device) changed */ eab->errCode = EASE_DEV_CHANGED; eab->state = EASE_idle; goto error; diff --git a/ltc11.c b/ltc11.c index 2343f17..c53d18f 100644 --- a/ltc11.c +++ b/ltc11.c @@ -18,7 +18,7 @@ #include #include #include -#include +#include #include "hardsup/serialsinq.h" #include "hardsup/el734_errcodes.h" #include "hardsup/el734fix.h" @@ -29,20 +29,20 @@ */ /*----------------------------------------------------------------------- The LTC11 Data Structure -*/ - typedef struct { - void *pData; - char *pHost; - int iPort; - int iChannel; - int iMode; - int iSensor; - int iControlHeat; - int iControlAnalog; - int iLastError; - time_t lastRequest; - float fLast; - } LTC11Driv, *pLTC11Driv; +*/ +typedef struct { + void *pData; + char *pHost; + int iPort; + int iChannel; + int iMode; + int iSensor; + int iControlHeat; + int iControlAnalog; + int iLastError; + time_t lastRequest; + float fLast; +} LTC11Driv, *pLTC11Driv; /*----------------------------------------------------------------------- A couple of defines for LTC11 modes and special error conditions */ @@ -56,10 +56,10 @@ #define BADANSWER -923 #define BADCONFIRM -924 /*-----------------------------------------------------------------------*/ - static void LTC11Unlock(pLTC11Driv self) - { - SerialNoReply(&(self->pData),"SLLOCK 0;"); - } +static void LTC11Unlock(pLTC11Driv self) +{ + SerialNoReply(&(self->pData), "SLLOCK 0;"); +} /*------------------------------------------------------------------------- The LTC11 can either control a heater or an analog output. It is a common @@ -67,546 +67,506 @@ is 3, no sensor is defined, if it is 6 it is in monitor mode, in both cases control is NOT there. */ - int LTC11GetMode(pEVDriver pEva, int *iMode) - { - pLTC11Driv self = NULL; - int iRet, iiMode; - char pBueffel[80]; - - self = (pLTC11Driv)pEva->pPrivate; - assert(self); - - if(self->pData == NULL) - { - self->iLastError = NOCONN; - return 0; - } - - /* query the state, it can be in an invalid mode */ - iRet = SerialWriteRead(&(self->pData),"QISTATE?;",pBueffel,79); - LTC11Unlock(self); - if(iRet != 1) - { - self->iLastError = iRet; - return 0; - } - if(strcmp(pBueffel,"?TMO") == 0) - { - self->iLastError = TIMEOUT; - return 0; - } - if(sscanf(pBueffel,"%d",&iiMode) != 1) - { - self->iLastError = EL734__BAD_ILLG; - return 0; - } - if( (iiMode != 1) && (iiMode != 2) ) - { - self->iLastError = BADSTATE; - *iMode = MISERABLE; - return 0; - } - - /* check the sensor in heater mode */ - iRet = SerialWriteRead(&(self->pData),"QOUT?1;",pBueffel,79); - LTC11Unlock(self); - if(iRet != 1) - { - self->iLastError = iRet; - return 0; - } - if(strcmp(pBueffel,"?TMO") == 0) - { - self->iLastError = TIMEOUT; - return 0; - } - if(sscanf(pBueffel,"%d",&iiMode) != 1) - { - self->iLastError = EL734__BAD_ILLG; - return 0; - } - if( (iiMode != 3) && (iiMode != 6 ) ) - { - *iMode = HEATER; - self->iControlHeat = iiMode; - return 1; - } +int LTC11GetMode(pEVDriver pEva, int *iMode) +{ + pLTC11Driv self = NULL; + int iRet, iiMode; + char pBueffel[80]; + + self = (pLTC11Driv) pEva->pPrivate; + assert(self); + + if (self->pData == NULL) { + self->iLastError = NOCONN; + return 0; + } + + /* query the state, it can be in an invalid mode */ + iRet = SerialWriteRead(&(self->pData), "QISTATE?;", pBueffel, 79); + LTC11Unlock(self); + if (iRet != 1) { + self->iLastError = iRet; + return 0; + } + if (strcmp(pBueffel, "?TMO") == 0) { + self->iLastError = TIMEOUT; + return 0; + } + if (sscanf(pBueffel, "%d", &iiMode) != 1) { + self->iLastError = EL734__BAD_ILLG; + return 0; + } + if ((iiMode != 1) && (iiMode != 2)) { + self->iLastError = BADSTATE; + *iMode = MISERABLE; + return 0; + } + + /* check the sensor in heater mode */ + iRet = SerialWriteRead(&(self->pData), "QOUT?1;", pBueffel, 79); + LTC11Unlock(self); + if (iRet != 1) { + self->iLastError = iRet; + return 0; + } + if (strcmp(pBueffel, "?TMO") == 0) { + self->iLastError = TIMEOUT; + return 0; + } + if (sscanf(pBueffel, "%d", &iiMode) != 1) { + self->iLastError = EL734__BAD_ILLG; + return 0; + } + if ((iiMode != 3) && (iiMode != 6)) { + *iMode = HEATER; + self->iControlHeat = iiMode; + return 1; + } + + /* check the sensor in analog mode */ + iRet = SerialWriteRead(&(self->pData), "QOUT?2;", pBueffel, 79); + LTC11Unlock(self); + if (iRet != 1) { + self->iLastError = iRet; + return 0; + } + if (strcmp(pBueffel, "?TMO") == 0) { + self->iLastError = TIMEOUT; + return 0; + } + if (sscanf(pBueffel, "%d", &iiMode) != 1) { + self->iLastError = EL734__BAD_ILLG; + return 0; + } + if ((iiMode != 3) && (iiMode != 6)) { + *iMode = ANALOG; + self->iControlAnalog = iiMode; + return 1; + } + /* if we are here something is very bad */ + self->iLastError = BADSTATE; + return 0; +} - /* check the sensor in analog mode */ - iRet = SerialWriteRead(&(self->pData),"QOUT?2;",pBueffel,79); - LTC11Unlock(self); - if(iRet != 1) - { - self->iLastError = iRet; - return 0; - } - if(strcmp(pBueffel,"?TMO") == 0) - { - self->iLastError = TIMEOUT; - return 0; - } - if(sscanf(pBueffel,"%d",&iiMode) != 1) - { - self->iLastError = EL734__BAD_ILLG; - return 0; - } - if( (iiMode != 3) && (iiMode != 6 ) ) - { - *iMode = ANALOG; - self->iControlAnalog = iiMode; - return 1; - } - /* if we are here something is very bad */ - self->iLastError = BADSTATE; - return 0; - } /*----------------------------------------------------------------------- iMode below 10 will be interpreted as heater control, above 10 as analog control. -*/ - int LTC11SetMode(pEVDriver pEva, int iMode) - { - pLTC11Driv self = NULL; - int iRet, iiMode; - char pBueffel[80], pCommand[20]; - - self = (pLTC11Driv)pEva->pPrivate; - assert(self); - - if(self->pData == NULL) - { - self->iLastError = NOCONN; - return 0; - } - - if(iMode < 10) /* heater mode */ - { - sprintf(pCommand,"SHCONT%1.1d;",iMode); - iRet = SerialNoReply(&(self->pData),pCommand); - LTC11Unlock(self); - if(iRet != 1) - { - self->iLastError = iRet; - return 0; - } - return 1; - } - else - { - iMode -= 10; - sprintf(pCommand,"SACONT%1.1d;",iMode); - iRet = SerialNoReply(&(self->pData),pCommand); - LTC11Unlock(self); - if(iRet != 1) - { - self->iLastError = iRet; - return 0; - } - return 1; - } - /* should not get here */ - self->iLastError = BADSTATE; - return 0; +*/ +int LTC11SetMode(pEVDriver pEva, int iMode) +{ + pLTC11Driv self = NULL; + int iRet, iiMode; + char pBueffel[80], pCommand[20]; + + self = (pLTC11Driv) pEva->pPrivate; + assert(self); + + if (self->pData == NULL) { + self->iLastError = NOCONN; + return 0; } + + if (iMode < 10) { /* heater mode */ + sprintf(pCommand, "SHCONT%1.1d;", iMode); + iRet = SerialNoReply(&(self->pData), pCommand); + LTC11Unlock(self); + if (iRet != 1) { + self->iLastError = iRet; + return 0; + } + return 1; + } else { + iMode -= 10; + sprintf(pCommand, "SACONT%1.1d;", iMode); + iRet = SerialNoReply(&(self->pData), pCommand); + LTC11Unlock(self); + if (iRet != 1) { + self->iLastError = iRet; + return 0; + } + return 1; + } + /* should not get here */ + self->iLastError = BADSTATE; + return 0; +} + /*-------------------------------------------------------------------------*/ - static int LTC11Get(pEVDriver pEva, float *fValue) - { - pLTC11Driv self = NULL; - int iRet; - char pBueffel[80]; - char pCommand[46]; - char c; - float fVal; - - self = (pLTC11Driv)pEva->pPrivate; - assert(self); +static int LTC11Get(pEVDriver pEva, float *fValue) +{ + pLTC11Driv self = NULL; + int iRet; + char pBueffel[80]; + char pCommand[46]; + char c; + float fVal; - if(self->pData == NULL) - { - self->iLastError = NOCONN; - return 0; - } - - if(time(NULL) < self->lastRequest) - { - *fValue = self->fLast; - return 1; - } - else - { - self->lastRequest = time(NULL) + 5; /* buffer 5 seconds */ - } - sprintf(pCommand,"QSAMP?%1.1d;",self->iSensor); - iRet = SerialWriteRead(&(self->pData),pCommand,pBueffel,79); - LTC11Unlock(self); - if(iRet != 1) - { - self->iLastError = iRet; - return 0; - } - if(strcmp(pBueffel,"?TMO") == 0) - { - self->iLastError = TIMEOUT; - return 0; - } - iRet = sscanf(pBueffel,"%f%c",fValue,&c); - if(iRet != 2) - { - self->iLastError = BADANSWER; - return 0; - } - if( (c != 'K') && (c != 'C') && (c != 'F') && (c != 'N') - && (c != 'V') && (c != 'O') ) - { - self->iLastError = BADANSWER; - return 0; - } - self->fLast = *fValue; - return 1; + self = (pLTC11Driv) pEva->pPrivate; + assert(self); + + if (self->pData == NULL) { + self->iLastError = NOCONN; + return 0; } + + if (time(NULL) < self->lastRequest) { + *fValue = self->fLast; + return 1; + } else { + self->lastRequest = time(NULL) + 5; /* buffer 5 seconds */ + } + sprintf(pCommand, "QSAMP?%1.1d;", self->iSensor); + iRet = SerialWriteRead(&(self->pData), pCommand, pBueffel, 79); + LTC11Unlock(self); + if (iRet != 1) { + self->iLastError = iRet; + return 0; + } + if (strcmp(pBueffel, "?TMO") == 0) { + self->iLastError = TIMEOUT; + return 0; + } + iRet = sscanf(pBueffel, "%f%c", fValue, &c); + if (iRet != 2) { + self->iLastError = BADANSWER; + return 0; + } + if ((c != 'K') && (c != 'C') && (c != 'F') && (c != 'N') + && (c != 'V') && (c != 'O')) { + self->iLastError = BADANSWER; + return 0; + } + self->fLast = *fValue; + return 1; +} + /*-------------------------------------------------------------------------*/ - static int LTC11Run(pEVDriver pEva, float fVal) - { - pLTC11Driv self = NULL; - int iRet, iMode; - char pBueffel[80]; - char pCommand[40]; - float fTest = 0.0, fDelta; - - self = (pLTC11Driv)pEva->pPrivate; - assert(self); - - if(self->pData == NULL) - { - self->iLastError = NOCONN; - return 0; - } +static int LTC11Run(pEVDriver pEva, float fVal) +{ + pLTC11Driv self = NULL; + int iRet, iMode; + char pBueffel[80]; + char pCommand[40]; + float fTest = 0.0, fDelta; - /* find our operation mode */ - iRet = LTC11GetMode(pEva,&iMode); - if( (iRet < 1) || (iMode == MISERABLE) ) - { - return 0; - } - - /* format command */ - sprintf(pCommand,"SETP %d,%f;",iMode, fVal); - - /* send command */ - iRet = SerialNoReply(&(self->pData),pCommand); - if(iRet != 1) - { - self->iLastError = iRet; - LTC11Unlock(self); - return 0; - } - - /* read back */ - sprintf(pCommand,"QSETP?%d;", iMode); - iRet = SerialWriteRead(&(self->pData),pCommand,pBueffel,79); - LTC11Unlock(self); - if(iRet != 1) - { - self->iLastError = iRet; - return 0; - } + self = (pLTC11Driv) pEva->pPrivate; + assert(self); - /* check confirmation */ - if(strcmp(pBueffel,"?TMO") == 0) - { - self->iLastError = TIMEOUT; - return 0; - } - sscanf(pBueffel,"%f",&fTest); - fDelta = fVal - fTest; - if(fDelta < 0.0) - fDelta = -fDelta; - - if(fDelta > 0.1) - { - self->iLastError = BADCONFIRM; - return 0; - } - - return 1; + if (self->pData == NULL) { + self->iLastError = NOCONN; + return 0; } + + /* find our operation mode */ + iRet = LTC11GetMode(pEva, &iMode); + if ((iRet < 1) || (iMode == MISERABLE)) { + return 0; + } + + /* format command */ + sprintf(pCommand, "SETP %d,%f;", iMode, fVal); + + /* send command */ + iRet = SerialNoReply(&(self->pData), pCommand); + if (iRet != 1) { + self->iLastError = iRet; + LTC11Unlock(self); + return 0; + } + + /* read back */ + sprintf(pCommand, "QSETP?%d;", iMode); + iRet = SerialWriteRead(&(self->pData), pCommand, pBueffel, 79); + LTC11Unlock(self); + if (iRet != 1) { + self->iLastError = iRet; + return 0; + } + + /* check confirmation */ + if (strcmp(pBueffel, "?TMO") == 0) { + self->iLastError = TIMEOUT; + return 0; + } + sscanf(pBueffel, "%f", &fTest); + fDelta = fVal - fTest; + if (fDelta < 0.0) + fDelta = -fDelta; + + if (fDelta > 0.1) { + self->iLastError = BADCONFIRM; + return 0; + } + + return 1; +} + /*------------------------------------------------------------------------*/ - static int LTC11Error(pEVDriver pEva, int *iCode, char *pError, - int iErrLen) - { - pLTC11Driv self = NULL; +static int LTC11Error(pEVDriver pEva, int *iCode, char *pError, + int iErrLen) +{ + pLTC11Driv self = NULL; - self = (pLTC11Driv)pEva->pPrivate; - assert(self); + self = (pLTC11Driv) pEva->pPrivate; + assert(self); + + *iCode = self->iLastError; + switch (*iCode) { + case NOCONN: + strncpy(pError, "No Connection to Bruker Controller", iErrLen); + break; + case MISERABLE: + case BADSTATE: + strncpy(pError, "The LTC-11 is in a very bad state", iErrLen); + break; + case BADANSWER: + strncpy(pError, "The LTC-11 returned a bad reply", iErrLen); + break; + case BADCONFIRM: + strncpy(pError, "The LTC-11 did not accept the new set point", + iErrLen); + break; + case TIMEOUT: + strncpy(pError, "Timeout receiving data from LTC-11", iErrLen); + break; + default: + SerialError(*iCode, pError, iErrLen); + break; + } + return 1; +} - *iCode = self->iLastError; - switch(*iCode) - { - case NOCONN: - strncpy(pError,"No Connection to Bruker Controller",iErrLen); - break; - case MISERABLE: - case BADSTATE: - strncpy(pError,"The LTC-11 is in a very bad state",iErrLen); - break; - case BADANSWER: - strncpy(pError,"The LTC-11 returned a bad reply",iErrLen); - break; - case BADCONFIRM: - strncpy(pError,"The LTC-11 did not accept the new set point",iErrLen); - break; - case TIMEOUT: - strncpy(pError,"Timeout receiving data from LTC-11",iErrLen); - break; - default: - SerialError(*iCode,pError,iErrLen); - break; - } - return 1; - } /*---------------------------------------------------------------------------*/ - static int LTC11Send(pEVDriver pEva, char *pCommand, char *pReply, - int iReplyLen) - { - pLTC11Driv self = NULL; - int iRet; +static int LTC11Send(pEVDriver pEva, char *pCommand, char *pReply, + int iReplyLen) +{ + pLTC11Driv self = NULL; + int iRet; - self = (pLTC11Driv)pEva->pPrivate; - assert(self); + self = (pLTC11Driv) pEva->pPrivate; + assert(self); - if(self->pData == NULL) - { - self->iLastError = NOCONN; - return 0; - } + if (self->pData == NULL) { + self->iLastError = NOCONN; + return 0; + } - iRet = SerialWriteRead(&(self->pData),pCommand, pReply, iReplyLen); - if(iRet != 1) - { - self->iLastError = iRet; - return 0; - } - return 1; - } + iRet = SerialWriteRead(&(self->pData), pCommand, pReply, iReplyLen); + if (iRet != 1) { + self->iLastError = iRet; + return 0; + } + return 1; +} + /*--------------------------------------------------------------------------*/ - static int LTC11Init(pEVDriver pEva) - { - pLTC11Driv self = NULL; - int iRet; - char pBueffel[80], pCommand[20]; +static int LTC11Init(pEVDriver pEva) +{ + pLTC11Driv self = NULL; + int iRet; + char pBueffel[80], pCommand[20]; - self = (pLTC11Driv)pEva->pPrivate; - assert(self); + self = (pLTC11Driv) pEva->pPrivate; + assert(self); - /* open port connection */ - self->pData = NULL; - iRet = SerialOpen(&(self->pData),self->pHost, self->iPort, self->iChannel); - if(iRet != 1) - { - self->iLastError = iRet; - return 0; - } - /* configure serial port terminators */ - SerialSendTerm(&(self->pData),";"); - SerialATerm(&(self->pData),"1;"); - SerialConfig(&(self->pData),30000); - - self->iSensor = 1; - - /* initialize control sensors to unknown, then call GetMode - to get real values - */ - self->iControlHeat = 6; - self->iControlAnalog = 6; - LTC11GetMode(pEva,&iRet); - - return 1; + /* open port connection */ + self->pData = NULL; + iRet = + SerialOpen(&(self->pData), self->pHost, self->iPort, self->iChannel); + if (iRet != 1) { + self->iLastError = iRet; + return 0; } + /* configure serial port terminators */ + SerialSendTerm(&(self->pData), ";"); + SerialATerm(&(self->pData), "1;"); + SerialConfig(&(self->pData), 30000); + + self->iSensor = 1; + + /* initialize control sensors to unknown, then call GetMode + to get real values + */ + self->iControlHeat = 6; + self->iControlAnalog = 6; + LTC11GetMode(pEva, &iRet); + + return 1; +} + /*-------------------------------------------------------------------------*/ - static int LTC11Close(pEVDriver pEva) - { - pLTC11Driv self = NULL; +static int LTC11Close(pEVDriver pEva) +{ + pLTC11Driv self = NULL; - self = (pLTC11Driv)pEva->pPrivate; - assert(self); + self = (pLTC11Driv) pEva->pPrivate; + assert(self); + + SerialClose(&(self->pData)); + self->pData = 0; + + return 1; +} - SerialClose(&(self->pData)); - self->pData = 0; - - return 1; - } /*---------------------------------------------------------------------------*/ - static int LTC11Fix(pEVDriver self, int iError) - { - pLTC11Driv pMe = NULL; - int iRet; - char pCommand[20], pBueffel[80]; - - assert(self); - pMe = (pLTC11Driv )self->pPrivate; - assert(pMe); +static int LTC11Fix(pEVDriver self, int iError) +{ + pLTC11Driv pMe = NULL; + int iRet; + char pCommand[20], pBueffel[80]; - switch(iError) - { - /* network errors */ - case EL734__BAD_FLUSH: - case EL734__BAD_RECV: - case EL734__BAD_RECV_NET: - case EL734__BAD_RECV_UNKN: - case EL734__BAD_RECVLEN: - case EL734__BAD_RECV1: - case EL734__BAD_RECV1_PIPE: - case EL734__BAD_RNG: - case EL734__BAD_SEND: - case EL734__BAD_SEND_PIPE: - case EL734__BAD_SEND_NET: - case EL734__BAD_SEND_UNKN: - case EL734__BAD_SENDLEN: - LTC11Close(self); - iRet = LTC11Init(self); - if(iRet) - { - return DEVREDO; - } - else - { - return DEVFAULT; - } - break; - case EL734__FORCED_CLOSED: - case NOCONN: - iRet = LTC11Init(self); - if(iRet) - { - return DEVREDO; - } - else - { - return DEVFAULT; - } - break; - /* fixable LTC11 Errors */ - case MISERABLE: - case BADSTATE: - iRet = SerialNoReply(&(pMe->pData),"SCONT;"); - LTC11Unlock(pMe); - return DEVREDO; - break; - case BADANSWER: - case BADCONFIRM: - case TIMEOUT: - return DEVREDO; - break; - default: - return DEVFAULT; - break; - } - return DEVFAULT; + assert(self); + pMe = (pLTC11Driv) self->pPrivate; + assert(pMe); + + switch (iError) { + /* network errors */ + case EL734__BAD_FLUSH: + case EL734__BAD_RECV: + case EL734__BAD_RECV_NET: + case EL734__BAD_RECV_UNKN: + case EL734__BAD_RECVLEN: + case EL734__BAD_RECV1: + case EL734__BAD_RECV1_PIPE: + case EL734__BAD_RNG: + case EL734__BAD_SEND: + case EL734__BAD_SEND_PIPE: + case EL734__BAD_SEND_NET: + case EL734__BAD_SEND_UNKN: + case EL734__BAD_SENDLEN: + LTC11Close(self); + iRet = LTC11Init(self); + if (iRet) { + return DEVREDO; + } else { + return DEVFAULT; + } + break; + case EL734__FORCED_CLOSED: + case NOCONN: + iRet = LTC11Init(self); + if (iRet) { + return DEVREDO; + } else { + return DEVFAULT; + } + break; + /* fixable LTC11 Errors */ + case MISERABLE: + case BADSTATE: + iRet = SerialNoReply(&(pMe->pData), "SCONT;"); + LTC11Unlock(pMe); + return DEVREDO; + break; + case BADANSWER: + case BADCONFIRM: + case TIMEOUT: + return DEVREDO; + break; + default: + return DEVFAULT; + break; } -/*------------------------------------------------------------------------*/ - void KillLTC11(void *pData) - { - pLTC11Driv pMe = NULL; - - pMe = (pLTC11Driv)pData; - assert(pMe); - - if(pMe->pHost) - { - free(pMe->pHost); - } - free(pMe); - } -/*------------------------------------------------------------------------*/ - pEVDriver CreateLTC11Driver(int argc, char *argv[]) - { - pEVDriver pNew = NULL; - pLTC11Driv pSim = NULL; - - /* check for arguments */ - if(argc < 3) - { - return NULL; - } - - pNew = CreateEVDriver(argc,argv); - pSim = (pLTC11Driv)malloc(sizeof(LTC11Driv)); - memset(pSim,0,sizeof(LTC11Driv)); - if(!pNew || !pSim) - { - return NULL; - } - pNew->pPrivate = pSim; - pNew->KillPrivate = KillLTC11; - - /* initalise LTC11Driver */ - pSim->iLastError = 0; - pSim->pHost = strdup(argv[0]); - pSim->iPort = atoi(argv[1]); - pSim->iChannel = atoi(argv[2]); - - - /* initialise function pointers */ - pNew->SetValue = LTC11Run; - pNew->GetValue = LTC11Get; - pNew->Send = LTC11Send; - pNew->GetError = LTC11Error; - pNew->TryFixIt = LTC11Fix; - pNew->Init = LTC11Init; - pNew->Close = LTC11Close; - - return pNew; - } -/*------------------------------------------------------------------------*/ - static int LTC11AssignControl(pEVDriver pEva, int iMode, int iSensor) - { - pLTC11Driv self = NULL; - int iRet, iRead = 0; - char pBueffel[80], pCommand[50]; + return DEVFAULT; +} + +/*------------------------------------------------------------------------*/ +void KillLTC11(void *pData) +{ + pLTC11Driv pMe = NULL; + + pMe = (pLTC11Driv) pData; + assert(pMe); + + if (pMe->pHost) { + free(pMe->pHost); + } + free(pMe); +} + +/*------------------------------------------------------------------------*/ +pEVDriver CreateLTC11Driver(int argc, char *argv[]) +{ + pEVDriver pNew = NULL; + pLTC11Driv pSim = NULL; + + /* check for arguments */ + if (argc < 3) { + return NULL; + } + + pNew = CreateEVDriver(argc, argv); + pSim = (pLTC11Driv) malloc(sizeof(LTC11Driv)); + memset(pSim, 0, sizeof(LTC11Driv)); + if (!pNew || !pSim) { + return NULL; + } + pNew->pPrivate = pSim; + pNew->KillPrivate = KillLTC11; + + /* initalise LTC11Driver */ + pSim->iLastError = 0; + pSim->pHost = strdup(argv[0]); + pSim->iPort = atoi(argv[1]); + pSim->iChannel = atoi(argv[2]); + + + /* initialise function pointers */ + pNew->SetValue = LTC11Run; + pNew->GetValue = LTC11Get; + pNew->Send = LTC11Send; + pNew->GetError = LTC11Error; + pNew->TryFixIt = LTC11Fix; + pNew->Init = LTC11Init; + pNew->Close = LTC11Close; + + return pNew; +} + +/*------------------------------------------------------------------------*/ +static int LTC11AssignControl(pEVDriver pEva, int iMode, int iSensor) +{ + pLTC11Driv self = NULL; + int iRet, iRead = 0; + char pBueffel[80], pCommand[50]; + + self = (pLTC11Driv) pEva->pPrivate; + assert(self); + assert((iMode == HEATER) || (iMode == ANALOG)); + + if (!self->pData) { + self->iLastError = NOCONN; + return 0; + } + sprintf(pCommand, "SOSEN %d,%d;", iMode, iSensor); + iRet = SerialNoReply(&(self->pData), pCommand); + if (iRet != 1) { + self->iLastError = iRet; + return 0; + } + sprintf(pCommand, "QOUT?%d;", iMode); + iRet = SerialWriteRead(&(self->pData), pCommand, pBueffel, 79); + LTC11Unlock(self); + if (strcmp(pBueffel, "?TMO") == 0) { + self->iLastError = TIMEOUT; + return 0; + } + sscanf(pBueffel, "%d;", &iRead); + if (iRead != iSensor) { + self->iLastError = BADCONFIRM; + return 0; + } + if (iMode == ANALOG) { + self->iControlAnalog = iSensor; + } else { + self->iControlHeat = iSensor; + } + /* switch back to control mode */ + SerialNoReply(&(self->pData), "SCONT;"); + return 1; +} - self = (pLTC11Driv)pEva->pPrivate; - assert(self); - assert( (iMode == HEATER) || (iMode == ANALOG) ); - - if(!self->pData) - { - self->iLastError = NOCONN; - return 0; - } - sprintf(pCommand,"SOSEN %d,%d;",iMode,iSensor); - iRet = SerialNoReply(&(self->pData),pCommand); - if(iRet != 1) - { - self->iLastError = iRet; - return 0; - } - sprintf(pCommand,"QOUT?%d;",iMode); - iRet = SerialWriteRead(&(self->pData),pCommand,pBueffel,79); - LTC11Unlock(self); - if(strcmp(pBueffel,"?TMO") == 0) - { - self->iLastError = TIMEOUT; - return 0; - } - sscanf(pBueffel,"%d;",&iRead); - if(iRead != iSensor) - { - self->iLastError = BADCONFIRM; - return 0; - } - if(iMode == ANALOG) - { - self->iControlAnalog = iSensor; - } - else - { - self->iControlHeat = iSensor; - } - /* switch back to control mode */ - SerialNoReply(&(self->pData),"SCONT;"); - return 1; - } /*-------------------------------------------------------------------------- handle LTC11 specific commands: - sensor requests or sets read sensor @@ -615,214 +575,176 @@ - controlanalog requests or sets sensor for analog control in all other cases fall back and call EVControllerWrapper to handle it or eventually throw an error. -*/ - int LTC11Action(SConnection *pCon, SicsInterp *pSics, void *pData, - int argc, char *argv[]) - { - - pEVControl self = NULL; - int iRet, iMode; - char pBueffel[256], pError[132]; - pLTC11Driv pMe = NULL; - float fVal; - - self = (pEVControl)pData; - assert(self); - pMe = (pLTC11Driv)self->pDriv->pPrivate; - assert(pMe); +*/ +int LTC11Action(SConnection * pCon, SicsInterp * pSics, void *pData, + int argc, char *argv[]) +{ - if(argc > 1) - { - strtolower(argv[1]); -/*------ sensor */ - if(strcmp(argv[1],"sensor") == 0) - { - if(argc > 2) /* set case */ - { - /* check permission */ - if(!SCMatchRights(pCon,usUser)) - { - return 0; - } - iRet = Tcl_GetInt(pSics->pTcl,argv[2],&iMode); - if(iRet != TCL_OK) - { - sprintf(pBueffel,"ERROR: needed integer, got %s", - argv[2]); - SCWrite(pCon,pBueffel,eError); - return 0; - } - pMe->iSensor = iMode; - SCSendOK(pCon); - return 1; - } - else /* get case */ - { - sprintf(pBueffel,"%s.sensor = %d", argv[0],pMe->iSensor); - SCWrite(pCon,pBueffel,eValue); - return 1; - } + pEVControl self = NULL; + int iRet, iMode; + char pBueffel[256], pError[132]; + pLTC11Driv pMe = NULL; + float fVal; + + self = (pEVControl) pData; + assert(self); + pMe = (pLTC11Driv) self->pDriv->pPrivate; + assert(pMe); + + if (argc > 1) { + strtolower(argv[1]); +/*------ sensor */ + if (strcmp(argv[1], "sensor") == 0) { + if (argc > 2) { /* set case */ + /* check permission */ + if (!SCMatchRights(pCon, usUser)) { + return 0; } -/*------ controlanalog */ - if(strcmp(argv[1],"controlanalog") == 0) - { - if(argc > 2) /* set case */ - { - /* check permission */ - if(!SCMatchRights(pCon,usUser)) - { - return 0; - } - iRet = Tcl_GetInt(pSics->pTcl,argv[2],&iMode); - if(iRet != TCL_OK) - { - sprintf(pBueffel,"ERROR: needed integer, got %s", - argv[2]); - SCWrite(pCon,pBueffel,eError); - return 0; - } - iRet = LTC11AssignControl(self->pDriv,ANALOG,iMode); - if(iRet != 1) - { - self->pDriv->GetError(self->pDriv,&iMode,pError,131); - sprintf(pBueffel,"ERROR: failed to set sensor: %s",pError); - SCWrite(pCon,pBueffel,eError); - return 0; - } - SCSendOK(pCon); - return 1; - } - else /* get case */ - { - sprintf(pBueffel,"%s.controlanalog = %d", argv[0],pMe->iControlAnalog); - SCWrite(pCon,pBueffel,eValue); - return 1; - } + iRet = Tcl_GetInt(pSics->pTcl, argv[2], &iMode); + if (iRet != TCL_OK) { + sprintf(pBueffel, "ERROR: needed integer, got %s", argv[2]); + SCWrite(pCon, pBueffel, eError); + return 0; } -/*------ controlheat */ - if(strcmp(argv[1],"controlheat") == 0) - { - if(argc > 2) /* set case */ - { - /* check permission */ - if(!SCMatchRights(pCon,usUser)) - { - return 0; - } - iRet = Tcl_GetInt(pSics->pTcl,argv[2],&iMode); - if(iRet != TCL_OK) - { - sprintf(pBueffel,"ERROR: needed integer, got %s", - argv[2]); - SCWrite(pCon,pBueffel,eError); - return 0; - } - iRet = LTC11AssignControl(self->pDriv,HEATER,iMode); - if(iRet != 1) - { - self->pDriv->GetError(self->pDriv,&iMode,pError,131); - sprintf(pBueffel,"ERROR: failed to set sensor: %s",pError); - SCWrite(pCon,pBueffel,eError); - return 0; - } - SCSendOK(pCon); - return 1; - } - else /* get case */ - { - sprintf(pBueffel,"%s.controlheat = %d", argv[0],pMe->iControlHeat); - SCWrite(pCon,pBueffel,eValue); - return 1; - } + pMe->iSensor = iMode; + SCSendOK(pCon); + return 1; + } else { /* get case */ + + sprintf(pBueffel, "%s.sensor = %d", argv[0], pMe->iSensor); + SCWrite(pCon, pBueffel, eValue); + return 1; + } + } +/*------ controlanalog */ + if (strcmp(argv[1], "controlanalog") == 0) { + if (argc > 2) { /* set case */ + /* check permission */ + if (!SCMatchRights(pCon, usUser)) { + return 0; } -/*-------- mode */ - else if(strcmp(argv[1],"mode") == 0) - { - if(argc > 2) /* set case */ - { - /* check permission */ - if(!SCMatchRights(pCon,usUser)) - { - return 0; - } - iRet = Tcl_GetInt(pSics->pTcl,argv[2],&iMode); - if(iRet != TCL_OK) - { - sprintf(pBueffel,"ERROR: needed integer, got %s", - argv[2]); - SCWrite(pCon,pBueffel,eError); - return 0; - } - iRet = LTC11SetMode(self->pDriv,iMode); - if(iRet != 1) - { - self->pDriv->GetError(self->pDriv,&iMode,pError,131); - sprintf(pBueffel,"ERROR: failed to set mode %s",pError); - SCWrite(pCon,pBueffel,eError); - return 0; - } - else - { - SCSendOK(pCon); - return 1; - } - } - else /* get case */ - { - iRet = LTC11GetMode(self->pDriv,&iMode); - if(iRet != 1) - { - self->pDriv->GetError(self->pDriv,&iMode,pError,131); - sprintf(pBueffel,"ERROR: failed to get mode %s",pError); - SCWrite(pCon,pBueffel,eError); - return 0; - } - if(iMode == ANALOG) - { - sprintf(pBueffel,"%s.mode = Analog Control", argv[0]); - } - else - { - sprintf(pBueffel,"%s.mode = Heater Control", argv[0]); - } - SCWrite(pCon,pBueffel,eValue); - return 1; - } + iRet = Tcl_GetInt(pSics->pTcl, argv[2], &iMode); + if (iRet != TCL_OK) { + sprintf(pBueffel, "ERROR: needed integer, got %s", argv[2]); + SCWrite(pCon, pBueffel, eError); + return 0; } + iRet = LTC11AssignControl(self->pDriv, ANALOG, iMode); + if (iRet != 1) { + self->pDriv->GetError(self->pDriv, &iMode, pError, 131); + sprintf(pBueffel, "ERROR: failed to set sensor: %s", pError); + SCWrite(pCon, pBueffel, eError); + return 0; + } + SCSendOK(pCon); + return 1; + } else { /* get case */ + + sprintf(pBueffel, "%s.controlanalog = %d", argv[0], + pMe->iControlAnalog); + SCWrite(pCon, pBueffel, eValue); + return 1; + } + } +/*------ controlheat */ + if (strcmp(argv[1], "controlheat") == 0) { + if (argc > 2) { /* set case */ + /* check permission */ + if (!SCMatchRights(pCon, usUser)) { + return 0; + } + iRet = Tcl_GetInt(pSics->pTcl, argv[2], &iMode); + if (iRet != TCL_OK) { + sprintf(pBueffel, "ERROR: needed integer, got %s", argv[2]); + SCWrite(pCon, pBueffel, eError); + return 0; + } + iRet = LTC11AssignControl(self->pDriv, HEATER, iMode); + if (iRet != 1) { + self->pDriv->GetError(self->pDriv, &iMode, pError, 131); + sprintf(pBueffel, "ERROR: failed to set sensor: %s", pError); + SCWrite(pCon, pBueffel, eError); + return 0; + } + SCSendOK(pCon); + return 1; + } else { /* get case */ + + sprintf(pBueffel, "%s.controlheat = %d", argv[0], + pMe->iControlHeat); + SCWrite(pCon, pBueffel, eValue); + return 1; + } + } +/*-------- mode */ + else if (strcmp(argv[1], "mode") == 0) { + if (argc > 2) { /* set case */ + /* check permission */ + if (!SCMatchRights(pCon, usUser)) { + return 0; + } + iRet = Tcl_GetInt(pSics->pTcl, argv[2], &iMode); + if (iRet != TCL_OK) { + sprintf(pBueffel, "ERROR: needed integer, got %s", argv[2]); + SCWrite(pCon, pBueffel, eError); + return 0; + } + iRet = LTC11SetMode(self->pDriv, iMode); + if (iRet != 1) { + self->pDriv->GetError(self->pDriv, &iMode, pError, 131); + sprintf(pBueffel, "ERROR: failed to set mode %s", pError); + SCWrite(pCon, pBueffel, eError); + return 0; + } else { + SCSendOK(pCon); + return 1; + } + } else { /* get case */ + + iRet = LTC11GetMode(self->pDriv, &iMode); + if (iRet != 1) { + self->pDriv->GetError(self->pDriv, &iMode, pError, 131); + sprintf(pBueffel, "ERROR: failed to get mode %s", pError); + SCWrite(pCon, pBueffel, eError); + return 0; + } + if (iMode == ANALOG) { + sprintf(pBueffel, "%s.mode = Analog Control", argv[0]); + } else { + sprintf(pBueffel, "%s.mode = Heater Control", argv[0]); + } + SCWrite(pCon, pBueffel, eValue); + return 1; + } + } /*--------- list */ - else if(strcmp(argv[1],"list") == 0) - { - /* print generals first */ - EVControlWrapper(pCon,pSics,pData,argc,argv); - /* print our add on stuff */ - sprintf(pBueffel,"%s.sensor = %d",argv[0],pMe->iSensor); - SCWrite(pCon,pBueffel,eValue); - sprintf(pBueffel,"%s.controlanalog = %d",argv[0],pMe->iControlAnalog); - SCWrite(pCon,pBueffel,eValue); - sprintf(pBueffel,"%s.controlheat = %d",argv[0],pMe->iControlHeat); - SCWrite(pCon,pBueffel,eValue); - iRet = LTC11GetMode(self->pDriv,&iMode); - if(iRet != 1) - { - self->pDriv->GetError(self->pDriv,&iMode,pError,131); - sprintf(pBueffel,"ERROR: failed to get mode %s",pError); - SCWrite(pCon,pBueffel,eError); - } - if(iMode == ANALOG) - { - sprintf(pBueffel,"%s.mode = Analog Control", argv[0]); - } - else - { - sprintf(pBueffel,"%s.mode = Heater Control", argv[0]); - } - SCWrite(pCon,pBueffel,eValue); - return 1; - } - else - { - return EVControlWrapper(pCon,pSics,pData,argc,argv); - } - } - return EVControlWrapper(pCon,pSics,pData,argc,argv); + else if (strcmp(argv[1], "list") == 0) { + /* print generals first */ + EVControlWrapper(pCon, pSics, pData, argc, argv); + /* print our add on stuff */ + sprintf(pBueffel, "%s.sensor = %d", argv[0], pMe->iSensor); + SCWrite(pCon, pBueffel, eValue); + sprintf(pBueffel, "%s.controlanalog = %d", argv[0], + pMe->iControlAnalog); + SCWrite(pCon, pBueffel, eValue); + sprintf(pBueffel, "%s.controlheat = %d", argv[0], pMe->iControlHeat); + SCWrite(pCon, pBueffel, eValue); + iRet = LTC11GetMode(self->pDriv, &iMode); + if (iRet != 1) { + self->pDriv->GetError(self->pDriv, &iMode, pError, 131); + sprintf(pBueffel, "ERROR: failed to get mode %s", pError); + SCWrite(pCon, pBueffel, eError); + } + if (iMode == ANALOG) { + sprintf(pBueffel, "%s.mode = Analog Control", argv[0]); + } else { + sprintf(pBueffel, "%s.mode = Heater Control", argv[0]); + } + SCWrite(pCon, pBueffel, eValue); + return 1; + } else { + return EVControlWrapper(pCon, pSics, pData, argc, argv); + } } + return EVControlWrapper(pCon, pSics, pData, argc, argv); +} diff --git a/ltc11.h b/ltc11.h index 4b8ed77..bdcc72d 100644 --- a/ltc11.h +++ b/ltc11.h @@ -13,12 +13,12 @@ #ifndef LTC11 #define LTC11 - pEVDriver CreateLTC11Driver(int argc, char *argv[]); - - int LTC11GetMode(pEVDriver self, int *iMode); - int LTC11SetMode(pEVDriver self, int iMode); - - int LTC11Action(SConnection *pCon, SicsInterp *pSics, void *pData, - int argc, char *argv[]); - -#endif +pEVDriver CreateLTC11Driver(int argc, char *argv[]); + +int LTC11GetMode(pEVDriver self, int *iMode); +int LTC11SetMode(pEVDriver self, int iMode); + +int LTC11Action(SConnection * pCon, SicsInterp * pSics, void *pData, + int argc, char *argv[]); + +#endif diff --git a/modbus.c b/modbus.c index bdb586d..52d328b 100644 --- a/modbus.c +++ b/modbus.c @@ -21,7 +21,8 @@ is not changed, i.e. an existing errCode is not overwritten. /*-------------------------------------------------------------------------*/ -static void double2ieee(double input, char ieee[4]) { +static void double2ieee(double input, char ieee[4]) +{ /* convert double to IEEE 32 bit floating number (denormalized numbers are considered as zero) */ @@ -29,10 +30,10 @@ static void double2ieee(double input, char ieee[4]) { int exponent; if (input == 0) { - ieee[0]= 0; - ieee[1]= 0; - ieee[2]= 0; - ieee[3]= 0; + ieee[0] = 0; + ieee[1] = 0; + ieee[2] = 0; + ieee[3] = 0; } else { mantissa = 0x1000000 * (frexp(fabs(input), &exponent)); exponent = exponent - 1 + 127; @@ -54,19 +55,20 @@ static void double2ieee(double input, char ieee[4]) { } /*-------------------------------------------------------------------------*/ -static double ieee2double(char ieee[4]) { +static double ieee2double(char ieee[4]) +{ /* IEEE 32 bit floating number to double (denormalized numbers are considered as zero) */ long mantissa; double output; int exponent; - - mantissa = ((ieee[1] << 16) & 0x7FFFFF) - | ((ieee[2] << 8) & 0xFF00) - | ((ieee[3] ) & 0xFF); - - exponent = (ieee[0] & 0x7F) * 2 + ((ieee[1] >> 7) & 1); /* raw exponent */ + + mantissa = ((ieee[1] << 16) & 0x7FFFFF) + | ((ieee[2] << 8) & 0xFF00) + | ((ieee[3]) & 0xFF); + + exponent = (ieee[0] & 0x7F) * 2 + ((ieee[1] >> 7) & 1); /* raw exponent */ if (exponent == 0 && mantissa == 0) { return 0.0; } @@ -76,62 +78,79 @@ static double ieee2double(char ieee[4]) { } return output * ldexp(1, exponent - 127); } + /*----------------------------------------------------------------------------*/ -static void uint2word(unsigned int adr, char word[2]) { +static void uint2word(unsigned int adr, char word[2]) +{ unsigned char *uword; - uword = (void *)word; + uword = (void *) word; uword[0] = adr / 256; uword[1] = adr % 256; } + /*----------------------------------------------------------------------------*/ -static unsigned int word2uint(char word[2]) { +static unsigned int word2uint(char word[2]) +{ unsigned char *uword; - uword = (void *)word; - return uword[0]*256 + uword[1]; + uword = (void *) word; + return uword[0] * 256 + uword[1]; } + /*----------------------------------------------------------------------------*/ -static long quad2long(char word[4]) { +static long quad2long(char word[4]) +{ unsigned char *uword; - uword = (void *)word; - return ((uword[0]*256 + uword[1])*256 + uword[2])*256 + uword[3]; + uword = (void *) word; + return ((uword[0] * 256 + uword[1]) * 256 + uword[2]) * 256 + uword[3]; } + /*----------------------------------------------------------------------------*/ -static void long2quad(long val, char word[4]) { +static void long2quad(long val, char word[4]) +{ unsigned char *uword; - uword = (void *)word; - uword[3] = val % 256; val = val/256; - uword[2] = val % 256; val = val/256; - uword[1] = val % 256; val = val/256; + uword = (void *) word; + uword[3] = val % 256; + val = val / 256; + uword[2] = val % 256; + val = val / 256; + uword[1] = val % 256; + val = val / 256; uword[0] = val; } + /*----------------------------------------------------------------------------*/ -static void fadr2word(int adr, char word[2]) { +static void fadr2word(int adr, char word[2]) +{ unsigned char *uword; - uword = (void *)word; - uword[0] = (adr*2) / 256 + 0x80; - uword[1] = (adr*2) % 256; + uword = (void *) word; + uword[0] = (adr * 2) / 256 + 0x80; + uword[1] = (adr * 2) % 256; } + /*----------------------------------------------------------------------------*/ -static int word2fadr(char word[2]) { +static int word2fadr(char word[2]) +{ unsigned char *uword; - uword = (void *)word; - return ((uword[0] & 0x7F)*256 + uword[1]) / 2; + uword = (void *) word; + return ((uword[0] & 0x7F) * 256 + uword[1]) / 2; } + /*----------------------------------------------------------------------------*/ -static int calc_crc(char *inp, int inpLen, int addCrc) { +static int calc_crc(char *inp, int inpLen, int addCrc) +{ /* CRC runs cyclic Redundancy Check Algorithm on input inp */ /* Returns value of 16 bit CRC after completion and */ /* always adds 2 crc bytes to message */ /* returns 0 if incoming message has correct CRC */ - unsigned int crc= 0xffff; + unsigned int crc = 0xffff; unsigned int next; int carry; int n; - + while (inpLen--) { - next = *(unsigned char *)inp; + next = *(unsigned char *) inp; crc ^= next; for (n = 0; n < 8; n++) { carry = crc & 1; @@ -147,50 +166,61 @@ static int calc_crc(char *inp, int inpLen, int addCrc) { inp[1] = crc / 256; } return crc; -} +} + /*----------------------------------------------------------------------------*/ -void ModBusDump(EaseBase *eab, int iout, char *fmt, char *buffer, int length) { +void ModBusDump(EaseBase * eab, int iout, char *fmt, char *buffer, + int length) +{ char buf[128]; int i; - - if (length > 40) length = 40; - for (i=0; i 40) + length = 40; + for (i = 0; i < length; i++) { + snprintf(buf + i * 3, 4, " %2.2X", (unsigned char) buffer[i]); } - buf[i*3]='\0'; + buf[i * 3] = '\0'; ParPrintf(eab, iout, fmt, buf); } + /*----------------------------------------------------------------------------*/ -void ModBusWrite(EaseBase *eab, int length) { +void ModBusWrite(EaseBase * eab, int length) +{ int iret; char trash[64]; int l; - - assert(length < sizeof (eab->cmd)); - - if (eab->errCode || eab->state == EASE_expect) return; + + assert(length < sizeof(eab->cmd)); + + if (eab->errCode || eab->state == EASE_expect) + return; while (availableRS232(eab->ser) == 1) { - l=sizeof(trash); + l = sizeof(trash); iret = readRS232TillTerm(eab->ser, trash, &l); - if (iret < 0) break; + if (iret < 0) + break; ModBusDump(eab, -2, "trash %s\n", trash, l); } calc_crc(eab->cmd, length, 1); - iret = writeRS232(eab->ser, eab->cmd, length+2); + iret = writeRS232(eab->ser, eab->cmd, length + 2); if (iret < 0) { eab->errCode = iret; return; } - ModBusDump(eab, -2, "cmd: %s", eab->cmd, length+2); + ModBusDump(eab, -2, "cmd: %s", eab->cmd, length + 2); eab->state = EASE_expect; eab->cmdtime = time(NULL); } + /*----------------------------------------------------------------------------*/ -int ModBusHandler(void *object) { +int ModBusHandler(void *object) +{ int iret, l; EaseBase *eab = EaseBaseCast(object); - - if (eab->state < EASE_idle) goto quit; + + if (eab->state < EASE_idle) + goto quit; if (availableNetRS232(eab->ser) || availableRS232(eab->ser)) { eab->msg[0] = '\0'; l = 5; @@ -202,7 +232,8 @@ int ModBusHandler(void *object) { goto quit; } if (iret == 1) { - if (eab->cmd[0] != eab->ans[0] || eab->cmd[1] != (eab->ans[1] & 0x7F)) { + if (eab->cmd[0] != eab->ans[0] + || eab->cmd[1] != (eab->ans[1] & 0x7F)) { iret = EASE_FAULT; ModBusDump(eab, eError, "bad answer: %s", eab->ans, l); } else if (eab->ans[1] & 0x80) { @@ -214,21 +245,21 @@ int ModBusHandler(void *object) { } else { ModBusDump(eab, eError, "bad answer: %s", eab->ans, l); }; - } else if (eab->ans[1] == 16) { /* answer from write n words */ - l=3; /* finish response */ - iret = readRS232TillTerm(eab->ser, eab->ans+5, &l); - l+=5; - } else if (eab->ans[1] == 3) { /* answer for read n words */ - l = eab->ans[2]; /* bytes to read */ - if (l<0 || l >= sizeof(eab->ans)-5) { - l=64; + } else if (eab->ans[1] == 16) { /* answer from write n words */ + l = 3; /* finish response */ + iret = readRS232TillTerm(eab->ser, eab->ans + 5, &l); + l += 5; + } else if (eab->ans[1] == 3) { /* answer for read n words */ + l = eab->ans[2]; /* bytes to read */ + if (l < 0 || l >= sizeof(eab->ans) - 5) { + l = 64; } - iret = readRS232TillTerm(eab->ser, eab->ans+5, &l); - l+=5; - } else if (eab->ans[1] == 8) { /* loopback info */ - l=1; - iret = readRS232TillTerm(eab->ser, eab->ans+5, &l); - l+=5; + iret = readRS232TillTerm(eab->ser, eab->ans + 5, &l); + l += 5; + } else if (eab->ans[1] == 8) { /* loopback info */ + l = 1; + iret = readRS232TillTerm(eab->ser, eab->ans + 5, &l); + l += 5; if (eab->state == EASE_lost) { if (eab->ans[4] == 44 && eab->ans[5] == 55) { eab->state = EASE_idle; @@ -255,7 +286,7 @@ int ModBusHandler(void *object) { } eab->state = EASE_read; } else if (eab->state == EASE_expect) { - if (time(NULL) > eab->cmdtime+20) { + if (time(NULL) > eab->cmdtime + 20) { eab->state = EASE_lost; } } else if (eab->state == EASE_lost) { @@ -275,42 +306,48 @@ error: quit: return EaseHandler(eab); } + /*----------------------------------------------------------------------------*/ -void ModBusPutFloats(EaseBase *eab, int adr, int npar, float val[]) { +void ModBusPutFloats(EaseBase * eab, int adr, int npar, float val[]) +{ int l, n; - + assert(npar <= 5); - - eab->cmd[0] = 1; /* device address */ - eab->cmd[1] = 16; /* write n words */ + + eab->cmd[0] = 1; /* device address */ + eab->cmd[1] = 16; /* write n words */ fadr2word(adr, eab->cmd + 2); - uint2word(npar*2, eab->cmd + 4); - eab->cmd[6] = npar*4; /* number of bytes */ + uint2word(npar * 2, eab->cmd + 4); + eab->cmd[6] = npar * 4; /* number of bytes */ l = 7; - for (n=0; ncmd+l); + for (n = 0; n < npar; n++) { + double2ieee(val[n], eab->cmd + l); l += 4; } ModBusWrite(eab, l); } + /*----------------------------------------------------------------------------*/ -void ModBusRequestValues(EaseBase *eab, int adr, int npar) { +void ModBusRequestValues(EaseBase * eab, int adr, int npar) +{ assert(npar <= 14); - - eab->cmd[0] = 1; /* device address */ - eab->cmd[1] = 3; /* read n words */ + + eab->cmd[0] = 1; /* device address */ + eab->cmd[1] = 3; /* read n words */ fadr2word(adr, eab->cmd + 2); - uint2word(npar*2, eab->cmd + 4); + uint2word(npar * 2, eab->cmd + 4); ModBusWrite(eab, 6); } + /*----------------------------------------------------------------------------*/ -static double ModBus2double(char ieee[4]) { +static double ModBus2double(char ieee[4]) +{ long t; /* convert 32 bit values by guessing the type. will not work when a floating point value is a very low positive number (below 2^-125) or when a time is divisible by 65536 ms */ - if (ieee[0]) { /* guess its a float */ + if (ieee[0]) { /* guess its a float */ return ieee2double(ieee); } if (ieee[1] != 0 && ieee[2] == 0 && ieee[3] == 0) { @@ -319,13 +356,15 @@ static double ModBus2double(char ieee[4]) { } /* guess its a time */ t = word2uint(ieee); - return (t * 65536 + word2uint(ieee+2)) * 0.001; + return (t * 65536 + word2uint(ieee + 2)) * 0.001; } + /*----------------------------------------------------------------------------*/ -float ModBusGet(EaseBase *eab, int adr, int type) { +float ModBusGet(EaseBase * eab, int adr, int type) +{ int startAdr; int i; - + if (eab->state != EASE_read) { return 0.0; } @@ -339,11 +378,13 @@ float ModBusGet(EaseBase *eab, int adr, int type) { } return ieee2double(eab->ans + 3 + i * 4); } -/*----------------------------------------------------------------------------*/ -void ModBusRequestValue(EaseBase *eab, int adr, int type) { - eab->cmd[0] = 1; /* device address */ - eab->cmd[1] = 3; /* read n words */ +/*----------------------------------------------------------------------------*/ +void ModBusRequestValue(EaseBase * eab, int adr, int type) +{ + + eab->cmd[0] = 1; /* device address */ + eab->cmd[1] = 3; /* read n words */ if (type == modBusInt) { uint2word(adr, eab->cmd + 2); uint2word(1, eab->cmd + 4); @@ -353,45 +394,49 @@ void ModBusRequestValue(EaseBase *eab, int adr, int type) { } ModBusWrite(eab, 6); } + /*----------------------------------------------------------------------------*/ -void ModBusPutValue(EaseBase *eab, int adr, int type, float val) { +void ModBusPutValue(EaseBase * eab, int adr, int type, float val) +{ int l; - - eab->cmd[0] = 1; /* device address */ - eab->cmd[1] = 16; /* write n words */ + + eab->cmd[0] = 1; /* device address */ + eab->cmd[1] = 16; /* write n words */ if (type == modBusInt) { uint2word(adr, eab->cmd + 2); uint2word(1, eab->cmd + 4); eab->cmd[6] = 2; - uint2word((int)(val), eab->cmd+7); + uint2word((int) (val), eab->cmd + 7); ModBusWrite(eab, 9); return; } fadr2word(adr, eab->cmd + 2); uint2word(2, eab->cmd + 4); - eab->cmd[6] = 4; /* number of bytes */ + eab->cmd[6] = 4; /* number of bytes */ if (type == modBusFloat) { - double2ieee(val, eab->cmd+7); + double2ieee(val, eab->cmd + 7); } else if (type == modBusTime) { - long2quad((long)(val * 1000. + 0.5), eab->cmd+7); + long2quad((long) (val * 1000. + 0.5), eab->cmd + 7); } else { - uint2word((int)(val + 0.5), eab->cmd+7); + uint2word((int) (val + 0.5), eab->cmd + 7); eab->cmd[9] = 0; eab->cmd[10] = 0; } ModBusWrite(eab, 11); } + /*----------------------------------------------------------------------------*/ -float ModBusGetValue(EaseBase *eab, int type) { - +float ModBusGetValue(EaseBase * eab, int type) +{ + if (eab->state != EASE_read) { return 0.0; } if (type == modBusFloat) { return ieee2double(eab->ans + 3); } else if (type == modBusTime) { - return quad2long(eab->ans+3) * 0.001; + return quad2long(eab->ans + 3) * 0.001; } else { - return word2uint(eab->ans+3); - } + return word2uint(eab->ans + 3); + } } diff --git a/modbus.h b/modbus.h index 1ea1b57..bcccaca 100644 --- a/modbus.h +++ b/modbus.h @@ -13,26 +13,26 @@ Markus Zolliker, Aug 2005 #define MODBUS_BAD_CRC -3090 -typedef enum {modBusFloat, modBusInt, modBusTime} ModBusType; +typedef enum { modBusFloat, modBusInt, modBusTime } ModBusType; int ModBusHandler(void *eab); -void ModBusPutFloats(EaseBase *eab, int adr, int npar, float val[]); +void ModBusPutFloats(EaseBase * eab, int adr, int npar, float val[]); /* put floats with contiguous adresses */ -void ModBusRequestValues(EaseBase *eab, int adr, int npar); +void ModBusRequestValues(EaseBase * eab, int adr, int npar); /* request floats or time (not int) with contiguous adresses */ - -float ModBusGet(EaseBase *eab, int adr, int type); + +float ModBusGet(EaseBase * eab, int adr, int type); /* get value from the ModBusRequestValues command (no int!) */ -void ModBusRequestValue(EaseBase *eab, int adr, int type); +void ModBusRequestValue(EaseBase * eab, int adr, int type); /* request one value of arbitrary type */ -float ModBusGetValue(EaseBase *eab, int type); +float ModBusGetValue(EaseBase * eab, int type); /* get this value */ -void ModBusPutValue(EaseBase *eab, int adr, int type, float val); +void ModBusPutValue(EaseBase * eab, int adr, int type, float val); /* put one value of arbitrary type */ #endif diff --git a/nextrics.c b/nextrics.c index 7c9b922..b60539a 100644 --- a/nextrics.c +++ b/nextrics.c @@ -35,22 +35,22 @@ #include "nxscript.h" -#define DET1X 256 /* x -length of detector 1 */ -#define DET1Y 128 /* y-length of detector 1 */ -#define DET1XS -.78 /* pixel size in x of detector 1 */ -#define DET1YS 1.486 /* pixel size in y of detector 1 */ +#define DET1X 256 /* x -length of detector 1 */ +#define DET1Y 128 /* y-length of detector 1 */ +#define DET1XS -.78 /* pixel size in x of detector 1 */ +#define DET1YS 1.486 /* pixel size in y of detector 1 */ #define DET1DESC "EMBL PSD" -#define DET2X 256 /* x -length of detector 1 */ -#define DET2Y 128 /* y-length of detector 1 */ -#define DET2XS -.78 /* pixel size in x of detector 1 */ -#define DET2YS 1.486 /* pixel size in y of detector 1 */ +#define DET2X 256 /* x -length of detector 1 */ +#define DET2Y 128 /* y-length of detector 1 */ +#define DET2XS -.78 /* pixel size in x of detector 1 */ +#define DET2YS 1.486 /* pixel size in y of detector 1 */ #define DET2DESC "EMBL PSD" -#define DET3X 256 /* x -length of detector 1 */ -#define DET3Y 128 /* y-length of detector 1 */ -#define DET3XS -.78 /* pixel size in x of detector 1 */ -#define DET3YS 1.486 /* pixel size in y of detector 1 */ +#define DET3X 256 /* x -length of detector 1 */ +#define DET3Y 128 /* y-length of detector 1 */ +#define DET3XS -.78 /* pixel size in x of detector 1 */ +#define DET3YS 1.486 /* pixel size in y of detector 1 */ #define DET3DESC "EMBL PSD" -#define DETAMAX 256 /* maximum length of pixelsize array */ +#define DETAMAX 256 /* maximum length of pixelsize array */ /* histogram memory names */ #define HM1 "hm1" @@ -70,1495 +70,1296 @@ name of hkl object holding crystallographic information #define HKLNAME "hkl" /*------------------------ the data structure ----------------------------*/ - typedef struct __NexTrics { - pObjectDescriptor pDes; - char *pCurrentFile; - char *pFileRoot; - pDataNumber pDanu; - NXdict pDict; - pHistMem pHistogram1, pHistogram2, pHistogram3; - int iFirst; - int iFrameNum; - pICallBack pCall; - float hm2Off, hm3Off, hm1off; - pHKL pCrystal; - int iHDF5; - pCounter pCount; - } NexTrics; +typedef struct __NexTrics { + pObjectDescriptor pDes; + char *pCurrentFile; + char *pFileRoot; + pDataNumber pDanu; + NXdict pDict; + pHistMem pHistogram1, pHistogram2, pHistogram3; + int iFirst; + int iFrameNum; + pICallBack pCall; + float hm2Off, hm3Off, hm1off; + pHKL pCrystal; + int iHDF5; + pCounter pCount; +} NexTrics; /* event type */ -#define NEWFRAME 1166 +#define NEWFRAME 1166 /*----------------------------------------------------------------------*/ - pNexTrics CreateNexTrics(pDataNumber pNum, char *pRoot, char *pDict, - SicsInterp *pSics) - { - pNexTrics pNew = NULL; - int iRet; - CommandList *pCom = NULL; - pSicsVariable pVar = NULL; - - /* allocate memory */ - pNew = (pNexTrics)malloc(sizeof(NexTrics)); - if(!pNew) - { - return NULL; - } - memset(pNew,0,sizeof(NexTrics)); - - /* new object descriptor and callback interface */ - pNew->pDes = CreateDescriptor(HM1); - pNew->pCall = CreateCallBackInterface(); - if(!pNew->pDes || !pNew->pCall) - { - free(pNew); - return NULL; - } - - /* initialize dictionary */ - iRet = NXDinitfromfile(pDict,&pNew->pDict); - if(iRet != NX_OK) - { - DeleteNexTrics(pNew); - return NULL; - } - if(strstr(pDict,"5") != NULL) - { - pNew->iHDF5 = 1; - } - pNew->pFileRoot = strdup(pRoot); - pNew->pDanu = pNum; - - /* find things in interpreter */ - pCom = FindCommand(pSics,HM1); - if(pCom) - { - pNew->pHistogram1 = (pHistMem)pCom->pData; - } - else - { - pNew->pHistogram1 = NULL; - } +pNexTrics CreateNexTrics(pDataNumber pNum, char *pRoot, char *pDict, + SicsInterp * pSics) +{ + pNexTrics pNew = NULL; + int iRet; + CommandList *pCom = NULL; + pSicsVariable pVar = NULL; + + /* allocate memory */ + pNew = (pNexTrics) malloc(sizeof(NexTrics)); + if (!pNew) { + return NULL; + } + memset(pNew, 0, sizeof(NexTrics)); + + /* new object descriptor and callback interface */ + pNew->pDes = CreateDescriptor(HM1); + pNew->pCall = CreateCallBackInterface(); + if (!pNew->pDes || !pNew->pCall) { + free(pNew); + return NULL; + } + + /* initialize dictionary */ + iRet = NXDinitfromfile(pDict, &pNew->pDict); + if (iRet != NX_OK) { + DeleteNexTrics(pNew); + return NULL; + } + if (strstr(pDict, "5") != NULL) { + pNew->iHDF5 = 1; + } + pNew->pFileRoot = strdup(pRoot); + pNew->pDanu = pNum; + + /* find things in interpreter */ + pCom = FindCommand(pSics, HM1); + if (pCom) { + pNew->pHistogram1 = (pHistMem) pCom->pData; + } else { + pNew->pHistogram1 = NULL; + } + + pCom = FindCommand(pSics, HM2); + if (pCom) { + pNew->pHistogram2 = (pHistMem) pCom->pData; + } else { + pNew->pHistogram2 = NULL; + } + pCom = FindCommand(pSics, HM3); + if (pCom) { + pNew->pHistogram3 = (pHistMem) pCom->pData; + } else { + pNew->pHistogram3 = NULL; + } + pCom = FindCommand(pSics, HKLNAME); + if (pCom) { + pNew->pCrystal = (pHKL) pCom->pData; + } else { + pNew->pCrystal = NULL; + } + pCom = FindCommand(pSics, "counter"); + if (pCom) { + pNew->pCount = (pCounter) pCom->pData; + } else { + pNew->pCrystal = NULL; + } + pNew->iFirst = 1; + pNew->iFrameNum = 0; + + pVar = FindVariable(pSics, HM1OFF); + if (pVar) { + pNew->hm1off = pVar->fVal; + } else { + pNew->hm1off = 0; + } + pVar = FindVariable(pSics, HM2OFF); + if (pVar) { + pNew->hm2Off = pVar->fVal; + } else { + pNew->hm2Off = +45.; + } + pVar = FindVariable(pSics, HM3OFF); + if (pVar) { + pNew->hm3Off = pVar->fVal; + } else { + pNew->hm3Off = 90.; + } + + + return pNew; +} - pCom = FindCommand(pSics,HM2); - if(pCom) - { - pNew->pHistogram2 = (pHistMem)pCom->pData; - } - else - { - pNew->pHistogram2 = NULL; - } - pCom = FindCommand(pSics,HM3); - if(pCom) - { - pNew->pHistogram3 = (pHistMem)pCom->pData; - } - else - { - pNew->pHistogram3 = NULL; - } - pCom = FindCommand(pSics,HKLNAME); - if(pCom) - { - pNew->pCrystal = (pHKL)pCom->pData; - } - else - { - pNew->pCrystal = NULL; - } - pCom = FindCommand(pSics,"counter"); - if(pCom) - { - pNew->pCount = (pCounter)pCom->pData; - } - else - { - pNew->pCrystal = NULL; - } - pNew->iFirst = 1; - pNew->iFrameNum = 0; - - pVar = FindVariable(pSics,HM1OFF); - if(pVar) - { - pNew->hm1off = pVar->fVal; - } - else - { - pNew->hm1off = 0; - } - pVar = FindVariable(pSics,HM2OFF); - if(pVar) - { - pNew->hm2Off = pVar->fVal; - } - else - { - pNew->hm2Off = +45.; - } - pVar = FindVariable(pSics,HM3OFF); - if(pVar) - { - pNew->hm3Off = pVar->fVal; - } - else - { - pNew->hm3Off = 90.; - } - - - return pNew; - } /*-------------------------------------------------------------------------*/ - void DeleteNexTrics(void *pData) - { - pNexTrics self = NULL; - - self = (pNexTrics)pData; - if(!self) - return; - - if(self->pDes) - DeleteDescriptor(self->pDes); - - if(self->pCurrentFile) - free(self->pCurrentFile); - - if(self->pFileRoot) - free(self->pFileRoot); - - if(self->pDict) - NXDclose(self->pDict,NULL); +void DeleteNexTrics(void *pData) +{ + pNexTrics self = NULL; + + self = (pNexTrics) pData; + if (!self) + return; + + if (self->pDes) + DeleteDescriptor(self->pDes); + + if (self->pCurrentFile) + free(self->pCurrentFile); + + if (self->pFileRoot) + free(self->pFileRoot); + + if (self->pDict) + NXDclose(self->pDict, NULL); + + if (self->pCall) + DeleteCallBackInterface(self->pCall); + + free(self); +} - if(self->pCall) - DeleteCallBackInterface(self->pCall); - - free(self); - } /*---------------------- a neXus error handler ---------------------------*/ - static void SNError(void *pData, char *text) - { - SConnection *pCon; - - assert(pData); - pCon = (SConnection *)pData; - SCWrite(pCon,text,eError); - } +static void SNError(void *pData, char *text) +{ + SConnection *pCon; + + assert(pData); + pCon = (SConnection *) pData; + SCWrite(pCon, text, eError); +} + /*--------------------------------------------------------------------------*/ - int NexTricsFactory(SConnection *pCon, SicsInterp *pSics, void *pData, - int argc, char *argv[]) - { - pNexTrics pNew = NULL; - pDataNumber pDanu = NULL; - CommandList *pCom; - char pBueffel[512]; - int iRet; - pDummy pDum; - - if(argc < 4) - { - SCWrite(pCon, - "ERROR: Insufficient number of arguments to NexTricsFactory",eError); - return 0; - } - - /* first item must be the name of a datanumber variable */ - pCom = FindCommand(pSics,argv[1]); - if(pCom) - { - pDanu = (pDataNumber)pCom->pData; - } - if( (!pCom) || (!pDanu)) - { - SCWrite(pCon,"ERROR: DataNumber object NOT found",eError); - return 0; - } - pDum = (pDummy)pDanu; - if(strcmp(pDum->pDescriptor->name,"DataNumber") != 0) - { - sprintf(pBueffel,"ERROR: %s is no DataNumber object",argv[1]); - SCWrite(pCon,pBueffel,eError); - return 0; - } - - /* install an error handler */ - NXMSetError((void *)pCon,SNError); - - pNew = CreateNexTrics(pDanu,argv[2],argv[3],pSics); - if(!pNew) - { - SCWrite(pCon,"ERROR: cannot create nexTrics, invalid dictionary file",eError); - SCWrite(pCon,"ERROR: or system objects missing.",eError); - return 0; - } - - /* create the command */ - iRet = AddCommand(pSics,"nxtrics",NexTricsAction,DeleteNexTrics, - pNew); - if(!iRet) - { - SCWrite(pCon,"ERROR: duplicate command nxtrics not created",eError); - } - return iRet; +int NexTricsFactory(SConnection * pCon, SicsInterp * pSics, void *pData, + int argc, char *argv[]) +{ + pNexTrics pNew = NULL; + pDataNumber pDanu = NULL; + CommandList *pCom; + char pBueffel[512]; + int iRet; + pDummy pDum; + + if (argc < 4) { + SCWrite(pCon, + "ERROR: Insufficient number of arguments to NexTricsFactory", + eError); + return 0; } -/*-------------------------------------------------------------------------*/ - static int DumpData(pNexTrics self, SConnection *pCon, NXhandle hfil, - int iFrameNum) - { - int iRet; - char pBueffel[512]; - CounterMode eMode; - HistInt lData[DET1X*DET1Y], i, lVal; - int iVal,lBeam; - float fVal, fTTheta, fTime = 0.; - pMotor pMot; - /* write motors */ - SNXSPutMotor(pServ->pSics,pCon,hfil,self->pDict, - "framechi","CHI"); - SNXSPutMotor(pServ->pSics,pCon,hfil,self->pDict, - "framephi","PHI"); - SNXSPutMotor(pServ->pSics,pCon,hfil,self->pDict, - "frameomega","OM"); - /* - read two theta - */ - pMot = FindMotor(pServ->pSics,"stt"); - if(!pMot) - { - sprintf(pBueffel,"WARNING: cannot find motor stt"); - SCWrite(pCon,pBueffel,eWarning); - return 0; - } - - /* get the position */ - iRet = MotorGetSoftPosition(pMot,pCon,&fTTheta); - - - /* write frame time */ - SNXFormatTime(pBueffel,512); - iRet = NXDputalias(hfil,self->pDict,"etime",pBueffel); - if(iRet != NX_OK) - { - SCWrite(pCon,"ERROR: cannot write frame time",eError); - } - - /* write counting parameters */ - if(self->pHistogram1 != NULL) - { - eMode = GetHistCountMode(self->pHistogram1); - fVal = GetHistPreset(self->pHistogram1); - lVal = GetHistMonitor(self->pHistogram1,1,pCon); - lBeam = GetHistMonitor(self->pHistogram1,4,pCon); - } - if(self->pHistogram2 != NULL) - { - eMode = GetHistCountMode(self->pHistogram2); - fVal = GetHistPreset(self->pHistogram2); - lVal = GetHistMonitor(self->pHistogram2,1,pCon); - lBeam = GetHistMonitor(self->pHistogram2,4,pCon); - } - if(self->pHistogram3 != NULL) - { - eMode = GetHistCountMode(self->pHistogram3); - fVal = GetHistPreset(self->pHistogram3); - lVal = GetHistMonitor(self->pHistogram3,1,pCon); - lBeam = GetHistMonitor(self->pHistogram3,4,pCon); - } - if(self->pCount != NULL) - { - eMode = GetCounterMode(self->pCount); - fVal = GetCounterPreset(self->pCount); - lVal = GetMonitor(self->pCount,1,pCon); - fTime = GetCountTime(self->pCount,pCon); - lBeam = GetMonitor(self->pCount,4,pCon); - } - if(eMode == eTimer) - { - strcpy(pBueffel,"Timer"); - } - else - { - strcpy(pBueffel,"Monitor"); - } - NXDputalias(hfil,self->pDict,"framemode",pBueffel); - NXDputalias(hfil,self->pDict,"framepreset",&fVal); - iVal = (int)lVal; - NXDputalias(hfil,self->pDict,"framemonitor",&iVal); - iVal = (int)lBeam; - NXDputalias(hfil,self->pDict,"sinqmonitor",&iVal); - NXDputalias(hfil,self->pDict,"cctime",&fTime); - - /* write detector1 histogram */ - if(self->pHistogram1 != NULL) - { - strcpy(pBueffel,"detector1"); - NXDupdate(self->pDict,"dnumber",pBueffel); - SNXSPutMotor(pServ->pSics,pCon,hfil,self->pDict, - "frametilt","DG1"); - GetHistogram(self->pHistogram1,pCon,0,0,DET1X*DET1Y,lData, - DET1X*DET1Y*sizeof(HistInt)); - NXDputalias(hfil,self->pDict,"framecounts",lData); - - /* - NXDopenalias(hfil,self->pDict,"framecounts"); - NXputdata(hfil,lData); - NXsetdimname(hfil,0,"frame_x"); - NXsetdimname(hfil,1,"frame_y"); - NXclosedata(hfil); - */ - - fVal = fTTheta + self->hm1off; - NXDputalias(hfil,self->pDict,"frame2theta",&fVal); - - /* the NXdata links */ - NXDaliaslink(hfil,self->pDict,"frame","detectorx"); - NXDaliaslink(hfil,self->pDict,"frame","detectory"); - NXDaliaslink(hfil,self->pDict,"frame","framecounts"); - } - /* - do detector 2 histogram - */ - if(self->pHistogram2 != NULL) - { - strcpy(pBueffel,"detector2"); - NXDupdate(self->pDict,"dnumber",pBueffel); - SNXSPutMotor(pServ->pSics,pCon,hfil,self->pDict, - "frametilt","DG2"); - GetHistogram(self->pHistogram2,pCon,0,0,DET2X*DET2Y,lData, - DET2X*DET2Y*sizeof(HistInt)); - NXDputalias(hfil,self->pDict,"framecounts",lData); - - /* code for reducing object number in HDF-4 - NXDopenalias(hfil,self->pDict,"framecounts"); - NXputdata(hfil,lData); - NXsetdimname(hfil,0,"frame_x"); - NXsetdimname(hfil,1,"frame_y"); - NXclosedata(hfil); - */ - - fVal = fTTheta + self->hm2Off; - NXDputalias(hfil,self->pDict,"frame2theta",&fVal); - - /* the NXdata links */ - NXDaliaslink(hfil,self->pDict,"frame","detectorx"); - NXDaliaslink(hfil,self->pDict,"frame","detectory"); - NXDaliaslink(hfil,self->pDict,"frame","framecounts"); - } - /* - do detector 3 histogram - */ - if(self->pHistogram3 != NULL) - { - strcpy(pBueffel,"detector3"); - NXDupdate(self->pDict,"dnumber",pBueffel); - SNXSPutMotor(pServ->pSics,pCon,hfil,self->pDict, - "frametilt","DG3"); - GetHistogram(self->pHistogram3,pCon,0,0,DET3X*DET3Y,lData, - DET3X*DET3Y*sizeof(HistInt)); - - NXDputalias(hfil,self->pDict,"framecounts",lData); - - /* code for reducing object numbers in HDF-4 - NXDopenalias(hfil,self->pDict,"framecounts"); - NXputdata(hfil,lData); - NXsetdimname(hfil,0,"frame_x"); - NXsetdimname(hfil,1,"frame_y"); - NXclosedata(hfil); - */ - - - fVal = fTTheta + self->hm3Off; - NXDputalias(hfil,self->pDict,"frame2theta",&fVal); - - /* the NXdata links */ - NXDaliaslink(hfil,self->pDict,"frame","detectorx"); - NXDaliaslink(hfil,self->pDict,"frame","detectory"); - NXDaliaslink(hfil,self->pDict,"frame","framecounts"); - } - - - /* temperature */ - SNXSPutEVVar(hfil,self->pDict,"temperature", - pCon, - "frametemp", - "framestdev"); - - /* close and done */ - sprintf(pBueffel,"Frame %d succesfully written",iFrameNum-1); - SCWrite(pCon,pBueffel,eLog); - - return 1; - } -/*--------------------------------------------------------------------------*/ - static int WriteFirstFrame(pNexTrics self, SConnection *pCon) - { - char pBueffel[1024]; - NXhandle hfil; - int iRet, iYear, i; - pSicsVariable pVar; - char *pText; - CommandList *pCom = NULL; - pHKL pCryst = NULL; - float fVal, fPix[DETAMAX]; - float fHKL[3], fUB[9]; - - iRet = NXopen(self->pCurrentFile,NXACC_RDWR,&hfil); - if(iRet != NX_OK) - { - sprintf(pBueffel,"ERROR: cannot open %s",self->pCurrentFile); - SCWrite(pCon,pBueffel,eError); - return 0; - } - - /* make sure: first frame */ - NXDupdate(self->pDict,"framename","frame0000"); - self->iFrameNum = 0; - - /* title */ - pVar = NULL; - pVar = FindVariable(pServ->pSics,"title"); - if(pVar) - { - pText = pVar->text; - } - else - { - SCWrite(pCon,"ERROR: Variable title not found ",eError); - pText = pBueffel; - } - iRet = NXDputalias(hfil,self->pDict,"etitle",pText); - if(iRet != NX_OK) - { - SCWrite(pCon,"ERROR: failed to write title",eError); - } - - /* start time */ - SNXFormatTime(pBueffel,1023); - iRet = NXDputalias(hfil,self->pDict,"etime",pBueffel); - if(iRet != NX_OK) - { - SCWrite(pCon,"ERROR: failed to write start time",eError); - } - - /* source info */ - strcpy(pBueffel,"SINQ at Paul Scherrer Institut, Villigen"); - iRet = NXDputalias(hfil,self->pDict,"sname",pBueffel); - if(iRet != NX_OK) - { - SCWrite(pCon,"ERROR: failed to write source name",eError); - } - strcpy(pBueffel,"Spallation Neutron Source"); - iRet = NXDputalias(hfil,self->pDict,"stype",pBueffel); - if(iRet != NX_OK) - { - SCWrite(pCon,"ERROR: failed to write source type",eError); - } - - /* instrument name */ - strcpy(pBueffel,"TRICS at SINQ, Paul Scherrer Institut, Switzerland"); - iRet = NXDputalias(hfil,self->pDict,"iname0",pBueffel); - if(iRet != NX_OK) - { - SCWrite(pCon,"ERROR: failed to write instrument name",eError); - } - - /* Collimator */ - SNXSPutMotor(pServ->pSics,pCon,hfil,self->pDict, - "cex1","cex1"); - SNXSPutMotor(pServ->pSics,pCon,hfil,self->pDict, - "cex2","cex2"); - - - /* Monochromator */ - pVar = NULL; - strcpy(pBueffel,"UNKNOWN"); - pVar = FindVariable(pServ->pSics,"monodescription"); - if(pVar) - { - pText = pVar->text; - } - else - { - SCWrite(pCon,"ERROR: Variable monodescription not found ",eError); - pText = pBueffel; - } - iRet = NXDputalias(hfil,self->pDict,"monodes",pText); - if(iRet != NX_OK) - { - SCWrite(pCon,"ERROR: failed to write monodescription",eError); - } - - /* lambda */ - if(self->pCrystal != NULL) - { - GetLambda(self->pCrystal,&fVal); - iRet = NXDputalias(hfil,self->pDict,"monolambda",&fVal); - if(iRet != NX_OK) - { - SCWrite(pCon,"ERROR: failed to write lambda",eError); - } - } - - /* two theta */ - pVar = NULL; - strcpy(pBueffel,"UNKNOWN"); - pVar = FindVariable(pServ->pSics,"mono2theta"); - if(pVar) - { - fVal = pVar->fVal; - } - else - { - SCWrite(pCon,"ERROR: Variable mono2theta not found ",eError); - fVal = -2188.99; - } - iRet = NXDputalias(hfil,self->pDict,"mono2theta",&fVal); - if(iRet != NX_OK) - { - SCWrite(pCon,"ERROR: failed to write monochromator 2 Theta",eError); - } - /* theta, needs work when lift operational */ - SNXSPutMotor(pServ->pSics,pCon,hfil,self->pDict, - "monotheta","MUCA"); - - - /* detector data - first set detector variables in dictionary - This is the first detector. - */ - if(self->pHistogram1 != NULL) - { - strcpy(pBueffel,"detector1"); - NXDupdate(self->pDict,"dnumber",pBueffel); - sprintf(pBueffel,"%d",DET1X); - NXDupdate(self->pDict,"framedim1",pBueffel); - sprintf(pBueffel,"%d",DET1Y); - NXDupdate(self->pDict,"framedim2",pBueffel); - strcpy(pBueffel,DET1DESC); - iRet = NXDputalias(hfil,self->pDict,"ddescription",pBueffel); - if(iRet != NX_OK) - { - SCWrite(pCon,"ERROR: failed to write detector1 description",eError); - } - for(i = 0; i < DET1X; i++) - { - fPix[i] = i * DET1XS; - } - iRet = NXDputalias(hfil,self->pDict,"detectorx",fPix); - if(iRet != NX_OK) - { - SCWrite(pCon,"ERROR: failed to write detector1 x-axis description",eError); - } - for(i = 0; i < DET1Y; i++) - { - fPix[i] = i * DET1YS; - } - iRet = NXDputalias(hfil,self->pDict,"detectory",fPix); - if(iRet != NX_OK) - { - SCWrite(pCon,"ERROR: failed to write detector1 y-axis description",eError); - } - pVar = NULL; - pVar = FindVariable(pServ->pSics,"det1zerox"); - if(pVar) - { - fVal = pVar->fVal; - } - else - { - SCWrite(pCon,"ERROR: Variable detector x zero point not found ",eError); - fVal = -2188.99; - } - iRet = NXDputalias(hfil,self->pDict,"detzerox",&fVal); - if(iRet != NX_OK) - { - SCWrite(pCon,"ERROR: failed to write detecor x zero point",eError); - } - pVar = NULL; - pVar = FindVariable(pServ->pSics,"det1zeroy"); - if(pVar) - { - fVal = pVar->fVal; - } - else - { - SCWrite(pCon,"ERROR: Variable detector y zero point not found ",eError); - fVal = -2188.99; - } - iRet = NXDputalias(hfil,self->pDict,"detzeroy",&fVal); - if(iRet != NX_OK) - { - SCWrite(pCon,"ERROR: failed to write detecor y zero point",eError); - } - pVar = NULL; - pVar = FindVariable(pServ->pSics,"detdist1"); - if(pVar) - { - fVal = pVar->fVal; - } - else - { - SCWrite(pCon,"ERROR: Variable detector distance not found ",eError); - fVal = -2188.99; - } - iRet = NXDputalias(hfil,self->pDict,"detdist",&fVal); - if(iRet != NX_OK) - { - SCWrite(pCon,"ERROR: failed to write detecor y zero point",eError); - } - iRet = 1; - iRet = NXDputalias(hfil,self->pDict,"detvalid",&iRet); - if(iRet != NX_OK) - { - SCWrite(pCon,"ERROR: failed to write frame validity",eError); - } - } - /* - second frame, but only if present - */ - if(self->pHistogram2 != NULL) - { - strcpy(pBueffel,"detector2"); - NXDupdate(self->pDict,"dnumber",pBueffel); - sprintf(pBueffel,"%d",DET2X); - NXDupdate(self->pDict,"framedim1",pBueffel); - sprintf(pBueffel,"%d",DET2Y); - NXDupdate(self->pDict,"framedim2",pBueffel); - strcpy(pBueffel,DET2DESC); - iRet = NXDputalias(hfil,self->pDict,"ddescription",pBueffel); - if(iRet != NX_OK) - { - SCWrite(pCon,"ERROR: failed to write detector2 description",eError); - } - for(i = 0; i < DET2X; i++) - { - fPix[i] = i * DET2XS; - } - iRet = NXDputalias(hfil,self->pDict,"detectorx",fPix); - if(iRet != NX_OK) - { - SCWrite(pCon,"ERROR: failed to write detector2 x-axis description", - eError); - } - for(i = 0; i < DET2Y; i++) - { - fPix[i] = i * DET2YS; - } - iRet = NXDputalias(hfil,self->pDict,"detectory",fPix); - if(iRet != NX_OK) - { - SCWrite(pCon,"ERROR: failed to write detector1 y-axis description", - eError); - } - pVar = NULL; - pVar = FindVariable(pServ->pSics,"det2zerox"); - if(pVar) - { - fVal = pVar->fVal; - } - else - { - SCWrite(pCon,"ERROR: Variable detector x zero point not found ", - eError); - fVal = -2188.99; - } - iRet = NXDputalias(hfil,self->pDict,"detzerox",&fVal); - if(iRet != NX_OK) - { - SCWrite(pCon,"ERROR: failed to write detecor x zero point", - eError); - } - pVar = NULL; - pVar = FindVariable(pServ->pSics,"det2zeroy"); - if(pVar) - { - fVal = pVar->fVal; - } - else - { - SCWrite(pCon,"ERROR: Variable detector2 y zero point not found ", - eError); - fVal = -2188.99; - } - iRet = NXDputalias(hfil,self->pDict,"detzeroy",&fVal); - if(iRet != NX_OK) - { - SCWrite(pCon,"ERROR: failed to write detecor y zero point", - eError); - } - pVar = NULL; - pVar = FindVariable(pServ->pSics,"detdist2"); - if(pVar) - { - fVal = pVar->fVal; - } - else - { - SCWrite(pCon,"ERROR: Variable detector distance not found ", - eError); - fVal = -2188.99; - } - iRet = NXDputalias(hfil,self->pDict,"detdist",&fVal); - if(iRet != NX_OK) - { - SCWrite(pCon,"ERROR: failed to write detecor2 y distance", - eError); - } - iRet = 1; - iRet = NXDputalias(hfil,self->pDict,"detvalid",&iRet); - if(iRet != NX_OK) - { - SCWrite(pCon,"ERROR: failed to write frame validity",eError); - } - } - /* - third detector, but only if present - */ - if(self->pHistogram3 != NULL) - { - strcpy(pBueffel,"detector3"); - NXDupdate(self->pDict,"dnumber",pBueffel); - sprintf(pBueffel,"%d",DET3X); - NXDupdate(self->pDict,"framedim1",pBueffel); - sprintf(pBueffel,"%d",DET3Y); - NXDupdate(self->pDict,"framedim2",pBueffel); - strcpy(pBueffel,DET3DESC); - iRet = NXDputalias(hfil,self->pDict,"ddescription",pBueffel); - if(iRet != NX_OK) - { - SCWrite(pCon,"ERROR: failed to write detector3 description",eError); - } - for(i = 0; i < DET3X; i++) - { - fPix[i] = i * DET3XS; - } - iRet = NXDputalias(hfil,self->pDict,"detectorx",fPix); - if(iRet != NX_OK) - { - SCWrite(pCon,"ERROR: failed to write detector2 x-axis description", - eError); - } - for(i = 0; i < DET3Y; i++) - { - fPix[i] = i * DET3YS; - } - iRet = NXDputalias(hfil,self->pDict,"detectory",fPix); - if(iRet != NX_OK) - { - SCWrite(pCon,"ERROR: failed to write detector1 y-axis description", - eError); - } - pVar = NULL; - pVar = FindVariable(pServ->pSics,"det3zerox"); - if(pVar) - { - fVal = pVar->fVal; - } - else - { - SCWrite(pCon,"ERROR: Variable detector 3 x zero point not found ", - eError); - fVal = -2188.99; - } - iRet = NXDputalias(hfil,self->pDict,"detzerox",&fVal); - if(iRet != NX_OK) - { - SCWrite(pCon,"ERROR: failed to write detecor x zero point", - eError); - } - pVar = NULL; - pVar = FindVariable(pServ->pSics,"det3zeroy"); - if(pVar) - { - fVal = pVar->fVal; - } - else - { - SCWrite(pCon,"ERROR: Variable detector 3 y zero point not found ", - eError); - fVal = -2188.99; - } - iRet = NXDputalias(hfil,self->pDict,"detzeroy",&fVal); - if(iRet != NX_OK) - { - SCWrite(pCon,"ERROR: failed to write detecor y zero point", - eError); - } - pVar = NULL; - pVar = FindVariable(pServ->pSics,"detdist3"); - if(pVar) - { - fVal = pVar->fVal; - } - else - { - SCWrite(pCon,"ERROR: Variable detector 3 distance not found ", - eError); - fVal = -2188.99; - } - iRet = NXDputalias(hfil,self->pDict,"detdist",&fVal); - if(iRet != NX_OK) - { - SCWrite(pCon,"ERROR: failed to write detecor 3 y distance", - eError); - } - iRet = 1; - iRet = NXDputalias(hfil,self->pDict,"detvalid",&iRet); - if(iRet != NX_OK) - { - SCWrite(pCon,"ERROR: failed to write frame validity",eError); - } - } - - /* do sample information */ - strcpy(pBueffel,"UNKNOWN"); - pVar = FindVariable(pServ->pSics,"sample"); - if(pVar) - { - pText = pVar->text; - } - else - { - SCWrite(pCon,"ERROR: Variable sample not found ",eError); - pText = pBueffel; - } - iRet = NXDputalias(hfil,self->pDict,"samplename",pText); - if(iRet != NX_OK) - { - SCWrite(pCon,"ERROR: failed to write sample name",eError); - } - if(self->pCrystal != NULL) - { - GetUB(self->pCrystal,fUB); - iRet = NXDputalias(hfil,self->pDict,"sampleub",fUB); - if(iRet != NX_OK) - { - SCWrite(pCon,"ERROR: failed to write sample UB",eError); - } - GetCurrentHKL(self->pCrystal,fHKL); - iRet = NXDputalias(hfil,self->pDict,"samplehkl",fHKL); - if(iRet != NX_OK) - { - SCWrite(pCon,"ERROR: failed to write HKL",eError); - } - } - - /* put the frame number */ - iRet = 0; - iRet = NXDputalias(hfil,self->pDict,"fnum",&iRet); - if(iRet != NX_OK) - { - SCWrite(pCon,"ERROR: failed to write initial frame number",eError); - } - - /* write actual data */ - iRet = DumpData(self,pCon,hfil,1); - - /* put the frame number */ - iRet = 1; - iRet = NXDputalias(hfil,self->pDict,"fnum",&iRet); - if(iRet != NX_OK) - { - SCWrite(pCon,"ERROR: failed to write initial frame number",eError); - } - self->iFrameNum = 1; - InvokeCallBack(self->pCall, NEWFRAME,&(self->iFrameNum)); - - self->iFirst = 0; - - /* close the file and go */ - NXclose(&hfil); - SendQuieck(QUIECK,self->pCurrentFile); - return iRet; - } -/*-------------------------------------------------------------------------*/ - static int ContinueFile(pNexTrics self, SConnection *pCon) - { - int iFrameNum, iRet; - char pBueffel[1024]; - float fVal; - NXhandle hfil; - - assert(self); - assert(pCon); - assert(self->iFirst == 0); - - /* let's start by opening the file*/ - iRet = NXopen(self->pCurrentFile,NXACC_RDWR,&hfil); - if(iRet != NX_OK) - { - sprintf(pBueffel,"ERROR: cannot reopen %s, NO data written", - self->pCurrentFile); - SCWrite(pCon,pBueffel,eError); - return 0; - } - - /* read the frame number, set the framename for further reading, - increment and write back again - */ - iRet = NXDgetalias(hfil,self->pDict,"fnum",&iFrameNum); - if(iRet != NX_OK) - { - SCWrite(pCon,"EERROR: cannot read old framenumber, NO data written",eError); - return 0; - } - sprintf(pBueffel,"frame%4.4d", iFrameNum); - NXDupdate(self->pDict,"framename",pBueffel); - iFrameNum++; - self->iFrameNum++; - InvokeCallBack(self->pCall, NEWFRAME,&(self->iFrameNum)); - iRet = NXDputalias(hfil,self->pDict,"fnum",&iFrameNum); - if(iRet != NX_OK) - { - SCWrite(pCon,"ERROR: cannot write new framenumber, NO data written",eError); - return 0; - } - - /* put in links to duplicates: entry */ - iRet = NXDaliaslink(hfil,self->pDict,"entry","etitle0"); - if(iRet != NX_OK) - { - SCWrite(pCon,"WARNING: cannot link against title",eWarning); - } - - /* links to instrument */ - iRet = NXDaliaslink(hfil,self->pDict,"inst0","iname0"); - if(iRet != NX_OK) - { - SCWrite(pCon,"WARNING: cannot link against instrument name",eWarning); - } - iRet = NXDaliaslink(hfil,self->pDict,"inst0","source0"); - if(iRet != NX_OK) - { - SCWrite(pCon,"WARNING: cannot link against source group",eWarning); - } - iRet = NXDaliaslink(hfil,self->pDict,"inst0","mono0"); - if(iRet != NX_OK) - { - SCWrite(pCon,"WARNING: cannot link against monochromator group", - eWarning); - } - iRet = NXDaliaslink(hfil,self->pDict,"inst0","coll0"); - if(iRet != NX_OK) - { - SCWrite(pCon,"WARNING: cannot link against collimator group", - eWarning); - } - - - - /* - links in detector group - detector 1 - */ - if(self->pHistogram1 != NULL) - { - strcpy(pBueffel,"detector1"); - NXDupdate(self->pDict,"dnumber",pBueffel); - iRet = NXDaliaslink(hfil,self->pDict,"det1","ddescription"); - if(iRet != NX_OK) - { - SCWrite(pCon,"WARNING: cannot link against detector description",eWarning); - } - iRet = NXDaliaslink(hfil,self->pDict,"det1","detectorx"); - if(iRet != NX_OK) - { - SCWrite(pCon,"WARNING: cannot link against detector x-axis",eWarning); - } - iRet = NXDaliaslink(hfil,self->pDict,"det1","detectory"); - if(iRet != NX_OK) - { - SCWrite(pCon,"WARNING: cannot link against detector y-axis",eWarning); - } - iRet = NXDaliaslink(hfil,self->pDict,"det1","detzerox"); - if(iRet != NX_OK) - { - SCWrite(pCon,"WARNING: cannot link against detector x zero ",eWarning); - } - iRet = NXDaliaslink(hfil,self->pDict,"det1","detzeroy"); - if(iRet != NX_OK) - { - SCWrite(pCon,"WARNING: cannot link against detector y zero",eWarning); - } - iRet = NXDaliaslink(hfil,self->pDict,"det1","detdist"); - if(iRet != NX_OK) - { - SCWrite(pCon,"WARNING: cannot link against detector distance", - eWarning); - } - iRet = 1; - iRet = NXDputalias(hfil,self->pDict,"detvalid",&iRet); - if(iRet != NX_OK) - { - SCWrite(pCon,"ERROR: failed to write frame validity",eError); - } - } - /* - links in detector group, detector 2 - */ - if(self->pHistogram2) - { - strcpy(pBueffel,"detector2"); - NXDupdate(self->pDict,"dnumber",pBueffel); - iRet = NXDaliaslink(hfil,self->pDict,"det1","ddescription"); - if(iRet != NX_OK) - { - SCWrite(pCon,"WARNING: cannot link against detector description", - eWarning); - } - iRet = NXDaliaslink(hfil,self->pDict,"det1","detectorx"); - if(iRet != NX_OK) - { - SCWrite(pCon,"WARNING: cannot link against detector x-axis", - eWarning); - } - iRet = NXDaliaslink(hfil,self->pDict,"det1","detectory"); - if(iRet != NX_OK) - { - SCWrite(pCon,"WARNING: cannot link against detector y-axis", - eWarning); - } - iRet = NXDaliaslink(hfil,self->pDict,"det1","detzerox"); - if(iRet != NX_OK) - { - SCWrite(pCon,"WARNING: cannot link against detector x zero ", - eWarning); - } - iRet = NXDaliaslink(hfil,self->pDict,"det1","detzeroy"); - if(iRet != NX_OK) - { - SCWrite(pCon,"WARNING: cannot link against detector y zero", - eWarning); - } - iRet = NXDaliaslink(hfil,self->pDict,"det1","detdist"); - if(iRet != NX_OK) - { - SCWrite(pCon,"WARNING: cannot link against detector distance", - eWarning); - } - iRet = 1; - iRet = NXDputalias(hfil,self->pDict,"detvalid",&iRet); - if(iRet != NX_OK) - { - SCWrite(pCon,"ERROR: failed to write frame validity",eError); - } - } - - /* - links in detector group, detector 3 - */ - if(self->pHistogram3) - { - strcpy(pBueffel,"detector3"); - NXDupdate(self->pDict,"dnumber",pBueffel); - iRet = NXDaliaslink(hfil,self->pDict,"det1","ddescription"); - if(iRet != NX_OK) - { - SCWrite(pCon,"WARNING: cannot link against detector description", - eWarning); - } - iRet = NXDaliaslink(hfil,self->pDict,"det1","detectorx"); - if(iRet != NX_OK) - { - SCWrite(pCon,"WARNING: cannot link against detector x-axis", - eWarning); - } - iRet = NXDaliaslink(hfil,self->pDict,"det1","detectory"); - if(iRet != NX_OK) - { - SCWrite(pCon,"WARNING: cannot link against detector y-axis", - eWarning); - } - iRet = NXDaliaslink(hfil,self->pDict,"det1","detzerox"); - if(iRet != NX_OK) - { - SCWrite(pCon,"WARNING: cannot link against detector x zero ", - eWarning); - } - iRet = NXDaliaslink(hfil,self->pDict,"det1","detzeroy"); - if(iRet != NX_OK) - { - SCWrite(pCon,"WARNING: cannot link against detector y zero", - eWarning); - } - iRet = NXDaliaslink(hfil,self->pDict,"det1","detdist"); - if(iRet != NX_OK) - { - SCWrite(pCon,"WARNING: cannot link against detector distance", - eWarning); - } - iRet = 1; - iRet = NXDputalias(hfil,self->pDict,"detvalid",&iRet); - if(iRet != NX_OK) - { - SCWrite(pCon,"ERROR: failed to write frame validity",eError); - } - } - - - /* links in sample group */ - iRet = NXDaliaslink(hfil,self->pDict,"samplev","samplename"); - if(iRet != NX_OK) - { - SCWrite(pCon,"WARNING: cannot link against sample name",eWarning); - } - if(self->pCrystal != NULL) - { - iRet = NXDaliaslink(hfil,self->pDict,"samplev","sampleub"); - if(iRet != NX_OK) - { - SCWrite(pCon,"WARNING: cannot link against sample UB",eWarning); - } - iRet = NXDaliaslink(hfil,self->pDict,"samplev","samplehkl"); - if(iRet != NX_OK) - { - SCWrite(pCon,"WARNING: cannot link against sample HKL",eWarning); - } - } - - /* write actual data */ - iRet = DumpData(self,pCon,hfil,iFrameNum); - - /* close the file and go */ - NXclose(&hfil); - SendQuieck(QUIECK,self->pCurrentFile); - return iRet; - + /* first item must be the name of a datanumber variable */ + pCom = FindCommand(pSics, argv[1]); + if (pCom) { + pDanu = (pDataNumber) pCom->pData; } -/*--------------------------------------------------------------------------*/ - int StartFile(pNexTrics self, SConnection *pCon) - { - char pBueffel[1024]; - NXhandle hfil; - int iRet, iYear, i; - pSicsVariable pVar; - char *pText; - CommandList *pCom = NULL; - pHKL pCryst = NULL; - float fVal, fPix[DETAMAX]; - - /* make a filename and open it */ - if(self->pCurrentFile) - free(self->pCurrentFile); - - pText = makeFilename(pServ->pSics,pCon); - changeExtension(pText,"hdf"); - if(pText == NULL) - { - return 0; - } - self->pCurrentFile = strdup(pText); - if(self->iHDF5) - { - iRet = NXopen(self->pCurrentFile,NXACC_CREATE5,&hfil); - } - else - { - iRet = NXopen(self->pCurrentFile,NXACC_CREATE,&hfil); - } - if(iRet != NX_OK) - { - sprintf(pBueffel,"ERROR: cannot open %s",self->pCurrentFile); - SCWrite(pCon,pBueffel,eError); - return 0; - } - - /* tell user what we are doing */ - sprintf(pBueffel,"Initialising file %s ......", self->pCurrentFile); - SCWrite(pCon,pBueffel,eWarning); - - - /* Write header data */ - SNXSPutGlobals(hfil,self->pCurrentFile, - "TRICS at SinQ, Paul Scherrer Institut, Switzerland", - pCon); - - self->iFirst = 1; - self->iFrameNum = 0; - InvokeCallBack(self->pCall, NEWFRAME,&(self->iFrameNum)); - - /* close the file and go */ - NXclose(&hfil); - return 1; - } -/*-------------------------------------------------------------------------*/ - int ReopenFile(pNexTrics self, char *filename) - { - char pBueffel[1024]; - NXhandle hfil; - int iRet, iFrameNum; - - assert(self); - - /* concat with data root and check for existence */ - sprintf(pBueffel,"%s/%s",self->pFileRoot,filename); - iRet = NXopen(pBueffel,NXACC_RDWR,&hfil); - if(iRet != NX_OK) - { - return 0; - } - else - { - if(self->pCurrentFile) - free(self->pCurrentFile); - self->pCurrentFile = strdup(pBueffel); - } - - /* check the framenumber, if already data written */ - iRet = NXDgetalias(hfil,self->pDict,"fnum",&iFrameNum); - if(iRet != NX_OK) - { - self->iFirst = 1; - } - else - { - self->iFirst = 0; - } - self->iFrameNum = iFrameNum; - InvokeCallBack(self->pCall, NEWFRAME,&(self->iFrameNum)); - return 1; + if ((!pCom) || (!pDanu)) { + SCWrite(pCon, "ERROR: DataNumber object NOT found", eError); + return 0; + } + pDum = (pDummy) pDanu; + if (strcmp(pDum->pDescriptor->name, "DataNumber") != 0) { + sprintf(pBueffel, "ERROR: %s is no DataNumber object", argv[1]); + SCWrite(pCon, pBueffel, eError); + return 0; } -/*--------------------------------------------------------------------------*/ - int DumpFrame(pNexTrics self, SConnection *pCon) - { - int iRet; - - assert(self); - assert(pCon); - - if(self->iFirst == 1) - { - iRet = WriteFirstFrame(self,pCon); - } - else - { - iRet = ContinueFile(self,pCon); - } - return iRet; - } + /* install an error handler */ + NXMSetError((void *) pCon, SNError); + + pNew = CreateNexTrics(pDanu, argv[2], argv[3], pSics); + if (!pNew) { + SCWrite(pCon, "ERROR: cannot create nexTrics, invalid dictionary file", + eError); + SCWrite(pCon, "ERROR: or system objects missing.", eError); + return 0; + } + + /* create the command */ + iRet = AddCommand(pSics, "nxtrics", NexTricsAction, DeleteNexTrics, + pNew); + if (!iRet) { + SCWrite(pCon, "ERROR: duplicate command nxtrics not created", eError); + } + return iRet; +} + /*-------------------------------------------------------------------------*/ - static int FrameInterest(int iEvent, void *pEvent, void *pUser) - { - SConnection *pCon = NULL; - int *iFrame; - char pBueffel[512]; - pCon = (SConnection *)pUser; - - /* kill condition check */ - if(pCon == NULL || !SCisConnected(pCon)) - { - return -1; - } +static int DumpData(pNexTrics self, SConnection * pCon, NXhandle hfil, + int iFrameNum) +{ + int iRet; + char pBueffel[512]; + CounterMode eMode; + HistInt lData[DET1X * DET1Y], i, lVal; + int iVal, lBeam; + float fVal, fTTheta, fTime = 0.; + pMotor pMot; + + /* write motors */ + SNXSPutMotor(pServ->pSics, pCon, hfil, self->pDict, "framechi", "CHI"); + SNXSPutMotor(pServ->pSics, pCon, hfil, self->pDict, "framephi", "PHI"); + SNXSPutMotor(pServ->pSics, pCon, hfil, self->pDict, "frameomega", "OM"); + /* + read two theta + */ + pMot = FindMotor(pServ->pSics, "stt"); + if (!pMot) { + sprintf(pBueffel, "WARNING: cannot find motor stt"); + SCWrite(pCon, pBueffel, eWarning); + return 0; + } + + /* get the position */ + iRet = MotorGetSoftPosition(pMot, pCon, &fTTheta); + + + /* write frame time */ + SNXFormatTime(pBueffel, 512); + iRet = NXDputalias(hfil, self->pDict, "etime", pBueffel); + if (iRet != NX_OK) { + SCWrite(pCon, "ERROR: cannot write frame time", eError); + } + + /* write counting parameters */ + if (self->pHistogram1 != NULL) { + eMode = GetHistCountMode(self->pHistogram1); + fVal = GetHistPreset(self->pHistogram1); + lVal = GetHistMonitor(self->pHistogram1, 1, pCon); + lBeam = GetHistMonitor(self->pHistogram1, 4, pCon); + } + if (self->pHistogram2 != NULL) { + eMode = GetHistCountMode(self->pHistogram2); + fVal = GetHistPreset(self->pHistogram2); + lVal = GetHistMonitor(self->pHistogram2, 1, pCon); + lBeam = GetHistMonitor(self->pHistogram2, 4, pCon); + } + if (self->pHistogram3 != NULL) { + eMode = GetHistCountMode(self->pHistogram3); + fVal = GetHistPreset(self->pHistogram3); + lVal = GetHistMonitor(self->pHistogram3, 1, pCon); + lBeam = GetHistMonitor(self->pHistogram3, 4, pCon); + } + if (self->pCount != NULL) { + eMode = GetCounterMode(self->pCount); + fVal = GetCounterPreset(self->pCount); + lVal = GetMonitor(self->pCount, 1, pCon); + fTime = GetCountTime(self->pCount, pCon); + lBeam = GetMonitor(self->pCount, 4, pCon); + } + if (eMode == eTimer) { + strcpy(pBueffel, "Timer"); + } else { + strcpy(pBueffel, "Monitor"); + } + NXDputalias(hfil, self->pDict, "framemode", pBueffel); + NXDputalias(hfil, self->pDict, "framepreset", &fVal); + iVal = (int) lVal; + NXDputalias(hfil, self->pDict, "framemonitor", &iVal); + iVal = (int) lBeam; + NXDputalias(hfil, self->pDict, "sinqmonitor", &iVal); + NXDputalias(hfil, self->pDict, "cctime", &fTime); + + /* write detector1 histogram */ + if (self->pHistogram1 != NULL) { + strcpy(pBueffel, "detector1"); + NXDupdate(self->pDict, "dnumber", pBueffel); + SNXSPutMotor(pServ->pSics, pCon, hfil, self->pDict, + "frametilt", "DG1"); + GetHistogram(self->pHistogram1, pCon, 0, 0, DET1X * DET1Y, lData, + DET1X * DET1Y * sizeof(HistInt)); + NXDputalias(hfil, self->pDict, "framecounts", lData); + + /* + NXDopenalias(hfil,self->pDict,"framecounts"); + NXputdata(hfil,lData); + NXsetdimname(hfil,0,"frame_x"); + NXsetdimname(hfil,1,"frame_y"); + NXclosedata(hfil); + */ + + fVal = fTTheta + self->hm1off; + NXDputalias(hfil, self->pDict, "frame2theta", &fVal); + + /* the NXdata links */ + NXDaliaslink(hfil, self->pDict, "frame", "detectorx"); + NXDaliaslink(hfil, self->pDict, "frame", "detectory"); + NXDaliaslink(hfil, self->pDict, "frame", "framecounts"); + } + /* + do detector 2 histogram + */ + if (self->pHistogram2 != NULL) { + strcpy(pBueffel, "detector2"); + NXDupdate(self->pDict, "dnumber", pBueffel); + SNXSPutMotor(pServ->pSics, pCon, hfil, self->pDict, + "frametilt", "DG2"); + GetHistogram(self->pHistogram2, pCon, 0, 0, DET2X * DET2Y, lData, + DET2X * DET2Y * sizeof(HistInt)); + NXDputalias(hfil, self->pDict, "framecounts", lData); + + /* code for reducing object number in HDF-4 + NXDopenalias(hfil,self->pDict,"framecounts"); + NXputdata(hfil,lData); + NXsetdimname(hfil,0,"frame_x"); + NXsetdimname(hfil,1,"frame_y"); + NXclosedata(hfil); + */ + + fVal = fTTheta + self->hm2Off; + NXDputalias(hfil, self->pDict, "frame2theta", &fVal); + + /* the NXdata links */ + NXDaliaslink(hfil, self->pDict, "frame", "detectorx"); + NXDaliaslink(hfil, self->pDict, "frame", "detectory"); + NXDaliaslink(hfil, self->pDict, "frame", "framecounts"); + } + /* + do detector 3 histogram + */ + if (self->pHistogram3 != NULL) { + strcpy(pBueffel, "detector3"); + NXDupdate(self->pDict, "dnumber", pBueffel); + SNXSPutMotor(pServ->pSics, pCon, hfil, self->pDict, + "frametilt", "DG3"); + GetHistogram(self->pHistogram3, pCon, 0, 0, DET3X * DET3Y, lData, + DET3X * DET3Y * sizeof(HistInt)); + + NXDputalias(hfil, self->pDict, "framecounts", lData); + + /* code for reducing object numbers in HDF-4 + NXDopenalias(hfil,self->pDict,"framecounts"); + NXputdata(hfil,lData); + NXsetdimname(hfil,0,"frame_x"); + NXsetdimname(hfil,1,"frame_y"); + NXclosedata(hfil); + */ + + + fVal = fTTheta + self->hm3Off; + NXDputalias(hfil, self->pDict, "frame2theta", &fVal); + + /* the NXdata links */ + NXDaliaslink(hfil, self->pDict, "frame", "detectorx"); + NXDaliaslink(hfil, self->pDict, "frame", "detectory"); + NXDaliaslink(hfil, self->pDict, "frame", "framecounts"); + } + + + /* temperature */ + SNXSPutEVVar(hfil, self->pDict, "temperature", + pCon, "frametemp", "framestdev"); + + /* close and done */ + sprintf(pBueffel, "Frame %d succesfully written", iFrameNum - 1); + SCWrite(pCon, pBueffel, eLog); + + return 1; +} + +/*--------------------------------------------------------------------------*/ +static int WriteFirstFrame(pNexTrics self, SConnection * pCon) +{ + char pBueffel[1024]; + NXhandle hfil; + int iRet, iYear, i; + pSicsVariable pVar; + char *pText; + CommandList *pCom = NULL; + pHKL pCryst = NULL; + float fVal, fPix[DETAMAX]; + float fHKL[3], fUB[9]; + + iRet = NXopen(self->pCurrentFile, NXACC_RDWR, &hfil); + if (iRet != NX_OK) { + sprintf(pBueffel, "ERROR: cannot open %s", self->pCurrentFile); + SCWrite(pCon, pBueffel, eError); + return 0; + } + + /* make sure: first frame */ + NXDupdate(self->pDict, "framename", "frame0000"); + self->iFrameNum = 0; + + /* title */ + pVar = NULL; + pVar = FindVariable(pServ->pSics, "title"); + if (pVar) { + pText = pVar->text; + } else { + SCWrite(pCon, "ERROR: Variable title not found ", eError); + pText = pBueffel; + } + iRet = NXDputalias(hfil, self->pDict, "etitle", pText); + if (iRet != NX_OK) { + SCWrite(pCon, "ERROR: failed to write title", eError); + } + + /* start time */ + SNXFormatTime(pBueffel, 1023); + iRet = NXDputalias(hfil, self->pDict, "etime", pBueffel); + if (iRet != NX_OK) { + SCWrite(pCon, "ERROR: failed to write start time", eError); + } + + /* source info */ + strcpy(pBueffel, "SINQ at Paul Scherrer Institut, Villigen"); + iRet = NXDputalias(hfil, self->pDict, "sname", pBueffel); + if (iRet != NX_OK) { + SCWrite(pCon, "ERROR: failed to write source name", eError); + } + strcpy(pBueffel, "Spallation Neutron Source"); + iRet = NXDputalias(hfil, self->pDict, "stype", pBueffel); + if (iRet != NX_OK) { + SCWrite(pCon, "ERROR: failed to write source type", eError); + } + + /* instrument name */ + strcpy(pBueffel, "TRICS at SINQ, Paul Scherrer Institut, Switzerland"); + iRet = NXDputalias(hfil, self->pDict, "iname0", pBueffel); + if (iRet != NX_OK) { + SCWrite(pCon, "ERROR: failed to write instrument name", eError); + } + + /* Collimator */ + SNXSPutMotor(pServ->pSics, pCon, hfil, self->pDict, "cex1", "cex1"); + SNXSPutMotor(pServ->pSics, pCon, hfil, self->pDict, "cex2", "cex2"); + + + /* Monochromator */ + pVar = NULL; + strcpy(pBueffel, "UNKNOWN"); + pVar = FindVariable(pServ->pSics, "monodescription"); + if (pVar) { + pText = pVar->text; + } else { + SCWrite(pCon, "ERROR: Variable monodescription not found ", eError); + pText = pBueffel; + } + iRet = NXDputalias(hfil, self->pDict, "monodes", pText); + if (iRet != NX_OK) { + SCWrite(pCon, "ERROR: failed to write monodescription", eError); + } + + /* lambda */ + if (self->pCrystal != NULL) { + GetLambda(self->pCrystal, &fVal); + iRet = NXDputalias(hfil, self->pDict, "monolambda", &fVal); + if (iRet != NX_OK) { + SCWrite(pCon, "ERROR: failed to write lambda", eError); + } + } + + /* two theta */ + pVar = NULL; + strcpy(pBueffel, "UNKNOWN"); + pVar = FindVariable(pServ->pSics, "mono2theta"); + if (pVar) { + fVal = pVar->fVal; + } else { + SCWrite(pCon, "ERROR: Variable mono2theta not found ", eError); + fVal = -2188.99; + } + iRet = NXDputalias(hfil, self->pDict, "mono2theta", &fVal); + if (iRet != NX_OK) { + SCWrite(pCon, "ERROR: failed to write monochromator 2 Theta", eError); + } + /* theta, needs work when lift operational */ + SNXSPutMotor(pServ->pSics, pCon, hfil, self->pDict, "monotheta", "MUCA"); + + + /* detector data + first set detector variables in dictionary + This is the first detector. + */ + if (self->pHistogram1 != NULL) { + strcpy(pBueffel, "detector1"); + NXDupdate(self->pDict, "dnumber", pBueffel); + sprintf(pBueffel, "%d", DET1X); + NXDupdate(self->pDict, "framedim1", pBueffel); + sprintf(pBueffel, "%d", DET1Y); + NXDupdate(self->pDict, "framedim2", pBueffel); + strcpy(pBueffel, DET1DESC); + iRet = NXDputalias(hfil, self->pDict, "ddescription", pBueffel); + if (iRet != NX_OK) { + SCWrite(pCon, "ERROR: failed to write detector1 description", + eError); + } + for (i = 0; i < DET1X; i++) { + fPix[i] = i * DET1XS; + } + iRet = NXDputalias(hfil, self->pDict, "detectorx", fPix); + if (iRet != NX_OK) { + SCWrite(pCon, "ERROR: failed to write detector1 x-axis description", + eError); + } + for (i = 0; i < DET1Y; i++) { + fPix[i] = i * DET1YS; + } + iRet = NXDputalias(hfil, self->pDict, "detectory", fPix); + if (iRet != NX_OK) { + SCWrite(pCon, "ERROR: failed to write detector1 y-axis description", + eError); + } + pVar = NULL; + pVar = FindVariable(pServ->pSics, "det1zerox"); + if (pVar) { + fVal = pVar->fVal; + } else { + SCWrite(pCon, "ERROR: Variable detector x zero point not found ", + eError); + fVal = -2188.99; + } + iRet = NXDputalias(hfil, self->pDict, "detzerox", &fVal); + if (iRet != NX_OK) { + SCWrite(pCon, "ERROR: failed to write detecor x zero point", eError); + } + pVar = NULL; + pVar = FindVariable(pServ->pSics, "det1zeroy"); + if (pVar) { + fVal = pVar->fVal; + } else { + SCWrite(pCon, "ERROR: Variable detector y zero point not found ", + eError); + fVal = -2188.99; + } + iRet = NXDputalias(hfil, self->pDict, "detzeroy", &fVal); + if (iRet != NX_OK) { + SCWrite(pCon, "ERROR: failed to write detecor y zero point", eError); + } + pVar = NULL; + pVar = FindVariable(pServ->pSics, "detdist1"); + if (pVar) { + fVal = pVar->fVal; + } else { + SCWrite(pCon, "ERROR: Variable detector distance not found ", + eError); + fVal = -2188.99; + } + iRet = NXDputalias(hfil, self->pDict, "detdist", &fVal); + if (iRet != NX_OK) { + SCWrite(pCon, "ERROR: failed to write detecor y zero point", eError); + } + iRet = 1; + iRet = NXDputalias(hfil, self->pDict, "detvalid", &iRet); + if (iRet != NX_OK) { + SCWrite(pCon, "ERROR: failed to write frame validity", eError); + } + } + /* + second frame, but only if present + */ + if (self->pHistogram2 != NULL) { + strcpy(pBueffel, "detector2"); + NXDupdate(self->pDict, "dnumber", pBueffel); + sprintf(pBueffel, "%d", DET2X); + NXDupdate(self->pDict, "framedim1", pBueffel); + sprintf(pBueffel, "%d", DET2Y); + NXDupdate(self->pDict, "framedim2", pBueffel); + strcpy(pBueffel, DET2DESC); + iRet = NXDputalias(hfil, self->pDict, "ddescription", pBueffel); + if (iRet != NX_OK) { + SCWrite(pCon, "ERROR: failed to write detector2 description", + eError); + } + for (i = 0; i < DET2X; i++) { + fPix[i] = i * DET2XS; + } + iRet = NXDputalias(hfil, self->pDict, "detectorx", fPix); + if (iRet != NX_OK) { + SCWrite(pCon, "ERROR: failed to write detector2 x-axis description", + eError); + } + for (i = 0; i < DET2Y; i++) { + fPix[i] = i * DET2YS; + } + iRet = NXDputalias(hfil, self->pDict, "detectory", fPix); + if (iRet != NX_OK) { + SCWrite(pCon, "ERROR: failed to write detector1 y-axis description", + eError); + } + pVar = NULL; + pVar = FindVariable(pServ->pSics, "det2zerox"); + if (pVar) { + fVal = pVar->fVal; + } else { + SCWrite(pCon, "ERROR: Variable detector x zero point not found ", + eError); + fVal = -2188.99; + } + iRet = NXDputalias(hfil, self->pDict, "detzerox", &fVal); + if (iRet != NX_OK) { + SCWrite(pCon, "ERROR: failed to write detecor x zero point", eError); + } + pVar = NULL; + pVar = FindVariable(pServ->pSics, "det2zeroy"); + if (pVar) { + fVal = pVar->fVal; + } else { + SCWrite(pCon, "ERROR: Variable detector2 y zero point not found ", + eError); + fVal = -2188.99; + } + iRet = NXDputalias(hfil, self->pDict, "detzeroy", &fVal); + if (iRet != NX_OK) { + SCWrite(pCon, "ERROR: failed to write detecor y zero point", eError); + } + pVar = NULL; + pVar = FindVariable(pServ->pSics, "detdist2"); + if (pVar) { + fVal = pVar->fVal; + } else { + SCWrite(pCon, "ERROR: Variable detector distance not found ", + eError); + fVal = -2188.99; + } + iRet = NXDputalias(hfil, self->pDict, "detdist", &fVal); + if (iRet != NX_OK) { + SCWrite(pCon, "ERROR: failed to write detecor2 y distance", eError); + } + iRet = 1; + iRet = NXDputalias(hfil, self->pDict, "detvalid", &iRet); + if (iRet != NX_OK) { + SCWrite(pCon, "ERROR: failed to write frame validity", eError); + } + } + /* + third detector, but only if present + */ + if (self->pHistogram3 != NULL) { + strcpy(pBueffel, "detector3"); + NXDupdate(self->pDict, "dnumber", pBueffel); + sprintf(pBueffel, "%d", DET3X); + NXDupdate(self->pDict, "framedim1", pBueffel); + sprintf(pBueffel, "%d", DET3Y); + NXDupdate(self->pDict, "framedim2", pBueffel); + strcpy(pBueffel, DET3DESC); + iRet = NXDputalias(hfil, self->pDict, "ddescription", pBueffel); + if (iRet != NX_OK) { + SCWrite(pCon, "ERROR: failed to write detector3 description", + eError); + } + for (i = 0; i < DET3X; i++) { + fPix[i] = i * DET3XS; + } + iRet = NXDputalias(hfil, self->pDict, "detectorx", fPix); + if (iRet != NX_OK) { + SCWrite(pCon, "ERROR: failed to write detector2 x-axis description", + eError); + } + for (i = 0; i < DET3Y; i++) { + fPix[i] = i * DET3YS; + } + iRet = NXDputalias(hfil, self->pDict, "detectory", fPix); + if (iRet != NX_OK) { + SCWrite(pCon, "ERROR: failed to write detector1 y-axis description", + eError); + } + pVar = NULL; + pVar = FindVariable(pServ->pSics, "det3zerox"); + if (pVar) { + fVal = pVar->fVal; + } else { + SCWrite(pCon, "ERROR: Variable detector 3 x zero point not found ", + eError); + fVal = -2188.99; + } + iRet = NXDputalias(hfil, self->pDict, "detzerox", &fVal); + if (iRet != NX_OK) { + SCWrite(pCon, "ERROR: failed to write detecor x zero point", eError); + } + pVar = NULL; + pVar = FindVariable(pServ->pSics, "det3zeroy"); + if (pVar) { + fVal = pVar->fVal; + } else { + SCWrite(pCon, "ERROR: Variable detector 3 y zero point not found ", + eError); + fVal = -2188.99; + } + iRet = NXDputalias(hfil, self->pDict, "detzeroy", &fVal); + if (iRet != NX_OK) { + SCWrite(pCon, "ERROR: failed to write detecor y zero point", eError); + } + pVar = NULL; + pVar = FindVariable(pServ->pSics, "detdist3"); + if (pVar) { + fVal = pVar->fVal; + } else { + SCWrite(pCon, "ERROR: Variable detector 3 distance not found ", + eError); + fVal = -2188.99; + } + iRet = NXDputalias(hfil, self->pDict, "detdist", &fVal); + if (iRet != NX_OK) { + SCWrite(pCon, "ERROR: failed to write detecor 3 y distance", eError); + } + iRet = 1; + iRet = NXDputalias(hfil, self->pDict, "detvalid", &iRet); + if (iRet != NX_OK) { + SCWrite(pCon, "ERROR: failed to write frame validity", eError); + } + } + + /* do sample information */ + strcpy(pBueffel, "UNKNOWN"); + pVar = FindVariable(pServ->pSics, "sample"); + if (pVar) { + pText = pVar->text; + } else { + SCWrite(pCon, "ERROR: Variable sample not found ", eError); + pText = pBueffel; + } + iRet = NXDputalias(hfil, self->pDict, "samplename", pText); + if (iRet != NX_OK) { + SCWrite(pCon, "ERROR: failed to write sample name", eError); + } + if (self->pCrystal != NULL) { + GetUB(self->pCrystal, fUB); + iRet = NXDputalias(hfil, self->pDict, "sampleub", fUB); + if (iRet != NX_OK) { + SCWrite(pCon, "ERROR: failed to write sample UB", eError); + } + GetCurrentHKL(self->pCrystal, fHKL); + iRet = NXDputalias(hfil, self->pDict, "samplehkl", fHKL); + if (iRet != NX_OK) { + SCWrite(pCon, "ERROR: failed to write HKL", eError); + } + } + + /* put the frame number */ + iRet = 0; + iRet = NXDputalias(hfil, self->pDict, "fnum", &iRet); + if (iRet != NX_OK) { + SCWrite(pCon, "ERROR: failed to write initial frame number", eError); + } + + /* write actual data */ + iRet = DumpData(self, pCon, hfil, 1); + + /* put the frame number */ + iRet = 1; + iRet = NXDputalias(hfil, self->pDict, "fnum", &iRet); + if (iRet != NX_OK) { + SCWrite(pCon, "ERROR: failed to write initial frame number", eError); + } + self->iFrameNum = 1; + InvokeCallBack(self->pCall, NEWFRAME, &(self->iFrameNum)); + + self->iFirst = 0; + + /* close the file and go */ + NXclose(&hfil); + SendQuieck(QUIECK, self->pCurrentFile); + return iRet; +} + +/*-------------------------------------------------------------------------*/ +static int ContinueFile(pNexTrics self, SConnection * pCon) +{ + int iFrameNum, iRet; + char pBueffel[1024]; + float fVal; + NXhandle hfil; + + assert(self); + assert(pCon); + assert(self->iFirst == 0); + + /* let's start by opening the file */ + iRet = NXopen(self->pCurrentFile, NXACC_RDWR, &hfil); + if (iRet != NX_OK) { + sprintf(pBueffel, "ERROR: cannot reopen %s, NO data written", + self->pCurrentFile); + SCWrite(pCon, pBueffel, eError); + return 0; + } + + /* read the frame number, set the framename for further reading, + increment and write back again + */ + iRet = NXDgetalias(hfil, self->pDict, "fnum", &iFrameNum); + if (iRet != NX_OK) { + SCWrite(pCon, "EERROR: cannot read old framenumber, NO data written", + eError); + return 0; + } + sprintf(pBueffel, "frame%4.4d", iFrameNum); + NXDupdate(self->pDict, "framename", pBueffel); + iFrameNum++; + self->iFrameNum++; + InvokeCallBack(self->pCall, NEWFRAME, &(self->iFrameNum)); + iRet = NXDputalias(hfil, self->pDict, "fnum", &iFrameNum); + if (iRet != NX_OK) { + SCWrite(pCon, "ERROR: cannot write new framenumber, NO data written", + eError); + return 0; + } + + /* put in links to duplicates: entry */ + iRet = NXDaliaslink(hfil, self->pDict, "entry", "etitle0"); + if (iRet != NX_OK) { + SCWrite(pCon, "WARNING: cannot link against title", eWarning); + } + + /* links to instrument */ + iRet = NXDaliaslink(hfil, self->pDict, "inst0", "iname0"); + if (iRet != NX_OK) { + SCWrite(pCon, "WARNING: cannot link against instrument name", + eWarning); + } + iRet = NXDaliaslink(hfil, self->pDict, "inst0", "source0"); + if (iRet != NX_OK) { + SCWrite(pCon, "WARNING: cannot link against source group", eWarning); + } + iRet = NXDaliaslink(hfil, self->pDict, "inst0", "mono0"); + if (iRet != NX_OK) { + SCWrite(pCon, "WARNING: cannot link against monochromator group", + eWarning); + } + iRet = NXDaliaslink(hfil, self->pDict, "inst0", "coll0"); + if (iRet != NX_OK) { + SCWrite(pCon, "WARNING: cannot link against collimator group", + eWarning); + } + + + + /* + links in detector group + detector 1 + */ + if (self->pHistogram1 != NULL) { + strcpy(pBueffel, "detector1"); + NXDupdate(self->pDict, "dnumber", pBueffel); + iRet = NXDaliaslink(hfil, self->pDict, "det1", "ddescription"); + if (iRet != NX_OK) { + SCWrite(pCon, "WARNING: cannot link against detector description", + eWarning); + } + iRet = NXDaliaslink(hfil, self->pDict, "det1", "detectorx"); + if (iRet != NX_OK) { + SCWrite(pCon, "WARNING: cannot link against detector x-axis", + eWarning); + } + iRet = NXDaliaslink(hfil, self->pDict, "det1", "detectory"); + if (iRet != NX_OK) { + SCWrite(pCon, "WARNING: cannot link against detector y-axis", + eWarning); + } + iRet = NXDaliaslink(hfil, self->pDict, "det1", "detzerox"); + if (iRet != NX_OK) { + SCWrite(pCon, "WARNING: cannot link against detector x zero ", + eWarning); + } + iRet = NXDaliaslink(hfil, self->pDict, "det1", "detzeroy"); + if (iRet != NX_OK) { + SCWrite(pCon, "WARNING: cannot link against detector y zero", + eWarning); + } + iRet = NXDaliaslink(hfil, self->pDict, "det1", "detdist"); + if (iRet != NX_OK) { + SCWrite(pCon, "WARNING: cannot link against detector distance", + eWarning); + } + iRet = 1; + iRet = NXDputalias(hfil, self->pDict, "detvalid", &iRet); + if (iRet != NX_OK) { + SCWrite(pCon, "ERROR: failed to write frame validity", eError); + } + } + /* + links in detector group, detector 2 + */ + if (self->pHistogram2) { + strcpy(pBueffel, "detector2"); + NXDupdate(self->pDict, "dnumber", pBueffel); + iRet = NXDaliaslink(hfil, self->pDict, "det1", "ddescription"); + if (iRet != NX_OK) { + SCWrite(pCon, "WARNING: cannot link against detector description", + eWarning); + } + iRet = NXDaliaslink(hfil, self->pDict, "det1", "detectorx"); + if (iRet != NX_OK) { + SCWrite(pCon, "WARNING: cannot link against detector x-axis", + eWarning); + } + iRet = NXDaliaslink(hfil, self->pDict, "det1", "detectory"); + if (iRet != NX_OK) { + SCWrite(pCon, "WARNING: cannot link against detector y-axis", + eWarning); + } + iRet = NXDaliaslink(hfil, self->pDict, "det1", "detzerox"); + if (iRet != NX_OK) { + SCWrite(pCon, "WARNING: cannot link against detector x zero ", + eWarning); + } + iRet = NXDaliaslink(hfil, self->pDict, "det1", "detzeroy"); + if (iRet != NX_OK) { + SCWrite(pCon, "WARNING: cannot link against detector y zero", + eWarning); + } + iRet = NXDaliaslink(hfil, self->pDict, "det1", "detdist"); + if (iRet != NX_OK) { + SCWrite(pCon, "WARNING: cannot link against detector distance", + eWarning); + } + iRet = 1; + iRet = NXDputalias(hfil, self->pDict, "detvalid", &iRet); + if (iRet != NX_OK) { + SCWrite(pCon, "ERROR: failed to write frame validity", eError); + } + } + + /* + links in detector group, detector 3 + */ + if (self->pHistogram3) { + strcpy(pBueffel, "detector3"); + NXDupdate(self->pDict, "dnumber", pBueffel); + iRet = NXDaliaslink(hfil, self->pDict, "det1", "ddescription"); + if (iRet != NX_OK) { + SCWrite(pCon, "WARNING: cannot link against detector description", + eWarning); + } + iRet = NXDaliaslink(hfil, self->pDict, "det1", "detectorx"); + if (iRet != NX_OK) { + SCWrite(pCon, "WARNING: cannot link against detector x-axis", + eWarning); + } + iRet = NXDaliaslink(hfil, self->pDict, "det1", "detectory"); + if (iRet != NX_OK) { + SCWrite(pCon, "WARNING: cannot link against detector y-axis", + eWarning); + } + iRet = NXDaliaslink(hfil, self->pDict, "det1", "detzerox"); + if (iRet != NX_OK) { + SCWrite(pCon, "WARNING: cannot link against detector x zero ", + eWarning); + } + iRet = NXDaliaslink(hfil, self->pDict, "det1", "detzeroy"); + if (iRet != NX_OK) { + SCWrite(pCon, "WARNING: cannot link against detector y zero", + eWarning); + } + iRet = NXDaliaslink(hfil, self->pDict, "det1", "detdist"); + if (iRet != NX_OK) { + SCWrite(pCon, "WARNING: cannot link against detector distance", + eWarning); + } + iRet = 1; + iRet = NXDputalias(hfil, self->pDict, "detvalid", &iRet); + if (iRet != NX_OK) { + SCWrite(pCon, "ERROR: failed to write frame validity", eError); + } + } + + + /* links in sample group */ + iRet = NXDaliaslink(hfil, self->pDict, "samplev", "samplename"); + if (iRet != NX_OK) { + SCWrite(pCon, "WARNING: cannot link against sample name", eWarning); + } + if (self->pCrystal != NULL) { + iRet = NXDaliaslink(hfil, self->pDict, "samplev", "sampleub"); + if (iRet != NX_OK) { + SCWrite(pCon, "WARNING: cannot link against sample UB", eWarning); + } + iRet = NXDaliaslink(hfil, self->pDict, "samplev", "samplehkl"); + if (iRet != NX_OK) { + SCWrite(pCon, "WARNING: cannot link against sample HKL", eWarning); + } + } + + /* write actual data */ + iRet = DumpData(self, pCon, hfil, iFrameNum); + + /* close the file and go */ + NXclose(&hfil); + SendQuieck(QUIECK, self->pCurrentFile); + return iRet; + +} + +/*--------------------------------------------------------------------------*/ +int StartFile(pNexTrics self, SConnection * pCon) +{ + char pBueffel[1024]; + NXhandle hfil; + int iRet, iYear, i; + pSicsVariable pVar; + char *pText; + CommandList *pCom = NULL; + pHKL pCryst = NULL; + float fVal, fPix[DETAMAX]; + + /* make a filename and open it */ + if (self->pCurrentFile) + free(self->pCurrentFile); + + pText = makeFilename(pServ->pSics, pCon); + changeExtension(pText, "hdf"); + if (pText == NULL) { + return 0; + } + self->pCurrentFile = strdup(pText); + if (self->iHDF5) { + iRet = NXopen(self->pCurrentFile, NXACC_CREATE5, &hfil); + } else { + iRet = NXopen(self->pCurrentFile, NXACC_CREATE, &hfil); + } + if (iRet != NX_OK) { + sprintf(pBueffel, "ERROR: cannot open %s", self->pCurrentFile); + SCWrite(pCon, pBueffel, eError); + return 0; + } + + /* tell user what we are doing */ + sprintf(pBueffel, "Initialising file %s ......", self->pCurrentFile); + SCWrite(pCon, pBueffel, eWarning); + + + /* Write header data */ + SNXSPutGlobals(hfil, self->pCurrentFile, + "TRICS at SinQ, Paul Scherrer Institut, Switzerland", + pCon); + + self->iFirst = 1; + self->iFrameNum = 0; + InvokeCallBack(self->pCall, NEWFRAME, &(self->iFrameNum)); + + /* close the file and go */ + NXclose(&hfil); + return 1; +} + +/*-------------------------------------------------------------------------*/ +int ReopenFile(pNexTrics self, char *filename) +{ + char pBueffel[1024]; + NXhandle hfil; + int iRet, iFrameNum; + + assert(self); + + /* concat with data root and check for existence */ + sprintf(pBueffel, "%s/%s", self->pFileRoot, filename); + iRet = NXopen(pBueffel, NXACC_RDWR, &hfil); + if (iRet != NX_OK) { + return 0; + } else { + if (self->pCurrentFile) + free(self->pCurrentFile); + self->pCurrentFile = strdup(pBueffel); + } + + /* check the framenumber, if already data written */ + iRet = NXDgetalias(hfil, self->pDict, "fnum", &iFrameNum); + if (iRet != NX_OK) { + self->iFirst = 1; + } else { + self->iFirst = 0; + } + self->iFrameNum = iFrameNum; + InvokeCallBack(self->pCall, NEWFRAME, &(self->iFrameNum)); + return 1; +} + +/*--------------------------------------------------------------------------*/ +int DumpFrame(pNexTrics self, SConnection * pCon) +{ + int iRet; + + assert(self); + assert(pCon); + + if (self->iFirst == 1) { + iRet = WriteFirstFrame(self, pCon); + } else { + iRet = ContinueFile(self, pCon); + } + + return iRet; +} + +/*-------------------------------------------------------------------------*/ +static int FrameInterest(int iEvent, void *pEvent, void *pUser) +{ + SConnection *pCon = NULL; + int *iFrame; + char pBueffel[512]; + pCon = (SConnection *) pUser; + + /* kill condition check */ + if (pCon == NULL || !SCisConnected(pCon)) { + return -1; + } + + if (iEvent != NEWFRAME) { + return 0; + } + + iFrame = (int *) pEvent; + assert(pCon); + sprintf(pBueffel, "framenumber = %d", *iFrame); + SCWrite(pCon, pBueffel, eWarning); + return 1; +} - if(iEvent != NEWFRAME ) - { - return 0; - } - - iFrame = (int *)pEvent; - assert(pCon); - sprintf(pBueffel,"framenumber = %d",*iFrame); - SCWrite(pCon,pBueffel,eWarning); - return 1; - } /*------------------------------------------------------------------------- NexusGetFrame opens a TRICS NeXus file and retrieves a frame for the specified detector from it. This is a special feature for the status display. ---------------------------------------------------------------------------*/ - static int NexusGetFrame(SConnection *pCon, pNexTrics self, - int iDetector, int iFrame) - { - char pBueffel[132]; - int iRet; - NXhandle hfil; - HistInt *lData = NULL; +static int NexusGetFrame(SConnection * pCon, pNexTrics self, + int iDetector, int iFrame) +{ + char pBueffel[132]; + int iRet; + NXhandle hfil; + HistInt *lData = NULL; - /* do a few range checks */ - if(iDetector < 1 || iDetector > 3) - { - sprintf(pBueffel,"ERROR: unknown detector %d requested",iDetector); - return 0; - } - if(iFrame < 0 || iFrame >= self->iFrameNum) - { - sprintf(pBueffel,"ERROR: frame %d not yet written",iDetector); - return 0; - } + /* do a few range checks */ + if (iDetector < 1 || iDetector > 3) { + sprintf(pBueffel, "ERROR: unknown detector %d requested", iDetector); + return 0; + } + if (iFrame < 0 || iFrame >= self->iFrameNum) { + sprintf(pBueffel, "ERROR: frame %d not yet written", iDetector); + return 0; + } - /* open file */ - iRet = NXopen(self->pCurrentFile,NXACC_READ,&hfil); - if(iRet != NX_OK) - { - sprintf(pBueffel,"ERROR: cannot open %s",self->pCurrentFile); - SCWrite(pCon,pBueffel,eError); - return 0; - } + /* open file */ + iRet = NXopen(self->pCurrentFile, NXACC_READ, &hfil); + if (iRet != NX_OK) { + sprintf(pBueffel, "ERROR: cannot open %s", self->pCurrentFile); + SCWrite(pCon, pBueffel, eError); + return 0; + } - /* open groups */ - sprintf(pBueffel,"frame%4.4d",iFrame); - iRet = NXopengroup(hfil,pBueffel,"NXentry"); - if(iRet != NX_OK) - { - sprintf(pBueffel,"ERROR: frame %d not found in %s",iFrame, - self->pCurrentFile); - SCWrite(pCon,pBueffel,eError); - NXclose(&hfil); - return 0; - } - sprintf(pBueffel,"detector%1.1d",iDetector); - iRet = NXopengroup(hfil,pBueffel,"NXdata"); - if(iRet != NX_OK) - { - sprintf(pBueffel,"ERROR: detector %d not found in %s",iFrame, - self->pCurrentFile); - SCWrite(pCon,pBueffel,eError); - NXclose(&hfil); - return 0; - } - iRet = NXopendata(hfil,"counts"); - if(iRet != NX_OK) - { - SCWrite(pCon,"ERROR: no counts found, file corrupted",eError); - NXclose(&hfil); - return 0; - } + /* open groups */ + sprintf(pBueffel, "frame%4.4d", iFrame); + iRet = NXopengroup(hfil, pBueffel, "NXentry"); + if (iRet != NX_OK) { + sprintf(pBueffel, "ERROR: frame %d not found in %s", iFrame, + self->pCurrentFile); + SCWrite(pCon, pBueffel, eError); + NXclose(&hfil); + return 0; + } + sprintf(pBueffel, "detector%1.1d", iDetector); + iRet = NXopengroup(hfil, pBueffel, "NXdata"); + if (iRet != NX_OK) { + sprintf(pBueffel, "ERROR: detector %d not found in %s", iFrame, + self->pCurrentFile); + SCWrite(pCon, pBueffel, eError); + NXclose(&hfil); + return 0; + } + iRet = NXopendata(hfil, "counts"); + if (iRet != NX_OK) { + SCWrite(pCon, "ERROR: no counts found, file corrupted", eError); + NXclose(&hfil); + return 0; + } - /* read data */ - lData = (HistInt *)malloc(DET1X*DET1Y*sizeof(HistInt)); - if(!lData) - { - SCWrite(pCon,"ERROR: out of memory in NexusGetFrame",eError); - NXclose(&hfil); - return 0; - } - memset(lData,0,DET1X*DET1Y*sizeof(HistInt)); - iRet = NXgetdata(hfil,lData); - if(iRet != NX_OK) - { - SCWrite(pCon,"ERROR: failed to read data",eError); - NXclose(&hfil); - return 0; - } + /* read data */ + lData = (HistInt *) malloc(DET1X * DET1Y * sizeof(HistInt)); + if (!lData) { + SCWrite(pCon, "ERROR: out of memory in NexusGetFrame", eError); + NXclose(&hfil); + return 0; + } + memset(lData, 0, DET1X * DET1Y * sizeof(HistInt)); + iRet = NXgetdata(hfil, lData); + if (iRet != NX_OK) { + SCWrite(pCon, "ERROR: failed to read data", eError); + NXclose(&hfil); + return 0; + } - /* send it */ - sprintf(pBueffel,"detector%1.1d",iDetector); - SCWriteZipped(pCon,pBueffel,lData,DET1X*DET1Y*sizeof(HistInt)); + /* send it */ + sprintf(pBueffel, "detector%1.1d", iDetector); + SCWriteZipped(pCon, pBueffel, lData, DET1X * DET1Y * sizeof(HistInt)); + + /* clean up */ + NXclose(&hfil); + free(lData); + return 1; +} - /* clean up */ - NXclose(&hfil); - free(lData); - return 1; - } /*---------------------------------------------------------------------------*/ - int NexTricsAction(SConnection *pCon, SicsInterp *pSics, void *pData, - int argc, char *argv[]) - { - pNexTrics self; - char pBueffel[1024]; - int iRet, iDet, iFrame; - long lID; - commandContext comCon; - - self = (pNexTrics)pData; - assert(self); - assert(pCon); - - /* check for subcommands */ - if(argc < 2) - { - sprintf(pBueffel,"ERROR: no subcommand found for %s",argv[0]); - SCWrite(pCon,pBueffel,eError); - return 0; - } +int NexTricsAction(SConnection * pCon, SicsInterp * pSics, void *pData, + int argc, char *argv[]) +{ + pNexTrics self; + char pBueffel[1024]; + int iRet, iDet, iFrame; + long lID; + commandContext comCon; - /* install an error handler */ - NXMSetError((void *)pCon,SNError); - - comCon = SCGetContext(pCon); - strtolower(argv[1]); - if(strcmp(argv[1],"start") == 0) - { - if(!SCMatchRights(pCon,usUser)) - { - return 0; - } - iRet = StartFile(self,pCon); - if(iRet) - { - SCSendOK(pCon); - } - return iRet; - } - else if(strcmp(argv[1],"file") == 0) - { - sprintf(pBueffel,"Currently writing to: %s",self->pCurrentFile); - SCWrite(pCon,pBueffel,eValue); - return 1; - } - else if(strcmp(argv[1],"oldframe") == 0) - { - if(argc < 4) - { - SCWrite(pCon,"ERROR: insufficient number of arguments to oldframe", - eError); - return 0; - } - iDet = atoi(argv[2]); - iFrame = atoi(argv[3]); - iRet = NexusGetFrame(pCon,self,iDet, iFrame); - return 1; - } - else if(strcmp(argv[1],"interest") == 0) - { - lID = RegisterCallback(self->pCall, NEWFRAME, FrameInterest, - SCCopyConnection(pCon), - SCDeleteConnection); - SCSendOK(pCon); - return 1; - } - else if(strcmp(argv[1],"framenum") == 0) - { - sprintf(pBueffel,"framenumber = %d",self->iFrameNum); - SCWrite(pCon,pBueffel,eValue); - return 1; - } - else if(strcmp(argv[1],"dumpframe") == 0) - { - if(!SCMatchRights(pCon,usUser)) - { - return 0; - } - iRet = DumpFrame(self,pCon); - if(iRet) - { - SCSendOK(pCon); - } - return iRet; - } - else if(strcmp(argv[1],"reopen") == 0) - { - if(!SCMatchRights(pCon,usUser)) - { - return 0; - } - if(argc < 3) - { - SCWrite(pCon,"ERROR: expected filename as parameter for reopen",eError); - return 0; - } - iRet = ReopenFile(self,argv[2]); - if(iRet) - { - SCSendOK(pCon); - } - return iRet; - } - sprintf(pBueffel,"ERROR: subcommand %s not recognized",argv[1]); - SCWrite(pCon,pBueffel,eError); + self = (pNexTrics) pData; + assert(self); + assert(pCon); + + /* check for subcommands */ + if (argc < 2) { + sprintf(pBueffel, "ERROR: no subcommand found for %s", argv[0]); + SCWrite(pCon, pBueffel, eError); + return 0; + } + + /* install an error handler */ + NXMSetError((void *) pCon, SNError); + + comCon = SCGetContext(pCon); + strtolower(argv[1]); + if (strcmp(argv[1], "start") == 0) { + if (!SCMatchRights(pCon, usUser)) { return 0; - } - - + } + iRet = StartFile(self, pCon); + if (iRet) { + SCSendOK(pCon); + } + return iRet; + } else if (strcmp(argv[1], "file") == 0) { + sprintf(pBueffel, "Currently writing to: %s", self->pCurrentFile); + SCWrite(pCon, pBueffel, eValue); + return 1; + } else if (strcmp(argv[1], "oldframe") == 0) { + if (argc < 4) { + SCWrite(pCon, "ERROR: insufficient number of arguments to oldframe", + eError); + return 0; + } + iDet = atoi(argv[2]); + iFrame = atoi(argv[3]); + iRet = NexusGetFrame(pCon, self, iDet, iFrame); + return 1; + } else if (strcmp(argv[1], "interest") == 0) { + lID = RegisterCallback(self->pCall, NEWFRAME, FrameInterest, + SCCopyConnection(pCon), SCDeleteConnection); + SCSendOK(pCon); + return 1; + } else if (strcmp(argv[1], "framenum") == 0) { + sprintf(pBueffel, "framenumber = %d", self->iFrameNum); + SCWrite(pCon, pBueffel, eValue); + return 1; + } else if (strcmp(argv[1], "dumpframe") == 0) { + if (!SCMatchRights(pCon, usUser)) { + return 0; + } + iRet = DumpFrame(self, pCon); + if (iRet) { + SCSendOK(pCon); + } + return iRet; + } else if (strcmp(argv[1], "reopen") == 0) { + if (!SCMatchRights(pCon, usUser)) { + return 0; + } + if (argc < 3) { + SCWrite(pCon, "ERROR: expected filename as parameter for reopen", + eError); + return 0; + } + iRet = ReopenFile(self, argv[2]); + if (iRet) { + SCSendOK(pCon); + } + return iRet; + } + sprintf(pBueffel, "ERROR: subcommand %s not recognized", argv[1]); + SCWrite(pCon, pBueffel, eError); + return 0; +} diff --git a/nextrics.h b/nextrics.h index bb34a29..ff07746 100644 --- a/nextrics.h +++ b/nextrics.h @@ -14,25 +14,25 @@ #define NEXTRICS #include - typedef struct __NexTrics *pNexTrics; +typedef struct __NexTrics *pNexTrics; /*----------------------------- live & death -----------------------------*/ - pNexTrics CreateNexTrics(pDataNumber pNum, char *pRoot, char *pDict, - SicsInterp *pSics); - void DeleteNexTrics(void *pData); +pNexTrics CreateNexTrics(pDataNumber pNum, char *pRoot, char *pDict, + SicsInterp * pSics); +void DeleteNexTrics(void *pData); - int NexTricsFactory(SConnection *pCon, SicsInterp *pSics, void *pData, - int argc, char *argv[]); +int NexTricsFactory(SConnection * pCon, SicsInterp * pSics, void *pData, + int argc, char *argv[]); /*----------------------------- interaction ------------------------------*/ - int StartFile(pNexTrics self, SConnection *pCon); - - int ReopenFile(pNexTrics self, char *filename); +int StartFile(pNexTrics self, SConnection * pCon); - int DumpFrame(pNexTrics self, SConnection *pCon); +int ReopenFile(pNexTrics self, char *filename); + +int DumpFrame(pNexTrics self, SConnection * pCon); + +int NexTricsAction(SConnection * pCon, SicsInterp * pSics, void *pData, + int argc, char *argv[]); - int NexTricsAction(SConnection *pCon, SicsInterp *pSics, void *pData, - int argc, char *argv[]); - #endif diff --git a/nxamor.c b/nxamor.c index 3a7a6c3..3711b52 100644 --- a/nxamor.c +++ b/nxamor.c @@ -11,7 +11,7 @@ Updated, Mark Koennecke, August 2001 Updated to store TOF-monitor, Mark Koennecke, September 2002 --------------------------------------------------------------------------*/ - + #include #include #include "fortify.h" @@ -27,7 +27,7 @@ #include "motor.h" #include "status.h" -#define MAXMOT 13 /* must be same as in amor2t.c */ +#define MAXMOT 13 /* must be same as in amor2t.c */ #include "amor2t.i" #include "amor2t.h" @@ -59,301 +59,278 @@ pAmor2T pAmor = NULL; static int psdSave = 1; /*------------------------------------------------------------------------*/ - static void WriteDiaphragm(NXhandle hfil, NXdict hdict, int i, - SConnection *pCon) - { - char pThing[30]; +static void WriteDiaphragm(NXhandle hfil, NXdict hdict, int i, + SConnection * pCon) +{ + char pThing[30]; - sprintf(pThing,"d%1.1dt",i); - SNXSPutMotor(pServ->pSics,pCon,hfil,hdict,pThing,pThing); - sprintf(pThing,"d%1.1db",i); - SNXSPutMotor(pServ->pSics,pCon,hfil,hdict,pThing,pThing); - sprintf(pThing,"d%1.1dl",i); - SNXSPutMotor(pServ->pSics,pCon,hfil,hdict,pThing,pThing); - sprintf(pThing,"d%1.1dr",i); - SNXSPutMotor(pServ->pSics,pCon,hfil,hdict,pThing,pThing); - } + sprintf(pThing, "d%1.1dt", i); + SNXSPutMotor(pServ->pSics, pCon, hfil, hdict, pThing, pThing); + sprintf(pThing, "d%1.1db", i); + SNXSPutMotor(pServ->pSics, pCon, hfil, hdict, pThing, pThing); + sprintf(pThing, "d%1.1dl", i); + SNXSPutMotor(pServ->pSics, pCon, hfil, hdict, pThing, pThing); + sprintf(pThing, "d%1.1dr", i); + SNXSPutMotor(pServ->pSics, pCon, hfil, hdict, pThing, pThing); +} + /*----------------------------------------------------------------------*/ - int WriteAmorHeader(char *file, SConnection *pCon) - { - NXhandle hfil; - NXdict hdict; - int iRet; - char pBueffel[512], pThing[80]; - CounterMode eMode; - CommandList *pCom = NULL; - float fVal; +int WriteAmorHeader(char *file, SConnection * pCon) +{ + NXhandle hfil; + NXdict hdict; + int iRet; + char pBueffel[512], pThing[80]; + CounterMode eMode; + CommandList *pCom = NULL; + float fVal; - /* open files */ - NXsetcache(TOFBLOCK); - iRet = NXopen(file,NXACC_CREATE5,&hfil); - if(iRet != NX_OK) - { - snprintf(pBueffel,511,"ERROR: cannot open file %s for writing",file); - SCWrite(pCon,pBueffel,eError); - return 0; - } - iRet = NXDinitfromfile(AMORDICT,&hdict); - if(iRet != NX_OK) - { - snprintf(pBueffel,511,"ERROR: cannot open dictionary file %s",AMORDICT); - SCWrite(pCon,pBueffel,eError); - return 0; - } - snprintf(pBueffel,511,"Writing to: %s", file); - SCWrite(pCon,pBueffel,eWarning); - - /* put some global information */ - SNXSPutGlobals(hfil,file,"AMOR",pCon); - SNXSPutVariable(pServ->pSics,pCon,hfil, hdict,"etitle","title"); - SNXFormatTime(pBueffel,512); - NXDputalias(hfil,hdict,"estart",pBueffel); - - /* instrument vGroup */ - NXDputalias(hfil,hdict,"iname",INSTNAME); - - /* source */ - NXDputalias(hfil,hdict,"sname",SOURCENAME); - NXDputalias(hfil,hdict,"stype",SOURCETYPE); - - /* chopper */ - NXDputalias(hfil,hdict,"cname",CHOPPERNAME); - SNXSPutDrivable(pServ->pSics, pCon,hfil,hdict, "chopperspeed", - "crot"); - SNXSPutDrivable(pServ->pSics, pCon,hfil,hdict,"chopper1phase", - "cphase1"); - SNXSPutDrivable(pServ->pSics, pCon,hfil,hdict, "chopper2phase", - "cphase2"); - - SNXSPutVariable(pServ->pSics,pCon,hfil, hdict,"crot", - "chopperrotation"); - - /* frame overlap mirror */ - SNXSPutVariable(pServ->pSics,pCon,hfil, hdict,"fomname", - "fomname"); - SNXSPutVariable(pServ->pSics,pCon,hfil, hdict,"fodist", - "fomdist"); - SNXSPutMotor(pServ->pSics,pCon,hfil,hdict,"fomh","ftz"); - SNXSPutMotor(pServ->pSics,pCon,hfil,hdict,"fomom","fom"); - - /* first Diaphragm */ - WriteDiaphragm(hfil,hdict,1,pCon); - sprintf(pThing,"d%1.1ddist",1); - SNXSPutVariable(pServ->pSics,pCon,hfil, hdict,pThing,pThing); - - /* polarizing, monochromating mirror */ - SNXSPutVariable(pServ->pSics,pCon,hfil, hdict,"polname", - "polname"); - SNXSPutVariable(pServ->pSics,pCon,hfil, hdict,"poldist", - "poldist"); - SNXSPutMotor(pServ->pSics,pCon,hfil,hdict,"polz","moz"); - SNXSPutMotor(pServ->pSics,pCon,hfil,hdict,"polom","mom"); - SNXSPutMotor(pServ->pSics,pCon,hfil,hdict,"poly","mty"); - SNXSPutMotor(pServ->pSics,pCon,hfil,hdict,"polzom","mtz"); - - /* second Diaphragm */ - WriteDiaphragm(hfil,hdict,2,pCon); - sprintf(pThing,"d%1.1ddist",2); - SNXSPutVariable(pServ->pSics,pCon,hfil, hdict,pThing,pThing); - - /* third Diaphragm */ - WriteDiaphragm(hfil,hdict,3,pCon); - sprintf(pThing,"d%1.1ddist",3); - SNXSPutVariable(pServ->pSics,pCon,hfil, hdict,pThing,pThing); - - /* sample table */ - SNXSPutVariable(pServ->pSics,pCon,hfil, hdict,"saname", - "sample"); - SNXSPutVariable(pServ->pSics,pCon,hfil, hdict,"stdist", - "sampledist"); - SNXSPutMotor(pServ->pSics,pCon,hfil,hdict,"somheight","stz"); - SNXSPutMotor(pServ->pSics,pCon,hfil,hdict,"schi","sch"); - SNXSPutMotor(pServ->pSics,pCon,hfil,hdict,"somega","som"); - SNXSPutMotor(pServ->pSics,pCon,hfil,hdict,"stheight","soz"); - fVal = ObVal(pAmor->aParameter,PARDH); - NXDputalias(hfil,hdict,"baseheight",&fVal); - - - /* fourth Diaphragm */ - WriteDiaphragm(hfil,hdict,4,pCon); - fVal = ObVal(pAmor->aParameter,PARDD4); - NXDputalias(hfil,hdict,"d4dist",&fVal); - fVal = ObVal(pAmor->aParameter,PARD4H); - NXDputalias(hfil,hdict,"d4base",&fVal); - - /* analyzer */ - SNXSPutVariable(pServ->pSics,pCon,hfil, hdict,"anname", - "ananame"); - SNXSPutVariable(pServ->pSics,pCon,hfil, hdict,"andist", - "anadist"); - SNXSPutMotor(pServ->pSics,pCon,hfil,hdict,"anoz","atz"); - SNXSPutMotor(pServ->pSics,pCon,hfil,hdict,"anom","aom"); - SNXSPutMotor(pServ->pSics,pCon,hfil,hdict,"antz","aoz"); - fVal = ObVal(pAmor->aParameter,PARADIS); - NXDputalias(hfil,hdict,"adis",&fVal); - fVal = ObVal(pAmor->aParameter,PARANA); - NXDputalias(hfil,hdict,"abase",&fVal); - - - /* fifth Diaphragm!!!!!!!!! */ - WriteDiaphragm(hfil,hdict,5,pCon); - fVal = ObVal(pAmor->aParameter,PARDD5); - NXDputalias(hfil,hdict,"d5dist",&fVal); - fVal = ObVal(pAmor->aParameter,PARD5H); - NXDputalias(hfil,hdict,"d5base",&fVal); - - /* counting data */ - pCom = FindCommand(pServ->pSics,"counter"); - if(pCom) - { - if(pCom->pData) - { - eMode = GetCounterMode((pCounter)pCom->pData); - if(eMode == eTimer) - { - strcpy(pBueffel,"timer"); - } - else - { - strcpy(pBueffel,"monitor"); - } - NXDputalias(hfil,hdict,"cnmode",pBueffel); - fVal = GetCounterPreset((pCounter)pCom->pData); - NXDputalias(hfil,hdict,"cnpreset",&fVal); - } - } - else - { - SCWrite(pCon,"WARNING: failed to find counter!",eWarning); - } - NXclose(&hfil); - NXDclose(hdict,NULL); - - return 1; + /* open files */ + NXsetcache(TOFBLOCK); + iRet = NXopen(file, NXACC_CREATE5, &hfil); + if (iRet != NX_OK) { + snprintf(pBueffel, 511, "ERROR: cannot open file %s for writing", + file); + SCWrite(pCon, pBueffel, eError); + return 0; } + iRet = NXDinitfromfile(AMORDICT, &hdict); + if (iRet != NX_OK) { + snprintf(pBueffel, 511, "ERROR: cannot open dictionary file %s", + AMORDICT); + SCWrite(pCon, pBueffel, eError); + return 0; + } + snprintf(pBueffel, 511, "Writing to: %s", file); + SCWrite(pCon, pBueffel, eWarning); + + /* put some global information */ + SNXSPutGlobals(hfil, file, "AMOR", pCon); + SNXSPutVariable(pServ->pSics, pCon, hfil, hdict, "etitle", "title"); + SNXFormatTime(pBueffel, 512); + NXDputalias(hfil, hdict, "estart", pBueffel); + + /* instrument vGroup */ + NXDputalias(hfil, hdict, "iname", INSTNAME); + + /* source */ + NXDputalias(hfil, hdict, "sname", SOURCENAME); + NXDputalias(hfil, hdict, "stype", SOURCETYPE); + + /* chopper */ + NXDputalias(hfil, hdict, "cname", CHOPPERNAME); + SNXSPutDrivable(pServ->pSics, pCon, hfil, hdict, "chopperspeed", "crot"); + SNXSPutDrivable(pServ->pSics, pCon, hfil, hdict, "chopper1phase", + "cphase1"); + SNXSPutDrivable(pServ->pSics, pCon, hfil, hdict, "chopper2phase", + "cphase2"); + + SNXSPutVariable(pServ->pSics, pCon, hfil, hdict, "crot", + "chopperrotation"); + + /* frame overlap mirror */ + SNXSPutVariable(pServ->pSics, pCon, hfil, hdict, "fomname", "fomname"); + SNXSPutVariable(pServ->pSics, pCon, hfil, hdict, "fodist", "fomdist"); + SNXSPutMotor(pServ->pSics, pCon, hfil, hdict, "fomh", "ftz"); + SNXSPutMotor(pServ->pSics, pCon, hfil, hdict, "fomom", "fom"); + + /* first Diaphragm */ + WriteDiaphragm(hfil, hdict, 1, pCon); + sprintf(pThing, "d%1.1ddist", 1); + SNXSPutVariable(pServ->pSics, pCon, hfil, hdict, pThing, pThing); + + /* polarizing, monochromating mirror */ + SNXSPutVariable(pServ->pSics, pCon, hfil, hdict, "polname", "polname"); + SNXSPutVariable(pServ->pSics, pCon, hfil, hdict, "poldist", "poldist"); + SNXSPutMotor(pServ->pSics, pCon, hfil, hdict, "polz", "moz"); + SNXSPutMotor(pServ->pSics, pCon, hfil, hdict, "polom", "mom"); + SNXSPutMotor(pServ->pSics, pCon, hfil, hdict, "poly", "mty"); + SNXSPutMotor(pServ->pSics, pCon, hfil, hdict, "polzom", "mtz"); + + /* second Diaphragm */ + WriteDiaphragm(hfil, hdict, 2, pCon); + sprintf(pThing, "d%1.1ddist", 2); + SNXSPutVariable(pServ->pSics, pCon, hfil, hdict, pThing, pThing); + + /* third Diaphragm */ + WriteDiaphragm(hfil, hdict, 3, pCon); + sprintf(pThing, "d%1.1ddist", 3); + SNXSPutVariable(pServ->pSics, pCon, hfil, hdict, pThing, pThing); + + /* sample table */ + SNXSPutVariable(pServ->pSics, pCon, hfil, hdict, "saname", "sample"); + SNXSPutVariable(pServ->pSics, pCon, hfil, hdict, "stdist", "sampledist"); + SNXSPutMotor(pServ->pSics, pCon, hfil, hdict, "somheight", "stz"); + SNXSPutMotor(pServ->pSics, pCon, hfil, hdict, "schi", "sch"); + SNXSPutMotor(pServ->pSics, pCon, hfil, hdict, "somega", "som"); + SNXSPutMotor(pServ->pSics, pCon, hfil, hdict, "stheight", "soz"); + fVal = ObVal(pAmor->aParameter, PARDH); + NXDputalias(hfil, hdict, "baseheight", &fVal); + + + /* fourth Diaphragm */ + WriteDiaphragm(hfil, hdict, 4, pCon); + fVal = ObVal(pAmor->aParameter, PARDD4); + NXDputalias(hfil, hdict, "d4dist", &fVal); + fVal = ObVal(pAmor->aParameter, PARD4H); + NXDputalias(hfil, hdict, "d4base", &fVal); + + /* analyzer */ + SNXSPutVariable(pServ->pSics, pCon, hfil, hdict, "anname", "ananame"); + SNXSPutVariable(pServ->pSics, pCon, hfil, hdict, "andist", "anadist"); + SNXSPutMotor(pServ->pSics, pCon, hfil, hdict, "anoz", "atz"); + SNXSPutMotor(pServ->pSics, pCon, hfil, hdict, "anom", "aom"); + SNXSPutMotor(pServ->pSics, pCon, hfil, hdict, "antz", "aoz"); + fVal = ObVal(pAmor->aParameter, PARADIS); + NXDputalias(hfil, hdict, "adis", &fVal); + fVal = ObVal(pAmor->aParameter, PARANA); + NXDputalias(hfil, hdict, "abase", &fVal); + + + /* fifth Diaphragm!!!!!!!!! */ + WriteDiaphragm(hfil, hdict, 5, pCon); + fVal = ObVal(pAmor->aParameter, PARDD5); + NXDputalias(hfil, hdict, "d5dist", &fVal); + fVal = ObVal(pAmor->aParameter, PARD5H); + NXDputalias(hfil, hdict, "d5base", &fVal); + + /* counting data */ + pCom = FindCommand(pServ->pSics, "counter"); + if (pCom) { + if (pCom->pData) { + eMode = GetCounterMode((pCounter) pCom->pData); + if (eMode == eTimer) { + strcpy(pBueffel, "timer"); + } else { + strcpy(pBueffel, "monitor"); + } + NXDputalias(hfil, hdict, "cnmode", pBueffel); + fVal = GetCounterPreset((pCounter) pCom->pData); + NXDputalias(hfil, hdict, "cnpreset", &fVal); + } + } else { + SCWrite(pCon, "WARNING: failed to find counter!", eWarning); + } + NXclose(&hfil); + NXDclose(hdict, NULL); + + return 1; +} + /*------------------------------------------------------------------------*/ - int WriteAmorScan(char *file, SConnection *pCon, pScanData pScan) - { - NXhandle hfil; - NXdict hdict; - int iRet, i; - char pBueffel[512], pDefinition[1024]; - CommandList *pCom = NULL; - float fVal; - float *fAxis = NULL; - long *lData = NULL; - int *iData = NULL; +int WriteAmorScan(char *file, SConnection * pCon, pScanData pScan) +{ + NXhandle hfil; + NXdict hdict; + int iRet, i; + char pBueffel[512], pDefinition[1024]; + CommandList *pCom = NULL; + float fVal; + float *fAxis = NULL; + long *lData = NULL; + int *iData = NULL; - /* open files */ - iRet = NXopen(file,NXACC_RDWR,&hfil); - if(iRet != NX_OK) - { - sprintf(pBueffel,"ERROR: cannot open file %s for writing",file); - SCWrite(pCon,pBueffel,eError); - return 0; - } - iRet = NXDinitfromfile(AMORDICT,&hdict); - if(iRet != NX_OK) - { - sprintf(pBueffel,"ERROR: cannot open dictionary file %s",AMORDICT); - SCWrite(pCon,pBueffel,eError); - return 0; - } - - - /* allocate memory for writing scan data */ - fAxis = (float *)malloc(pScan->iNP*sizeof(float)); - lData = (long *)malloc(pScan->iNP*sizeof(long)); - iData = (int *)malloc(pScan->iNP*sizeof(int)); - if( (!fAxis) || (!lData) || (!iData) ) - { - SCWrite(pCon,"ERROR: out of memory in WriteAmorScan",eError); - return 0; - } - memset(fAxis,0,pScan->iNP*sizeof(float)); - memset(lData,0,pScan->iNP*sizeof(long)); - memset(iData,0,pScan->iNP*sizeof(int)); - - /* write scan variables */ - for(i = 0; i < pScan->iScanVar; i++) - { - /* build definition string */ - NXDget(hdict,"scanroot",pBueffel, 512); - strcpy(pDefinition,pBueffel); - strcat(pDefinition," "); - GetScanVarName(pScan,i,pBueffel,512); - strcat(pDefinition,pBueffel); - sprintf(pBueffel," -rank 1 -dim {%d} ", pScan->iNP); - strcat(pDefinition,pBueffel); - if(i == 0) - { - strcat(pDefinition," -attr {axis,1}"); - } - /* get data and write */ - GetScanVar(pScan,i,fAxis,pScan->iNP); - NXDputdef(hfil,hdict,pDefinition,fAxis); - if(i == 0) - { - NXDget(hdict,"sdana",pBueffel,512); - NXDdeflink(hfil,hdict,pBueffel,pDefinition); - } - } - - /* - Write counted data: Here there is a convention which has to be - valid in amorscan as well: GetCounts gets the main detector. - GetMonitor 0 the second detector, GetMonitor 1 the first detector - other spin, GetMonitor 2, the second detector the other spin, - getMonitor 3, the first monitor, getMonitor 4 the second monitor - */ - sprintf(pBueffel,"%d",pScan->iNP); - NXDupdate(hdict,"scanlength",pBueffel); - GetScanCounts(pScan,lData,pScan->iNP); - for(i = 0; i < pScan->iNP; i++) - { - iData[i] = (int)lData[i]; - } - NXDputalias(hfil,hdict, "spinupup",iData); - NXDaliaslink(hfil,hdict,"sdana","spinupup"); - GetScanMonitor(pScan,0,lData,pScan->iNP); - for(i = 0; i < pScan->iNP; i++) - { - iData[i] = (int)lData[i]; - } - NXDputalias(hfil,hdict, "spinuplo",iData); - NXDaliaslink(hfil,hdict,"sdana","spinuplo"); - - /* monitors */ - GetScanMonitor(pScan,3,lData,pScan->iNP); - for(i = 0; i < pScan->iNP; i++) - { - iData[i] = (int)lData[i]; - } - NXDputalias(hfil,hdict, "smonitor1",iData); - GetScanMonitor(pScan,4,lData,pScan->iNP); - for(i = 0; i < pScan->iNP; i++) - { - iData[i] = (int)lData[i]; - } - NXDputalias(hfil,hdict, "smonitor2",iData); - - /* to be added: polarizing mode, possibly coz, cox, com etc. */ - - /* a few motors which may or may not be useful */ - SNXSPutMotor(pServ->pSics,pCon,hfil,hdict,"sdetx","cox"); - SNXSPutMotor(pServ->pSics,pCon,hfil,hdict,"sdetom","com"); - SNXSPutMotor(pServ->pSics,pCon,hfil,hdict,"sdetheight","coz"); - - /* close and go */ - NXclose(&hfil); - NXDclose(hdict,NULL); - free(fAxis); - free(lData); - free(iData); - - return 1; + /* open files */ + iRet = NXopen(file, NXACC_RDWR, &hfil); + if (iRet != NX_OK) { + sprintf(pBueffel, "ERROR: cannot open file %s for writing", file); + SCWrite(pCon, pBueffel, eError); + return 0; } + iRet = NXDinitfromfile(AMORDICT, &hdict); + if (iRet != NX_OK) { + sprintf(pBueffel, "ERROR: cannot open dictionary file %s", AMORDICT); + SCWrite(pCon, pBueffel, eError); + return 0; + } + + + /* allocate memory for writing scan data */ + fAxis = (float *) malloc(pScan->iNP * sizeof(float)); + lData = (long *) malloc(pScan->iNP * sizeof(long)); + iData = (int *) malloc(pScan->iNP * sizeof(int)); + if ((!fAxis) || (!lData) || (!iData)) { + SCWrite(pCon, "ERROR: out of memory in WriteAmorScan", eError); + return 0; + } + memset(fAxis, 0, pScan->iNP * sizeof(float)); + memset(lData, 0, pScan->iNP * sizeof(long)); + memset(iData, 0, pScan->iNP * sizeof(int)); + + /* write scan variables */ + for (i = 0; i < pScan->iScanVar; i++) { + /* build definition string */ + NXDget(hdict, "scanroot", pBueffel, 512); + strcpy(pDefinition, pBueffel); + strcat(pDefinition, " "); + GetScanVarName(pScan, i, pBueffel, 512); + strcat(pDefinition, pBueffel); + sprintf(pBueffel, " -rank 1 -dim {%d} ", pScan->iNP); + strcat(pDefinition, pBueffel); + if (i == 0) { + strcat(pDefinition, " -attr {axis,1}"); + } + /* get data and write */ + GetScanVar(pScan, i, fAxis, pScan->iNP); + NXDputdef(hfil, hdict, pDefinition, fAxis); + if (i == 0) { + NXDget(hdict, "sdana", pBueffel, 512); + NXDdeflink(hfil, hdict, pBueffel, pDefinition); + } + } + + /* + Write counted data: Here there is a convention which has to be + valid in amorscan as well: GetCounts gets the main detector. + GetMonitor 0 the second detector, GetMonitor 1 the first detector + other spin, GetMonitor 2, the second detector the other spin, + getMonitor 3, the first monitor, getMonitor 4 the second monitor + */ + sprintf(pBueffel, "%d", pScan->iNP); + NXDupdate(hdict, "scanlength", pBueffel); + GetScanCounts(pScan, lData, pScan->iNP); + for (i = 0; i < pScan->iNP; i++) { + iData[i] = (int) lData[i]; + } + NXDputalias(hfil, hdict, "spinupup", iData); + NXDaliaslink(hfil, hdict, "sdana", "spinupup"); + GetScanMonitor(pScan, 0, lData, pScan->iNP); + for (i = 0; i < pScan->iNP; i++) { + iData[i] = (int) lData[i]; + } + NXDputalias(hfil, hdict, "spinuplo", iData); + NXDaliaslink(hfil, hdict, "sdana", "spinuplo"); + + /* monitors */ + GetScanMonitor(pScan, 3, lData, pScan->iNP); + for (i = 0; i < pScan->iNP; i++) { + iData[i] = (int) lData[i]; + } + NXDputalias(hfil, hdict, "smonitor1", iData); + GetScanMonitor(pScan, 4, lData, pScan->iNP); + for (i = 0; i < pScan->iNP; i++) { + iData[i] = (int) lData[i]; + } + NXDputalias(hfil, hdict, "smonitor2", iData); + + /* to be added: polarizing mode, possibly coz, cox, com etc. */ + + /* a few motors which may or may not be useful */ + SNXSPutMotor(pServ->pSics, pCon, hfil, hdict, "sdetx", "cox"); + SNXSPutMotor(pServ->pSics, pCon, hfil, hdict, "sdetom", "com"); + SNXSPutMotor(pServ->pSics, pCon, hfil, hdict, "sdetheight", "coz"); + + /* close and go */ + NXclose(&hfil); + NXDclose(hdict, NULL); + free(fAxis); + free(lData); + free(iData); + + return 1; +} + /*----------------------------------------------------------------------- WriteTOFDetector writes the histogram memory data in TOF mode. As the histogram memory can become quite large at AMOR, the data is @@ -361,8 +338,8 @@ static int psdSave = 1; in this routine. -------------------------------------------------------------------------*/ static int WriteTOFDetector(char *name, pHistMem pHM, int *iDim, - NXhandle hfil, NXdict hdict, - SConnection *pCon) + NXhandle hfil, NXdict hdict, + SConnection * pCon) { int nChunk, chunkSize, iChunk[3], i, iStart[3], nTime, iRet; long iLength; @@ -371,467 +348,428 @@ static int WriteTOFDetector(char *name, pHistMem pHM, int *iDim, const float *fTime; int start; - fTime = GetHistTimeBin(pHM,&nTime); + fTime = GetHistTimeBin(pHM, &nTime); iDim[2] = nTime; - iLength = iDim[0]*iDim[1]*iDim[2]; - if( (iLength*4) < TOFBLOCK) - { - sprintf(pBueffel," -chunk {%d,%d,%d} ",iDim[0], iDim[1], iDim[2]); - NXDupdate(hdict,"chunk",pBueffel); - lData = (HistInt *)malloc(iLength*sizeof(HistInt)); - if(!lData) - { - SCWrite(pCon, - "ERROR: out of memory, failed to write histogram",eError); - SCSetInterrupt(pCon,eAbortBatch); - return 0; - } - memset(lData,0,iLength*sizeof(HistInt)); - iRet = GetHistogramDirect(pHM,pCon, - 0,0,iLength,lData,iLength*sizeof(HistInt)); - if(!iRet) - { - SCWrite(pCon,"ERROR: failed to read Hm data",eError); - SCSetInterrupt(pCon,eAbortBatch); - free(lData); - return 0; - } - SicsWait(2); - NXDputalias(hfil,hdict,name,lData); - NXDputalias(hfil,hdict,"detchunk",iDim); - NXDaliaslink(hfil,hdict,"dana",name); - } - else - { + iLength = iDim[0] * iDim[1] * iDim[2]; + if ((iLength * 4) < TOFBLOCK) { + sprintf(pBueffel, " -chunk {%d,%d,%d} ", iDim[0], iDim[1], iDim[2]); + NXDupdate(hdict, "chunk", pBueffel); + lData = (HistInt *) malloc(iLength * sizeof(HistInt)); + if (!lData) { + SCWrite(pCon, + "ERROR: out of memory, failed to write histogram", eError); + SCSetInterrupt(pCon, eAbortBatch); + return 0; + } + memset(lData, 0, iLength * sizeof(HistInt)); + iRet = GetHistogramDirect(pHM, pCon, + 0, 0, iLength, lData, + iLength * sizeof(HistInt)); + if (!iRet) { + SCWrite(pCon, "ERROR: failed to read Hm data", eError); + SCSetInterrupt(pCon, eAbortBatch); + free(lData); + return 0; + } + SicsWait(2); + NXDputalias(hfil, hdict, name, lData); + NXDputalias(hfil, hdict, "detchunk", iDim); + NXDaliaslink(hfil, hdict, "dana", name); + } else { /* - implement chunked writing. We strive to write layers in Y. The - number of chunks needs to fulfill three conditions then: - - multiple of xSize* timeBin; - - close to TOFBLOCK in size - - divide Y without remainder. - */ + implement chunked writing. We strive to write layers in Y. The + number of chunks needs to fulfill three conditions then: + - multiple of xSize* timeBin; + - close to TOFBLOCK in size + - divide Y without remainder. + */ iChunk[0] = iDim[0]; iChunk[2] = iDim[2]; iChunk[1] = 1; - chunkSize = iDim[0]*iDim[2]; - for(i = 1; i < 64; i++) - { - if( (iDim[1] % i) == 0) - { - if(i*chunkSize*sizeof(HistInt) < TOFBLOCK) - { - iChunk[1] = i; + chunkSize = iDim[0] * iDim[2]; + for (i = 1; i < 64; i++) { + if ((iDim[1] % i) == 0) { + if (i * chunkSize * sizeof(HistInt) < TOFBLOCK) { + iChunk[1] = i; } } } - sprintf(pBueffel,"Segmented TOF data in %d chunks",iDim[1]/iChunk[1]); - SCWrite(pCon,pBueffel,eWarning); + sprintf(pBueffel, "Segmented TOF data in %d chunks", + iDim[1] / iChunk[1]); + SCWrite(pCon, pBueffel, eWarning); /* now we have a chunkSize, lets go and write! - */ - NXDputalias(hfil,hdict,"detchunk",iChunk); - chunkSize = iChunk[1]*iChunk[0]*iChunk[2]; - sprintf(pBueffel," -chunk {%d,%d,%d} ",iChunk[0], iChunk[1], iChunk[2]); - NXDupdate(hdict,"chunk",pBueffel); - lData = (HistInt *)malloc(chunkSize*sizeof(HistInt)); - if(!lData) - { - SCWrite(pCon,"ERROR: out of memory while writing TOF data", - eError); - SCSetInterrupt(pCon,eAbortBatch); + */ + NXDputalias(hfil, hdict, "detchunk", iChunk); + chunkSize = iChunk[1] * iChunk[0] * iChunk[2]; + sprintf(pBueffel, " -chunk {%d,%d,%d} ", iChunk[0], iChunk[1], + iChunk[2]); + NXDupdate(hdict, "chunk", pBueffel); + lData = (HistInt *) malloc(chunkSize * sizeof(HistInt)); + if (!lData) { + SCWrite(pCon, "ERROR: out of memory while writing TOF data", eError); + SCSetInterrupt(pCon, eAbortBatch); return 0; } - NXDopenalias(hfil,hdict,name); - for(i = 0; i < iDim[1]/iChunk[1]; i++) - { - memset(lData,0,chunkSize*sizeof(HistInt)); - iRet = GetHistogramDirect(pHM,pCon, - 0,i*chunkSize,(i+1)*chunkSize,lData, - chunkSize*sizeof(HistInt)); - if(!iRet) - { - SCWrite(pCon,"ERROR: failed to read HM data",eError); - SCSetInterrupt(pCon,eAbortBatch); - free(lData); - return 0; + NXDopenalias(hfil, hdict, name); + for (i = 0; i < iDim[1] / iChunk[1]; i++) { + memset(lData, 0, chunkSize * sizeof(HistInt)); + iRet = GetHistogramDirect(pHM, pCon, + 0, i * chunkSize, (i + 1) * chunkSize, + lData, chunkSize * sizeof(HistInt)); + if (!iRet) { + SCWrite(pCon, "ERROR: failed to read HM data", eError); + SCSetInterrupt(pCon, eAbortBatch); + free(lData); + return 0; } /* - yield a little in order to allow other clients to receive a - response. Also allow for interrupting. - */ + yield a little in order to allow other clients to receive a + response. Also allow for interrupting. + */ SicsWait(2); iStart[0] = 0; - iStart[1] = i*iChunk[1]; + iStart[1] = i * iChunk[1]; iStart[2] = 0; - NXputslab(hfil,lData,iStart, iChunk); - sprintf(pBueffel,"Wrote chunk %d", i); - SCWrite(pCon,pBueffel,eWarning); + NXputslab(hfil, lData, iStart, iChunk); + sprintf(pBueffel, "Wrote chunk %d", i); + SCWrite(pCon, pBueffel, eWarning); /* - yield a little in order to allow other clients to receive a - response. Also allow for interrupting. - */ + yield a little in order to allow other clients to receive a + response. Also allow for interrupting. + */ SicsWait(2); } /* - close groups till root - */ + close groups till root + */ NXclosedata(hfil); NXclosegroup(hfil); NXclosegroup(hfil); NXclosegroup(hfil); /* - make link - */ - NXDaliaslink(hfil,hdict,"dana",name); - NXDaliaslink(hfil,hdict,"dana","detchunk"); + make link + */ + NXDaliaslink(hfil, hdict, "dana", name); + NXDaliaslink(hfil, hdict, "dana", "detchunk"); } - if(lData) - free(lData); - return 1; + if (lData) + free(lData); + return 1; } + /*-----------------------------------------------------------------------*/ - int WriteAmorTOF(char *file, SConnection *pCon, pHistMem pHM) - { - NXhandle hfil; - NXdict hdict; - int iRet, i, iLength; - char pBueffel[512]; - float fVal, *fAxis = NULL, *fTime2 = NULL; - CommandList *pCom = NULL; - const float *fTime; - HistInt *lData = NULL, lVal; - int detxsize, detysize, iDim[MAXDIM]; +int WriteAmorTOF(char *file, SConnection * pCon, pHistMem pHM) +{ + NXhandle hfil; + NXdict hdict; + int iRet, i, iLength; + char pBueffel[512]; + float fVal, *fAxis = NULL, *fTime2 = NULL; + CommandList *pCom = NULL; + const float *fTime; + HistInt *lData = NULL, lVal; + int detxsize, detysize, iDim[MAXDIM]; - /* open files */ - iRet = NXopen(file,NXACC_RDWR,&hfil); - if(iRet != NX_OK) - { - sprintf(pBueffel,"ERROR: cannot open file %s for writing",file); - SCWrite(pCon,pBueffel,eError); - return 0; - } - iRet = NXDinitfromfile(AMORDICT,&hdict); - if(iRet != NX_OK) - { - sprintf(pBueffel,"ERROR: cannot open dictionary file %s",AMORDICT); - SCWrite(pCon,pBueffel,eError); - return 0; - } - - - /* a few motors which may or may not be useful */ - SNXSPutMotor(pServ->pSics,pCon,hfil,hdict,"detx","cox"); - SNXSPutMotor(pServ->pSics,pCon,hfil,hdict,"detom","com"); - SNXSPutMotor(pServ->pSics,pCon,hfil,hdict,"detheight","coz"); - - /* write counter related stuff */ - pCom = FindCommand(pServ->pSics,"counter"); - if(pCom) - { - if(pCom->pData) - { - fVal = GetCountTime((pCounter)pCom->pData,pCon); - NXDputalias(hfil,hdict,"cntime",&fVal); - - /* the assignment of monitors has to be checked once - the Schlumpf is done - */ - lVal = GetMonitor((pCounter)pCom->pData,1, pCon); - NXDputalias(hfil,hdict,"cnmon1",&lVal); - lVal = GetMonitor((pCounter)pCom->pData,4, pCon); - NXDputalias(hfil,hdict,"cnmon2",&lVal); - } - } - else - { - SCWrite(pCon,"WARNING: failed to find counter!",eWarning); - } - - /* - find dimensions of detector - */ - GetHistDim(pHM,iDim,&iLength); - detxsize = iDim[0]; - detysize = iDim[1]; - /* update detector size */ - sprintf(pBueffel,"%d",detxsize); - NXDupdate(hdict,"detxsize",pBueffel); - sprintf(pBueffel,"%d",detysize); - NXDupdate(hdict,"detysize",pBueffel); - - - /* write two axis */ - if(detxsize > detysize) - iLength = detxsize; - else - iLength = detysize; - - fAxis = (float *)malloc(iLength*sizeof(float)); - if(!fAxis) - { - SCWrite(pCon,"ERROR: out of memory in WriteAmorTOF",eError); - return 0; - } - for(i = 0; i < detxsize; i++) - { - fAxis[i] = (float)i; - } - NXDputalias(hfil,hdict,"detxx",fAxis); - for(i = 0; i < detysize; i++) - { - fAxis[i] = (float)i; - } - NXDputalias(hfil,hdict,"dety",fAxis); - NXDaliaslink(hfil,hdict,"dana","detxx"); - NXDaliaslink(hfil,hdict,"dana","dety"); - free(fAxis); - - - /* add height and distances */ - fVal = ObVal(pAmor->aParameter,PARDS); - NXDputalias(hfil,hdict,"detdist",&fVal); - fVal = ObVal(pAmor->aParameter,PARDDH); - NXDputalias(hfil,hdict,"detbase",&fVal); - - - /* deal with time binning */ - fTime = GetHistTimeBin(pHM,&iLength); - iDim[2] = iLength; - fTime2 = (float *)malloc(iLength*sizeof(float)); - if(fTime2) - { - for(i = 0; i < iLength; i++) - { - fTime2[i] = fTime[i]/10.; - } - sprintf(pBueffel,"%d",iLength); - NXDupdate(hdict,"timebin",pBueffel); - NXDputalias(hfil,hdict,"dettime",fTime2); - NXDputalias(hfil,hdict,"singletime",fTime2); - NXDaliaslink(hfil,hdict,"dana","dettime"); - free(fTime2); - fTime2 = NULL; - } - else - { - SCWrite(pCon,"ERROR: out of memory while writing time binning", - eError); - SCSetInterrupt(pCon,eAbortBatch); - NXclose(&hfil); - NXDclose(hdict,NULL); - return 0; - } - - /* finally get histogram */ - if(iDim[2] == 2) /* 2D data, no time binning on this detector */ - { - iLength = detxsize*detysize; - lData = (HistInt *)malloc(iLength*sizeof(HistInt)); - if(!lData) - { - SCWrite(pCon, - "ERROR: out of memory, failed to write histogram",eError); - NXclose(&hfil); - NXDclose(hdict,NULL); - SCSetInterrupt(pCon,eAbortBatch); - return 0; - } - memset(lData,0,iLength*sizeof(HistInt)); - iRet = GetHistogram(pHM,pCon, 0,0,iLength, - lData,iLength*sizeof(HistInt)); - if(!iRet) - { - SCWrite(pCon,"ERROR: failed to read HM", eError); - SCSetInterrupt(pCon,eAbortBatch); - NXclose(&hfil); - NXDclose(hdict,NULL); - return 0; - } - NXDputalias(hfil,hdict,"spinup2d",lData); - NXDaliaslink(hfil,hdict,"dana","spinup2d"); - } - else - { - if(psdSave){ - iRet = WriteTOFDetector("spinup",pHM, iDim,hfil,hdict,pCon); - if(!iRet) - { - NXclose(&hfil); - NXDclose(hdict,NULL); - return 0; - } - } else { - SCWrite(pCon,"PSD writing supressed!",eWarning); - } -#define MAXSINGLE 3 - /* - now get and write single detectors - */ - iLength = iDim[0]*iDim[1]*iDim[2]; - lData = (HistInt *)malloc(MAXSINGLE*iDim[2]*sizeof(HistInt)); - if(!lData) - { - SCWrite(pCon,"ERROR: out of memory while writing single detectors", - eError); - SCSetInterrupt(pCon,eAbortBatch); - NXclose(&hfil); - NXDclose(hdict,NULL); - return 0; - } - else - { - memset(lData,0,MAXSINGLE*iDim[2]*sizeof(HistInt)); - iRet = GetHistogramDirect(pHM,pCon,0,iLength, - iLength + MAXSINGLE*iDim[2], - lData, MAXSINGLE*iDim[2]*sizeof(HistInt)); - if(!iRet) - { - SCWrite(pCon,"ERROR: failed to read single detector HM data", - eError); - SCSetInterrupt(pCon,eAbortBatch); - free(lData); - NXclose(&hfil); - NXDclose(hdict,NULL); - return 0; - } - NXDputalias(hfil,hdict,"singleup",lData); - NXDaliaslink(hfil,hdict,"singledana","singleup"); - NXDaliaslink(hfil,hdict,"singledana","singletime"); - /* - the TOF monitor - */ - NXDputalias(hfil,hdict,"singletofmon",lData+2*iDim[2]); - NXDaliaslink(hfil,hdict,"dana","singletofmon"); - NXDaliaslink(hfil,hdict,"singledana","singletofmon"); - } - } - - /* to do: add polarizing code */ - - if(lData) - free(lData); - - NXclose(&hfil); - NXDclose(hdict,NULL); - - return 1; + /* open files */ + iRet = NXopen(file, NXACC_RDWR, &hfil); + if (iRet != NX_OK) { + sprintf(pBueffel, "ERROR: cannot open file %s for writing", file); + SCWrite(pCon, pBueffel, eError); + return 0; + } + iRet = NXDinitfromfile(AMORDICT, &hdict); + if (iRet != NX_OK) { + sprintf(pBueffel, "ERROR: cannot open dictionary file %s", AMORDICT); + SCWrite(pCon, pBueffel, eError); + return 0; } -/*-----------------------------------------------------------------------*/ - static pHistMem pMeme = NULL; - - int AmorStore(SConnection *pCon, SicsInterp *pSics, void *pData, - int argc, char *argv[]) - { - char pBueffel[512], *pFile = NULL; - int iRet, iFlag; - Status oldStatus; - - /* - if arguments, check for psdsave - */ - if(argc > 1){ - strtolower(argv[1]); - if(strcmp(argv[1],"psdsave") == 0){ - if(argc > 2){ - psdSave = atof(argv[2]); - SCSendOK(pCon); - return 1; - } else { - sprintf(pBueffel,"storeamor.psdSave = %d",psdSave); - SCWrite(pCon,pBueffel,eValue); - return 1; - } - } - } - pFile = SNXMakeFileName(pSics,pCon); - sprintf(pBueffel,"Writing file %s .....",pFile); - SCWrite(pCon,pBueffel,eWarning); - - oldStatus = GetStatus(); - SetStatus(eWriting); - LockDeviceExecutor(pServ->pExecutor); - iRet = WriteAmorHeader(pFile,pCon); - if(iRet) - { - iRet = WriteAmorTOF(pFile,pCon,pMeme); - } - SetStatus(oldStatus); - UnlockDeviceExecutor(pServ->pExecutor); - free(pFile); - SCSendOK(pCon); - return iRet; - } -/*---------------------------------------------------------------------*/ - int AmorStoreMake(SConnection *pCon, SicsInterp *pSics, void *pData, - int argc, char *argv[]) - { - CommandList *pCom = NULL; - char pBueffel[512]; - int iRet; + /* a few motors which may or may not be useful */ + SNXSPutMotor(pServ->pSics, pCon, hfil, hdict, "detx", "cox"); + SNXSPutMotor(pServ->pSics, pCon, hfil, hdict, "detom", "com"); + SNXSPutMotor(pServ->pSics, pCon, hfil, hdict, "detheight", "coz"); - if(argc < 3) - { - SCWrite(pCon, - "ERROR: insufficient number of arguments to AmorStoreMake", - eError); + /* write counter related stuff */ + pCom = FindCommand(pServ->pSics, "counter"); + if (pCom) { + if (pCom->pData) { + fVal = GetCountTime((pCounter) pCom->pData, pCon); + NXDputalias(hfil, hdict, "cntime", &fVal); + + /* the assignment of monitors has to be checked once + the Schlumpf is done + */ + lVal = GetMonitor((pCounter) pCom->pData, 1, pCon); + NXDputalias(hfil, hdict, "cnmon1", &lVal); + lVal = GetMonitor((pCounter) pCom->pData, 4, pCon); + NXDputalias(hfil, hdict, "cnmon2", &lVal); + } + } else { + SCWrite(pCon, "WARNING: failed to find counter!", eWarning); + } + + /* + find dimensions of detector + */ + GetHistDim(pHM, iDim, &iLength); + detxsize = iDim[0]; + detysize = iDim[1]; + /* update detector size */ + sprintf(pBueffel, "%d", detxsize); + NXDupdate(hdict, "detxsize", pBueffel); + sprintf(pBueffel, "%d", detysize); + NXDupdate(hdict, "detysize", pBueffel); + + + /* write two axis */ + if (detxsize > detysize) + iLength = detxsize; + else + iLength = detysize; + + fAxis = (float *) malloc(iLength * sizeof(float)); + if (!fAxis) { + SCWrite(pCon, "ERROR: out of memory in WriteAmorTOF", eError); + return 0; + } + for (i = 0; i < detxsize; i++) { + fAxis[i] = (float) i; + } + NXDputalias(hfil, hdict, "detxx", fAxis); + for (i = 0; i < detysize; i++) { + fAxis[i] = (float) i; + } + NXDputalias(hfil, hdict, "dety", fAxis); + NXDaliaslink(hfil, hdict, "dana", "detxx"); + NXDaliaslink(hfil, hdict, "dana", "dety"); + free(fAxis); + + + /* add height and distances */ + fVal = ObVal(pAmor->aParameter, PARDS); + NXDputalias(hfil, hdict, "detdist", &fVal); + fVal = ObVal(pAmor->aParameter, PARDDH); + NXDputalias(hfil, hdict, "detbase", &fVal); + + + /* deal with time binning */ + fTime = GetHistTimeBin(pHM, &iLength); + iDim[2] = iLength; + fTime2 = (float *) malloc(iLength * sizeof(float)); + if (fTime2) { + for (i = 0; i < iLength; i++) { + fTime2[i] = fTime[i] / 10.; + } + sprintf(pBueffel, "%d", iLength); + NXDupdate(hdict, "timebin", pBueffel); + NXDputalias(hfil, hdict, "dettime", fTime2); + NXDputalias(hfil, hdict, "singletime", fTime2); + NXDaliaslink(hfil, hdict, "dana", "dettime"); + free(fTime2); + fTime2 = NULL; + } else { + SCWrite(pCon, "ERROR: out of memory while writing time binning", + eError); + SCSetInterrupt(pCon, eAbortBatch); + NXclose(&hfil); + NXDclose(hdict, NULL); + return 0; + } + + /* finally get histogram */ + if (iDim[2] == 2) { /* 2D data, no time binning on this detector */ + iLength = detxsize * detysize; + lData = (HistInt *) malloc(iLength * sizeof(HistInt)); + if (!lData) { + SCWrite(pCon, + "ERROR: out of memory, failed to write histogram", eError); + NXclose(&hfil); + NXDclose(hdict, NULL); + SCSetInterrupt(pCon, eAbortBatch); + return 0; + } + memset(lData, 0, iLength * sizeof(HistInt)); + iRet = GetHistogram(pHM, pCon, 0, 0, iLength, + lData, iLength * sizeof(HistInt)); + if (!iRet) { + SCWrite(pCon, "ERROR: failed to read HM", eError); + SCSetInterrupt(pCon, eAbortBatch); + NXclose(&hfil); + NXDclose(hdict, NULL); + return 0; + } + NXDputalias(hfil, hdict, "spinup2d", lData); + NXDaliaslink(hfil, hdict, "dana", "spinup2d"); + } else { + if (psdSave) { + iRet = WriteTOFDetector("spinup", pHM, iDim, hfil, hdict, pCon); + if (!iRet) { + NXclose(&hfil); + NXDclose(hdict, NULL); return 0; - } - - /* we need a parameter which is the name of the histogram memory*/ - pCom = FindCommand(pServ->pSics,argv[1]); - if(!pCom) - { - sprintf(pBueffel,"ERROR: Histogram memory %s NOT found", argv[1]); - SCWrite(pCon,pBueffel,eError); - return 0; - } - if(!pCom->pData) - { - sprintf(pBueffel,"ERROR: Histogram memory %s NOT found", argv[1]); - SCWrite(pCon,pBueffel,eError); - return 0; - } - pMeme = (pHistMem)pCom->pData; - - /* we need another parameter which is the name of the - 2theta calculation module + } + } else { + SCWrite(pCon, "PSD writing supressed!", eWarning); + } +#define MAXSINGLE 3 + /* + now get and write single detectors */ - pCom = FindCommand(pServ->pSics,argv[2]); - if(!pCom) - { - sprintf(pBueffel,"ERROR: amor2T module %s NOT found", argv[2]); - SCWrite(pCon,pBueffel,eError); - return 0; - } - if(!pCom->pData) - { - sprintf(pBueffel,"ERROR: amor2t module %s NOT found", argv[2]); - SCWrite(pCon,pBueffel,eError); - return 0; - } - pAmor = (pAmor2T)pCom->pData; - if(argc > 3) { - strncpy(AMORDICT,argv[3],1023); - } + iLength = iDim[0] * iDim[1] * iDim[2]; + lData = (HistInt *) malloc(MAXSINGLE * iDim[2] * sizeof(HistInt)); + if (!lData) { + SCWrite(pCon, "ERROR: out of memory while writing single detectors", + eError); + SCSetInterrupt(pCon, eAbortBatch); + NXclose(&hfil); + NXDclose(hdict, NULL); + return 0; + } else { + memset(lData, 0, MAXSINGLE * iDim[2] * sizeof(HistInt)); + iRet = GetHistogramDirect(pHM, pCon, 0, iLength, + iLength + MAXSINGLE * iDim[2], + lData, + MAXSINGLE * iDim[2] * sizeof(HistInt)); + if (!iRet) { + SCWrite(pCon, "ERROR: failed to read single detector HM data", + eError); + SCSetInterrupt(pCon, eAbortBatch); + free(lData); + NXclose(&hfil); + NXDclose(hdict, NULL); + return 0; + } + NXDputalias(hfil, hdict, "singleup", lData); + NXDaliaslink(hfil, hdict, "singledana", "singleup"); + NXDaliaslink(hfil, hdict, "singledana", "singletime"); + /* + the TOF monitor + */ + NXDputalias(hfil, hdict, "singletofmon", lData + 2 * iDim[2]); + NXDaliaslink(hfil, hdict, "dana", "singletofmon"); + NXDaliaslink(hfil, hdict, "singledana", "singletofmon"); + } + } + + /* to do: add polarizing code */ + + if (lData) + free(lData); + + NXclose(&hfil); + NXDclose(hdict, NULL); + + return 1; +} + +/*-----------------------------------------------------------------------*/ +static pHistMem pMeme = NULL; + +int AmorStore(SConnection * pCon, SicsInterp * pSics, void *pData, + int argc, char *argv[]) +{ + char pBueffel[512], *pFile = NULL; + int iRet, iFlag; + Status oldStatus; + + /* + if arguments, check for psdsave + */ + if (argc > 1) { + strtolower(argv[1]); + if (strcmp(argv[1], "psdsave") == 0) { + if (argc > 2) { + psdSave = atof(argv[2]); + SCSendOK(pCon); + return 1; + } else { + sprintf(pBueffel, "storeamor.psdSave = %d", psdSave); + SCWrite(pCon, pBueffel, eValue); + return 1; + } + } + } - /* install command */ - iRet = AddCommand(pSics,"storeamor", - AmorStore,NULL,NULL); - if(!iRet) - { - sprintf(pBueffel,"ERROR: duplicate command amorstore NOT created"); - SCWrite(pCon,pBueffel,eError); - return 0; - } - return 1; - } - + pFile = SNXMakeFileName(pSics, pCon); + sprintf(pBueffel, "Writing file %s .....", pFile); + SCWrite(pCon, pBueffel, eWarning); + + oldStatus = GetStatus(); + SetStatus(eWriting); + LockDeviceExecutor(pServ->pExecutor); + iRet = WriteAmorHeader(pFile, pCon); + if (iRet) { + iRet = WriteAmorTOF(pFile, pCon, pMeme); + } + SetStatus(oldStatus); + UnlockDeviceExecutor(pServ->pExecutor); + free(pFile); + SCSendOK(pCon); + return iRet; +} + +/*---------------------------------------------------------------------*/ +int AmorStoreMake(SConnection * pCon, SicsInterp * pSics, void *pData, + int argc, char *argv[]) +{ + CommandList *pCom = NULL; + char pBueffel[512]; + int iRet; + + if (argc < 3) { + SCWrite(pCon, + "ERROR: insufficient number of arguments to AmorStoreMake", + eError); + return 0; + } + + /* we need a parameter which is the name of the histogram memory */ + pCom = FindCommand(pServ->pSics, argv[1]); + if (!pCom) { + sprintf(pBueffel, "ERROR: Histogram memory %s NOT found", argv[1]); + SCWrite(pCon, pBueffel, eError); + return 0; + } + if (!pCom->pData) { + sprintf(pBueffel, "ERROR: Histogram memory %s NOT found", argv[1]); + SCWrite(pCon, pBueffel, eError); + return 0; + } + pMeme = (pHistMem) pCom->pData; + + /* we need another parameter which is the name of the + 2theta calculation module + */ + pCom = FindCommand(pServ->pSics, argv[2]); + if (!pCom) { + sprintf(pBueffel, "ERROR: amor2T module %s NOT found", argv[2]); + SCWrite(pCon, pBueffel, eError); + return 0; + } + if (!pCom->pData) { + sprintf(pBueffel, "ERROR: amor2t module %s NOT found", argv[2]); + SCWrite(pCon, pBueffel, eError); + return 0; + } + pAmor = (pAmor2T) pCom->pData; + if (argc > 3) { + strncpy(AMORDICT, argv[3], 1023); + } + /* install command */ + iRet = AddCommand(pSics, "storeamor", AmorStore, NULL, NULL); + if (!iRet) { + sprintf(pBueffel, "ERROR: duplicate command amorstore NOT created"); + SCWrite(pCon, pBueffel, eError); + return 0; + } + return 1; +} diff --git a/nxamor.h b/nxamor.h index 138cd04..628dced 100644 --- a/nxamor.h +++ b/nxamor.h @@ -14,16 +14,16 @@ #include #include - int WriteAmorHeader(char *file, SConnection *pCon); +int WriteAmorHeader(char *file, SConnection * pCon); - int WriteAmorScan(char *file, SConnection *pCon, pScanData pScan); +int WriteAmorScan(char *file, SConnection * pCon, pScanData pScan); - int WriteAmorTOF(char *file, SConnection *pCon, pHistMem pHM); +int WriteAmorTOF(char *file, SConnection * pCon, pHistMem pHM); - int AmorStore(SConnection *pCon, SicsInterp *pSics, void *pData, - int argc, char *argv[]); - int AmorStoreMake(SConnection *pCon, SicsInterp *pSics, void *pData, - int argc, char *argv[]); +int AmorStore(SConnection * pCon, SicsInterp * pSics, void *pData, + int argc, char *argv[]); +int AmorStoreMake(SConnection * pCon, SicsInterp * pSics, void *pData, + int argc, char *argv[]); #endif diff --git a/nxsans.c b/nxsans.c index 3c0ffca..a4b58db 100644 --- a/nxsans.c +++ b/nxsans.c @@ -54,7 +54,7 @@ #include "modriv.h" #include "motor.h" #include "nxutil.h" -#include "nxdata.h" +#include "nxdata.h" #include "countdriv.h" #include "counter.h" #include "danu.h" @@ -69,728 +69,637 @@ #define HISTNAME "banana" #define SAMPLETABLE "sampletable" -static int gummiFlag = 0; /* a flag indicating stroboscopic, or gummi mode */ +static int gummiFlag = 0; /* a flag indicating stroboscopic, or gummi mode */ /*-----------------------------------------------------------------------*/ - static void SNError(void *pData, char *text) - { - SConnection *pCon; - - assert(pData); - pCon = (SConnection *)pData; - SCWrite(pCon,text,eError); +static void SNError(void *pData, char *text) +{ + SConnection *pCon; + + assert(pData); + pCon = (SConnection *) pData; + SCWrite(pCon, text, eError); +} + +/*-------------------------------------------------------------------------*/ +NXhandle SNXStartSANS(SConnection * pCon, SicsInterp * pSics) +{ + NXhandle pFile = NULL; + char *filename = NULL; + pSicsVariable pVar = NULL; + int iStat; + char pBueffel[512]; + + /* get a filename */ + filename = SNXMakeFileName(pSics, pCon); + if (!filename) { + return NULL; } -/*-------------------------------------------------------------------------*/ - NXhandle SNXStartSANS(SConnection *pCon, SicsInterp *pSics) - { - NXhandle pFile = NULL; - char *filename = NULL; - pSicsVariable pVar = NULL; - int iStat; - char pBueffel[512]; - - /* get a filename */ - filename = SNXMakeFileName(pSics,pCon); - if(!filename) - { - return NULL; - } - - /* create a Nexus file */ - NXopen(filename,NXACC_CREATE,&pFile); - if(!pFile) - { - SCWrite(pCon,"ERROR: cannot create data file ",eError); - return NULL; - } - - /* tell Uwe User what we are doing */ - sprintf(pBueffel,"Writing %s ......",filename); - SCWrite(pCon,pBueffel,eWarning); - - /* store global attributes */ - iStat = NXputattr(pFile,"file_name",filename, - strlen(filename)+1,NX_CHAR); - if(iStat == NX_ERROR) - { - SCWrite(pCon,"ERROR: writing file_name attribute to Nexus file",eError); - } - - /* throw away filename, no longer needed */ - free(filename); - /* write creation time */ - SNXFormatTime(pBueffel,512); - iStat = NXputattr(pFile,"file_time",pBueffel, - strlen(pBueffel)+1,NX_CHAR); - if(iStat == NX_ERROR) - { - SCWrite(pCon,"ERROR: writing date attribute to Nexus file",eError); - } - pVar = FindVariable(pSics,"instrument"); - if(pVar) - { - iStat = NXputattr(pFile,"instrument",pVar->text, - strlen(pVar->text)+1,NX_CHAR); - if(iStat == NX_ERROR) - { - SCWrite(pCon,"ERROR: writing instrument attribute to Nexus file",eError); - } - } - pVar = NULL; - pVar = FindVariable(pSics,"user"); - if(pVar) - { - iStat = NXputattr(pFile,"owner",pVar->text, - strlen(pVar->text)+1,NX_CHAR); - if(iStat == NX_ERROR) - { - SCWrite(pCon,"ERROR: writing owner attribute to Nexus file",eError); - } - } + /* create a Nexus file */ + NXopen(filename, NXACC_CREATE, &pFile); + if (!pFile) { + SCWrite(pCon, "ERROR: cannot create data file ", eError); + return NULL; + } + + /* tell Uwe User what we are doing */ + sprintf(pBueffel, "Writing %s ......", filename); + SCWrite(pCon, pBueffel, eWarning); + + /* store global attributes */ + iStat = NXputattr(pFile, "file_name", filename, + strlen(filename) + 1, NX_CHAR); + if (iStat == NX_ERROR) { + SCWrite(pCon, "ERROR: writing file_name attribute to Nexus file", + eError); + } + + /* throw away filename, no longer needed */ + free(filename); + + /* write creation time */ + SNXFormatTime(pBueffel, 512); + iStat = NXputattr(pFile, "file_time", pBueffel, + strlen(pBueffel) + 1, NX_CHAR); + if (iStat == NX_ERROR) { + SCWrite(pCon, "ERROR: writing date attribute to Nexus file", eError); + } + pVar = FindVariable(pSics, "instrument"); + if (pVar) { + iStat = NXputattr(pFile, "instrument", pVar->text, + strlen(pVar->text) + 1, NX_CHAR); + if (iStat == NX_ERROR) { + SCWrite(pCon, "ERROR: writing instrument attribute to Nexus file", + eError); + } + } + pVar = NULL; + pVar = FindVariable(pSics, "user"); + if (pVar) { + iStat = NXputattr(pFile, "owner", pVar->text, + strlen(pVar->text) + 1, NX_CHAR); + if (iStat == NX_ERROR) { + SCWrite(pCon, "ERROR: writing owner attribute to Nexus file", + eError); + } + } + + pVar = NULL; + pVar = FindVariable(pSics, "adress"); + if (pVar) { + iStat = NXputattr(pFile, "owner_adress", pVar->text, + strlen(pVar->text) + 1, NX_CHAR); + if (iStat == NX_ERROR) { + SCWrite(pCon, "ERROR: writing owner_adress attribute to Nexus file", + eError); + } + } + pVar = NULL; + pVar = FindVariable(pSics, "phone"); + if (pVar) { + iStat = NXputattr(pFile, "owner_telephone_number", pVar->text, + strlen(pVar->text) + 1, NX_CHAR); + if (iStat == NX_ERROR) { + SCWrite(pCon, + "ERROR: writing owner_telephone_number attribute to Nexus file", + eError); + } + } + pVar = NULL; + pVar = FindVariable(pSics, "fax"); + if (pVar) { + iStat = NXputattr(pFile, "owner_fax_number", pVar->text, + strlen(pVar->text) + 1, NX_CHAR); + if (iStat == NX_ERROR) { + SCWrite(pCon, + "ERROR: writing owner_fax_number attribute to Nexus file", + eError); + } + } + pVar = NULL; + pVar = FindVariable(pSics, "email"); + if (pVar) { + iStat = NXputattr(pFile, "owner_email", pVar->text, + strlen(pVar->text) + 1, NX_CHAR); + if (iStat == NX_ERROR) { + SCWrite(pCon, "ERROR: writing owner_email attribute to Nexus file", + eError); + } + } + pVar = NULL; + return pFile; +} - pVar = NULL; - pVar = FindVariable(pSics,"adress"); - if(pVar) - { - iStat = NXputattr(pFile,"owner_adress",pVar->text, - strlen(pVar->text)+1,NX_CHAR); - if(iStat == NX_ERROR) - { - SCWrite(pCon,"ERROR: writing owner_adress attribute to Nexus file",eError); - } - } - pVar = NULL; - pVar = FindVariable(pSics,"phone"); - if(pVar) - { - iStat = NXputattr(pFile,"owner_telephone_number",pVar->text, - strlen(pVar->text)+1,NX_CHAR); - if(iStat == NX_ERROR) - { - SCWrite(pCon,"ERROR: writing owner_telephone_number attribute to Nexus file",eError); - } - } - pVar = NULL; - pVar = FindVariable(pSics,"fax"); - if(pVar) - { - iStat = NXputattr(pFile,"owner_fax_number",pVar->text, - strlen(pVar->text)+1,NX_CHAR); - if(iStat == NX_ERROR) - { - SCWrite(pCon,"ERROR: writing owner_fax_number attribute to Nexus file",eError); - } - } - pVar = NULL; - pVar = FindVariable(pSics,"email"); - if(pVar) - { - iStat = NXputattr(pFile,"owner_email",pVar->text, - strlen(pVar->text)+1,NX_CHAR); - if(iStat == NX_ERROR) - { - SCWrite(pCon,"ERROR: writing owner_email attribute to Nexus file",eError); - } - } - pVar = NULL; - return pFile; - } /*--------------------------------------------------------------------------*/ - int SNMakeSANS(SConnection *pCon, SicsInterp *pSics, NXdict pDict) - { - NXhandle Nfil = NULL; - char pBueffel[512]; - float fVal; - int iVal, iSet; - int iAxis[256]; - int i, iRet; - long lVal; - HistInt *lData = NULL; - const float *fTime = NULL; - CommandList *pCom = NULL; - pHistMem self = NULL; - CounterMode eMode; - pVelSel pVelo = NULL; - pSPS pSiem = NULL; - const char *pNamPos = NULL; - float fRot, fTilt, fLambda; - pDummy pDum; - pIDrivable pDrive; - int iDim[MAXDIM], nDim, histSize,iStart; - - /* start file */ - Nfil = SNXStartSANS(pCon,pSics); - if(!Nfil) - { - return 0; - } - - /* - during all this, no extensive error checking will be done, - just write the error and continue, save at all cost - */ - - /* put all this global information */ - SNXSPutVariable(pSics,pCon,Nfil,pDict,"etitle","title"); - SNXSPutVariable(pSics,pCon,Nfil,pDict,"etime","starttime"); - SNXFormatTime(pBueffel,511); - NXDputalias(Nfil,pDict,"endtime",pBueffel); - strcpy(pBueffel,"SANS at SINQ,PSI"); - NXDputalias(Nfil,pDict,"iname",pBueffel); - strcpy(pBueffel,"SINQ at PSI,Villigen, Switzerland"); - NXDputalias(Nfil,pDict,"sname",pBueffel); - strcpy(pBueffel,"Spallation"); - NXDputalias(Nfil,pDict,"stype",pBueffel); - - /* put the velocity selector data */ - NXDputalias(Nfil,pDict,"vname","Dornier Velocity Selector"); - - fRot = 0.; - fTilt = 0.; - pCom = FindCommand(pSics,"nvs"); - if(pCom) - { - pVelo = (pVelSel)pCom->pData; - if(!pVelo) - { - SCWrite(pCon,"WARNING: Velocity Selctor not found",eWarning); +int SNMakeSANS(SConnection * pCon, SicsInterp * pSics, NXdict pDict) +{ + NXhandle Nfil = NULL; + char pBueffel[512]; + float fVal; + int iVal, iSet; + int iAxis[256]; + int i, iRet; + long lVal; + HistInt *lData = NULL; + const float *fTime = NULL; + CommandList *pCom = NULL; + pHistMem self = NULL; + CounterMode eMode; + pVelSel pVelo = NULL; + pSPS pSiem = NULL; + const char *pNamPos = NULL; + float fRot, fTilt, fLambda; + pDummy pDum; + pIDrivable pDrive; + int iDim[MAXDIM], nDim, histSize, iStart; + + /* start file */ + Nfil = SNXStartSANS(pCon, pSics); + if (!Nfil) { + return 0; + } + + /* + during all this, no extensive error checking will be done, + just write the error and continue, save at all cost + */ + + /* put all this global information */ + SNXSPutVariable(pSics, pCon, Nfil, pDict, "etitle", "title"); + SNXSPutVariable(pSics, pCon, Nfil, pDict, "etime", "starttime"); + SNXFormatTime(pBueffel, 511); + NXDputalias(Nfil, pDict, "endtime", pBueffel); + strcpy(pBueffel, "SANS at SINQ,PSI"); + NXDputalias(Nfil, pDict, "iname", pBueffel); + strcpy(pBueffel, "SINQ at PSI,Villigen, Switzerland"); + NXDputalias(Nfil, pDict, "sname", pBueffel); + strcpy(pBueffel, "Spallation"); + NXDputalias(Nfil, pDict, "stype", pBueffel); + + /* put the velocity selector data */ + NXDputalias(Nfil, pDict, "vname", "Dornier Velocity Selector"); + + fRot = 0.; + fTilt = 0.; + pCom = FindCommand(pSics, "nvs"); + if (pCom) { + pVelo = (pVelSel) pCom->pData; + if (!pVelo) { + SCWrite(pCon, "WARNING: Velocity Selctor not found", eWarning); + } + iRet = VSGetRotation(pVelo, &fVal); + if (!iRet) { + SCWrite(pCon, "WARNING: failed to read velocity selector speed", + eWarning); + } else { + fRot = fVal; + NXDputalias(Nfil, pDict, "vrot", &fVal); + } + iRet = VSGetTilt(pVelo, &fTilt); + if (!iRet) { + SCWrite(pCon, "WARNING: failed to read velocity selector tilt angle", + eWarning); + } + } + SNXSPutMotor(pSics, pCon, Nfil, pDict, "vtilt", "tilt"); + CalculateLambda(fRot, fTilt, &fLambda); + NXDputalias(Nfil, pDict, "vlambda", &fLambda); + + + /* monitor 1 */ + pCom = FindCommand(pSics, HISTNAME); + if (!pCom) { + sprintf(pBueffel, "ERROR: histogram memory %s not found", HISTNAME); + SCWrite(pCon, pBueffel, eError); + return 0; + } + self = (pHistMem) pCom->pData; + assert(self); + lVal = GetHistMonitor(self, 0, pCon); + iVal = (int) lVal; + NXDputalias(Nfil, pDict, "m1counts", &iVal); + lVal = GetHistMonitor(self, 4, pCon); + iVal = (int) lVal; + NXDputalias(Nfil, pDict, "pbcounts", &iVal); + + /* the collimator */ + pCom = FindCommand(pSics, "sps2"); + if (!pCom) { + SCWrite(pCon, "WARNING: sps-unit for reading collimator NOT found", + eWarning); + } else { + pSiem = (pSPS) pCom->pData; + if (!pSiem) { + SCWrite(pCon, "WARNING: sps-unit for reading collimator NOT found", + eWarning); + } else { + iRet = SPSGetSANS(pSiem, &fVal); + if (iRet <= 0) { + SCWrite(pCon, "WARNING: Failed to read SPS", eWarning); + } else { + NXDputalias(Nfil, pDict, "colli", &fVal); + } + /* as we got the sps, get the attenuator as well */ + iRet = SPSGetStatus(pSiem, 38, &iSet); + if (iRet < 0) { + SCWrite(pCon, "WARNING: Failed to read SPS", eWarning); + } else { + if (iSet) { + iVal = 0; } - iRet = VSGetRotation(pVelo,&fVal); - if(!iRet) - { - SCWrite(pCon,"WARNING: failed to read velocity selector speed", - eWarning); - } - else - { - fRot = fVal; - NXDputalias(Nfil,pDict,"vrot",&fVal); + } + iRet = SPSGetStatus(pSiem, 39, &iSet); + if (iRet < 0) { + SCWrite(pCon, "WARNING: Failed to read SPS", eWarning); + } else { + if (iSet) { + iVal = 1; } - iRet = VSGetTilt(pVelo,&fTilt); - if(!iRet) - { - SCWrite(pCon,"WARNING: failed to read velocity selector tilt angle",eWarning); + } + iRet = SPSGetStatus(pSiem, 40, &iSet); + if (iRet < 0) { + SCWrite(pCon, "WARNING: Failed to read SPS", eWarning); + } else { + if (iSet) { + iVal = 2; } - } - SNXSPutMotor(pSics,pCon,Nfil,pDict,"vtilt","tilt"); - CalculateLambda(fRot, fTilt, &fLambda); - NXDputalias(Nfil,pDict,"vlambda",&fLambda); - - - /* monitor 1 */ - pCom = FindCommand(pSics,HISTNAME); - if(!pCom) - { - sprintf(pBueffel,"ERROR: histogram memory %s not found",HISTNAME); - SCWrite(pCon,pBueffel,eError); - return 0; - } - self = (pHistMem)pCom->pData; - assert(self); - lVal = GetHistMonitor(self,0,pCon); - iVal = (int)lVal; - NXDputalias(Nfil,pDict,"m1counts",&iVal); - lVal = GetHistMonitor(self,4,pCon); - iVal = (int)lVal; - NXDputalias(Nfil,pDict,"pbcounts",&iVal); - - /* the collimator */ - pCom = FindCommand(pSics,"sps2"); - if(!pCom) - { - SCWrite(pCon,"WARNING: sps-unit for reading collimator NOT found", - eWarning); - } - else - { - pSiem = (pSPS)pCom->pData; - if(!pSiem) - { - SCWrite(pCon,"WARNING: sps-unit for reading collimator NOT found", - eWarning); + } + iRet = SPSGetStatus(pSiem, 41, &iSet); + if (iRet < 0) { + SCWrite(pCon, "WARNING: Failed to read SPS", eWarning); + } else { + if (iSet) { + iVal = 3; } - else - { - iRet = SPSGetSANS(pSiem,&fVal); - if(iRet <= 0) - { - SCWrite(pCon,"WARNING: Failed to read SPS",eWarning); - } - else - { - NXDputalias(Nfil,pDict,"colli",&fVal); - } - /* as we got the sps, get the attenuator as well */ - iRet = SPSGetStatus(pSiem,38,&iSet); - if(iRet <0) - { - SCWrite(pCon,"WARNING: Failed to read SPS",eWarning); - } - else - { - if(iSet) - { - iVal = 0; - } - } - iRet = SPSGetStatus(pSiem,39,&iSet); - if(iRet <0) - { - SCWrite(pCon,"WARNING: Failed to read SPS",eWarning); - } - else - { - if(iSet) - { - iVal = 1; - } - } - iRet = SPSGetStatus(pSiem,40,&iSet); - if(iRet <0) - { - SCWrite(pCon,"WARNING: Failed to read SPS",eWarning); - } - else - { - if(iSet) - { - iVal = 2; - } - } - iRet = SPSGetStatus(pSiem,41,&iSet); - if(iRet <0) - { - SCWrite(pCon,"WARNING: Failed to read SPS",eWarning); - } - else - { - if(iSet) - { - iVal = 3; - } - } - iRet = SPSGetStatus(pSiem,42,&iSet); - if(iRet <0) - { - SCWrite(pCon,"WARNING: Failed to read SPS",eWarning); - } - else - { - if(iSet) - { - iVal = 4; - } - } - iRet = SPSGetStatus(pSiem,43,&iSet); - if(iRet <0) - { - SCWrite(pCon,"WARNING: Failed to read SPS",eWarning); - } - else - { - if(iSet) - { - iVal = 5; - } - } - NXDputalias(Nfil,pDict,"atti",&iVal); + } + iRet = SPSGetStatus(pSiem, 42, &iSet); + if (iRet < 0) { + SCWrite(pCon, "WARNING: Failed to read SPS", eWarning); + } else { + if (iSet) { + iVal = 4; } - } - - /* the sample */ - SNXSPutVariable(pSics,pCon,Nfil,pDict,"san","sample"); - SNXSPutVariable(pSics,pCon,Nfil,pDict,"saenv","environment"); - SNXSPutMotor(pSics,pCon,Nfil,pDict,"sax","sax"); - SNXSPutMotor(pSics,pCon,Nfil,pDict,"say","say"); - SNXSPutMotor(pSics,pCon,Nfil,pDict,"saz","saz"); - SNXSPutMotorNull(pSics,pCon,Nfil,pDict,"saxn","sax"); - SNXSPutMotorNull(pSics,pCon,Nfil,pDict,"sayn","say"); - SNXSPutMotorNull(pSics,pCon,Nfil,pDict,"sazn","saz"); - - - /* goniometer */ - SNXSPutMotor(pSics,pCon,Nfil,pDict,"gphi","gphi"); - SNXSPutMotor(pSics,pCon,Nfil,pDict,"gtheta","gtheta"); - SNXSPutMotorNull(pSics,pCon,Nfil,pDict,"gphin","gphi"); - SNXSPutMotorNull(pSics,pCon,Nfil,pDict,"gthetan","gtheta"); - - SNXSPutMotor(pSics,pCon,Nfil,pDict,"saom","som"); - SNXSPutMotorNull(pSics,pCon,Nfil,pDict,"saomn","som"); - SNXSPutMotor(pSics,pCon,Nfil,pDict,"sapos","spos"); - SNXSPutMotorNull(pSics,pCon,Nfil,pDict,"saposn","spos"); - pCom = FindCommand(pSics,SAMPLETABLE); - if(pCom) - { - if(pCom->pData) - { - pNamPos = FindNamPos((pMulMot)pCom->pData,pCon); - if(pNamPos) - { - NXDputalias(Nfil,pDict,"sanampos",(char *)pNamPos); - } - } - } - /* write sample environment here */ - pCom = FindCommand(pSics,"temperature"); - if(pCom) - { - pDum = (pDummy)pCom->pData; - pDrive = pDum->pDescriptor->GetInterface(pDum,DRIVEID); - if(pDrive) /* a proper environment device */ - { - fVal = pDrive->GetValue(pDum,pCon); - NXDputalias(Nfil,pDict,"satemp",&fVal); - } - } - pCom = FindCommand(pSics,"magnet"); - if(pCom) - { - pDum = (pDummy)pCom->pData; - pDrive = pDum->pDescriptor->GetInterface(pDum,DRIVEID); - if(pDrive) /* a proper environment device */ - { - fVal = pDrive->GetValue(pDum,pCon); - NXDputalias(Nfil,pDict,"samag",&fVal); - } - } - - /* magnet motors. This instrument has motorized magnets crawling - through the hall */ - pCom = FindCommand(pSics,"mom"); - if(pCom) - { - SNXSPutMotor(pSics,pCon,Nfil,pDict,"mom","mom"); - } - pCom = FindCommand(pSics,"mz"); - if(pCom) - { - SNXSPutMotor(pSics,pCon,Nfil,pDict,"mz","mz"); - } - - - /* put Beam Stop */ - /* read beamstop number */ - iVal = 1; - pCom = FindCommand(pSics,"sps1"); - if(!pCom) - { - SCWrite(pCon,"WARNING: sps-unit for reading beamstop NOT found",eWarning); - } - else - { - pSiem = (pSPS)pCom->pData; - if(!pSiem) - { - SCWrite(pCon,"WARNING: sps-unit for reading beamstop NOT found",eWarning); + } + iRet = SPSGetStatus(pSiem, 43, &iSet); + if (iRet < 0) { + SCWrite(pCon, "WARNING: Failed to read SPS", eWarning); + } else { + if (iSet) { + iVal = 5; } - else - { - iRet = SPSGetStatus(pSiem,8,&iSet); - if(iRet <0) - { - SCWrite(pCon,"WARNING: Failed to read SPS",eWarning); - } - else - { - if(iSet) - { - iVal = 2; - } - } - iRet = SPSGetStatus(pSiem,9,&iSet); - if(iRet <0) - { - SCWrite(pCon,"WARNING: Failed to read SPS",eWarning); - } - else - { - if(iSet) - { - iVal = 3; - } - } - iRet = SPSGetStatus(pSiem,10,&iSet); - if(iRet <0) - { - SCWrite(pCon,"WARNING: Failed to read SPS",eWarning); - } - else - { - if(iSet) - { - iVal = 4; - } - } + } + NXDputalias(Nfil, pDict, "atti", &iVal); + } + } + + /* the sample */ + SNXSPutVariable(pSics, pCon, Nfil, pDict, "san", "sample"); + SNXSPutVariable(pSics, pCon, Nfil, pDict, "saenv", "environment"); + SNXSPutMotor(pSics, pCon, Nfil, pDict, "sax", "sax"); + SNXSPutMotor(pSics, pCon, Nfil, pDict, "say", "say"); + SNXSPutMotor(pSics, pCon, Nfil, pDict, "saz", "saz"); + SNXSPutMotorNull(pSics, pCon, Nfil, pDict, "saxn", "sax"); + SNXSPutMotorNull(pSics, pCon, Nfil, pDict, "sayn", "say"); + SNXSPutMotorNull(pSics, pCon, Nfil, pDict, "sazn", "saz"); + + + /* goniometer */ + SNXSPutMotor(pSics, pCon, Nfil, pDict, "gphi", "gphi"); + SNXSPutMotor(pSics, pCon, Nfil, pDict, "gtheta", "gtheta"); + SNXSPutMotorNull(pSics, pCon, Nfil, pDict, "gphin", "gphi"); + SNXSPutMotorNull(pSics, pCon, Nfil, pDict, "gthetan", "gtheta"); + + SNXSPutMotor(pSics, pCon, Nfil, pDict, "saom", "som"); + SNXSPutMotorNull(pSics, pCon, Nfil, pDict, "saomn", "som"); + SNXSPutMotor(pSics, pCon, Nfil, pDict, "sapos", "spos"); + SNXSPutMotorNull(pSics, pCon, Nfil, pDict, "saposn", "spos"); + pCom = FindCommand(pSics, SAMPLETABLE); + if (pCom) { + if (pCom->pData) { + pNamPos = FindNamPos((pMulMot) pCom->pData, pCon); + if (pNamPos) { + NXDputalias(Nfil, pDict, "sanampos", (char *) pNamPos); + } + } + } + /* write sample environment here */ + pCom = FindCommand(pSics, "temperature"); + if (pCom) { + pDum = (pDummy) pCom->pData; + pDrive = pDum->pDescriptor->GetInterface(pDum, DRIVEID); + if (pDrive) { /* a proper environment device */ + fVal = pDrive->GetValue(pDum, pCon); + NXDputalias(Nfil, pDict, "satemp", &fVal); + } + } + pCom = FindCommand(pSics, "magnet"); + if (pCom) { + pDum = (pDummy) pCom->pData; + pDrive = pDum->pDescriptor->GetInterface(pDum, DRIVEID); + if (pDrive) { /* a proper environment device */ + fVal = pDrive->GetValue(pDum, pCon); + NXDputalias(Nfil, pDict, "samag", &fVal); + } + } + + /* magnet motors. This instrument has motorized magnets crawling + through the hall */ + pCom = FindCommand(pSics, "mom"); + if (pCom) { + SNXSPutMotor(pSics, pCon, Nfil, pDict, "mom", "mom"); + } + pCom = FindCommand(pSics, "mz"); + if (pCom) { + SNXSPutMotor(pSics, pCon, Nfil, pDict, "mz", "mz"); + } + + + /* put Beam Stop */ + /* read beamstop number */ + iVal = 1; + pCom = FindCommand(pSics, "sps1"); + if (!pCom) { + SCWrite(pCon, "WARNING: sps-unit for reading beamstop NOT found", + eWarning); + } else { + pSiem = (pSPS) pCom->pData; + if (!pSiem) { + SCWrite(pCon, "WARNING: sps-unit for reading beamstop NOT found", + eWarning); + } else { + iRet = SPSGetStatus(pSiem, 8, &iSet); + if (iRet < 0) { + SCWrite(pCon, "WARNING: Failed to read SPS", eWarning); + } else { + if (iSet) { + iVal = 2; } - } - NXDputalias(Nfil,pDict,"bst",&iVal); - SNXSPutMotor(pSics,pCon,Nfil,pDict,"vsx","BeamStopX"); - SNXSPutMotor(pSics,pCon,Nfil,pDict,"vsy","BeamStopY"); - SNXSPutMotorNull(pSics,pCon,Nfil,pDict,"vsxnull","BeamStopX"); - SNXSPutMotorNull(pSics,pCon,Nfil,pDict,"vsynull","BeamStopY"); - - /* what this is all about: the detector */ - SNXSPutMotor(pSics,pCon,Nfil,pDict,"ddx","DetectorX"); - SNXSPutMotor(pSics,pCon,Nfil,pDict,"ddy","DetectorY"); - SNXSPutMotorNull(pSics,pCon,Nfil,pDict,"ddxn","DetectorX"); - SNXSPutMotorNull(pSics,pCon,Nfil,pDict,"ddyn","DetectorY"); - SNXSPutMotor(pSics,pCon,Nfil,pDict,"ddchi","DetectorRotation"); - pCom = FindCommand(pSics,HISTNAME); - if(!pCom) - { - sprintf(pBueffel,"ERROR: histogram memory %s not found",HISTNAME); - SCWrite(pCon,pBueffel,eError); - return 0; - } - self = (pHistMem)pCom->pData; - assert(self); - eMode = GetHistCountMode(self); - if(eMode == eTimer) - { - strcpy(pBueffel,"Timer"); - } - else - { - strcpy(pBueffel,"Monitor"); - } - NXDputalias(Nfil,pDict,"ddm",pBueffel); - fVal = GetHistPreset(self); - NXDputalias(Nfil,pDict,"ddp",&fVal); - lVal = GetHistMonitor(self,1,pCon); - iVal = (int)lVal; - NXDputalias(Nfil,pDict,"ddmo",&iVal); - fVal = GetHistCountTime(self,pCon); - NXDputalias(Nfil,pDict,"ddtime",&fVal); + } + iRet = SPSGetStatus(pSiem, 9, &iSet); + if (iRet < 0) { + SCWrite(pCon, "WARNING: Failed to read SPS", eWarning); + } else { + if (iSet) { + iVal = 3; + } + } + iRet = SPSGetStatus(pSiem, 10, &iSet); + if (iRet < 0) { + SCWrite(pCon, "WARNING: Failed to read SPS", eWarning); + } else { + if (iSet) { + iVal = 4; + } + } + } + } + NXDputalias(Nfil, pDict, "bst", &iVal); + SNXSPutMotor(pSics, pCon, Nfil, pDict, "vsx", "BeamStopX"); + SNXSPutMotor(pSics, pCon, Nfil, pDict, "vsy", "BeamStopY"); + SNXSPutMotorNull(pSics, pCon, Nfil, pDict, "vsxnull", "BeamStopX"); + SNXSPutMotorNull(pSics, pCon, Nfil, pDict, "vsynull", "BeamStopY"); - /* - Deal with actual histogram. Due to stroboscopic modes and the - new detector electronics we need to find out about the size - ourselves now. And possibly write time binning information. - */ - GetHistDim(self, iDim,&nDim); - /* - handle time binning - */ - fTime = GetHistTimeBin(self,&iVal); - if(iVal > 2) - { - NXDputalias(Nfil,pDict,"ddtb",(void *)fTime); - nDim = 3; - iDim[2] = iVal; - } + /* what this is all about: the detector */ + SNXSPutMotor(pSics, pCon, Nfil, pDict, "ddx", "DetectorX"); + SNXSPutMotor(pSics, pCon, Nfil, pDict, "ddy", "DetectorY"); + SNXSPutMotorNull(pSics, pCon, Nfil, pDict, "ddxn", "DetectorX"); + SNXSPutMotorNull(pSics, pCon, Nfil, pDict, "ddyn", "DetectorY"); + SNXSPutMotor(pSics, pCon, Nfil, pDict, "ddchi", "DetectorRotation"); + pCom = FindCommand(pSics, HISTNAME); + if (!pCom) { + sprintf(pBueffel, "ERROR: histogram memory %s not found", HISTNAME); + SCWrite(pCon, pBueffel, eError); + return 0; + } + self = (pHistMem) pCom->pData; + assert(self); + eMode = GetHistCountMode(self); + if (eMode == eTimer) { + strcpy(pBueffel, "Timer"); + } else { + strcpy(pBueffel, "Monitor"); + } + NXDputalias(Nfil, pDict, "ddm", pBueffel); + fVal = GetHistPreset(self); + NXDputalias(Nfil, pDict, "ddp", &fVal); + lVal = GetHistMonitor(self, 1, pCon); + iVal = (int) lVal; + NXDputalias(Nfil, pDict, "ddmo", &iVal); + fVal = GetHistCountTime(self, pCon); + NXDputalias(Nfil, pDict, "ddtime", &fVal); - histSize = 1; - for(i = 0; i < nDim; i++) - { - histSize *= iDim[i]; - } - lData = (HistInt *)malloc(histSize*sizeof(HistInt)); - if(!lData) - { - SCWrite(pCon,"ERROR: out of memory, FAILED to store data, file corrupt", - eError); - NXclose(&Nfil); - return 0; - } - GetHistogram(self,pCon,0,0,histSize,lData,histSize*sizeof(HistInt)); - sprintf(pBueffel," %d ",iDim[0]); - NXDupdate(pDict,"dim1",pBueffel); - sprintf(pBueffel," %d ",iDim[1]); - NXDupdate(pDict,"dim2",pBueffel); - if(nDim == 2) - { - sprintf(pBueffel," -rank 2 -dim {%d,%d} ", iDim[0], iDim[1]); - NXDupdate(pDict,"countdim",pBueffel); - } - else if (nDim == 3) - { - sprintf(pBueffel," -rank 3 -dim {%d,%d,%d} ", iDim[0], iDim[1], - iDim[2]); - NXDupdate(pDict,"countdim",pBueffel); - sprintf(pBueffel," %d ",iDim[2]); - NXDupdate(pDict,"timedim",pBueffel); - } - NXDputalias(Nfil,pDict,"ddcounts",lData); - free(lData); + /* + Deal with actual histogram. Due to stroboscopic modes and the + new detector electronics we need to find out about the size + ourselves now. And possibly write time binning information. + */ + GetHistDim(self, iDim, &nDim); + /* + handle time binning + */ + fTime = GetHistTimeBin(self, &iVal); + if (iVal > 2) { + NXDputalias(Nfil, pDict, "ddtb", (void *) fTime); + nDim = 3; + iDim[2] = iVal; + } - /* write x and y axis */ - for(i = 0; i < iDim[0]; i++) - { - iAxis[i] = i; - } - NXDputalias(Nfil,pDict,"ddcx",iAxis); - for(i = 0; i < iDim[1]; i++) - { - iAxis[i] = i; - } - NXDputalias(Nfil,pDict,"ddcy",iAxis); - - - - /* - write gummi monitors when apropriate - */ - if(nDim == 3 && gummiFlag != 0) - { - histSize = 3*iDim[2]; - lData = (HistInt *)malloc(histSize*sizeof(HistInt)); - if(lData == NULL) - { - SCWrite(pCon,"WARNING: failed to allocate memory for monitors", - eWarning); - } else { - memset(lData,0,histSize*sizeof(HistInt)); - iStart = iDim[0]*iDim[1]*iDim[2]; - GetHistogramDirect(self,pCon,0,iStart,iStart+histSize, - lData,histSize*sizeof(HistInt)); - NXDputalias(Nfil,pDict,"gummimon1",lData); - NXDputalias(Nfil,pDict,"gummimon2",lData+iDim[2]); - NXDputalias(Nfil,pDict,"gummimon3",lData+2*iDim[2]); - free(lData); - } - } - - /* - write detector temperature. It is a hot one............ - */ - if(pSiem) - { - iRet = SPSGetADC(pSiem,1,&iVal); - if(iRet) - { - fVal = iVal/269.9; - NXDputalias(Nfil,pDict,"ddtemp",&fVal); - } - } - - /* do the linking in th data vgroup */ - NXDaliaslink(Nfil,pDict,"dan","ddcounts"); - NXDaliaslink(Nfil,pDict,"dan","ddcx"); - NXDaliaslink(Nfil,pDict,"dan","ddcy"); - NXDaliaslink(Nfil,pDict,"dan","ddmo"); - NXDaliaslink(Nfil,pDict,"dan","vlambda"); - if(nDim == 3) - { - NXDaliaslink(Nfil,pDict,"dan","ddtb"); - } - - /* send quieck message for automatic copying*/ - i = 131; - iVal = NX_CHAR; - NXgetattr(Nfil,"file_name",pBueffel,&i,&iVal); - SendQuieck(QUIECK,pBueffel); - /* close this and go ............. */ + histSize = 1; + for (i = 0; i < nDim; i++) { + histSize *= iDim[i]; + } + lData = (HistInt *) malloc(histSize * sizeof(HistInt)); + if (!lData) { + SCWrite(pCon, + "ERROR: out of memory, FAILED to store data, file corrupt", + eError); NXclose(&Nfil); - return 1; - } + return 0; + } + GetHistogram(self, pCon, 0, 0, histSize, lData, + histSize * sizeof(HistInt)); + sprintf(pBueffel, " %d ", iDim[0]); + NXDupdate(pDict, "dim1", pBueffel); + sprintf(pBueffel, " %d ", iDim[1]); + NXDupdate(pDict, "dim2", pBueffel); + if (nDim == 2) { + sprintf(pBueffel, " -rank 2 -dim {%d,%d} ", iDim[0], iDim[1]); + NXDupdate(pDict, "countdim", pBueffel); + } else if (nDim == 3) { + sprintf(pBueffel, " -rank 3 -dim {%d,%d,%d} ", iDim[0], iDim[1], + iDim[2]); + NXDupdate(pDict, "countdim", pBueffel); + sprintf(pBueffel, " %d ", iDim[2]); + NXDupdate(pDict, "timedim", pBueffel); + } + NXDputalias(Nfil, pDict, "ddcounts", lData); + free(lData); + + /* write x and y axis */ + for (i = 0; i < iDim[0]; i++) { + iAxis[i] = i; + } + NXDputalias(Nfil, pDict, "ddcx", iAxis); + for (i = 0; i < iDim[1]; i++) { + iAxis[i] = i; + } + NXDputalias(Nfil, pDict, "ddcy", iAxis); + + + + /* + write gummi monitors when apropriate + */ + if (nDim == 3 && gummiFlag != 0) { + histSize = 3 * iDim[2]; + lData = (HistInt *) malloc(histSize * sizeof(HistInt)); + if (lData == NULL) { + SCWrite(pCon, "WARNING: failed to allocate memory for monitors", + eWarning); + } else { + memset(lData, 0, histSize * sizeof(HistInt)); + iStart = iDim[0] * iDim[1] * iDim[2]; + GetHistogramDirect(self, pCon, 0, iStart, iStart + histSize, + lData, histSize * sizeof(HistInt)); + NXDputalias(Nfil, pDict, "gummimon1", lData); + NXDputalias(Nfil, pDict, "gummimon2", lData + iDim[2]); + NXDputalias(Nfil, pDict, "gummimon3", lData + 2 * iDim[2]); + free(lData); + } + } + + /* + write detector temperature. It is a hot one............ + */ + if (pSiem) { + iRet = SPSGetADC(pSiem, 1, &iVal); + if (iRet) { + fVal = iVal / 269.9; + NXDputalias(Nfil, pDict, "ddtemp", &fVal); + } + } + + /* do the linking in th data vgroup */ + NXDaliaslink(Nfil, pDict, "dan", "ddcounts"); + NXDaliaslink(Nfil, pDict, "dan", "ddcx"); + NXDaliaslink(Nfil, pDict, "dan", "ddcy"); + NXDaliaslink(Nfil, pDict, "dan", "ddmo"); + NXDaliaslink(Nfil, pDict, "dan", "vlambda"); + if (nDim == 3) { + NXDaliaslink(Nfil, pDict, "dan", "ddtb"); + } + + /* send quieck message for automatic copying */ + i = 131; + iVal = NX_CHAR; + NXgetattr(Nfil, "file_name", pBueffel, &i, &iVal); + SendQuieck(QUIECK, pBueffel); + /* close this and go ............. */ + NXclose(&Nfil); + return 1; +} + /*------------------- The Mechanics for setting Up ------------------------*/ - typedef struct { - pObjectDescriptor pDes; - NXdict pDict; - } DictStruct, *pDictStruct; +typedef struct { + pObjectDescriptor pDes; + NXdict pDict; +} DictStruct, *pDictStruct; /*-------------------------------------------------------------------------*/ - static pDictStruct MakeDictStruct(char *pFile) - { - pDictStruct pNew = NULL; - int iRet; - - pNew = (pDictStruct)malloc(sizeof(DictStruct)); - if(!pNew) - { - return NULL; - } - memset(pNew,0,sizeof(DictStruct)); - pNew->pDes = CreateDescriptor("StoreData"); - if(!pNew->pDes) - { - free(pNew); - return NULL; - } - - iRet = NXDinitfromfile(pFile,&(pNew->pDict)); - if(iRet != NX_OK) - { - DeleteDescriptor(pNew->pDes); - free(pNew); - return NULL; - } - return pNew; - } -/*--------------------------------------------------------------------------*/ - static void KillDictStruct(void *pData) - { - pDictStruct self = NULL; - - self = (pDictStruct)pData; - assert(self); - - if(self->pDes) - { - DeleteDescriptor(self->pDes); - } - if(self->pDict) - { - NXDclose(self->pDict,NULL); - } - free(self); - } +static pDictStruct MakeDictStruct(char *pFile) +{ + pDictStruct pNew = NULL; + int iRet; + + pNew = (pDictStruct) malloc(sizeof(DictStruct)); + if (!pNew) { + return NULL; + } + memset(pNew, 0, sizeof(DictStruct)); + pNew->pDes = CreateDescriptor("StoreData"); + if (!pNew->pDes) { + free(pNew); + return NULL; + } + + iRet = NXDinitfromfile(pFile, &(pNew->pDict)); + if (iRet != NX_OK) { + DeleteDescriptor(pNew->pDes); + free(pNew); + return NULL; + } + return pNew; +} /*--------------------------------------------------------------------------*/ - int SNStoreSANS(SConnection *pCon, SicsInterp *pSics, void *pData, int argc, - char *argv[]) - - { - char pBueffel[80]; - pDictStruct self = NULL; - self = (pDictStruct)pData; +static void KillDictStruct(void *pData) +{ + pDictStruct self = NULL; - assert(self); - assert(pCon); - assert(pSics); + self = (pDictStruct) pData; + assert(self); - if(argc > 1){ - strtolower(argv[1]); - if(strcmp(argv[1],"gummi") == 0){ - if(argc > 2){ - if(!SCMatchRights(pCon,usMugger)){ - return 0; - } - gummiFlag = atoi(argv[2]); - SCSendOK(pCon); - return 1; - } else - { - sprintf(pBueffel,"%s.gummi = %d",argv[0], gummiFlag); - SCWrite(pCon,pBueffel,eValue); - return 1; - } - } - } + if (self->pDes) { + DeleteDescriptor(self->pDes); + } + if (self->pDict) { + NXDclose(self->pDict, NULL); + } + free(self); +} - return SNMakeSANS(pCon,pSics,self->pDict); - } /*--------------------------------------------------------------------------*/ - int InitSANS(SConnection *pCon, SicsInterp *pSics, void *pData, +int SNStoreSANS(SConnection * pCon, SicsInterp * pSics, void *pData, + int argc, char *argv[]) +{ + char pBueffel[80]; + pDictStruct self = NULL; + self = (pDictStruct) pData; + + assert(self); + assert(pCon); + assert(pSics); + + if (argc > 1) { + strtolower(argv[1]); + if (strcmp(argv[1], "gummi") == 0) { + if (argc > 2) { + if (!SCMatchRights(pCon, usMugger)) { + return 0; + } + gummiFlag = atoi(argv[2]); + SCSendOK(pCon); + return 1; + } else { + sprintf(pBueffel, "%s.gummi = %d", argv[0], gummiFlag); + SCWrite(pCon, pBueffel, eValue); + return 1; + } + } + } + + return SNMakeSANS(pCon, pSics, self->pDict); +} + +/*--------------------------------------------------------------------------*/ +int InitSANS(SConnection * pCon, SicsInterp * pSics, void *pData, int argc, char *argv[]) - { - pDictStruct pNew = NULL; - char pBueffel[512]; - - if(argc < 2) - { - SCWrite(pCon,"ERROR: not enough arguments for IniSANS",eError); - return 0; - } - - pNew = MakeDictStruct(argv[1]); - if(!pNew) - { - sprintf(pBueffel,"ERROR: failed to initialise NXDDL from file %s", - argv[1]); - SCWrite(pCon,pBueffel,eError); - return 0; - } - AddCommand(pSics,"StoreData",SNStoreSANS,KillDictStruct,pNew); - return 1; - } +{ + pDictStruct pNew = NULL; + char pBueffel[512]; + + if (argc < 2) { + SCWrite(pCon, "ERROR: not enough arguments for IniSANS", eError); + return 0; + } + + pNew = MakeDictStruct(argv[1]); + if (!pNew) { + sprintf(pBueffel, "ERROR: failed to initialise NXDDL from file %s", + argv[1]); + SCWrite(pCon, pBueffel, eError); + return 0; + } + AddCommand(pSics, "StoreData", SNStoreSANS, KillDictStruct, pNew); + return 1; +} diff --git a/nxsans.h b/nxsans.h index fc35e86..a42dd42 100644 --- a/nxsans.h +++ b/nxsans.h @@ -8,9 +8,9 @@ ---------------------------------------------------------------------------*/ #ifndef NXSANS #define NXSANS - int InitSANS(SConnection *pCon, SicsInterp *pSics, void *pData, - int argc, char *argv[]); - int SNStoreSANS(SConnection *pCon, SicsInterp *pSics, void *pData, +int InitSANS(SConnection * pCon, SicsInterp * pSics, void *pData, + int argc, char *argv[]); +int SNStoreSANS(SConnection * pCon, SicsInterp * pSics, void *pData, int argc, char *argv[]); diff --git a/oicom.c b/oicom.c index 970d611..c7eaf9d 100644 --- a/oicom.c +++ b/oicom.c @@ -21,9 +21,10 @@ is not changed, i.e. an existing errCode is not overwritten. /*----------------------------------------------------------------------------*/ -int OiHandler(Eve *eve) { +int OiHandler(Eve * eve) +{ int iret, l; - + if (availableNetRS232(eve->ser)) { l = sizeof(eve->ans); iret = readRS232TillTerm(eve->ser, eve->ans, &l); @@ -46,15 +47,15 @@ int OiHandler(Eve *eve) { if (strcmp(eve->ans, eve->version) == 0) { /* we are still connected with the same device */ } else if (*eve->version == '\0') { - strncat(eve->version, eve->ans, sizeof(eve->version)-1); - } else { /* version (and therefore device) changed */ + strncat(eve->version, eve->ans, sizeof(eve->version) - 1); + } else { /* version (and therefore device) changed */ eve->errCode = EVE_DEV_CHANGED; eve->state = idleState; goto error; } eve->state = idleState; goto quit; - } else if (eve->cmd[1] == 'k') { /* ck */ + } else if (eve->cmd[1] == 'k') { /* ck */ } else if (eve->cmd[0] != eve->ans[0]) { iret = EVE_ILL_ANS; } @@ -66,7 +67,7 @@ int OiHandler(Eve *eve) { } eve->state = readState; } else if (eve->state == expectState) { - if (time(NULL) > eve->cmdtime+60) { + if (time(NULL) > eve->cmdtime + 60) { eve->errCode = TIMEOUT; eve->state = lostState; } @@ -83,10 +84,11 @@ quit: return EveHandler(eve); } -double OiGetFlt(Eve *eve, int dig, int *pdig) { +double OiGetFlt(Eve * eve, int dig, int *pdig) +{ char *endp, *p; double val; - + if (eve->state != readState) { /* eve->errCode = EVE_ILL_ANS; */ return 0.0; @@ -96,25 +98,27 @@ double OiGetFlt(Eve *eve, int dig, int *pdig) { if (pdig != NULL) { *pdig = strlen(eve->ans) - (p - eve->ans) - 1; } - val=strtod(eve->ans+1, &endp); + val = strtod(eve->ans + 1, &endp); if (*endp != '\0') { eve->errCode = EVE_ILL_ANS; return 0.0; } } else { - val=strtol(eve->ans+1, &endp, 10); + val = strtol(eve->ans + 1, &endp, 10); if (*endp != '\0') { eve->errCode = EVE_ILL_ANS; return 0.0; } - if (eve->syntax == 0) { /* old style format */ - for (; dig > 0; dig--) val=val*0.1; + if (eve->syntax == 0) { /* old style format */ + for (; dig > 0; dig--) + val = val * 0.1; } } return val; } -void OiSet(Eve *eve, char *cmd, double val, int dig) { +void OiSet(Eve * eve, char *cmd, double val, int dig) +{ char buf[64]; long lval; @@ -125,4 +129,3 @@ void OiSet(Eve *eve, char *cmd, double val, int dig) { } EveWrite(eve, buf); } - diff --git a/oicom.h b/oicom.h index 29ab58a..72536b5 100644 --- a/oicom.h +++ b/oicom.h @@ -8,9 +8,6 @@ Markus Zolliker, Aug 2004 #include "rs232controller.h" #include "eve.h" -int OiHandler(Eve *eve); -double OiGetFlt(Eve *eve, int dig, int *pdig); -void OiSet(Eve *eve, char *cmd, double val, int dig); - - - +int OiHandler(Eve * eve); +double OiGetFlt(Eve * eve, int dig, int *pdig); +void OiSet(Eve * eve, char *cmd, double val, int dig); diff --git a/oxinst.c b/oxinst.c index 10d2304..a8b6129 100644 --- a/oxinst.c +++ b/oxinst.c @@ -20,28 +20,32 @@ is not changed, i.e. an existing errCode is not overwritten. #include "oxinst.h" /*----------------------------------------------------------------------------*/ -char *OxiCorrect(char *str) { +char *OxiCorrect(char *str) +{ /* there are sometimes communication errors with the IGH as the errors always follow the same pattern, they can be corrected, with the following code. The argument is corrected in place, the result is NULL or a text - describing the conversion */ + describing the conversion */ int i; unsigned char chr; static char buf[32]; char *result = NULL; - - if (str[0] == '?') return NULL; - for (i=0; i<=24; i++, str++) { + + if (str[0] == '?') + return NULL; + for (i = 0; i <= 24; i++, str++) { chr = *str; - if (chr == 0) return result; + if (chr == 0) + return result; if (chr > 0x60) { if (chr > 0xC0) { chr -= 0x80; } else { chr -= 0x40; } - snprintf(buf, sizeof buf, "%2.2x->%2.2x (%c)", (unsigned char)*str, chr, chr); + snprintf(buf, sizeof buf, "%2.2x->%2.2x (%c)", (unsigned char) *str, + chr, chr); *str = chr; result = buf; } @@ -52,14 +56,17 @@ char *OxiCorrect(char *str) { } else { return "overflow"; } -} +} + /*----------------------------------------------------------------------------*/ -int OxiHandler(void *object) { +int OxiHandler(void *object) +{ int iret, l; EaseBase *eab = EaseBaseCast(object); char *corr; - - if (eab->state < EASE_idle) goto quit; + + if (eab->state < EASE_idle) + goto quit; if (availableNetRS232(eab->ser) || availableRS232(eab->ser)) { eab->msg[0] = '\0'; l = sizeof(eab->ans); @@ -83,15 +90,15 @@ int OxiHandler(void *object) { if (strcmp(eab->ans, eab->version) == 0) { /* we are still connected with the same device */ } else if (*eab->version == '\0') { - strncat(eab->version, eab->ans, sizeof(eab->version)-1); - } else { /* version (and therefore device) changed */ + strncat(eab->version, eab->ans, sizeof(eab->version) - 1); + } else { /* version (and therefore device) changed */ eab->errCode = EASE_DEV_CHANGED; eab->state = EASE_idle; goto error; } eab->state = EASE_idle; goto quit; - } else if (eab->cmd[2] == 'k') { /* ?ck */ + } else if (eab->cmd[2] == 'k') { /* ?ck */ } else { eab->tmo = 120; if (eab->syntax <= -8) { @@ -128,10 +135,11 @@ quit: return EaseHandler(eab); } -double OxiGet(EaseBase *eab, int dig, int *pdig, double old) { +double OxiGet(EaseBase * eab, int dig, int *pdig, double old) +{ char *endp, *p; double val; - + if (eab->state != EASE_read) { eab->errCode = EASE_ILL_ANS; return old; @@ -141,35 +149,38 @@ double OxiGet(EaseBase *eab, int dig, int *pdig, double old) { if (pdig != NULL) { *pdig = strlen(eab->ans) - (p - eab->ans) - 1; } - val=strtod(eab->ans+1, &endp); + val = strtod(eab->ans + 1, &endp); if (*endp != '\0') { eab->errCode = EASE_ILL_ANS; return old; } } else { - val=strtol(eab->ans+1, &endp, 10); + val = strtol(eab->ans + 1, &endp, 10); if (*endp != '\0') { eab->errCode = EASE_ILL_ANS; return old; } - if (eab->syntax <= 0) { /* old style format */ - for (; dig > 0; dig--) val=val*0.1; + if (eab->syntax <= 0) { /* old style format */ + for (; dig > 0; dig--) + val = val * 0.1; } } return val; } -void OxiSet(EaseBase *eab, char *cmd, double val, int dig) { +void OxiSet(EaseBase * eab, char *cmd, double val, int dig) +{ char buf[64]; double f; - + if (eab->syntax > 0) { f = fabs(val); - if (f < 1.0) f = 1.0; + if (f < 1.0) + f = 1.0; dig = 5 - log10(f); - if (dig < 0) dig = 0; + if (dig < 0) + dig = 0; } snprintf(buf, sizeof(buf), "%s%.*f", cmd, dig, val); EaseWrite(eab, buf); } - diff --git a/oxinst.h b/oxinst.h index 7634ed7..2848211 100644 --- a/oxinst.h +++ b/oxinst.h @@ -12,8 +12,8 @@ Markus Zolliker, March 2005 #include "ease.h" int OxiHandler(void *eab); -double OxiGet(EaseBase *eab, int dig, int *pdig, double old); -void OxiSet(EaseBase *eab, char *cmd, double val, int dig); +double OxiGet(EaseBase * eab, int dig, int *pdig, double old); +void OxiSet(EaseBase * eab, char *cmd, double val, int dig); /* usage of the syntax field of EaseBase: syntax <= 0: old syntax, in general without decimal point diff --git a/pardef.c b/pardef.c index 9c4445f..ce5accb 100644 --- a/pardef.c +++ b/pardef.c @@ -32,8 +32,8 @@ typedef enum { NO_OP, FMT_OP, SET_OP, GET_OP, INIT_OP } ParOp; typedef struct Context { struct Context *next; ParData *obj; - ParAct act; /* action called */ - ParAct action; /* copy of act, but set to PAR_NOOP when name does not match */ + ParAct act; /* action called */ + ParAct action; /* copy of act, but set to PAR_NOOP when name does not match */ char *parName; int argc; char **argv; @@ -54,26 +54,29 @@ typedef struct Context { char combiName[80]; char *grpFmt; int exact; - char *callName; /* the called name of the object (different from obj->name in case of an alias) */ - int enumText; /* show enum text */ + char *callName; /* the called name of the object (different from obj->name in case of an alias) */ + int enumText; /* show enum text */ } Context; static char *loggerDir = NULL; static int showTime = 0; -static void *initObj; /* this object is in initialization mode */ +static void *initObj; /* this object is in initialization mode */ -static Context *ctx=NULL, *freeContexts=NULL; +static Context *ctx = NULL, *freeContexts = NULL; void ParKill(void *object); -static ParClass parClass={"Par", sizeof(ParData), 0, {&parClass}}; +static ParClass parClass = { "Par", sizeof(ParData), 0, {&parClass} +}; /*----------------------------------------------------------------------------*/ -void *ParCast(ParClass *class, void *object) { +void *ParCast(ParClass * class, void *object) +{ ParClass *t; - - if (! object) return NULL; - t = ((ParData *)object)->class; + + if (!object) + return NULL; + t = ((ParData *) object)->class; assert(t->base[0] == &parClass); if (t && t->base[class->level] == class) { return object; @@ -81,33 +84,37 @@ void *ParCast(ParClass *class, void *object) { return NULL; } } + /*----------------------------------------------------------------------------*/ -void *ParCheck(ParClass *class, void *object) { +void *ParCheck(ParClass * class, void *object) +{ ParClass *t; - + assert(object); - t = ((ParData *)object)->class; + t = ((ParData *) object)->class; assert(t->base[0] == &parClass); assert(t && t->base[class->level] == class); return object; } + /*----------------------------------------------------------------------------*/ -void *ParMakeClass(ParClass *class, ParClass *base) { +void *ParMakeClass(ParClass * class, ParClass * base) +{ int i; - + if (class->base[0] == NULL) { /* initialize */ if (base == NULL) { base = &parClass; } assert(class->size >= base->size); - for (i=0; i<=base->level; i++) { + for (i = 0; i <= base->level; i++) { class->base[i] = base->base[i]; } - assert(ibase[i] = class; class->level = i; - } else if (base) { /* check */ - for (i=0; i<=base->level; i++) { + } else if (base) { /* check */ + for (i = 0; i <= base->level; i++) { assert(class->base[i] == base->base[i]); } assert(class->base[i] == class); @@ -115,15 +122,17 @@ void *ParMakeClass(ParClass *class, ParClass *base) { } return class; } + /*--------------------------------------------------------------------------*/ -int ParPrintf(void *object, int iOut, const char *fmt, ...) { +int ParPrintf(void *object, int iOut, const char *fmt, ...) +{ va_list ap; char buf0[128]; int l; char *buf, *dyn = NULL; SConnection *con; ParData *pobj = object; - + con = NULL; if (pobj) { if (ctx && pobj == ctx->obj && ctx->con) { @@ -136,63 +145,72 @@ int ParPrintf(void *object, int iOut, const char *fmt, ...) { } if (iOut < 0) { - if (!con) return 0; /* no connection, no verbose output */ - if (-iOut > pobj->verbose) return 0; /* check verbosity level */ + if (!con) + return 0; /* no connection, no verbose output */ + if (-iOut > pobj->verbose) + return 0; /* check verbosity level */ iOut = eValue; } - + va_start(ap, fmt); l = vsnprintf(buf0, sizeof(buf0), fmt, ap); va_end(ap); if (l >= sizeof buf0) { /* we have probably a C99 conforming snprintf and need a larger buffer */ - dyn = malloc(l+1); + dyn = malloc(l + 1); if (dyn != NULL) { va_start(ap, fmt); - vsnprintf(dyn, l+1, fmt, ap); + vsnprintf(dyn, l + 1, fmt, ap); va_end(ap); } buf = dyn; } else { buf = buf0; } - + if (con) { - SCWrite(con, buf, iOut); /* writes to command log when user or manager */ + SCWrite(con, buf, iOut); /* writes to command log when user or manager */ } else if (iOut >= 0) { - WriteToCommandLog(">", buf); /* no connection, write to commandlog only */ + WriteToCommandLog(">", buf); /* no connection, write to commandlog only */ } - if (dyn) free(dyn); + if (dyn) + free(dyn); return 1; } + /*-------------------------------------------------------------------------*/ -static void ParBegin(void) { +static void ParBegin(void) +{ Context *p; - + if (freeContexts) { p = freeContexts; freeContexts = p->next; } else { - p = calloc(1,sizeof(*ctx)); + p = calloc(1, sizeof(*ctx)); assert(p); } p->next = ctx; ctx = p; ctx->callName = NULL; } + /*-------------------------------------------------------------------------*/ -static void ParEnd(void) { +static void ParEnd(void) +{ Context *p; - + assert(ctx); p = ctx->next; ctx->next = freeContexts; freeContexts = ctx; ctx = p; } + /*-------------------------------------------------------------------------*/ -static void ParDo(SConnection *con, ParData *o, ParAct a, char *parName) { +static void ParDo(SConnection * con, ParData * o, ParAct a, char *parName) +{ ctx->act = a; ctx->action = a; ctx->con = con; @@ -210,23 +228,26 @@ static void ParDo(SConnection *con, ParData *o, ParAct a, char *parName) { } o->pardef(o); } + /*--------------------------------------------------------------------------*/ -char *ParArg2Str(int argc, char *argv[], char *result, int maxsize) { +char *ParArg2Str(int argc, char *argv[], char *result, int maxsize) +{ int i, argsize; char *p, *res; - + argsize = 0; if (result == NULL) { maxsize = INT_MAX; - for (i=0; i maxsize) { argc = i; @@ -236,10 +257,10 @@ char *ParArg2Str(int argc, char *argv[], char *result, int maxsize) { } } p = result; - *p='\0'; - for (i=0; i 0) { - *p=' '; + *p = ' '; p++; } strcpy(p, argv[i]); @@ -247,14 +268,16 @@ char *ParArg2Str(int argc, char *argv[], char *result, int maxsize) { } return res; } + /*-------------------------------------------------------------------------*/ -static int ParSaveAll(void *object, char *name, FILE *fil) { +static int ParSaveAll(void *object, char *name, FILE * fil) +{ ParData *o = ParCheck(&parClass, object); int ret; - + ParBegin(); ctx->saveFile = fil; - assert(0==strcasecmp(o->name, name)); + assert(0 == strcasecmp(o->name, name)); if (o->creationCmd) { fprintf(fil, "if {[catch { %s }] == 0} {\n", o->creationCmd); } @@ -267,18 +290,22 @@ static int ParSaveAll(void *object, char *name, FILE *fil) { ParEnd(); return ret; } + /*--------------------------------------------------------------------------*/ -FILE *ParSaveFile(void) { +FILE *ParSaveFile(void) +{ if (ctx) { return ctx->saveFile; } return NULL; } + /*--------------------------------------------------------------------------*/ -int ParLog(void *object) { +int ParLog(void *object) +{ ParData *o = ParCheck(&parClass, object); int next; - + if (o->desc == NULL) { free(o); return 0; @@ -301,63 +328,74 @@ int ParLog(void *object) { ParEnd(); return 0; } + /*--------------------------------------------------------------------------*/ -void ParLogForced(void *object) { +void ParLogForced(void *object) +{ ParData *o = ParCheck(&parClass, object); int next; - + ParBegin(); ctx->now = time(NULL); showTime = 1; ParDo(0, o, PAR_LOG, NULL); o->logTime = ctx->now; if (o->logPending) { - o->logPending = 2; /* tell ParLog that we are done already, but task is still pending */ + o->logPending = 2; /* tell ParLog that we are done already, but task is still pending */ } ParEnd(); } + /*-------------------------------------------------------------------------*/ -static int ParCallBack(int event, void *eventData, void *userData) { - char *pBuf = (char *)eventData; - SConnection *con = (SConnection *)userData; +static int ParCallBack(int event, void *eventData, void *userData) +{ + char *pBuf = (char *) eventData; + SConnection *con = (SConnection *) userData; /* check kill condition */ - if(con == NULL || !SCisConnected(con)){ + if (con == NULL || !SCisConnected(con)) { return -1; } if (event == VALUECHANGE) { - SCWrite(con,pBuf,eValue); + SCWrite(con, pBuf, eValue); return 1; } return 1; } + /*----------------------------------------------------------------------------*/ -static int ParOutError(SConnection *con, ParData *o) { +static int ParOutError(SConnection * con, ParData * o) +{ switch (ctx->returnValue) { case AMBIGUOS: - SCPrintf(con, eError, "ERROR: doubly defined parameter %s.%s", o->name, ctx->thisPar); + SCPrintf(con, eError, "ERROR: doubly defined parameter %s.%s", o->name, + ctx->thisPar); break; case ILLPRIV: - SCPrintf(con, eError, "ERROR: insufficient privilege for %s.%s", o->name, ctx->thisPar); + SCPrintf(con, eError, "ERROR: insufficient privilege for %s.%s", + o->name, ctx->thisPar); break; case ILLNUM: SCPrintf(con, eError, "ERROR: illegal value", o->name, ctx->valueArg); break; case ILLARGC: - SCPrintf(con, eError, "ERROR: illegal number of arguments for %s %s", o->name, ctx->thisPar); + SCPrintf(con, eError, "ERROR: illegal number of arguments for %s %s", + o->name, ctx->thisPar); break; case BADLOG: - SCPrintf(con, eError, "ERROR: can not create log directory for %s %s", o->name, ctx->thisPar); + SCPrintf(con, eError, "ERROR: can not create log directory for %s %s", + o->name, ctx->thisPar); break; case UNKPAR: - SCPrintf(con, eError, "ERROR: %s %s is unknown", o->name, ctx->thisPar); + SCPrintf(con, eError, "ERROR: %s %s is unknown", o->name, + ctx->thisPar); break; /* - case BUSY: - SCPrintf(con, eError, "ERROR: %s busy", o->name); - break; - */ + case BUSY: + SCPrintf(con, eError, "ERROR: %s busy", o->name); + break; + */ default: if (ctx->returnValue < 0) { return -1; @@ -367,13 +405,15 @@ static int ParOutError(SConnection *con, ParData *o) { } return -1; } + /*----------------------------------------------------------------------------*/ -static void ParListSugar(SConnection *con, ParData *o) { +static void ParListSugar(SConnection * con, ParData * o) +{ ParInfo *p; char buf[512]; int l, i; char *sugar; - + p = o->infoList; l = snprintf(buf, sizeof buf, "%s sugar =", o->name); while (p != NULL) { @@ -381,56 +421,66 @@ static void ParListSugar(SConnection *con, ParData *o) { sugar = LoggerName(p->log); if (strchr(sugar, '.') == NULL && strcmp(sugar, o->name) != 0) { i = snprintf(buf + l, sizeof buf - l, " %s", sugar); - if ( i<=0 ) break; + if (i <= 0) + break; l += i; - if (l >= sizeof buf - 1) break; + if (l >= sizeof buf - 1) + break; } } p = p->next; } SCWrite(con, buf, eValue); } + /*----------------------------------------------------------------------------*/ -void ParSaveConn(void *object, SConnection *con) { +void ParSaveConn(void *object, SConnection * con) +{ ParData *o = ParCheck(&parClass, object); int rights; - + rights = SCGetRights(con); if (rights >= usMugger && rights <= usUser && con->sockHandle >= 0) { - if(o->conn != NULL){ - SCDeleteConnection(o->conn); - } + if (o->conn != NULL) { + SCDeleteConnection(o->conn); + } o->conn = SCCopyConnection(con); } } + /*----------------------------------------------------------------------------*/ -static int ParExecute(SConnection *con, SicsInterp *sics, void *object, int argc, char *argv[]) { - static char *empty[1]={""}; +static int ParExecute(SConnection * con, SicsInterp * sics, void *object, + int argc, char *argv[]) +{ + static char *empty[1] = { "" }; long id; int iret, logIt = 0; ParData *o = ParCheck(&parClass, object); char *setArgv[2]; - + ParBegin(); ctx->callName = argv[0]; ParSaveConn(o, con); - - if (argc>1) ctx->thisPar = argv[1]; - if (argc >= 2 && 0==strcasecmp(argv[1], "list")) { + + if (argc > 1) + ctx->thisPar = argv[1]; + if (argc >= 2 && 0 == strcasecmp(argv[1], "list")) { ctx->argc = argc - 2; ctx->argv = argv + 2; ParDo(con, o, PAR_LIST, NULL); ParEnd(); return 1; } - if (argc == 1) { /* no args */ + if (argc == 1) { /* no args */ ctx->enumText = 0; ParDo(con, o, PAR_SHOW, ""); if (ctx->returnValue == 0) { SCSendOK(con); ctx->returnValue = 1; } - } else if ((0 == strcasecmp(argv[1], "log") || 0 == strcasecmp(argv[1], "unlog"))) { + } else + if ((0 == strcasecmp(argv[1], "log") + || 0 == strcasecmp(argv[1], "unlog"))) { if (argc < 3) { ctx->returnValue = ILLARGC; ctx->thisPar = argv[1]; @@ -441,7 +491,9 @@ static int ParExecute(SConnection *con, SicsInterp *sics, void *object, int argc ctx->exact = 0; ParDo(con, o, PAR_LOGSWITCH, argv[2]); } - } else if ((0 == strcasecmp(argv[1], "save") || 0 == strcasecmp(argv[1], "unsave"))) { + } else + if ((0 == strcasecmp(argv[1], "save") + || 0 == strcasecmp(argv[1], "unsave"))) { if (argc != 3) { ctx->returnValue = ILLARGC; } else { @@ -449,33 +501,33 @@ static int ParExecute(SConnection *con, SicsInterp *sics, void *object, int argc ParDo(con, o, PAR_SAVESWITCH, argv[2]); } SCparChange(con); - } else if (strcmp(argv[1],"interest") == 0) { + } else if (strcmp(argv[1], "interest") == 0) { if (!o->pCall) { o->pCall = CreateCallBackInterface(); } assert(o->pCall); - id = RegisterCallback(o->pCall,VALUECHANGE, ParCallBack, - SCCopyConnection(con), SCDeleteConnection); + id = RegisterCallback(o->pCall, VALUECHANGE, ParCallBack, + SCCopyConnection(con), SCDeleteConnection); SCSendOK(con); ParEnd(); return 1; - } else if (strcmp(argv[1],"uninterest") == 0) { + } else if (strcmp(argv[1], "uninterest") == 0) { if (o->pCall) { RemoveCallbackCon(o->pCall, con); } SCSendOK(con); ParEnd(); return 1; - } else if (strcmp(argv[1],"sugar") == 0) { + } else if (strcmp(argv[1], "sugar") == 0) { ParListSugar(con, o); ParEnd(); return 1; - } else if (strcmp(argv[1],"enumText") == 0) { + } else if (strcmp(argv[1], "enumText") == 0) { if (argc == 3) { ctx->enumText = 1; ParDo(con, o, PAR_SHOW, argv[2]); } - } else if (strcmp(argv[1],"endinit") == 0) { + } else if (strcmp(argv[1], "endinit") == 0) { initObj = NULL; ParEnd(); return 1; @@ -500,29 +552,32 @@ static int ParExecute(SConnection *con, SicsInterp *sics, void *object, int argc /* parameter not found, try to use args as set value for pure object not a very good idea: a typo in a parameter name will change pure value --> use always '=' - if (ctx->returnValue == 0) { - ctx->argc = argc - 1; - ctx->argv = argv + 1; - errPar = ctx->thisPar; - ParDo(con, o, PAR_SET, ""); - if (ctx->returnValue <= 0) { - ctx->thisPar = errPar; - ctx->returnValue = UNKPAR; - } - } - */ + if (ctx->returnValue == 0) { + ctx->argc = argc - 1; + ctx->argv = argv + 1; + errPar = ctx->thisPar; + ParDo(con, o, PAR_SET, ""); + if (ctx->returnValue <= 0) { + ctx->thisPar = errPar; + ctx->returnValue = UNKPAR; + } + } + */ } } if (ctx->returnValue == 0) { ctx->returnValue = UNKPAR; } iret = ParOutError(con, o); - if (logIt) ParLogForced(o); /* log changes */ + if (logIt) + ParLogForced(o); /* log changes */ ParEnd(); return iret; } + /*----------------------------------------------------------------------------*/ -static void KillLogger(ParInfo *par) { +static void KillLogger(ParInfo * par) +{ if (par->log != NULL) { LoggerKill(par->log); if (par->sugarStatus == 1) { @@ -532,8 +587,10 @@ static void KillLogger(ParInfo *par) { par->log = NULL; } } + /*----------------------------------------------------------------------------*/ -int ParSwitchLog(int on, char *name) { +int ParSwitchLog(int on, char *name) +{ char buf[80], alias[80]; KillLogger(ctx->par); @@ -548,24 +605,29 @@ int ParSwitchLog(int on, char *name) { } if (loggerDir == NULL) { loggerDir = IFindOption(pSICSOptions, "LoggerDir"); - if (loggerDir == NULL) loggerDir="./"; + if (loggerDir == NULL) + loggerDir = "./"; LoggerSetDir(loggerDir); } ctx->par->log = LoggerMake(name, ctx->obj->period, ctx->exact); if (ctx->par->log == NULL) { return BADLOG; } - if (ctx->par->sugarStatus == 0 && name != buf && strcmp(name,buf) != 0) { - snprintf(alias, sizeof alias, "%s %s", ctx->obj->name, ctx->par->name); + if (ctx->par->sugarStatus == 0 && name != buf + && strcmp(name, buf) != 0) { + snprintf(alias, sizeof alias, "%s %s", ctx->obj->name, + ctx->par->name); ctx->par->sugarStatus = SugarMake(name, alias); } } return 1; } + /*--------------------------------------------------------------------------*/ -void ParFind(void) { +void ParFind(void) +{ ParInfo *p, **last, **endList; - + assert(ctx); if (ctx->par == NULL) { last = &ctx->obj->infoList; @@ -582,7 +644,7 @@ void ParFind(void) { } else { p = NULL; } - if (p == NULL) { /* not found: search again from list head */ + if (p == NULL) { /* not found: search again from list head */ p = ctx->obj->infoList; while (p != NULL && 0 != strcmp(p->name, ctx->parName)) { if (p == ctx->par) { @@ -593,7 +655,8 @@ void ParFind(void) { } if (p == NULL) { p = calloc(1, sizeof *p); - if (p == NULL) return; + if (p == NULL) + return; p->name = ctx->parName; p->log = NULL; p->saveIt = 0; @@ -605,8 +668,10 @@ void ParFind(void) { } ctx->par = p; } + /*--------------------------------------------------------------------------*/ -long ParText2Int(char *text) { +long ParText2Int(char *text) +{ long num = 0; if (strcasecmp(text, "undefined") == 0 || text[0] == '\0') { @@ -614,7 +679,7 @@ long ParText2Int(char *text) { } if (ctx->enumList) { while (ctx->enumList[num] != NULL) { - if (strcasecmp(ctx->enumList[num],text) == 0) { + if (strcasecmp(ctx->enumList[num], text) == 0) { return num; } num++; @@ -622,15 +687,18 @@ long ParText2Int(char *text) { } return -1; } + /*--------------------------------------------------------------------------*/ -char *ParInt2Text(int num) { +char *ParInt2Text(int num) +{ int i; static char buf[12]; - + if (num == PAR_LNAN) { - return ""; /* undefined */ + return ""; /* undefined */ } - if (! ctx->enumList) return NULL; + if (!ctx->enumList) + return NULL; for (i = 0; i <= num; i++) { if (ctx->enumList[i] == NULL) { return NULL; @@ -638,12 +706,16 @@ char *ParInt2Text(int num) { } return ctx->enumList[num]; } + /*----------------------------------------------------------------------------*/ -void ParGroup(char *groupFmt) { +void ParGroup(char *groupFmt) +{ ctx->grpFmt = groupFmt; } + /*----------------------------------------------------------------------------*/ -void ParName(char *name) { +void ParName(char *name) +{ if (ctx->grpFmt && *ctx->grpFmt) { snprintf(ctx->combiName, sizeof ctx->combiName, ctx->grpFmt, name); @@ -654,13 +726,13 @@ void ParName(char *name) { ParFind(); ctx->fmt = NULL; ctx->action = ctx->act; - + assert(ctx); switch (ctx->act) { case PAR_SHOW: case PAR_SET: ctx->enumList = NULL; - if (0==strcasecmp(name, ctx->thisPar)) { + if (0 == strcasecmp(name, ctx->thisPar)) { ctx->access = -1; } else { ctx->action = PAR_NOOP; @@ -674,25 +746,25 @@ void ParName(char *name) { case PAR_LOG: return; case PAR_LOGSWITCH: - if (0==strcasecmp(name, ctx->thisPar)) { + if (0 == strcasecmp(name, ctx->thisPar)) { ctx->access = -1; } else { ctx->action = PAR_NOOP; } return; case PAR_SAVESWITCH: - if (0==strcasecmp(name, ctx->thisPar)) { + if (0 == strcasecmp(name, ctx->thisPar)) { ctx->access = -1; } else { ctx->action = PAR_NOOP; } return; case PAR_INIT: - /* for save: use -1 as default value */ + /* for save: use -1 as default value */ ctx->access = -1; ctx->doit = -1; - ctx->logName = ""; /* log by default */ - ctx->exact = 0; /* not exact by default */ + ctx->logName = ""; /* log by default */ + ctx->exact = 0; /* not exact by default */ return; case PAR_GET: if (0 != strcasecmp(name, ctx->thisPar)) { @@ -705,8 +777,10 @@ void ParName(char *name) { return; } } + /*----------------------------------------------------------------------------*/ -static int RestoreMode(void) { +static int RestoreMode(void) +{ assert(ctx); if (initObj == ctx->obj) { return 1; @@ -714,14 +788,16 @@ static int RestoreMode(void) { initObj = NULL; return 0; } + /*----------------------------------------------------------------------------*/ -ParOp ParWhat(int numeric) { +ParOp ParWhat(int numeric) +{ static char buf[80]; char *sp, *lname; int i; ParOp op; int on; - + assert(ctx); switch (ctx->action) { case PAR_LIST: @@ -732,7 +808,9 @@ ParOp ParWhat(int numeric) { ctx->doit = 0; } } - if (ctx->doit || (ctx->argc > 0 && 0 == strcasecmp(ctx->argv[0], "all"))) return FMT_OP; + if (ctx->doit + || (ctx->argc > 0 && 0 == strcasecmp(ctx->argv[0], "all"))) + return FMT_OP; break; case PAR_LOG: if (ctx->par && ctx->par->log) { @@ -778,7 +856,7 @@ ParOp ParWhat(int numeric) { } break; case PAR_INIT: - if (! RestoreMode()) { + if (!RestoreMode()) { if (ctx->access < 0) { ctx->access = usInternal; } @@ -789,13 +867,13 @@ ParOp ParWhat(int numeric) { ctx->doit = 1; } } - if (ctx->doit) { /* set save flag */ + if (ctx->doit) { /* set save flag */ if (ctx->par) { ctx->par->saveIt = 1; } } } - if (ctx->logName) { /* set log */ + if (ctx->logName) { /* set log */ if (ctx->par) { if (ctx->logName[0] != '\0') { lname = ctx->logName; @@ -834,9 +912,11 @@ ParOp ParWhat(int numeric) { } if (ctx->par->saveLog) { if (ctx->par->log) { - fprintf(ctx->saveFile, " %s log %s %s\n", ctx->obj->name, ctx->parName, LoggerName(ctx->par->log)); + fprintf(ctx->saveFile, " %s log %s %s\n", ctx->obj->name, + ctx->parName, LoggerName(ctx->par->log)); } else { - fprintf(ctx->saveFile, " %s unlog %s\n", ctx->obj->name, ctx->parName); + fprintf(ctx->saveFile, " %s unlog %s\n", ctx->obj->name, + ctx->parName); } } if (ctx->par && ctx->par->saveIt == 1) { @@ -852,11 +932,13 @@ ParOp ParWhat(int numeric) { default: return NO_OP; } - ctx->action = PAR_NOOP; /* for the result of ParActionIs */ + ctx->action = PAR_NOOP; /* for the result of ParActionIs */ return NO_OP; } + /*----------------------------------------------------------------------------*/ -void ParOut(char *buf) { +void ParOut(char *buf) +{ int l, i, j, m, ln, lp, iret; char *p; char buffer[256]; @@ -865,22 +947,23 @@ void ParOut(char *buf) { char *sep; char *saved, *logged; time_t last; - + assert(ctx); - assert(ctx->fmt==NULL); + assert(ctx->fmt == NULL); switch (ctx->action) { case PAR_LIST: /* - if (ctx->par->log) { - snprintf(buffer, sizeof buffer, "%s", LoggerName(ctx->par->log)); + if (ctx->par->log) { + snprintf(buffer, sizeof buffer, "%s", LoggerName(ctx->par->log)); + } else { + */ + if (ctx->parName[0] != '\0') { + snprintf(buffer, sizeof buffer, "%s.%s", ctx->callName, + ctx->parName); } else { - */ - if (ctx->parName[0] != '\0') { - snprintf(buffer, sizeof buffer, "%s.%s", ctx->callName, ctx->parName); - } else { - snprintf(buffer, sizeof buffer, "%s", ctx->callName); - } - + snprintf(buffer, sizeof buffer, "%s", ctx->callName); + } + if (ctx->enumList) { i = strtol(buf, &endp, 0); if (endp != buf) { @@ -889,27 +972,34 @@ void ParOut(char *buf) { } p = buf; /* find dot or end of number */ - while (*p == ' ') p++; /* skip blanks */ + while (*p == ' ') + p++; /* skip blanks */ i = 0; - if (p[i] == '-') i++; + if (p[i] == '-') + i++; j = i; - while (p[i] >= '0' && p[i] <='9') i++; + while (p[i] >= '0' && p[i] <= '9') + i++; l = strlen(p); ln = strlen(buffer) - strlen(ctx->callName); if (i != j && (buf[i] == '.' || buf[i] <= ' ')) { - l += 16 - i - ln; /* decimal point or end of number at least 16 chars after object name */ + l += 16 - i - ln; /* decimal point or end of number at least 16 chars after object name */ lp = strlen(p); - if (l < lp) l = lp; - m = 23 - l - ln; /* unit/comment at least 23 chars after object name */ - } else { /* non numeric value */ - l = 21 - ln; /* text right justified if possible */ + if (l < lp) + l = lp; + m = 23 - l - ln; /* unit/comment at least 23 chars after object name */ + } else { /* non numeric value */ + l = 21 - ln; /* text right justified if possible */ /* m = 1; */ m = 23 - l - ln; } - if (m < 1) m = 1; - if (ctx->listTail == NULL) ctx->listTail = ""; + if (m < 1) + m = 1; + if (ctx->listTail == NULL) + ctx->listTail = ""; m += strlen(ctx->listTail); - if (l <= 0) l = 1; + if (l <= 0) + l = 1; saved = ""; logged = ""; if (ctx->argc > 0 && 0 == strcasecmp(ctx->argv[0], "all")) { @@ -922,7 +1012,8 @@ void ParOut(char *buf) { saved = " (saved by driver)"; } } - ParPrintf(NULL, eWarning, "%s %*s%*s%s%s", buffer, l, p, m, ctx->listTail, logged, saved); + ParPrintf(NULL, eWarning, "%s %*s%*s%s%s", buffer, l, p, m, + ctx->listTail, logged, saved); break; case PAR_SHOW: if (ctx->enumText) { @@ -932,19 +1023,30 @@ void ParOut(char *buf) { } else { p == NULL; } - if (p == NULL) p = ""; /* undefined */ + if (p == NULL) + p = ""; /* undefined */ ParPrintf(NULL, eValue, "%s", p); break; } - if (ctx->parName[0]) { p=" "; } else { p=""; } - ParPrintf(NULL, eValue, "%s%s%s = %s", ctx->callName, p, ctx->parName, buf); + if (ctx->parName[0]) { + p = " "; + } else { + p = ""; + } + ParPrintf(NULL, eValue, "%s%s%s = %s", ctx->callName, p, ctx->parName, + buf); break; case PAR_SET: - if (ctx->parName[0]) { p=" "; } else { p=""; } - ParPrintf(NULL, eValue, "%s%s%s = %s", ctx->callName, p, ctx->parName, buf); + if (ctx->parName[0]) { + p = " "; + } else { + p = ""; + } + ParPrintf(NULL, eValue, "%s%s%s = %s", ctx->callName, p, ctx->parName, + buf); if (!ctx->obj->logPending) { ctx->obj->logPending = 1; - TaskRegister(pServ->pTasker, ParLog, NULL, NULL, ctx->obj, 0); /* schedule ParLog */ + TaskRegister(pServ->pTasker, ParLog, NULL, NULL, ctx->obj, 0); /* schedule ParLog */ } break; case PAR_LOG: @@ -953,85 +1055,110 @@ void ParOut(char *buf) { ctx->par->state = PAR_NOT_READY; last = LoggerLastTime(ctx->par->log); if (last != 0 && ctx->now - ctx->obj->period > last) { - LoggerWrite(ctx->par->log, ctx->now - ctx->obj->period, ctx->obj->period, buf); + LoggerWrite(ctx->par->log, ctx->now - ctx->obj->period, + ctx->obj->period, buf); } } else if (ctx->par->state != PAR_ALWAYS_READY) { break; } if (showTime && ctx->obj->pCall) { - snprintf(buffer, sizeof buffer, "