/** \file counterdriv.c * \brief Sics counter driver for the ANSTO beam monitor. * * A SICS counter can manage several monitors, this is the driver * for the beam monitor developed at ANSTO * * Copyright: see file Copyright.txt * * Ferdi Franceschini July 2006 * */ #include #include #include #include #include #include "fortify.h" #include #include #include #include #include "anstoutil.h" #ifdef SPLINT /*@-incondefs@*/ int gettimeofday(/*@out@*/ struct timeval *restrict tp, /*@null@*/ void *restrict tzp); char *strdup(const char *s); int strcasecmp(const char *s1, const char *s2); int strncasecmp(const char *s1, const char *s2, size_t n); unsigned long long int strtoull(const char *nptr, /*@null@*/ char **endptr, int base); /*@+incondefs@*/ #endif /*@-incondefs@*/ /*@observer@*//*@dependent@*/ Tcl_Interp *InterpGetTcl(SicsInterp *pSics); int readRS232(prs232 self, /*@out@*/void *data, /*@out@*/int *dataLen); int readRS232TillTerm(prs232 self, /*@out@*/void *data, /*@out@*/int *dataLen); void getRS232Error(int iCode, /*@out@*/ char *errorBuffer, int errorBufferLen); /*@observer@*//*@dependent@*/ pCounterDriver CreateCounterDriver(char *name, char *type); void KillRS232(/*@only@ frees pData */ void *pData); /*@+incondefs@*/ typedef unsigned long long int uint64; typedef struct { int length; char body[8192]; } BUFFER; typedef struct { prs232 controller; int state; int errorCode; char *errorMsg; /**< Points to memory for error messages */ char *host; int iPort; float dummy_threshold; BUFFER buffer; uint64 counter_value; } BeamMon, *pBeamMon; /** \brief file logging * * Logs text to a debug file. The file is opened and closed for each call. * * \param flag character used to distinguish calls * \param pText pointer to text to be logged */ static void flog(char flag, char* pText) { FILE* file; file = fopen("flog.txt", "a"); if (file) { struct timeval tv; (void) gettimeofday(&tv, NULL); fprintf(file, "%02d:%02d:%02d:%06d::%c::%s", tv.tv_sec % (24 * 3600) / 3600, tv.tv_sec % (3600) / 60, tv.tv_sec % 60, tv.tv_usec, flag, pText); if (strchr(pText, '\n') == NULL) (void) fputc('\n', file); (void) fclose(file); } } /** \brief Writes a line to the Monitor * used for sending commands. * * \param *cntrData provides access to a monitor's data * \param *text pointer to NULL terminated text to send. * \return SUCCESS or FAILURE */ static int MonWrite(pBeamMon self, char* text) { size_t len; int status; len = strlen(text); if (len > 0) flog('>', text); status = writeRS232(self->controller, text, (int) len); if (status != 1) { self->errorCode = status; return FAILURE; } return SUCCESS; } /** \brief Reads a line from the Monitor * used for sending commands. * * \param *cntrData provides access to a monitor's data * \param *text pointer to NULL terminated text to receive. * \param *pLen inout pointer to length of text to receive. * \return SUCCESS or FAILURE */ static int MonRead(pBeamMon self, /*@out@*/ char* text, int *pLen) { int i, status, retries=20; *text = '\0'; for (i=0; icontroller, text, pLen); switch (status) { case 1: if (pLen > 0) flog('<', text); return SUCCESS; case TIMEOUT: flog('<', "*TIMEOUT*"); self->errorCode = status; continue; default: flog('<', "*ERROR*"); self->errorCode = status; return FAILURE; } } flog('<', "***TIMEOUT***"); return FAILURE; } /** \brief drains any pending input on the RS232 channel * * \param *cntrData provides access to a monitor's data */ static void MonDrainInput(CounterDriver *cntrData) { int iRet; int len; char reply[1024]; BeamMon* self = NULL; self = (BeamMon *) cntrData->pData; while (availableRS232(self->controller) != 0) { len = (int) sizeof(reply); iRet = MonRead(self, reply, &len); if (iRet == FAILURE) { return; } } } /** \brief sends a command to the monitor and gets the reply * * \param cntrData provides access to a monitor's data * \param pText command to send * \param pReply space for reply * \param iReplyLen length of space for reply * \return SUCCESS or FAILURE */ static int MonSend(CounterDriver *cntrData, char *pText, char *pReply, int iReplyLen) { BeamMon *self = NULL; int status; self = (BeamMon *) cntrData->pData; MonDrainInput(cntrData); status = MonWrite(self, pText); if (status != SUCCESS) return status; if ((status = MonRead(self, pReply, &iReplyLen)) == SUCCESS) { pReply[iReplyLen] = '\0'; return SUCCESS; } return status; } /** \brief sends a command to the monitor and gets the reply * * \param cntrData provides access to a monitor's data * \param pText command to send * \param buffer space for reply * \return SUCCESS or FAILURE */ static int MonSendBuffer(CounterDriver *cntrData, char *pText, BUFFER* buffer) { int status; buffer->length = 0; status = MonSend(cntrData, pText, buffer->body, (int) sizeof(buffer->body)); if (status == SUCCESS) { buffer->length = (int) strlen(buffer->body); } return status; } /** \brief parses and acts upon the READ line * * \param *cntrData provides access to a monitor's data * \param bp pointer to buffer containing the text line * * This function sets the state of the counter based on state flags reported by * the monitor. */ static void HandleReport(CounterDriver *cntrData, BUFFER* bp) { //READ xxxx 00:00:00.000000 0.000000 0 0.00 //0123456789012345678901234567890 BeamMon* self = NULL; char *cp = NULL; char *ep = NULL; char str[100]; self = (BeamMon *) cntrData->pData; /* TODO better than this */ cp = &bp->body[26]; cntrData->fTime = (float) strtod(cp, &ep); cp = ep; switch (toupper(bp->body[5])) { case 'I': /* idle */ case 'S': /* stopped */ self->state = HWIdle; break; case 'R': /* running */ self->state = HWBusy; break; case 'P': /* paused */ self->state = HWPause; break; default: /* should not happen */ self->state = HWFault; break; } if ((self->state == HWBusy || self->state == HWPause) && (toupper(bp->body[8]) == (int) 'G')) /* Gated */ self->state = HWNoBeam; self->counter_value = strtoull(cp, &ep, 10); cntrData->fLastCurrent = (float) self->counter_value; (void) snprintf(str, sizeof(str), "READ %s, %f, %f, %f\n", cntrData->eMode == eTimer ? "eTimer" : cntrData->eMode == ePreset ? "ePreset" : "Unknown", cntrData->fPreset, cntrData->fLastCurrent, cntrData->fTime); flog('.', str); } /** \brief handles an input line received on the RS232 channel * * \param cntrData provides access to a monitor's data * \param bp pointer to buffer containing the line of input * * This function sets the state of the counter based on events reported by * the monitor. */ static void MonHandleInput(CounterDriver *cntrData, BUFFER* bp) { BeamMon* self = NULL; const char et[] = "EVENT TERMINAL"; const char eri[] = "EVENT RANGE IN"; const char ero[] = "EVENT RANGE OUT"; const char rpt[] = "READ"; self = (BeamMon *) cntrData->pData; /* TODO handle the line */ flog('=', bp->body); if (strncasecmp(bp->body, et, sizeof(et) - 1) == 0) { if (self->state == HWBusy) self->state = HWIdle; } if (strncasecmp(bp->body, eri, sizeof(eri) - 1) == 0) if (self->state == HWPause) self->state = HWBusy; if (strncasecmp(bp->body, ero, sizeof(ero) - 1) == 0) if (self->state == HWBusy) self->state = HWPause; if (strncasecmp(bp->body, rpt, sizeof(rpt) - 1) == 0) { HandleReport(cntrData, &self->buffer); } bp->length = 0; } /** \brief look for input on the socket * * breaks input into lines terminated by pairs and passes complete lines to MonHandleInput for processing. * * \param cntrData provides access to a monitor's data * \param timeout upper limit on time to wait for data to arrive */ static void MonLookForInput(CounterDriver *cntrData, /*@unused@*/ int timeout) { BeamMon* self = NULL; int iRet, len; int iLen = 0; int jLen = 0; char reply[1024]; self = (BeamMon *) cntrData->pData; while (availableRS232(self->controller) != 0) { len = (int) sizeof(reply); iRet = MonRead(self, reply, &len); if (iRet == FAILURE) { return; } iLen = 0; while (iLen < len) { char* pTerm = strstr(&reply[iLen], "\r\n"); if (pTerm) jLen = &pTerm[2] - &reply[iLen]; else jLen = len - iLen; strncpy(&self->buffer.body[self->buffer.length], &reply[iLen], (size_t) jLen); self->buffer.length += jLen; self->buffer.body[self->buffer.length] = '\0'; iLen += jLen; if (pTerm) { /* handle the line */ MonHandleInput(cntrData, &self->buffer); } self->buffer.length = 0; } } } /** \brief Returns the counter status, * implements the GetStatus method in the MotorDriver interface. * * \param *cntrData provides access to a monitor's data * \param *fControl is set to the current value of the counting control variable. This can either be the counting time already passed or the count rate of the control monitor in ePreset mode. * \return * - HWIdle The counter has finished and is idle. * - HWFault hardware fault or the counter returned an absurd value. * - HWNoBeam There is no incident beam. * - HWPause Counting has been paused. * - HWBusy The counter is busy counting. */ static int MonGetStatus(CounterDriver *cntrData, float *fControl) { BeamMon *self = NULL; int status; self = (BeamMon *) cntrData->pData; MonLookForInput(cntrData, 0); status = MonSendBuffer(cntrData, "SICS READ", &self->buffer); if (status == SUCCESS) { /* TODO */ MonHandleInput(cntrData, &self->buffer); } if (cntrData->eMode == eTimer) *fControl = cntrData->fTime; else *fControl = cntrData->fLastCurrent; switch (self->state) { case HWIdle: return HWIdle; case HWNoBeam: return HWNoBeam; case HWPause: return HWPause; case HWBusy: return HWBusy; case HWFault: default: return HWFault; } } /** \brief Starts counting in the current mode and with the current preset * * \param *cntrData provides access to a monitor's data * \return SUCCESS or FAILURE * * This function also sets some of the parameters in the monitor for mode and * preset. * * TODO: check the return from the monitor */ static int MonStart(CounterDriver *cntrData) { BeamMon *self = NULL; int status; char str[100]; (void) snprintf(str, sizeof(str), "START %s, %f, %f, %f\n", cntrData->eMode == eTimer ? "eTimer" : cntrData->eMode == ePreset ? "ePreset" : "Unknown", cntrData->fPreset, cntrData->fLastCurrent, cntrData->fTime); flog('.', str); self = (BeamMon *) cntrData->pData; MonDrainInput(cntrData); if (cntrData->eMode == eTimer) { status = MonSendBuffer(cntrData, "SICS SET TE_CHECK=TIMER", &self->buffer); if (status != SUCCESS || strcasecmp(self->buffer.body, "OK") != 0) { self->errorCode = /* TODO */ 0; return FAILURE; } } else { status = MonSendBuffer(cntrData, "SICS SET TE_CHECK=COUNTER", &self->buffer); if (status != SUCCESS || strcasecmp(self->buffer.body, "OK") != 0) { self->errorCode = /* TODO */ 0; return FAILURE; } } /*@-duplicatequals@ for uint64 */ /*@-formattype@ for uint64 */ (void) snprintf(str, sizeof(str), "SICS SET TERMINAL=%llu", (uint64) cntrData->fPreset); /*@+formattype@*/ /*@+duplicatequals@*/ status = MonSendBuffer(cntrData, str, &self->buffer); if (status != SUCCESS || strcasecmp(self->buffer.body, "OK") != 0) { self->errorCode = /* TODO */ 0; return FAILURE; } status = MonSendBuffer(cntrData, "SICS START", &self->buffer); if (status != SUCCESS || strcasecmp(self->buffer.body, "OK") != 0) { self->errorCode = /* TODO */ 0; return FAILURE; } self->state = HWBusy; return SUCCESS; } /** \brief Pauses a counting operation * * \param *cntrData provides access to a monitor's data * \return SUCCESS or FAILURE * * TODO: check if we should set the state to HWPause or just leave it till we * get it back from the monitor. */ static int MonPause(CounterDriver *cntrData) { BeamMon *self = NULL; int status; self = (BeamMon *) cntrData->pData; status = MonSendBuffer(cntrData, "SICS PAUSE", &self->buffer); if (status == SUCCESS) { self->state = HWPause; return SUCCESS; } return FAILURE; } /* \brief Continues a paused counting operation. * * \param *cntrData provides access to a monitor's data * \return SUCCESS or FAILURE * * TODO: check if we should set the sate to HWBusy or just leave it till we * get it back from the monitor. */ static int MonContinue(CounterDriver *cntrData) { BeamMon *self = NULL; int status; self = (BeamMon *) cntrData->pData; status = MonSendBuffer(cntrData, "SICS CONTINUE", &self->buffer); if (status == SUCCESS) { self->state = HWBusy; return SUCCESS; } return FAILURE; } /** \brief Cancels a counting operation. This is an emergency stop used when interrupting an operation. * \param *cntrData provides access to a monitor's data * \return SUCCESS or FAILURE * * TODO: check if we should set the sate to HWIdle or just leave it till we * get it back from the monitor. */ static int MonHalt(CounterDriver *cntrData) { BeamMon *self = NULL; int status; self = (BeamMon *) cntrData->pData; status = MonSendBuffer(cntrData, "SICS STOP", &self->buffer); if (status == SUCCESS) { self->state = HWIdle; return SUCCESS; } return FAILURE; } /** \brief Reads the counter and the monitors in the lCounts array. * * \param *cntrData provides access to a monitor's data * \return SUCCESS or FAILURE */ static int MonReadValues(CounterDriver *cntrData) { BeamMon *self = NULL; int status; flog('.', "MonReadValues"); self = (BeamMon *) cntrData->pData; status = MonSendBuffer(cntrData, "SICS READ", &self->buffer); if (status == SUCCESS) { HandleReport(cntrData, &self->buffer); cntrData->lCounts[0] = (long) self->counter_value; /* NOTE: truncation */ return SUCCESS; } return FAILURE; } /* \brief Called when an error condition is reported by a counter operation. * * \param *cntrData provides access to a monitor's data * \param *iCode error code returned to logical counter. * \param *error error message * \param iErrLen maximum error message length allowed. * \return SUCCESS or FAILURE */ static int MonGetError(CounterDriver *cntrData, int *iCode, char *error, int iErrLen) { BeamMon *self = NULL; flog('.', "MonGetError"); self = (BeamMon *) cntrData->pData; /* Allocate iErrLen bytes for error messages */ if (self->errorMsg == NULL) { self->errorMsg = (char *) malloc((size_t) iErrLen); if (self->errorMsg == NULL) { return FAILURE; } } error = self->errorMsg; *iCode = self->errorCode; switch (*iCode) { case 0: strncpy(error, "UNKNOWN ERROR: counterdriv did not set an errorcode.", (size_t) iErrLen); break; case NOTCONNECTED: case TIMEOUT: case BADSEND: case BADMEMORY: case INCOMPLETE: getRS232Error(*iCode, error, iErrLen); break; default: (void) snprintf(error, (size_t) iErrLen, "Unknown error code: %d, returned from counterdriv", *iCode); } self->errorCode = 0; return SUCCESS; } /* \brief Tries to fix problem associated with iCode error reported by MonGetError. * * \param *cntrData provides access to a monitor's data * \param *iCode error code from MonGetError. * \return This code tells the logical counter if an error is recoverable. * - COREDO try to redo the last count operation. * - COTERM count operation failed, give up. */ static int MonTryAndFixIt(CounterDriver *cntrData, int iCode) { BeamMon *self = NULL; flog('.', "MonTryAndFixIt"); self = (BeamMon *) cntrData->pData; assert(self != NULL); switch(iCode){ case 0: /* Unknown error */ return COTERM; case NOTCONNECTED: if (initRS232(self->controller) == 1) return COREDO; return COTERM; case BADSEND: case TIMEOUT: case BADMEMORY: /* Won't happen if MonConnect sets the send terminator */ case INCOMPLETE: return COREDO; } return COTERM; } /*\brief Sets a parameter to a given value. * * \param *cntrData provides access to a monitor's data * \param *name the name of the parameter to set. * \param iCter counter to set */ static int MonSet(CounterDriver *cntrData, char *name, int iCter, float fVal) { BeamMon *self = NULL; char str[100]; (void) snprintf(str, 100, "MonSet(%s, %d, %f)", name, iCter, fVal); flog('.', str); self = (BeamMon *) cntrData->pData; if(strcmp(name,"threshold") == 0){ //TODO set threshold self->dummy_threshold = fVal; } /* TODO*/ return SUCCESS; } static int MonGet(CounterDriver *cntrData, char *name, int iCter, float *fVal) { BeamMon *self = NULL; char str[100]; self = (BeamMon *) cntrData->pData; if(strcasecmp(name,"threshold") == 0){ //TODO get threshold *fVal = self->dummy_threshold; } /* TODO*/ (void) snprintf(str, 100, "MonGet(%s, %d, %f)", name, iCter, *fVal); flog('.', str); return SUCCESS; } static void KillMon(/*@null@*/ pCounterDriver cntrData) { if (cntrData != NULL) { if (cntrData->pData != NULL) { pBeamMon self = (pBeamMon) cntrData->pData; if (self->host) { free(self->host); self->host = NULL; } if (self->errorMsg) { free(self->errorMsg); self->errorMsg = NULL; } KillRS232(self->controller); free(cntrData->pData); cntrData->pData = NULL; } /* TODO free(cntrData); */ } } /*@only@*/ prs232 createRS232(char *host, int iPort); /** \brief Open a connection to the motor controller * \param *pCon (r) connection object. * \param *host (r) Beam Monitor host address or name. * \param port Beam Monitor port number * \return controller structure */ /*@null@*/ /*@only@*/ static prs232 MonConnect(/*@dependent@*/SConnection *pCon, char *host, int port) { prs232 controller=NULL; char pError[ERRLEN]; int msecTimeout = 5000; /* 5000msec timeout */ controller=createRS232(host,port); if (controller==NULL) { (void) snprintf(pError, ERRLEN, "ERROR: failed to create controller for %s at port %d", host, port); (void) SCWrite(pCon,pError,eError); return NULL; } if ( initRS232(controller) != 1) { (void) snprintf(pError, ERRLEN, "ERROR: failed to connect to %s at port %d", host, port); (void) SCWrite(pCon,pError,eError); KillRS232(controller); return NULL; } setRS232ReplyTerminator(controller,"\r\n"); setRS232SendTerminator(controller,"\r\n"); setRS232Timeout(controller, msecTimeout); return controller; } /*@observer@*//*@null@*/ pCounterDriver CreateMonCounter(/*@observer@*/SConnection *pCon, /*@observer@*/char *name, char *params) { BeamMon *newCtr = NULL; pCounterDriver pCntDriv = NULL; char *pPtr = NULL; Tcl_Interp *interp; interp = InterpGetTcl(pServ->pSics); newCtr = (BeamMon *)malloc(sizeof(BeamMon)); if(NULL == newCtr){ (void) SCWrite(pCon,"ERROR: no memory to allocate counter driver", eError); return NULL; } newCtr->controller = NULL; newCtr->state = HWIdle; newCtr->errorCode = 0; newCtr->errorMsg = NULL; newCtr->host = NULL; newCtr->iPort = 0; newCtr->dummy_threshold = 0; pCntDriv = CreateCounterDriver(name, "anstomonitor"); if(!pCntDriv) { free(newCtr); return NULL; } pCntDriv->GetStatus = MonGetStatus; pCntDriv->Start = MonStart; pCntDriv->Pause = MonPause; pCntDriv->Continue = MonContinue; pCntDriv->Halt = MonHalt; pCntDriv->ReadValues = MonReadValues; pCntDriv->GetError = MonGetError; pCntDriv->TryAndFixIt = MonTryAndFixIt; pCntDriv->Set = MonSet; pCntDriv->Get = MonGet; pCntDriv->Send = MonSend; pCntDriv->iNoOfMonitors = 1; memset(newCtr, 0, sizeof(BeamMon)); newCtr->state = HWIdle; /*@-mustfreeonly@ pData = NULL after CreateCounterDriver is called */ pCntDriv->pData = newCtr; /*@+mustfreeonly@*/ /* Get hostname and port from the list of named parameters */ if ((pPtr=getParam(pCon, interp, params,"port",1)) == NULL) { KillMon(pCntDriv); return NULL; } (void) sscanf(pPtr,"%d", &newCtr->iPort); if ((pPtr=getParam(pCon, interp, params,"host",1)) == NULL) { KillMon(pCntDriv); return NULL; } /*@-mustfreeonly@ host = NULL after BeamMon is created */ newCtr->host = strdup(pPtr); /*@+mustfreeonly@*/ /*@-mustfreeonly@ controller = NULL after BeamMon is created */ newCtr->controller = MonConnect(pCon, newCtr->host, newCtr->iPort); /*@+mustfreeonly@*/ newCtr->dummy_threshold = 1.7e6; return pCntDriv; }