/*============================================================================= Filename: mgntSub.c Abs: This file contains all subroutine support for the device control and readback (magnet) subroutine records. Rem: All functions called by the subroutine record get passed one argument: Functions: Description ------------ ---------------------------- mgntInit General Initialization mgntDegaussInit Init for degauss waveform set points mgntExplodeInit Init for Records using Poly Coeffs waveform mgntStdzInit Init for stdz waveform set points mgntCalbLimitsInit Init for Records checking calibration measured currents mgntInitPoly Init for Records using Poly Coeffs mgntNumPolyCoef Find Number of Polynomial Coefficients mgntDbPoly Conversion from B to I mgntReversePoly Estimate Value doing Reverse Poly I to B (Newton) mgntPhyDeltas Calc Reverse Polynomial Epsilon and Deltas for Alarm and Warning Limits in Physical Units for BACT,BMON and MPS mgntRawDeltas Calc Deltas for Alarm and Warning Limits in Raw Units mgntLimits Set Alarm and Warning Limits for ACT and MON mgntBCONLimits Set Alarm and Warning Limits for BCON mgntMpsLimits Set Alarm Limit flag for MPS mgntCalbLimits Set in-tolerance flag for calibration measured currents mgntExplode Populate waveform with polynomial coeffients from subRecord mgntDegauss Put degaussing set points into a waveform mgntStdz Put standardize set points into a waveform mgntSlcStat Builds the SLC db STAT secondary mgntSlcStatMsg Builds the SLC STAT message seen on the SCP mgntHstaDecode Parses HSTACTRL into bo's (slc->epics) mgntHstaEncode creates one 16 bit hsta word in slc format mgntStatDecode Parses STAT into individual outputs mgntDrifting Check for significant change in bact All functions return a long integer. 0 = OK, -1 = ERROR. The subroutine record ignores the status returned by the Init routines. For the calculation routines, the record status (STAT) is set to SOFT_ALARM (unless it is already set to LINK_ALARM due to severity maximization) and the severity (SEVR) is set to psub->brsv (BRSV - set by the user in the database though it is expected to be invalid) Side: Place all functions called by the subroutine records in the mgntSub.dbd file also Auth: dd-mmm-yyyy, Author's Name (USERNAME) Rev: dd-mmm-yyyy, Reviewer's Name (USERNAME -------------------------------------------------------------- Mod: 17-Apr-2023, A. Le (ANLE): Do not set DAC Error bit if ISETPT.STAT is UDF 27-Feb-2023, A. Le (ANLE): Clear turned off by operator bit correctly 01-Feb-2022, K. Luchini (LUCHINI): remove BCXCBS2 21-Oct-2022, K. Luchini (LUCHINI): add BCXCBX13 and BCXCBS21 Degauss setpt waveform 02-Jun-2022, Shantha Condamoor (scondam) Added alarm subroutines for SPEAR. Called only from mgntApp/Db/spear database files 13-Sep-2021, K. Luchini (LUCHINI): add degauss waveforms MGNT_DEGAUS_I2_BXHS thru MGNT_DEGAUS_I8_BXHS int mgntDegaussOscillate function 22-Sep-2020, K. Luchini (LUCHINI): modify mgntDeguassOscillate to change the number of data points from 52 to 54 fo the soft x-ray chicane 01-Mar-2020, K. Luchini (LUCHINI): chg CONFIG_STRING_SLAVE to CONFIG_STRING 17-Dec-2018, K. Luchini (LUCHINI): chg genSubRecord to aSubRoutine for mgntDegaussInit, mgntDegauss,mgntStdz mgntCalbLimitsInit, mgntCalbLimits Add mgntStdzInit 05-Sep-2018, K. Luchini (LUCHINI): chg mgntHstaEncode and mgntSlcStat slave check 06-May-2015, K. Luchini (LUCHINI): mgntReversePoly check for NaN - not a number 22-Oct-2012, K. Luchini (LUCHINI): add check for secondary lower limit in mgntMpsLimits 27-Oct-2011, K. Luchini (LUCHINI): modify mgntMpsLimits to add special tolerance checking for the self-seating bend in the undulator (bxhs2). Checking if bact is above a hard limit for in-tolerance. 01-Aug-2011, K. Luchini (LUCHINI): chg mgntRawDeltas calculation of stdz tolerance 06-Apr-2009, K. Luchini (LUCHINI): add mgntMpsLimits 23-Aug-2007, K. Luchini (LUCHINI): chg mgntRiplOK subroutine 13-Jan-2007, K. Luchini (LUCHINI): changed filename to mgntSub.c and added standard headers some some functions. dd-mmm-2005, Stephanie Allison (SAA): ported magnet subroutines from slc micro job. ==============================================================*/ #include "copyright_SLAC.h" /* Header files */ #include "debugPrint.h" #ifdef DEBUG_PRINT int mgntSubFlag = DP_INFO; #endif #include /* for calloc */ #include /* for memset() */ #include /* for pow() */ #include /* for DBADDR */ #include /* for struct subRecord */ #include /* for struct sSubRecord in site area */ #include /* for struct aSubRecord */ #include /* for struct waveformRecord */ #include /* for epicsExport */ #include /* for epicsRegisterFunction */ #include /* epicsMutexMustCreate,etc */ #include /* for struct timespec */ #include /* for MAX_STRING_SIZE */ #include /* NO_ALARM, INVALID_ALARM */ #include /* for S_rec_outMem */ #include /* for S_dev_noDeviceFound */ #include /* for S_dev_lowValue */ #include /* for recGblRecordError() */ #include /* for DBF_DOUBLE */ #include /* for callocMustSucceed() */ #include /* DEGAUSS_TYPE_TRUE, etc */ #include /* for CTRL_DEGAUSS */ // mdunning 8/3/17: define macro dbGetPdbAddrFromLink below, due to its removal in base 3.15 #define dbGetPdbAddrFromLink(PLNK) \ ( ( (PLNK)->type != DB_LINK ) \ ? 0 \ : ( ( (struct dbAddr *)( (PLNK)->value.pv_link.pvt) ) ) ) typedef struct devicePvt_s { epicsUInt32 npts; epicsMutexId mlock; }devicePvt_ts; /* Local Prototypes */ static void mgntSlcStatMsg(unsigned short stat, unsigned short hsta, unsigned short onoffctrl, unsigned short *pval); static epicsUInt16 mgntDegaussOscillate( epicsUInt32 type, mgntDegauss_ts *dpvt_ps, epicsUInt32 debug); static epicsUInt16 mgntDegaussStandard( epicsUInt32 ncycles, double imin, double imax, mgntDegauss_ts *dpvt_ps ); /*============================================================================= Name: mgntInit Abs: Magnet initialization subroutine record Rem: Side: None Ret: long 0 - Successful (always) ==============================================================================*/ static long mgntInit(subRecord *psub) { long status=SUCCESS; /* * General purpose initialization required since all subroutine records * require a non-NULL init routine even if no initialization is required. * Note that most subroutines in this file use this routine as an init * routine. If init logic is needed for a specific subroutine, create a * new routine for it - don't modify this one. */ return(status); } /*============================================================================= Name: mgntDegaussInit Abs: Initialize records for function that generates degauss cycle set points Args: Type Name Access Description ------------------- ----------- ---------- ---------------------------- subRecord * psub read/write pointer to subroutine record Rem: Init Subroutine for PRIM:LOCA:UNIT:DEGAUSSUB Input: -------- INPA = :DEGAUSIMIN INPB = :DEGAUSIMAX INPC = :DEVICETYPE INPD = :DEGAUSCYCLENUM INPE = :DEGAUSMETHOD INPF = :PSTYPE INPG = :DEBUG INPH = :DEGAUSSTEP Output: -------- VALA = :DEGAUSWF - output waveform VALB = function status return DPVT = Pointer to private device informaiton Side: None Ret: long 0 - Successful -1 - for invalid INPA ==============================================================================*/ long mgntDegaussInit(aSubRecord *psub) { long status = SUCCESS; mgntDegauss_ts *dpvt_ps = NULL; /* Check that this pv has not already been initialized waveform too small */ if ( psub->dpvt || (psub->novaftva!=DBF_DOUBLE) { recGblRecordError(S_dev_badInpType,(void *)psub,"mgntDegauss: init_record"); return(-1); } /* Create the private device information */ dpvt_ps = callocMustSucceed(1,sizeof(mgntDegauss_ts),"calloc failed for mgntDegaussInit" ); dpvt_ps->mlock = epicsMutexMustCreate(); dpvt_ps->nelem = psub->nova; /* max items in array */ dpvt_ps->data_a = (double *)psub->vala; /* ptr to array */ dpvt_ps->nord_p = &psub->neva; /* # of items read in arary */ dpvt_ps->psType_p = (epicsUInt32 *)psub->f; /* power supply type */ psub->dpvt = dpvt_ps; return(status); } /*============================================================================= Name: mgntStdzInit Abs: Initialize records for function that generates degauss cycle set points Args: Type Name Access Description ------------------- ----------- ---------- ---------------------------- subRecord * psub read/write pointer to subroutine record Rem: Init Subroutine for PRIM:LOCA:UNIT:DEGAUSSUB Input: -------- INPA = :STDZIMIN INPB = :STDZIMAX INPC = :STDZIFINAL INPD = :STDZCYCLENUM INPE = :STDZDIRECT.RVAL INPG = :DEBUG Output: -------- VALA = :DEGAUSWF - output waveform VALB = function status return (0-success, 1=wf too small) DPVT = Pointer to private device informaiton Side: None Ret: long 0 - Successful -1 - Record unexpectedly initalized ==============================================================================*/ long mgntStdzInit(aSubRecord *psub) { long status = SUCCESS; devicePvt_ts *dpvt_ps = NULL; /* Check that this pv has not already been initialized */ if ( psub->dpvt ) return (-1); /* Check that this pv has an array of doubles for the degauss waveform */ if (psub->ftva!=DBF_DOUBLE) { recGblRecordError(S_dev_badInpType,(void *)psub,"mgntStdz: init_record"); return(-1); } /* Create the private device information */ dpvt_ps = callocMustSucceed(1,sizeof(devicePvt_ts),"calloc failed for mgntStdzInit" ); dpvt_ps->mlock = epicsMutexMustCreate(); psub->dpvt = dpvt_ps; return(status); } /*============================================================================= Name: mgntExplodeInit Abs: Initialize records that use in polynomial coefficients to waveform Args: Type Name Access Description ------------------- ----------- ---------- ---------------------------- subRecord * psub read/write pointer to subroutine record Rem: Init Subroutine for PRIM:LOCA:UNIT:COEF2WF Input: -------- INPA = :POLYCOEF (subroutine record) INPB = :IVB (wafeform record) Output: -------- DPVT = Pointer to array of pointers such that ptr[0] = ptr to subrecord :POLYCOEF ptr[1] = ptr to waveform record :IVB Side: None Ret: long 0 - Successful -1 - for invalid INPA or invalid INPB ==============================================================================*/ long mgntExplodeInit(subRecord *psub) { long status=SUCCESS; DBADDR *pdbAddr=0; DBADDR *pwfAddr=0; subRecord *prec=0; waveformRecord *pwf=0; struct mgntWfCoef *pdpvt=0; /* Check that this pv has not already been initialized */ if (psub->dpvt) return( -1 ); psub->dpvt = 0; pdbAddr = dbGetPdbAddrFromLink(&psub->inpa); if (!pdbAddr) { recGblRecordError(S_dev_noDeviceFound,(void *)psub,"sub: init_record"); return(-1); } /* Create an array of 2 pointers */ pdpvt = (mgntWfCoef *)calloc(sizeof(mgntWfCoef),1); if (!pdpvt) { recGblRecordError(S_rec_outMem,(void *)psub,"sub: init_record"); return -1; } /* Diagnostic message */ prec = (subRecord *)pdbAddr->precord; pdpvt->pcoef = &prec->a; /* ptr to subroutine record :POLYCOEF.A */ psub->dpvt = pdpvt; /* return private data pointer */ /* Determine if we have a DB_LINK as INPB, if not then we'll have a CONSTANT */ if((psub->inpb).type==CONSTANT) return(status); /* Get the pointer to the record in INPB. * Is this a valid pv? If so, then verify that data type is double. * Later need to verify that this is a wavefore record... */ pwfAddr = dbGetPdbAddrFromLink(&psub->inpb); if (!pwfAddr || (pwfAddr->field_type != DBF_DOUBLE)) return(-1); /* Set the private data information */ pwf = (waveformRecord *)pwfAddr->precord; pdpvt->pdata = (double *)pwf->bptr; /* ptr to data :IVB */ pdpvt->pnord = (epicsUInt32 *)&pwf->nord; /* ptr to num or coefficients */ /* copied to waveform record */ pdpvt->nelem = pwfAddr->no_elements; /* max number of data elements in record */ return(status); } /*============================================================================= Name: mgntIVBInit Abs: Initialize records that used in polynomial coefficients to output a waveform Args: Type Name Access Description ------------------- ----------- ---------- ---------------------------- aSubRecord * psub read/write pointer to subroutine record Rem: Init Subroutine for PRIM:LOCA:UNIT:POLYCOEF Input: -------- INPA = :0:POLYCOEF 0th polynomial coefficient (offset) INPA = :1:POLYCOEF 1st polynomial coefficient (slope) INPA = :2:POLYCOEF 2nd polynomial coefficient ... ... INPK = :10:POLYCOEF 10th polynomial coefficient INPL = :11:POLYCOEF 11th polynomial coefficient INPM = :NPOLYCOEF Output: ---- OUTA = :IVB (wafeform record) Side: None Ret: long 0 - Successful -1 - for invalid data type of NOA-NOL,NOVA or privata device info already initialized. ==============================================================================*/ long mgntIVBInit(aSubRecord *psub) { long status=SUCCESS; epicsUInt32 idx; epicsUInt32 *type_p = (epicsUInt32 *)&psub->fta; devicePvt_ts *dpvt_ps = NULL; /* Check that this pv has not already been initialized */ if ( psub->dpvt || (psub->novamlock = epicsMutexMustCreate(); psub->dpvt = dpvt_ps; for (idx=MGNT_MAX_POLY_COEF && (psub->ftva!=DBF_DOUBLE); (idx>0) && !status; idx--) if (type_p[idx]!=DBF_DOUBLE) status = ERROR; if (status) recGblRecordError(S_db_badField, (void *)psub,"mgntNumPolyCoef: init_record"); return(status); } /*============================================================================= Name: mgntIVB Abs: Copy polynomial coefficients from subRecord into a waveform record. Args: Type Name Access Description ------------------- ----------- ---------- ---------------------------- aSubRecord * psub read/write pointer to subroutine record Rem: Init Subroutine for PRIM:LOCA:UNIT:POLYCOEF Input: -------- INPA = :0:POLYCOEF 0th polynomial coefficient (offset) INPA = :1:POLYCOEF 1st polynomial coefficient (slope) INPA = :2:POLYCOEF 2nd polynomial coefficient ... ... INPK = :10:POLYCOEF 10th polynomial coefficient INPL = :11:POLYCOEF 11th polynomial coefficient INPM = :NPOLYCOEF Output: ---- OUTA = :IVB (wafeform record) OUTB = :IVBMSG mgntIVB status (0=success, 1=wf too small) Side: None Ret: long 0 - Successful -1 - Record initialization failed ==============================================================================*/ long mgntIVB(aSubRecord *psub) { long status = SUCCESS; epicsUInt32 idx; epicsUInt32 nelem; double **coef_pp = (double **)&psub->a; /* polynomial coefficients */ devicePvt_ts *dpvt_ps = NULL; size_t nbytes = sizeof(double) * psub->nova; /* Check that this pv has been initialized. If not, exit with an error */ if ( !psub->dpvt ) return (-1); /* clear waveform */ epicsMutexMustLock(dpvt_ps->mlock); memset(psub->vala,0,nbytes); epicsMutexUnlock(dpvt_ps->mlock); psub->neva=0; dpvt_ps = (devicePvt_ts *)psub->dpvt; nelem = min(*(epicsUInt32 *)psub->m,psub->nova); /* update wf with polynomial coefficients */ epicsMutexMustLock(dpvt_ps->mlock) for (idx=0; idxvala)[idx] = coef_pp[0][idx]; /* update wf with poly coef */ psub->neva = nelem; /* set # of elements written to wf */ epicsMutexUnlock(dpvt_ps->mlock); if (psub->neva != *(epicsUInt32 *)(psub->m)) *(epicsUInt16 *)psub->valb = 1; else *(epicsUInt16 *)psub->valb = SUCCESS; return(status); } /*============================================================================= Name: mgntDegauss Abs: Generate degauss cycle set points using specified method in INPH Args: Type Name Access Description ------------------- ----------- ---------- ---------------------------- subRecord * psub read/write pointer to subroutine record Rem: Init Subroutine for PRIM:LOCA:UNIT:DEGAUSSUB Input: -------- INPA = :DEGAUSIMIN Minimum degauss current set point INPB = :DEGAUSIMAX Maximum degauss current set point INPC = :DEGAUSTYPE Type of degauss, (0=none, 1=bcxhs1, 2=bcxss1, 3=bcxxl1, 4=cryo) INPD = :DEGAUSCYCLENUM Number of degauss cycles (1=cycle is up/down) INPE = :DEGAUSMETHOD type of degauss algorithm (none=0,1=standard,2=oscillating) INPF = :PSTYPE ps type (bipolar,unipolar,unipolar w/reversing switch) INPG = :DEBUG Debug flag (0=no debug mode, 1=debug mode) INPF = :PSTYPE Power Supply Type INPH = :DEGAUSSTEP Step size for degaus if D=0 (standard), degauss method. Output: -------- VALA = :DEGAUSWF Degauss setpt array VALB = :DEGAUSMSG mgntDegauss function status such that: 0=success, 1=none, 2=wf too small, setpts dropped, 3=invalide ps type (inpf), 4=invalid type (inpc) VALC = :DEGAUSCYCLENUM Number of expected degauss cycles DPVT = Pointer to private data information Side: None Ret: long 0 - Successful -1 - Private device info is not avaiable ==============================================================================*/ long mgntDegauss(aSubRecord *psub) { long status = SUCCESS; unsigned long i = 0; epicsUInt32 ncycles = 1; /* num of cycles for a standard degauss method */ size_t nbytes = psub->nova * sizeof(double); char *method_c[DEGAUSS_METHOD_NUM] = {"None", "Standard" , "Oscillation" }; char *type_c[DEGAUSS_TYPE_NUM] = {"None", "BCXH1", "BCXSS1" , "BCXXL1", "CRYO", "XCPEPX1", "BCXCBX13"}; char *pstype_c[PS_TYPE_NUM] = {"Bipolar", "Unipolar" , "Unipolar_PolSW", "None" }; mgntDegauss_ts *dpvt_ps = (mgntDegauss_ts *)psub->dpvt; /* Get the address of wavefor record, and pointer to data */ if ( !dpvt_ps ) return(-1); /* Clear the waveform. aSub ssets the NORd field of * the waveform record based on the value of NOVA */ epicsMutexMustLock(dpvt_ps->mlock); memset(psub->vala,0,nbytes); epicsMutexUnlock(dpvt_ps->mlock); psub->neva=0; /* max wf elements */ *(epicsUInt16 *)psub->valb=SUCCESS; /* deguass msg status */ /* The supply must be bipolar of unipolar with a polarity switch * to degauss a magnets. So if no degauss method is specified then * return without a warning. Otherwise, set a warning. */ if (*(unsigned short *)psub->f==PS_TYPE_UNIPOLAR ) { if ( *(epicsUInt32 *)psub->g ) printf("%s PS Type %s (%lu)\n", psub->name, pstype_c[min(DEGAUSS_TYPE_NUM,*(epicsUInt32 *)psub->f)], *(long unsigned *)psub->f); if ( *(unsigned short *)psub->e ) *(epicsUInt16 *)psub->valb = MGNT_DEGAUSS_PS_ERR; else *(epicsUInt16 *)psub->valb = MGNT_DEGAUSS_NONE; return(status); } /* If debug flag then print othe degauss method for this device */ if ( *(epicsUInt32 *)psub->g ) printf("%s DEGAUSS Method %s (%lu)\n", psub->name, method_c[min(DEGAUSS_METHOD_NUM,*(epicsUInt32 *)psub->e)], *(long unsigned *)psub->e); /* * OK, now we have a power supply that is either bipolar or * unipolar with a polarity switch. Now determine the degauss method */ switch( *(epicsUInt32 *)psub->e ) { case DEGAUSS_METHOD_OSCILLATE: if ( *(epicsUInt32 *)psub->g ) printf("%s DEGAUSS Type %s (%lu)\n", psub->name, type_c[min(DEGAUSS_TYPE_NUM,*(epicsUInt32 *)psub->c)], *(long unsigned *)psub->c); *(epicsUInt16 *)psub->valb = mgntDegaussOscillate( *(epicsUInt32 *)psub->c,dpvt_ps , *(epicsUInt32 *)psub->g); break; /* Use the standard degaussing althorithm used here */ case DEGAUSS_METHOD_STANDARD: *(epicsUInt16 *)psub->valb = mgntDegaussStandard( ncycles, *(double *)psub->a, *(double *)psub->b, dpvt_ps ); break; case DEGAUSS_METHOD_NONE: *(epicsUInt16 *)psub->valb = MGNT_DEGAUSS_NONE; break; default: *(epicsUInt16 *)psub->valb = MGNT_DEGAUSS_TYPE_ERR; /* unkown degauss method */ break; }/* End of case statement */ /* calculate the number of degauss cycles */ *(epicsInt32 *)psub->valc = *dpvt_ps->nord_p/2; /* if debug flag is set, print out the waveform */ if (psub->neva && *(epicsUInt32 *)psub->g ) { for (i=0; i< psub->neva; i++) printf("\t(%lu): %g\n",i,dpvt_ps->data_a[i]); printf("\tcnt: (%lu)\n",i); } return(status); } /*============================================================================= Name: mgntDegaussStandard Abs: Get standard degauss setpoints Args: ncycles Number of degauss cycles Type: integer Use: epicsUInt32 Acc: read-only Mech: By value imin Minimuim current Type: real-number Use: double Acc: read-only Mech: By value imax Maximuim current Type: real-number Use: double Acc: read-only Mech: By value dpvt_ps Private device info Type: pointer Use: mgntDevice_ts * Acc: read-write access Mech: By reference Rem: This function is called by mgntDegauss() Side: None Ret: epicsUInt16 0 - Successful 1 - No degauss 2 - Degauss array is too small 3 - Invalid PS type, must be bipolar 4 - Invalid type (MAD name) ==============================================================================*/ static epicsUInt16 mgntDegaussStandard( epicsUInt32 ncycles, double imin, double imax, mgntDegauss_ts *dpvt_ps ) { epicsUInt16 status = SUCCESS; /* status return (valb) */ epicsUInt32 nelem=0; /* # of elements in array */ epicsUInt32 i=0; /* index count */ /* determine the ps type, bipolar or unipolar with polarity switch */ switch( *dpvt_ps->psType_p ) { case PS_TYPE_BIPOLAR: nelem = ncycles*2+2; if ( dpvt_ps->nelem < nelem ) { nelem = dpvt_ps->nelem; status = MGNT_DEGAUSS_WF_WARN; /* waveform not large enough for data */ } epicsMutexMustLock(dpvt_ps->mlock); dpvt_ps->data_a[0] = 0.0; /* start from zero. */ for (i=1; ivala[i++] = imax * (exp((-1*i/ncycles) * sin(i/(pi/2.0))); */ dpvt_ps->data_a[i++] = imax; /* Set maximuim current */ dpvt_ps->data_a[i++] = imin; /* Set minimum current */ } dpvt_ps->data_a[i++] = 0; /* end at zero */ *dpvt_ps->nord_p=i; /* set # elem in array */ epicsMutexUnlock(dpvt_ps->mlock); break; case PS_TYPE_UNIPOLAR_REVSW: nelem = ncycles * 5; if ( dpvt_ps->nelem < nelem ) { nelem = dpvt_ps->nelem; status = MGNT_DEGAUSS_WF_WARN; /* waveform not long enough for data */ } epicsMutexMustLock(dpvt_ps->mlock); for (i=0; idata_a[i++] = 0.0; /* Set zero so we can switch polarity */ dpvt_ps->data_a[i++] = imax; /* Set maximuim current */ dpvt_ps->data_a[i++] = 0.0; /* Set zero so we can switch polarity */ dpvt_ps->data_a[i++] = imin; /* Set minimum current */ dpvt_ps->data_a[i++] = 0.0; /* Set zero so we can switch polarity */ } *dpvt_ps->nord_p = i; /* set the # of items in array */ epicsMutexUnlock(dpvt_ps->mlock); break; default: *dpvt_ps->nord_p = 0; status = MGNT_DEGAUSS_PS_ERR; /* ps is not bipolar */ break; }/* End of PSTYPE switch statement */ return(status); } /*============================================================================= Name: mgntDegaussOscillate Abs: Get oscillating degauss setpoint data based on MAD Name (type) Args: type Data type for oscillating degass method Type: integer Note: 0=None, 1=BXHS,2=BXXS,3=BCXXL,4=CRYO Use: epicsUInt32 5=BXHS2, 6=BXHS3, 7=BXHS4, 8=BXHS5 Acc: read-only 9=BXHS6, 10-BXHS7, 11-BXHS8 Mech: By value dpvt_ps Private device info Type: pointer Use: mgntDevice_ts * Acc: read-write access Mech: By reference debug_flag Debug flag Type: pointer Use: epicsUInt32 Acc: read-only Mech: By value Rem: This function is called by mgntDegauss() Side: None Ret: epicsUInt16 0 - Successful 1 - No degauss 2 - Degauss array is too small 3 - Invalid PS type, must be bipolar 4 - Invalid type (MAD name) ==============================================================================*/ static epicsUInt16 mgntDegaussOscillate( epicsUInt32 type, mgntDegauss_ts *dpvt_ps , epicsUInt32 debug ) { #define ARRAY_SIZE(x) (sizeof((x))/sizeof((x)[0])) /* determine statuc array size */ MGNT_DEGAUSS_I_BXHS; /* degauss data for hard X-ray bend chicane */ MGNT_DEGAUSS_I_BXSS; /* degauss data for soft X-ray bend chicane */ MGNT_DEGAUSS_I_BCXXL; /* degauss data for xleap chicane */ MGNT_DEGAUSS_I_CRYO; /* degauss data for cryo quadrupole */ MGNT_DEGAUSS_I_XCPEPX1; /* degauss data for peppex correctors */ MGNT_DEGAUSS_I_BCXCBX13; /* degauss data for bcxcbx13 bend chicane */ epicsUInt16 status = SUCCESS; long nelem = 0; double *data_p = NULL; size_t nbytes = 0; if ( *dpvt_ps->psType_p != PS_TYPE_BIPOLAR ) { *dpvt_ps->nord_p=0; status = MGNT_DEGAUSS_PS_ERR; } else { /* oscillating data type */ switch (type) { case DEGAUSS_TYPE_BXHS: data_p = (double *)mgnt_i_bxhs_a; nelem = ARRAY_SIZE(mgnt_i_bxhs_a); break; case DEGAUSS_TYPE_BXSS: data_p = (double *)mgnt_i_bxss_a; nelem = ARRAY_SIZE(mgnt_i_bxss_a); break; case DEGAUSS_TYPE_BCXXL: data_p = (double *)mgnt_i_bcxxl_a; nelem = ARRAY_SIZE(mgnt_i_bcxxl_a); break; case DEGAUSS_TYPE_CRYO: data_p = (double *)mgnt_i_cryo_a; nelem = ARRAY_SIZE(mgnt_i_cryo_a); break; case DEGAUSS_TYPE_XCPEPX1: data_p = (double *)mgnt_i_xcpepx1_a; nelem = ARRAY_SIZE(mgnt_i_xcpepx1_a); break; /* Same degauss setpoints used for BCXCBX13 and BCXCBX21 */ case DEGAUSS_TYPE_BCXCBX13: data_p = (double *)mgnt_i_bcxcbx13_a; nelem = ARRAY_SIZE(mgnt_i_bcxcbx13_a); break; case DEGAUSS_TYPE_NONE: *dpvt_ps->nord_p = 0; status = MGNT_DEGAUSS_NONE; break; default: *dpvt_ps->nord_p = 0; status = MGNT_DEGAUSS_TYPE_ERR; break; } if (debug) printf("mgntDegausOscillate: wf nelem=%ld\n",nelem); if ((status==SUCCESS) && data_p) { if (nelem > dpvt_ps->nelem) { nelem = dpvt_ps->nelem; /* set # of elements read to max elements */ status = MGNT_DEGAUSS_WF_WARN; } nbytes = nelem * sizeof(double); epicsMutexMustLock(dpvt_ps->mlock); memcpy(dpvt_ps->data_a,data_p,nbytes); *dpvt_ps->nord_p = nelem; epicsMutexUnlock(dpvt_ps->mlock); } } return (status ); } /*============================================================================= Name: mgntStdz Abs: Generate standardize cycle set points Args: Type Name Access Description ------------------- ----------- ---------- ---------------------------- aSubRecord * psub read/write pointer to subroutine record Rem: Init Subroutine for PRIM:LOCA:UNIT:DEGAUSSUB Input: -------- INPA = :STDZIMIN Minimum stdz current set point INPB = :STDZIMAX Maximum stdz current set point INPC = :STDZIFINAL Final stdz current set point INPD = :STDZCYCLENUM Number of stdz cylces (1=cycle is up/down) INPE = :STDZDIRECT Stdz direction (0=up, 1=down) INPF = :STDZDISABLE Standardize disabled (0=enabled, 1=disabled) INPG = :DEBUG Debug flag (0=no debug mode, 1=debug mode) Output: -------- VALA = :STDZWF - standardize setpoints (waveform) VALB = :STDZMSG - status message Number of set points in waveform DPVT = Private device information Side: None Ret: long 0 - Successful -1 - priviate device info is not available ==============================================================================*/ long mgntStdz(aSubRecord *psub) { long status = SUCCESS; long i = 0; long i_num = 0; double *data_a = (double *)psub->vala; size_t nbytes = psub->nova * sizeof(double); devicePvt_ts *dpvt_ps = (devicePvt_ts *)psub; /* Get the address of waveform record, and pointer to data */ if ( !dpvt_ps ) return(-1); /* Clear the standardize waveform */ epicsMutexMustLock(dpvt_ps->mlock); memset((double *)psub->vala,0,nbytes); epicsMutexUnlock(dpvt_ps->mlock); psub->neva = 0; /* Check if standardize is enabled. If not then set no standardize and exit. */ if ( *(epicsUInt32 *)psub->f || (*(long *)psub->d==0) || (*(long *)psub->d<0)) { *(epicsUInt16 *)psub->valb = MGNT_STDZ_NONE; return(status); } /* Calcuate the number of standardize set points. * and make sure it doesn't exceed the wf length. */ i_num = *(long *)psub->d*2+1; if (i_num > psub->nova) { *(epicsUInt16 *)psub->valb = MGNT_STDZ_WF_WARN; i_num = psub->nova; } *(epicsUInt16 *)psub->valb = SUCCESS; epicsMutexMustLock(dpvt_ps->mlock); switch( *(epicsUInt32 *)psub->e ) { case STDZ_UP: /*standardize in the up-direction */ for (i=0; ia; /* mimimum current */ data_a[i++] = *(double *)psub->b; /* maximum current */ } data_a[i] = *(double *)psub->c; /* final current */ psub->neva=i_num; /* # data pts set in array */ break; case STDZ_DOWN: /* standardize in the down-direction */ for (i=0; ib; /* maximum current */ data_a[i++] = *(double *)psub->a; /* minimum current */ } data_a[i] = *(double *)psub->c; /* final current */ psub->neva=i_num; /* # data pts set in array */ break; }/* End of switch statement */ epicsMutexUnlock(dpvt_ps->mlock); return(status); } /*============================================================================= Name: mgntCalbLimitsInit Abs: Determine calibration measure current data points are within expected limits. Args: Type Name Access Description ------------------- ----------- ---------- ---------------------------- aSubRecord * psub read/write pointer to subroutine record Rem: Init routine for calibration PRIM:LOCA:UNIT:CALBLIMITS Input: -------- A = Number of points to be fit (NPTS) B = Array of X values C = Array of Y values Output: -------- VALA = flag measured currents within tolerance (1=ok,0=bad) DPVT = Pointer to array of pointers such that npts = number of data points in arrays lock = mutex lock Side: None Ret: long 0 - Successful -1 - 2nd init attempted or INPB and INPC unexpected data type ==============================================================================*/ long mgntCalbLimitsInit(aSubRecord *psub) { long status = ERROR; devicePvt_ts *dpvt_ps = NULL; /* Check that this pv has not already been initialized */ if (psub->dpvt) { recGblRecordError(S_dev_badInit,(void *)psub,"mgntCalbLimits: init_record"); return(status); } else if ((psub->ftb!=DBF_DOUBLE) || (psub->ftc!=DBF_DOUBLE)) { recGblRecordError(S_db_badField,(void *)psub,"mgntCalbLimits: init_record"); return(status); } status = OK; /* Allocate memory for private device information */ dpvt_ps = callocMustSucceed(1,sizeof(devicePvt_ts),"calloc failed for mgntCalbInit" ); dpvt_ps->mlock = epicsMutexMustCreate(); /* * Get number of points in arrays. The arrays should contain the * same number of elemnts, but if not then use the smallest number */ dpvt_ps->npts = min(psub->nob,psub->noc); if (dpvt_ps->npts<0) dpvt_ps->npts = 0; psub->dpvt = dpvt_ps; return(status); } /*============================================================================= Name: mgntInitPoly Abs: Initialize records that use polynomial coefficients. Args: Type Name Access Description ------------------- ----------- ---------- ---------------------------- subRecord * psub read/write pointer to subroutine record Rem: Init Subroutine for PRIM:LOCA:UNIT:$(RAW)REQ and PRIM:LOCA:UNIT:$(PHY)ACT Input: -------- INPB = Number of polynomial coefficients - used to access the coefficients themselves Output: -------- DPVT = Pointer to polynomial coefficients Rem: Init Subroutine for PRIM:LOCA:UNIT:$(RAW)REQ and PRIM:LOCA:UNIT:$(PHY)ACT Side: None Ret: long 0 - Successful -1 - for invalid INPB ==============================================================================*/ static long mgntInitPoly(subRecord *psub) { long status = SUCCESS; /* * Get polynomial coeffs - assume INPB is from a subRecord and * A through L are contiguous. Assume A is the constant term * and B to L are the higher order terms. */ DBADDR *pdbAddr = dbGetPdbAddrFromLink(&psub->inpb); psub->dpvt = 0; if (!pdbAddr) return -1; psub->dpvt = &((subRecord *)pdbAddr->precord)->a; return(status); } /*============================================================================= Name: mgntNumPolyCoef Abs: Find Number of Polynomial Coefficients and output Coefficents as a WF Args: Type Name Access Description ------------------- ----------- ---------- ---------------------------- aSubRecord * psub read/write pointer to subroutine record Input: -------- INPA = :0:POLYCOEF - 0th polynomial coefficient (offset) INPA = :1:POLYCOEF - 1st polynomial coefficient (slope) INPA = :2:POLYCOEF - 2nd polynomial coefficient ... ... INPK = :10:POLYCOEF - 10th polynomial coefficient INPL = :11:POLYCOEF - 11th polynomial coefficient Output: ---- OUTA = :NPOLYCOEF - number of polynomial coefficents (non-zero) OUTB = :IVB - waveform of poly coefficients. Rem: Init Subroutine for PRIM:LOCA:UNIT:POLYCOEF Side: None Ret: long 0 - Successful (always) -1 - Initalizeation must have failed ==============================================================================*/ static long mgntNumPolyCoef(subRecord *psub) { long status = SUCCESS; epicsInt32 idx; double *polyCoef_a; /* Countdown until the most significant non-zero coefficient is found. */ /* Note: * for (idx = MGNT_MAX_POLY_COEF, polyCoef_a = &psub->l; * (idx > 0) && (polyCoef_a[idx] == 0); idx--) { } doesn't work */ polyCoef_a = &psub->l; for (idx = MGNT_MAX_POLY_COEF;(idx > 0) && (*polyCoef_a== 0); idx--, polyCoef_a--) {} psub->val = (double)idx; /* DEBUGPRINT(DP_DEBUG, mgntSubFlag, ("mgntNumPolyCoef for %s = %d.\n", psub->name, idx)); */ return(status); } /*============================================================================= Name: mgntDbPoly Abs: Convert Physical Units to Raw Units using polynomial conversion. Use same algorithm as ref_rmx_dbs:dbpoly.a38 - see PDL in header at top of module. Args: Type Name Access Description ------------------- ----------- ---------- ---------------------------- subRecord * psub read/write pointer to subroutine record Input: -------- VAL = Value in Physical Units A = Spare B = Number of polynomial coefficients C = Polynomial Coeff A (offset if linear) D = Polynomial Coeff B (slope if linear) DPVT = Pointer to polynomial coefficients (set by mgntInitPoly) Output: ------- K = Value in Raw Units L = Slope of the polynomial at the DES value Rem: Called by mgntPoly and mgntReversePoly. Side: None Ret: long 0 - Successful -1 - if B is invalid or invalid pointer to poly coeffs. ==============================================================================*/ static long mgntDbPoly(subRecord *psub) { long status = SUCCESS; long idx; /* Simple linear conversion */ if (psub->b == LINEAR_COEF_NUM) { psub->l = psub->d; psub->k = psub->c + (psub->val * psub->d); } else { /* * Must have a valid number of coefficients and a valid poly coeff array */ if ((psub->b < LINEAR_COEF_NUM) || (psub->b > MGNT_MAX_POLY_COEF) || (!psub->dpvt)){ if (!psub->dpvt) { DEBUGPRINT(DP_INFO, mgntSubFlag, ("mgntDbPoly for %s: Invalid coef array.\n", psub->name)); } else { DEBUGPRINT(DP_INFO, mgntSubFlag, ("mgntDbPoly for %s: Invalid poly coef.\n", psub->name)); } DEBUGPRINT(DP_INFO, mgntSubFlag, ("mgntDbPoly for %s: Invalid coef array; b: %f dpvt: %p\n", psub->name,psub->b, psub->dpvt )); status = ERROR; } else { /* * Do polynomial conversion using algorithm from ref_rmx_dbs:dbpoly.a38. * Find first derivative of the polynomial at the input value - * it'll be used to find reasonable alarm limits later. */ psub->k = 0.0; /* idx =psub->b-1; psub->k = ((double *)psub->dpvt)[idx];*/ /* highest order coeff */ psub->l = 0.0; for (idx = psub->b-1; idx >=0; idx--) { psub->l = (psub->l * psub->val) + psub->k; /* was + val*/ psub->k = (psub->k * psub->val) + ((double *)psub->dpvt)[idx]; } /* DEBUGPRINT(DP_DEBUG, mgntSubFlag, ("mgntDbPoly for %s: after loop- l: %f k: %f val: %f\n", psub->name, psub->l,psub->k,psub->val )); */ } } return(status); } /*============================================================================= Name: mgntPoly Abs: Convert Physical Units to Raw Units using polynomial conversion. Args: Type Name Access Description ------------------- ----------- ---------- ---------------------------- subRecord * psub read/write pointer to subroutine record Input: -------- VAL = Value in Physical Units A = spare B = Number of polynomial coefficients - :POLYCOEF.VAL C = Polynomial Coeff A (offset if linear) - :POLYCOEF.A D = Polynomial Coeff B (slope if linear) - :POLYCOEF.B E = Drive High Limit - :BCTRL.DRVH F = Drive Low Limit - :BCTRL.DRVL G = Fast Feedback Desired Value -- deprecated - :BFBCK H = Fast Feedback - :FBCK.RVAL Disable (0), Enable (1), unavailable (2) DPVT = Pointer to polynomial coefficients (set by mgntInitPoly) Output: -------- K = Value in Raw Units L = Slope of the polynomial at the DES value Rem: Subroutine for PRIM:LOCA:UNIT:$(PHY)DES. Side: None Ret: long 0 - Successful -1 - If bad return from mgntDbPoly. ==============================================================================*/ static long mgntPoly(subRecord *psub) { long status = SUCCESS; /* Use feedback value if feedback is enabled */ if ((psub->h > 0.5) && (psub->h < 2.0)) psub->val = psub->g; /* Adjust VAL if it's outside of reasonable limits */ if (psub->val > psub->e) psub->val = psub->e; else if (psub->val < psub->f) psub->val = psub->f; /* Perform conversion */ if (mgntDbPoly(psub)) { DEBUGPRINT(DP_INFO, mgntSubFlag, ("mgntPoly returning -1 for %s:\n", psub->name)); status = ERROR; } return(status); } /*============================================================================= Name: mgntReversePoly Abs: Estimate Physical Units Value from Raw Value. Use same algorithm as ref_rmx_reentrant:reverse_dbpoly.c.86. Args: Type Name Access Description ------------------- ----------- ---------- ---------------------------- subRecord * psub read/write pointer to subroutine record Input: ------- VAL = Initial Guess of Physical Units Value A = spare B = Number of polynomial coefficients - must be between 2 and 12. C = Polynomial Coeff A (offset if linear) D = Polynomial Coeff B (slope if linear) E = Raw Value F = Epsilon - desired accuracy of the Estimated Value G = Maximum iteration count DPVT = Pointer to polynomial coefficients (set by mgntInitPoly) Output: ------- H = Previous Estimate of Value in Physical Units I = Number of iterations J = Convergence Status (see defines at the top of the file) K = Value in Raw Units corresponding to VAL L = Slope of the polynomial at the DES value VAL = Final Estimate of Value in Physical Units Rem: Subroutine for PRIM:LOCA:UNIT:$(PHY)ACT and MON Side: None Ret: long 0 - Successful 1 - Failure ==============================================================================*/ static long mgntReversePoly(subRecord *psub) { long status = SUCCESS; /* Simple linear conversion */ if (psub->val != psub->val ) psub->val = 0.0; /* check for NaN - not a number */ psub->h = psub->val; psub->j = MGNT_CONVERGED; if (psub->b == 2) { psub->i = 0; psub->l = psub->d; psub->val = psub->a = (psub->e - psub->c)/psub->d; } else { double diff = psub->f + 1; double prev_diff = psub->f; /* * Iterate until we get close enough. */ for (psub->i = 0.0; (psub->i <= psub->g) && (psub->j == MGNT_CONVERGED);psub->i += 1.0) { if (mgntDbPoly(psub)==-1) { psub->j = MGNT_POLY_ERROR; } else if ((psub->l > -MGNT_MIN_SLOPE) && (psub->l < MGNT_MIN_SLOPE)) { psub->j = MGNT_ZERO_SLOPE; } else if (diff <= psub->f) { /* DEBUGPRINT(DP_DEBUG, mgntSubFlag, ("mgntReversePoly for %s completed in %f iterations!!!\n", psub->name,psub->i )); */ break; } else { /* save previous difference for verifying convergence */ prev_diff = diff; diff = MGNT_CHICKEN_FACTOR * (psub->e - psub->k)/psub->l; /* need a new guess: slide on the slope towards answer */ psub->h = psub->val; psub->val += diff; if (diff < 0) diff *= -1; /* checking for NaN - not a number */ if ( psub->val != psub->val ) { if (psub->h == psub->h ) psub->val = psub->h; else psub->val = 0; psub->j = MGNT_NO_CONVERGENCE; psub->stat = CALC_ALARM; psub->sevr = INVALID_ALARM; break; } } } /* End of FOR loop */ /* * Are we here because we ran into an error or ran out of iterations? */ if (psub->j != MGNT_CONVERGED) { /* DEBUGPRINT(DP_DEBUG, mgntSubFlag, ("mgntReversePoly for %s: No convergence; J= %f\n", psub->name, psub->j)); */ status = ERROR; } else if (psub->i > psub->g) { /* * Were we still on our way towards an answer? */ if (diff <= prev_diff) { psub->j = MGNT_ALMOST_CONVERGED; /* DEBUGPRINT(DP_DEBUG, mgntSubFlag, ("mgntReversePoly for %s: almost converged; J= %f\n" ,psub->name, psub->j)); */ } else { psub->j = MGNT_NO_CONVERGENCE; /* DEBUGPRINT(DP_DEBUG, mgntSubFlag, ("mgntReversePoly for %s: convergence; J= %f\n",psub->name, psub->j)); */ } status = ERROR; } } return(status); } /*============================================================================= Name: mgntPhyDelta Abs: Calculate deltas used for alarm and warning limits Args: Type Name Access Description ------------------- ----------- ---------- ---------------------------- subRecord * psub read/write pointer to subroutine record Inputs: -------- A = Desired Value B = Minimum Warning Limit Delta (abs tol for small abs(B)) C = Fraction of DES for ACT Warning Limit D = Minimum Alarm Limit Delta (abs tol) E = Fraction of DES for ACT Alarm Limit NOTE: B,C,D,E same as TOLS in the SLC database (TOLS = B,D abs tol; C,E fractional; B,C for trim; D,E for check) Trim tol translates to Warning limits; Check tol to alarm limits F = Mulitple of ACT deltas used for MON deltas $(MFRAC) non-zero -2nd ADC available zero - 2nd ADC not available NOTE: F same as TOLF in the SLC database (TOLF = redundant transductor tolerance factor) G = Divisor of alarm limit delta to find epsilon (slc hardcoded 30) H = BACT P = MPS absolute tolerance Q = MPS relative tolerance Outputs: --------- I = ACT warning delta, "TOLMX" for trim in magtrck.f86 J = ACT alarm delta, "CHCK_TOL*" for check (E*A initially; D if < D) K = MON warning delta L = MON alarm delta M = Out of tolerance (for trim; ="1" if out-of-tol) N = MPS alarm delta VAL = Epsilon (ref. chck_tols/30 check_readbacks.f86) Rem: Calculate deltas used for alarm and warning limits for primary (ACT) and secondary (MON) physical readbacks. Calculate epsilon used in the reverse polynomial calculation. Side: Warning and alarm deltas for ACT are fractions of DES. Also check that the deltas are not too small (for small values of DES). Warning and alarm deltas for MON are multiples of the ACT deltas. Ret: long 0 - Successful (always) ==============================================================================*/ long mgntPhyDeltas(struct sSubRecord *psub) { long status = SUCCESS; /* TRIM tolearances - warming */ if ((psub->b > 0.0) || (psub->c > 0.0)) { psub->i = psub->c * psub->a; if (psub->i < 0) psub->i *= -1; if (psub->i < psub->b) /* bact warning */ psub->i = psub->b; if (psub->f > 0.0) /* bmon warning */ psub->k = psub->i * psub->f; else psub->k = 0.0; } else { psub->i = 0.0; /* bact warning */ psub->k = 0.0; /* bmon warning */ } /* CHCK tolerances - alarm */ if ((psub->d > 0.0) || (psub->e > 0.0)) { psub->j = psub->e * psub->a; if (psub->j < 0) psub->j *= -1; if (psub->j < psub->d) psub->j = psub->d; /* bact alarm */ if (psub->f > 0.0) /* bmon alarm */ psub->l = psub->j * psub->f; else psub->l = 0.0; } else { psub->j = 0.0; /* bact alarm */ psub->l = 0.0; /* bmon alarm */ } /* MPS Tolerances */ if ((psub->p > 0.0) || (psub->q > 0.0)) { psub->n = psub->q/100 * psub->a; /* Relative tolerance */ if (psub->n < 0) psub->n *= -1; /* get absolute tolerance */ /* Use maximum of relative vs absolute tolerance. Relative is used with a bdes near zero */ if (psub->n < psub->p) /* absolute tolerance */ psub->n = psub->p; } else { psub->n = 0.0; } /* * Epsilon must be a fraction of the ACT alarm delta. */ psub->val = psub->j; if (psub->g > 1.0) { psub->val /= psub->g; } /* see if bdes-bact > tolmax (i) */ psub->m = psub->a - psub->h; if (psub->m < 0) psub->m *= -1; if ( (psub->m) > psub-> i ){ psub->m = 1; /* set out of tol */ } else psub->m = 0; /* reset out of tol */ return(status); } /*============================================================================= Name: mgntRawDeltas Abs: Calculate deltas used for alarm and warning limits Args: Type Name Access Description ------------------- ----------- ---------- ---------------------------- subRecord * psub read/write pointer to subroutine record Inputs: -------- A = Desired Value (not used) B = Absolute tolerance used for standardization tolerance C = Fraction of maximum stdz current usef for standardize tolerance Note: B,C same as ATOL in the SLC database D = Physical ACT Warning Delta (BDELTAS.I) E = Physical ACT Alarm Delta (BDELTAS.J) F = Physical MON Warning Delta (BDELTAS.K) G = Physical MON Alarm Delta (BDELTAS.L) H = Raw/Physical Slope from mgntPoly (BDES.L ) Outputs: ----------- I = ACT warning delta (slc TOLMX) J = ACT alarm delta (slc CURR_TOL) K = MON warning delta L = MON alarm delta VAL = standardize tolerance (largest of o,p,b) Rem: Calculate deltas used for alarm and warning limits for primary (ACT) and secondary (MON) raw readbacks based on physical deltas. Also calculate tolerance for standardization. Side: None Ret: int 0 - Successful (always) ==============================================================================*/ long mgntRawDeltas(struct sSubRecord *psub) { long status = SUCCESS; psub->val = psub->c; /* minimum stdz tolerance */ if (psub->val < 0) psub->val += -1; /* make sure we have a postive # */ if (psub->val < psub->b) psub->val = psub->b; /* get largest value for tolerance */ /* * Check for zero input deltas. Otherwise, multiply by slope to * get approximate raw deltas corresponding to physical deltas. */ if (psub->d > 0.0) psub->i = psub->d * psub->h; else psub->i = 0.0; if (psub->e > 0.0) psub->j = psub->e * psub->h; else psub->j = 0.0; if (psub->f > 0.0) psub->k = psub->f * psub->h; else psub->k = 0.0; if (psub->g > 0.0) psub->l = psub->g * psub->h; else psub->l = 0.0; return(status); } /*============================================================================= Name: mgntLimits Abs: Calculate B-field alarm and warning limits from deltas. Args: Type Name Access Description ------------------- ----------- ---------- ---------------------------- subRecord * psub read/write pointer to subroutine record Input: -------- A = Desired Field / Current B = Maximum (DRVH) $(WDEL) C = Minimum (DRVL) $(WFRAC) D = Warning Delta (0 = disable) E = Alarm Delta (0 = disable) F = Disable Alarm Checking (ie, setpoint currently changing) (0=no, 1=yes) (0=calc limits, 1=set limits to min/max) G = State (0=off, 1=on) of Power Supply H = hardware status (hsta) :HSTA Outputs: --------- I = HIGH value J = LOW value K = HIHI value L = LOLO value VAL = Not Used Rem: Calculate B alarm and warning limits from deltas. If the disable alarms flag is set or the supply is off, then use max/min values to disable alarms. Side: None Ret: long 0 - Successful (always) ==============================================================================*/ long mgntLimits(struct subRecord *psub) { long status = SUCCESS; epicsUInt32 fbck = (epicsUInt32)psub->h & HSTA_FBCKCTRL; epicsUInt32 pau = (epicsUInt32)psub->h & HSTA_PAU; /* * Set alarm and warning limits beyond the range * This will disable alarming. */ psub->i = psub->b+1; psub->j = psub->c-1; psub->k = psub->b+1; psub->l = psub->c-1; /* * If alarms are disabled, ps is off, feedback or pattern aware is enabled * then set limits beyond the range so it will never go out-of-toleance. * Otherwise, set the proper alarm and warning limits. */ if ((psub->f < 0.01) && (psub->g > 0.01) && !fbck && !pau) { if (psub->d > 0.0) { /* warning deltas */ psub->i = psub->a + psub->d; psub->j = psub->a - psub->d; } if (psub->e > 0.0) { /* alarm deltas */ psub->k = psub->a + psub->e; psub->l = psub->a - psub->e; } } return(status); } /*============================================================================= Name: mgntMpsLimits Abs: Calculate if an MPS alarm should exists for this magnets B-field Args: Type Name Access Description ------------------- ----------- ---------- ---------------------------- aSubRecord * psub read/write pointer to subroutine record Input: -------- A = Signals to monitor for MPS :MPS.RVAL 0 - NONE, No MPS Monitoring for this magnet 1 - PS ON 2 - PS ON and BACT B = abs(BDES-BACT) :BADIFF C = MPS tolerance of BACT :BDELTAS.N D = Actual B-field (BACT) :BACT E = Bitmask for tolerance check algorithm. bitNo Hex Desc 0 0x1 if (bdes-bact) f) then INTOL_BMIN=true else INTOL_BMIN=false (only check if A=2) 2 0x4 if (g < bact > h) then INTOL_BRANGE=true else INTOL_BRANGE=false 3 0x8 if (bact > i) then INTOL_BMIN2=true else INTOL_BMIN2=false NOTE: Used to protect the undulator by preventing the hutch stopper S2 from being pulled if the electron beam energy is below 3.3GeV. The BAS brings beam to S2 at that energy but SXR does not want to run below 3.3GeV. Email from RHI to Mboyes 10/16/2012 4:37pm So if E=0, then MPS does not look at this magnet, and all outputs VALA thru BALD are set to OK (ie 1). Note: MPS requiires that the outputs MUST goto bi or bo records. F = B-field hard lower limit :MPSBLLIM G = MPS B-field min :MPSBMIN H = MPS B-field max :MPSBMAX I = B-field hard lower limit #3 :MPSBLLIM2 Output: --------- VALA = B-field within tol of (BDES-BACT) (1=ok,0=fault) :INTOL VALB = B-field is greater than F (1=ok,0=fault) :INTOL_BMIN VALC = B-field is within (g < bact > h) (1=ok,0=fault) :INTOL_BRANGE VALD = B-field is greater than I (1=ok,0=fault) :INTOL_BMIN2 Rem: Side: Basically, this pv is only used when MPS checks BACT, which is done when :MPS.RVAL = 2 Ret: long 0 - Successful (always) ==============================================================================*/ long mgntMpsLimits(struct aSubRecord *psub) { long status = SUCCESS; /* * Is the b-field of this magnet monitored by mps? If yes, then MPS expects * the b-field to be above a minimum. */ if (*(epicsUInt32 *)psub->a==2) { /* * Should we check that the actual field is above a hard lower limit (V1)? * NOTE: the self-seating bend chicane magnet (bxhs2) must * have the field at or above a certain b-field. * Otherwise mps is required to trip the beam. */ if ( (*(epicsUInt32 *)psub->e & MPS_CHK_LIMIT) == MPS_CHK_LIMIT ) { /* In-tol if bact is larger then hard limit */ if ( *(double *)psub->d > *(double *)psub->f ) *(epicsUInt32 *)psub->valb = 1; /* in-tolerance */ else *(epicsUInt32 *)psub->valb = 0; /* out-of-tolerance */ } else *(epicsUInt32 *)psub->valb = 1; /* don't care, set in-tol */ /* * Should we check that the actual field is above a second hard lower limit (V3)? * NOTE: Used to protect the undulator by preventing the hutch stopper S2 * from being pulled if the electron beam energy is below 3.3GeV. * The BAS brings beam to S2 at that energy but SXR does not want to run below 3.3GeV. * Email from RHI to Mboyes 10/16/2012 4:37pm */ if ( (*(epicsUInt32 *)psub->e & MPS_CHK_LIMIT2) == MPS_CHK_LIMIT2 ) { /* In-tol if bact is larger than hard limit */ if ( *(double *)psub->d > *(double *)psub->i ) *(epicsUInt32 *)psub->vald = 1; /* in-tolerance */ else *(epicsUInt32 *)psub->vald = 0; /* out-of-tolerance */ } else *(epicsUInt32 *)psub->vald = 1; /* don't care, set in-tol */ /* * Should we ckeck that the actual field is within a certain range (V2)? */ if ( (*(epicsUInt32 *)psub->e & MPS_CHK_RANGE) == MPS_CHK_RANGE ) { if ( (*(double *)psub->d > *(double *)psub->g) && (*(double *)psub->d < *(double *)psub->h) ) *(epicsUInt32 *)psub->valc = 1; /* in-tolerance */ else *(epicsUInt32 *)psub->valc = 0; /* out-of-tolerance */ } else *(epicsUInt32 *)psub->valc = 1; /* don't care, set in-tol */ /* * Should we ckeck that the actual field is within * a certain percentage of the desired set point (BDES) (Std)? * Note: the default is to check the adiff < mps_tol */ if ( ((*(epicsUInt32 *)psub->e & MPS_CHK_TOL) == MPS_CHK_TOL) || (*(epicsUInt32 *)psub->e==0) ) { if (*(double *)psub->b < *(double *)psub->c) *(epicsUInt32 *)psub->vala = 1; /* in-tolerance */ else *(epicsUInt32 *)psub->vala = 0; /* out-of-tolerance */ } else *(epicsUInt32 *)psub->vala = 1; /* don't care, set in-tol */ } /* bact is not monitored by mps */ else { *(epicsUInt32 *)psub->vala=1; *(epicsUInt32 *)psub->valb=1; *(epicsUInt32 *)psub->valc=1; } return(status); } /*============================================================================= Name: mgntBCONLimits Abs: Calculate alarm and warning limits for BCON from BDES Args: Type Name Access Description ------------------- ----------- ---------- ---------------------------- aSubRecord * psub read/write pointer to subroutine record Input: -------- INPA = :BDES - Desired Field / Current INPB = :BDELTAS.I - B-field Warning Delta calculated (from BDELTAS.I) INPG = :DEBUG - Debug flag (0=no debug mode, 1=debug mode) no longer use a hard coded epsilon = 5e-08; Output: --------- VALA = HIGH value VALB = LOW value VALC = HIHI value VALD = LOLO value VALE = Delta Rem: Side: If BDES does not equal BCON, it turns yellow. Use check tolerance (warning) for epsilon around bdes. Ret: long 0 - Successful (always) ==============================================================================*/ long mgntBCONLimits(struct aSubRecord *psub) { long status = SUCCESS; double prev_delta= *(double *)psub->valb; *(double *)psub->vala = *(double *)psub->a + *(double *)psub->b; /* HIGH */ *(double *)psub->valb = *(double *)psub->a - *(double *)psub->b; /* LOW */ *(double *)psub->valc = *(double *)psub->a + *(double *)psub->b; /* HIHI */ *(double *)psub->vald = *(double *)psub->a - *(double *)psub->b; /* LOLO */ if ( *(epicsUInt32 *)psub->g && (*(double *)psub->valb > prev_delta) ) printf("%s BCON Alarm Delta new delta: %g prev delta: %g\n",psub->name,*(double *)psub->b,prev_delta); return(status); } /*============================================================================= Name: mgntMcorLimits Abs: Calculate the MCOR limits Args: Type Name Access Description ------------------- ----------- ---------- ---------------------------- aSubRecord * psub read/write pointer to subroutine record Where is MCOR::<2-digit channel> channel = 00 to 16, where 00 is the slot 00 is the controller. Input: -------- A = Mcor Type (0,1,2,3,6,12,30,0) :TYPE.RVAL B = Mcor type (0-7), used as index :TYPE Output: --------- VALA: dac imax in amps :IRANGE_DAC_SET VALB: dac imin in amps VALC: adc imax in amps :IRANGE_ADC_SET VALD: adc imin in amps VALE: fbck imax in amps :IRANGE_FBCK_SET VALF: fbck imin in amps Note: dac settings are 2% above full scale, so that the full scale adc on the monitor an feedback inputs can be reached. fbck settings can also be used for IRANGE_FBCK_SET and IRANGE_DAC_SET adc settings can also be used for IRANGE_ADC_SET Rem: Below is a table of MCOR types (amps) and the corresponding DAC, ADC and Feedback currents. Refer to page 9 section Full Scale Current, of the Hardwrae Users's Manual in SharePoint https://slacspace.slac.stanford.edu/sites/controls/specialprojects/mcor_controller/Documents/Project%20Documents/MCOR%20Hardware%20Users%20Manual.pdf www.slac.stanford.edu/grp/lcls/controls/global/subsystems/mgnt/hw/psController/mcor/EMCOR_Hardwre_Users_Manual.pdf MCOR DAC ADC FBCK DAC FULL SCALE :TYPE.VAL 30 30 30 30 30.7692 5 20 20 20 20 20.15128 6 12 12 12 12 12.30768 4 9 9 12 9 9.23076 7 6 6 12 6 6.15384 3 2 2 2 2 2.05128 2 1.5 1.5 2 1.5 1.53846 selection not provided 1 1 2 1 1.02564 1 Side: None Ret: long 0 - Successful (always) ==============================================================================*/ long mgntMcorLimits(struct aSubRecord *psub) { long status = SUCCESS; static const double mcor_dac_a[8] = {0, 1.02564, 2.05128, 6.15384, 12.30768, 30.7692, 20.5128, 9.23076}; static const double mcor_adc_a[8] = {0,2,2,12,12,30,30,12}; static const double mcor_fbck_a[8] = {0,1,2,6,12,30,20,9}; switch( *(unsigned short *)psub->a ) { case MCOR30: case MCOR20: case MCOR12: case MCOR9: case MCOR6: case MCOR2: case MCOR1: *(double *)psub->vala = mcor_dac_a[*(epicsUInt32 *)psub->b]; /* dac imax amps */ *(double *)psub->valb = mcor_dac_a[*(epicsUInt32 *)psub->b]*-1; /* dac imin amps */ *(double *)psub->valc = mcor_adc_a[*(epicsUInt32 *)psub->b]; /* adc imax amps */ *(double *)psub->vald = mcor_adc_a[*(epicsUInt32 *)psub->b]*-1; /* adc imin amps */ *(double *)psub->vale = mcor_fbck_a[*(epicsUInt32 *)psub->b]; /* fbck imax amps */ *(double *)psub->valf = mcor_fbck_a[*(epicsUInt32 *)psub->b]*-1; /* fbck imin amps */ break; default: /* amps */ *(double *)psub->vala = 0.0; *(double *)psub->valb = 0.0; *(double *)psub->valc = 0.0; *(double *)psub->vald = 0.0; *(double *)psub->vale = 0.0; *(double *)psub->valf = 0.0; break; } /* End of switch statement */ return(status); } /*============================================================================= Name: mgntCalbLimits Abs: Check calibration measure currents are within tolerances Args: Type Name Access Description ------------------- ----------- ---------- ---------------------------- aSubRecord * psub read/write pointer to subroutine record Input: -------- A = Number of points to be fit (NPTS) :CALBSTEPNUM B = Array of measured currents :CALBIACTWF C = Array of current setpoints :CALBICTRLWF D = minimum current tolerance (0.5) E = maximum current tolerance (2.0) F = stdz absoulte current tolerance on ides-iact G = stdz fractional tolerance on max current H = :VSETPT slope (ESLO) Output: --------- VALA = Measured current in-tolerance (1=Ok,0=bad) VALB = Current ratio VALC = Tolerance for calibrated dac y-intercept VALD = Tolerance for calibrated dac slope Rem: Side: None Ret: long 0 - Successful (always) ==============================================================================*/ long mgntCalbLimits(struct aSubRecord *psub) { long status = SUCCESS; epicsUInt32 npts = *(epicsUInt32 *)psub->a; double iratio = 0.0; double *iact_a = (double *)psub->b; double *ictrl_a = (double *)psub->c; devicePvt_ts *dpvt_ps = (devicePvt_ts *)psub->dpvt; if (!psub->dpvt) return(ERROR); npts = min(npts,dpvt_ps->npts); if (npts<=1) return(ERROR); epicsMutexMustLock(dpvt_ps->mlock); iratio = (iact_a[npts-1] - iact_a[0])/(ictrl_a[npts-1] - ictrl_a[0]); epicsMutexUnlock(dpvt_ps->mlock); if (iratio<0) iratio *= -1.; if ((iratio<(*(double *)psub->d)) || (iratio>(*(double *)psub->e))) (*(epicsUInt32 *)psub->vala) = 0; /* set out-of-tolerance */ else (*(epicsUInt32 *)psub->vala) = 1; /* set in-tolerancce */ (*(double *)psub->valb) = iratio; (*(double *)psub->valc) = (*(double *)psub->f) * (*(double *)psub->h); (*(double *)psub->vald) = (*(double *)psub->g) * (*(double *)psub->h); /* Ensure that the tolerances are positive */ if ((*(double*)psub->valc)< 0) (*(double *)psub->valc) *= -1.; if ((*(double*)psub->vald)< 0) (*(double *)psub->vald) *= -1.; return(status); } /*============================================================================= Name: mgntExplode Abs: Populate waveform with polynomial coefficients from subroutine record :POLYCOEF.A thru L Args: Type Name Access Description ------------------- ----------- ---------- ---------------------------- subRecord * psub read/write pointer to subroutine record Rem: Init Subroutine for PRIM:LOCA:UNIT:COEF2WF Input: -------- INPA = :POLYCOEF (subroutine record) INPB = :IVB (wafeform record) DPVT = Pointer to array of pointers such that ptr[0] = ptr to subrecord :POLYCOEF ptr[1] = ptr to waveform record :IVB Output: -------- write data to :IVB from :POLYCOEF.A thru L :IVB.NORD to :POLYCOEF.VAL Side: None Ret: long 0 - Successful -1 - for invalid INPA or invalid INPB ==============================================================================*/ long mgntExplode(subRecord *psub) { long status=SUCCESS; epicsUInt32 i,num; mgntWfCoef *pdev=psub->dpvt; /* Get the address of waveform record, and pointer to data */ if (!pdev || !pdev->pdata || psub->a<0) return(-1); if (!pdev->nelem || !psub->a) return(status); /* Popuplate waveform with subroutine record polynomial coefficients */ num = min(psub->a,pdev->nelem); for (i=0; ipdata[i] = pdev->pcoef[i]; } /* Set the number of elements read from subroutine record */ *pdev->pnord = num; return(status); } /*============================================================================= Name: mgntHstaDecode Abs: Decode SLC Magnet Parimary Secondary STAT Args: Type Name Access Description ------------------- ----------- ---------- ---------------------------- sSubRecord * psub read/write pointer to subroutine record Input: ------ INPA = HSTACTRL Outputs: -------- I = Completely Happy J = Out of Service (no functions allowed for this device) K = In Trouble (functions allowed) L = Turned off by operator M = Polarity Reversed (not used) N = Feedback Control (no functions allowed for this device) O = Mini-Stdz Required P = Calibrate Disable Q = Perturb Disble R = Trim Disable S = Standardize Disabled T = U = Magnet uses IVBD V = Shunt/Booster (not used) W = No AUTO Trim (not used) X = State Y = No Analog Control Rem: Side: Ret: long 0 - Successful (always) ==============================================================================*/ static long mgntHstaDecode (sSubRecord *psub) { long status = SUCCESS; epicsUInt32 temp; epicsUInt32 mask = (HSTA_NOCALB | HSTA_NOPTRB | HSTA_NOTRIM | HSTA_NOSTDZ); temp = (epicsUInt32)psub->a; psub->i = temp & HSTA_GOOD; /* Device is Good */ psub->j = (temp & HSTA_DEAD)>>HSTA_DEAD_SHFT; /* Device is out-of-service */ psub->k = (temp & HSTA_SICK)>>HSTA_SICK_SHFT; /* Device is in-trouble */ psub->l = (temp & HSTA_TURNEDOFF)>>HSTA_TURNEDOFF_SHFT; /* Turned off by Operator */ /* Determine the state of the power supply */ if (psub->l >0) psub->x = PSOFF; /* ps is turned off */ else psub->x = PSON; /* ps is turned on */ psub->m = (temp & HSTA_REVERSE)>>HSTA_REVERSE_SHFT; /* polarity reversed */ psub->n = (temp & HSTA_FBCKCTRL)>>HSTA_FBCKCTRL_SHFT; /* feedback control */ /* psub->o = (temp & HSTA_MINI_STDZ_REQ)>>HSTA_MINISTDZ_SHFT; mini-stdz required */ psub->p = (temp & HSTA_NOCALB)>>HSTA_NOCALB_SHFT; /* calibrate disabled */ psub->q = (temp & HSTA_NOPTRB)>>HSTA_NOPTRB_SHFT; /* perturb disabled */ psub->r = (temp & HSTA_NOTRIM)>>HSTA_NOTRIM_SHFT; /* trim disabled */ psub->s = (temp & HSTA_NOSTDZ)>>HSTA_NOSTDZ_SHFT; /* stdz disabled */ /* psub->t = (temp & HSTA_NORETRY)>>HSTA_NOTRIMRETRY_SHFT; no retry on trim */ psub->v = (temp & HSTA_IVBD)>>HSTA_IVBD_SHFT; /* I to B down direction */ /* psub->u = (temp & HSTA_SHUNTED)>>HSTA_SHUNTED_SHFT; Shunt or boost ps */ /* psub->w = (temp & HSTA_NOAUTOTRIM)>>HSTA_NOAUTOTRIM_SHFT; no auto trim */ if ( (temp & mask)==mask ) psub->y = 1; /* set no analog control */ else psub->y = 0; /* analog control ok */ DEBUGPRINT(DP_DEBUG, mgntSubFlag, ("mgntHstaDecode for %s: temp=0x%.4lx \n", psub->name,(long)temp)); return(status); } /*============================================================================= Name: mgntHstaEncode Abs: Encode the EPICS Magnet Hardware Status from the SLC equivilent Args: Type Name Access Description ------------------- ----------- ---------- ---------------------------- sSubRecord * psub read/write pointer to subroutine record Input: ------- INPA = NOT USED !! deprecated 10/24/2011 luchini Reversing switch hw INPB = $(DEV):PSTYPE.RVAL - PS Type, 0=bipolar, 1=unipolar, 2=unipolar w/reversing switch INPC = $(DEV):TURNEDOFF.RVAL - PS turned off by users (0=NO,1-YES) INPD = $(DEV):CONFIG.RVAL - (0=blank,1=String,2=String Main) INPE = $(DEV):PSCATATORY.RVAL - (0=small, 1=intermediate, 2=bulk,3=modulator,4=noone) INPF = $(DEV):INTLKSUMY - Interlock fault status (0=OK, 1=FAULT) INPG = $(DEV):AUTOCTRL.RVAL - Automatically ctrl'ed (for EFC) INPH = NOT USED INPI = NOT USED - !! deprecated - Completely Happy from slc INPJ = $(DEV):OUTOFSERVICE.RVAL - Out of Service (0=In-Servie, 1=Out-of-Service) INPK = NOT USED - !! deprecated - In Trouble from slc INPL = $(DEV):STATE.RVAL - PS On/Off Status INPM = NOT USED - !! deprecated $(DEV):REVSWSTATE - Polarity Reversed INPN = $(DEV):FBCKENABLE.RVAL - Feedback Control, used for matlab feedback only INPO = $(DEV):PAU - Pattern Aware INPP = $(DEV):CALBDISABLE.RVAL - Calibrate Disabled INPQ = $(DEV):PERTBDISABLE.RVAL - Perturb Disabled INPR = $(DEV):TRIMDISABLE.RVAL - Trim Disabled INPS = $(DEV):STDZDISABLE.RVAL - Standardize Disable INPT = $(DEV):FBCK (dr) - Fast feedback control INPU = $(DEV):TRIMTYPE.RVAL - Trim Type (1=Linear Trim type; 0=3-Linear) INPV = $(DEV):STDZDIRECT.RVAL - Magnet uses IVBD from epics INPW = $(DEV):DEGAUSENABLE.RVAL - Degaussed Enabled INPX = NOT USED Output: ---------- C = PS turned off by user (0=NO,1=YES") Y = Feedback control Z = 16 bit HSTA formated for slc Rem: Only the feedback software can change the EPICS pv FBCKCTRL Side: None Ret: long 0 - Successful (always) ==============================================================================*/ static long mgntHstaEncode (sSubRecord *psub) { long status=SUCCESS; epicsUInt32 val = 0; epicsUInt32 fbck = 0; /* * DR: if either FBCKENABLE (matlab) is Enabled or if FBCK (fastfbck) is On, * then display feedback control */ if ( ((epicsUInt32)psub->t >0.1) && ((epicsUInt32)psub->t < 2) ) { fbck =1; /* Fast Feedback */ } fbck = ( (epicsUInt32)psub->n || fbck ); /* Matlab feedback */ psub->y = fbck; /* * form 16 bit HSTA. start w zero, * shift bits and or */ /*val |= (((epicsUInt32)psub->i)<j)<k)<l > 0.1){ /* :STATE */ val &= HSTA_ON_MASK; /* clear bit, ps is ON */ } /* * Otherwise, the ps is off, so check to see if it was * turned off by an operator. If so, then * set the Turned Off flag in HSTA */ else if (psub->f == 0.) { val |= HSTA_TURNEDOFF; /* ps turned off by operator */ } else { val &= ~HSTA_TURNEDOFF; /*clear bit, Ps Turned Off by operator */ } /* * If the ps has reversing switch hardware and it is a unipolar device * and the current polarity switch state is reverse then set HSTA to reverse polarity */ if ( (((epicsUInt32) psub->b)==PS_TYPE_UNIPOLAR_REVSW) && (((epicsUInt32)psub->m)==REVERSE_POLARITY) ) val |= (1<o)<d==CONFIG_STRING) || ((epicsUInt32)psub->e==PS_BULK)) val |= (0xF<w)<p)<q)<r)<s)<g)<u)<v)<val = (double)val; return(status); } /*============================================================================= Name: mgntSlcStat Abs: Formulates slc status given relevant control bo's and SEVR/STAT inputs Args: Type Name Access Description ------------------- ----------- ---------- ---------------------------- subRecord * psub read point to subroutine record Input: --------- INPA - $(DEV):BACT.STAT INPB - $(DEV):BDES.STAT INPC - $(DEV):IRIPL.STAT INPD - $(ADEV):SETPT.STAT INPE - $(ADEV):ACT.STAT INPF - $(DEV):BCON.STAT (optional) INPG - $(DEV):BACT.SEVR INPH - $(DEV):BDES.SEVR INPI - $(DEV):IRIPL.SEVR INPJ - $(ADEV):SETPT.SEVR INPK - $(ADEV):IACT.SEVR INPL - $(DEV):BCON.SEVR (optional) INPM - $(DEV):STATE.RVAL INPN - $(DEV):STDZOK INPO - $(DEV):CALBOK INPP - $(DEV):OUTOFSERVICE.RVAL INPQ - $(DEV):CONFIG (0=blank,1=String,2=String Main) INPR - $(DEV):HSTA INPS - $(DEV):CTRL.RVAL !! Reused 4/15/2010 !!$(DEV):BDELTAS.M - out of tol for bdes-bact !! deprecated - now uses BACT.SEVR>NO_ALARM INPT - $(DEV):DEGAUSOK INPV - $(DEV):INTLKSUMY INPZ - $(DEV):AUTOCTRL - set to 1, indicates EF Correctors Output: --------- U - Input to UNAVAIL via UNAVAILGO seq record W - EPICS STAT X - EPICS SEVR (severity) VAL - SLC STAT bitmask Rem: Subroutine for $(DEV):STATSUB -> STAT ! INDIVIDUALLY CONTROLLED MAGNETS ! ! Quadrupoles, correctors and other magnets on individual 'op amp' ! power supplies are controlled by a channel of a 16 bit TRANSIAC ! DAC and monitored by a channel of a SAM. The database structure ! for all such magnets is identical and is described for QUADs ! in detail below. LGPS's are similar, but have a few extra secondaries. ! ! Note: The HDSC definitions which BITB in the name are only valid for ! BITBUS controlled magnets which includes: LGPSs, XCORs, YCORs, ! QTRMs, BTRMs and SOLNs. Also, BITBUS controlled devices have ! the PSC2 and PSI bit definitions set. Also, when the ARC Mover ! bit is set for BITBUS controlled magnets, the ramp time is ! converted to 20Hz instead of 100Hz for other BITBUS supplies. ! ! BIT HDSC(Descriptor) HSTA(Hdwe Status) STAT(Status) BIT ! ! 0001 Dual DB Devices Completely Happy Completely Happy 0001 green ! 0002 Poor Tracking Substandard but OK 0002 yellow ! 0004 -B in Norm Polarity Out of Service Offline 0004 cyan ! 0008 Absolute Set In Trouble Sick 0008 red ! 0010 Wrap phase at 360 Turned OFF by VAX Is Turned OFF 0010 STAT_OFFLINE ! 0020 Fast Ramp Stdz Polarity Reversed Standardize OK 0020 STAT_STDZOK ! 0040 Polarity Switch Feedback Control Calibration OK 0040 STAT_CALOK ! 0080 PSC Reset Enabled Pattern Aware BACT Drifting 0080 STAT_DRIFTING ! 0100 PSC 2 Calibrate Disabled Database Error 0100 STAT_DBERR ! 0200 PSi/RF req to Trim Perturb Disabled DAC Error 0200 STAT_DACERR ! 0400 Second ADC Trim Disabled ADC Error 0400 STAT_ADCERR ! 0800 PAU/ Pulsed LGPS Standardize Disab. OUT of Range 0800 STAT_BADCUR ! 1000 ARC Mover/BITB Conv Degauss Enabled OUT of Tolerance 1000 STAT_OUTTOL ! 2000 BITB On/Off Switch Magnet uses IVBD BAD Ripple 2000 STAT_BADRIPL ! 4000 BITB MultiChan PS Auto-controlled BAD BACT 4000 STAT_BADBACT ! 8000 Trim coil reversed No AUTO Trim 8000 ! Side: Only one of the 4 LSB conditions should be set. High order bits (8-15) indicate particular error condition. SLC tries to adjust BACT iteratively when found the be out of tol with the desired B-field BDES, based on prev IACT-calculated. IACT if after max iterations, still is out of tol, then BADBACT is set. The Lower nibble of stat is universal for all magnet types. init : =STAT(IUN).AND..NOT.(ERRBITS.OR.STATBITS.OR.OFFBITS) STATBITS =(STAT_GOOD+STAT_OK+STAT_DEAD+STAT_SICK), ERRBITS =(STAT_DBERR+STAT_DACERR+ STAT_ADCERR+STAT_BADCUR+ STAT_OUTTOL+STAT_BADRIPL+STAT_BADBACT), SAVBITS =(STAT_OFF+STAT_STDZOK+STAT_CALOK), OFFBITS = STAT_DEAD+HSTA_OFFLINE, TOLBITS = STAT_OUTTOL+STAT_SICK, GOODBITS = STAT_GOOD+STAT_OK, DBBITS = STAT_DBERR+STAT_SICK, CURBITS = STAT_BADCUR+STAT_SICK, Use a mask to clear every high order bit except Calibration OK and Is Turned off bits for "Turned Off". For "Offline", clear every high order bit, leaving the OFFLINE high order bit as the only one set. Ret: long - Always 0 ==============================================================================*/ static long mgntSlcStat (sSubRecord *psub) { long status = SUCCESS; unsigned short stat=0; unsigned short dead = 0; unsigned short pson = 0; unsigned short slave = 0; /* establish w and x as worst case sevr/stat */ psub->w = psub->a; /* set EPICS STAT to BACT.STAT */ psub->x = psub->g; /* set EPICS SEVR to BACT.SEVR */ /* IS BDES.SEVR have a more sever error than EPICS STAT severity */ if (psub->h > psub->x) { psub->w = psub->b; /* set EPICS STAT to BDES.STAT */ psub->x = psub->h; /* set EPICS SEVR to BDES.SEVR */ } if (psub->i > psub->x) { psub->w = psub->c; /* set EPICS STAT to IRIPL.STAT */ psub->x = psub->i; /* set EPICS SEVR to IRIPL.SEVR */ } if (psub->j > psub->x) { psub->w = psub->d; /* set EPICS STAT to ISETPT.STAT */ psub->x = psub->j; /* set EPICS SEVR to ISETPT.SEVR */ } if (psub->k > psub->x) { psub->w = psub->e; /* set EPICS STAT to IACT.STAT to */ psub->x = psub->k; /* set EPICS SEVR to IACT.SEVR */ } /* For standard magnet use for BCON, for EF Correctors used for GapAct */ if (psub->l > psub->x) { psub->w = psub->f; /* set EPICS STAT to BCON.STAT/to */ psub->x = psub->l; /* set EPICS SEVR to BCON.SEVR */ } /* Is Power Supply Off? If yes, first check if it tripped. */ if ( psub->m == 0. ) { if (psub->v > 0.1) stat |= STAT_TRIPPED; /* ps tripped */ else stat |= STAT_OFFLINE; /* turned off */ } else pson = 1; if (psub->t > 0.1 ) stat |= (STAT_DEGAUSOK); /* Is degauss successful? */ if (psub->n > 0.1) stat |= (STAT_STDZOK); /* Is standardize successful? */ if (psub->o > 0.1) stat |= (STAT_CALOK); /* Is calibrate successful? */ if (psub->p > 0.1) { stat |= STAT_DEAD; /* Is device out-of-service? */ dead = 1; } if (psub->i==MINOR_ALARM) stat |= (STAT_BADRIPL | STAT_OK); /* needed for yellow bad ripl message */ /* Check states for magnet that are not a string slave. */ if ( (epicsUInt32) psub->q==CONFIG_STRING ) slave=1; if ( !slave ) { /* Is there a communication or dac write error? */ if (psub->d==COMM_ALARM || psub->d==WRITE_ALARM || psub->d==LINK_ALARM) { stat |= (STAT_DACERR | STAT_SICK); /* Set DAC error and In-Trouble bits */ } /* Is there a communication or adc read error? */ if (psub->e==COMM_ALARM || psub->e==READ_ALARM || psub->e==UDF_ALARM || psub->d==LINK_ALARM || psub->k==INVALID_ALARM) { /* Is there a communication error or a adc read error */ stat |= (STAT_ADCERR | STAT_SICK); /* Set ADC error and In-Trouble bits */ } /* Is bact out of tolerance with bdes? Bad ripple is checked and set in code above. */ if (psub->g > MINOR_ALARM ) { stat |= (STAT_OUTTOL | STAT_SICK); /* Set out-of-tol and (old)warning bit, now sick bit */ } /* Did we have any alarms occur that caused bact does not converge to bdes? */ if (psub->a==BAD_SUB_ALARM) { stat |= (STAT_BADBACT | STAT_SICK); /* Set bad bact bit */ } /* BCON error ? */ if (psub->l > NO_ALARM) { if (psub->l > MINOR_ALARM) /* BCON Alarm */ stat |= STAT_SICK; else stat |= STAT_OK; /* STAT doesn't have a bit for BCON warning */ } } if (stat & STAT_DEAD) { /* preserve this - the only case is Offline */ if (dead) { /* if offline clear all other STAT bits */ stat &= 0x0000; stat |= STAT_DEAD; } else { stat &= STAT_LSB_MASK; stat |= STAT_DEAD; } } else if (stat & STAT_SICK) { stat &= STAT_LSB_MASK; stat |= STAT_SICK; } else if (stat & STAT_OK) { stat &= STAT_LSB_MASK; stat |= STAT_OK; } else stat |= STAT_GOOD; if (stat & STAT_OFFLINE){ /* if turned off, clear all other bits except calok */ stat &= 0x0000; stat |= 0x0044; } /* if stat is not previously set to SICK or DEAD or OK, set to GOOD if (!( ((stat & STAT_SICK) == STAT_SICK) || ((stat & STAT_DEAD) == STAT_DEAD) || ((stat & STAT_OK) == STAT_OK) ) ) stat |= STAT_GOOD;*/ /* The device is considered unavailable for any control * functions tobe performed if any of the following is true. * 1) ps current cannot be controlled (ie. nocalb,noptrb,notrim,nostdz) * 2) device is out-of-service * 3) ps is on but we have an ps fault (mcor pwr module fault but bulk on) * 4) ps is off and not in middle of degaus procedure */ if ( slave || dead || (pson && (psub->v==MAJOR_ALARM)) || (!pson && psub->s!=CTRL_DEGAUSS) ) psub->u = 1; /* device is not ready for control - unavail */ else psub->u = 0; /* device is ready for control */ psub->val = (double)stat; if (psub->val > 0xffff){ DEBUGPRINT(DP_ERROR, mgntSubFlag, ("mgntSlcStat stat ERROR for %s = 0x%x; val = %f\n", psub->name, (unsigned short)stat, psub->val)); } return(status); } /*============================================================================= Name: mgntSlcStatMsg Abs: SLC Status Message eventually sent to $(DEV):STATMSG (MBBO) Args: Type Name Access Description ------------------- ----------- ---------- ---------------------------- unsigned short stat read-only STAT unsigned short hsta read-only HSTA unsigned short pval read-write SLC STATMSG bitmask H Rem: This function returns a bitmask value which can be mapped to a string in the mbbo $(DEV):STATMSG. The message is indicates the device status "worst case". Side: Function must be re-entrant. Table (SLC info) from Nancy Spencer below. In summary, the SLC has a total of 17 possible strings, we will not be implementing a few, so 16 strings will be sufficient. The strings are as follows, listed from MOST SEVERE to LEAST SEVERE: ------------------------------SLC----------------------------------- -------LCLS--------- String Color Condition for string EPICS ------ ----- ------------------------------------------------- --------------------- OFFLine Cyan STAT_DEAD + HSTA_DEAD both set (magnet not in use) STAT_DEAD + HSTA_DEAD (both governed by OUTOFSERVICE) TurnedOff Red STAT_OFFLINE + HSTA_TURNEDOFF both set(turned off user)HSTA_TURNEDOFF +STAT_OFFLINE ONNoCtrl Red HSTA_TURNEDOFF set, STAT_OFFLINE clear (Local Mode) Not Implementing <<<<< won't happen in lcls - whenever STATE toggles, both STAT_OFFLINE and HSTA_TURNEDOFF change Tripped Red STAT_OFFLINE set, HSTA_TURNEDOFF clear (tripped off) STAT_OFFLINE + fault NoControl White HSTA_NOCALB+HSTA_NOPTRB+HSTA_NOTRIM+HSTA_NOSTDZallset HSTA_NOCTRL Fdbk Ctrl White HSTA_FBCKCTRL HSTA_FBCKCTRL DB Err Red STAT_DBERR + STAT_SICK both set (db error) Not Implementing <<<<< DAC Error Red STAT_DACERR + STAT_SICK both set STAT_SICK + STAT_DACERR ADC Error Red STAT_ADCERR + STAT_SICK both set STAT_SICK + STAT_ADCERR Out-Range Red STAT_BADCUR + STAT_SICK both set Not Implementing <<<<<< OutofTol Red STAT_OUTTOL + STAT_SICK both set STAT_SICK + STAT_OUTTOL Bad Rippl Yellow STAT_BADRIPL + STAT_OK both set STAT_OK + STAT_BADRIPL Bad Bact Red STAT_BADBACT + STAT_SICK both set STAT_SICK + STAT_BADBACT BdesChang Yellow STAT_OK + STAT_OUTTOL both set Not Implementing <<<< DAC Warn Yellow STAT_OK + STAT_DACERR both set Not Implementing <<<< Drifting Yellow STAT_DRIFTING + STAT_OK both set (Not yet outofTol) FUTURE BCON WarningYellow Not Cal'd Yellow HSTA_NOCALB clear + STAT_CALOK clear(Cal was req'ed) !STAT_CALOK + !HSTA_NOCALB Not Stdz'd Yellow HSTA_NOSTDZ clear + STAT_STDZOK clear(Stdz was req'ed)STAT_STDZOK + !HSTA_NOSTDZ Good Ret: None ==============================================================================*/ static void mgntSlcStatMsg(unsigned short stat, unsigned short hsta, unsigned short onoffctrl, unsigned short *pval) { unsigned short statmsg = 0; /* * Is this device Offline? * If yes, then check HSTA to see if it is Out-Of-Service. * Both HSTA_DEAD and STAT_DEAD are governed by OUTOFSERVICE pv * this means they are (offline) not OFFLINE (Turned off) */ if (stat & STAT_DEAD) { if (hsta & HSTA_DEAD) statmsg = STAT_DEAD_SHFT; /* * We should never get here - but just in case * the device has been turned off. */ else statmsg = STAT_OFFLINE_SHFT; /* turned off */ } else if (stat & STAT_TRIPPED) statmsg = STAT_TRIPPED_SHFT; /* ps tripped */ else { /* * Has this device been turned off from the VAX? * If yes, then does the micro think that this * device has been turned off? */ /* set hsta to "good" whenever ps is not Offline or Tripped */ hsta |= HSTA_GOOD; if (hsta & HSTA_TURNEDOFF) { if (stat & STAT_OFFLINE) /* STAT_OFFLINE set when STATE = 0*/ statmsg = STAT_OFFLINE_SHFT; /* * At this point the device was suppose tobe * turned off from the VAX but the micro thinks * it is online. So, is there and ADC error * which could cause this contradiction? */ else if (stat & STAT_ADCERR) statmsg = STAT_ADCERR_SHFT; else { /* * This is a bad state - we think it's off but it's really on; * however we'll refuse to do any operations to it * ON and no control - need to add later...no bits left in statmsg */ } } /* * Is this device controlled by the feedback system? */ else if ( hsta & HSTA_FBCKCTRL ) statmsg = STAT_FBCKCTRL_SHFT; /* * OK, since the offline and no control issues * have been resolved, do we have any error or warning * conditions set in STAT? If yes, then display the * most severe. * NOTE: If warnings exists then the OK bit * will be set in STAT (ie bit 2). If an error exists then * the SICK bit will be set in STAT (ie: bit 4). * The type of error or warning condition is indicated * by the bits set in the upper byte of STAT (ie: bits 8-15). */ else if ((stat & DAC_ERRBITS)==DAC_ERRBITS ) statmsg = STAT_DACERR_SHFT; else if ((stat & ADC_ERRBITS)==ADC_ERRBITS ) statmsg = STAT_ADCERR_SHFT; /* * The BADCUR bits are not being set in STAT * else if ((stat & BADCUR_ERRBITS)==BADCUR_ERRBITS ) * statmsg = STAT_BADCUR_SHFT; */ /* * If within check tol, BDELTAS.M is not set causing * STAT_OUTTOL not to be set, therefore BACT is still yellow */ else if ((stat & OUTTOL_ERRBITS)==OUTTOL_ERRBITS ) statmsg = STAT_OUTTOL_SHFT; else if ((stat & BADRIPL_ERRBITS)==BADRIPL_ERRBITS ) statmsg = STAT_BADRIPL_SHFT; else if ((stat & BADBACT_ERRBITS)==BADBACT_ERRBITS ) statmsg = STAT_BADBACT_SHFT; else if ((stat & STAT_SICK)==STAT_SICK) statmsg = STAT_OK_SHFT; /* BCON alarm */ /* * BDES Change is NOT implemented so REUSED this STAT bit for * a degauss warning */ else if ( ((stat & STAT_DEGAUSOK)==0) && (hsta & HSTA_DEGAUS_ENB) ) statmsg = STAT_DEGAUSWARN_SHFT; else if ( ((stat & STAT_CALOK)==0) && ((hsta & HSTA_NOCALB)==0) ) statmsg = STAT_CALBOK_SHFT; else if ( ((stat & STAT_STDZOK)==0) && ((hsta & HSTA_NOSTDZ)==0) ) statmsg = STAT_NOSTDZ_SHFT; else if ( (stat & STAT_OK)==STAT_OK) /* BCON Warning*/ statmsg = STAT_OK_SHFT; } /* Is this magnet a string slave? */ if ( ((hsta & HSTA_NOCTRL)==HSTA_NOCTRL) && !onoffctrl && ((hsta & HSTA_AUTOCTRL)==0)) statmsg = STAT_NOCTRL_SHFT; *pval = statmsg; return; } /*============================================================================= Name: mgntStatDecode Abs: Decodes SLC STAT into 16 different outputs Subroutine for STATCTRLSUB Args: Type Name Access Description ------------------- ----------- ---------- ---------------------------- subRecord * psub read/write pointer to subroutine record Input: ------- INPA = $(DEV):STAT INPB = $(DEV):HSTA INPC = Not used INPD = $(DEV):ONOFFCTRL.RVAL INPE = $(USEG):GapAct.SEVR, only used for EF correctors in undulator Outputs: --------- G - H - I - J - ... W - SLC STATMSG bitmask Rem: Takes slc-style STAT and decodes into indiv bits. Takes HSTA Interlock summary (fault) and on/off control inputs in order to pass along to the subroutine that figures out worst case status message. Side: None Ret: long 0 - Successful (always) ==============================================================================*/ static long mgntStatDecode (sSubRecord *psub) { long status=SUCCESS; unsigned short stat; unsigned short statmsg=0; unsigned short hsta=0; unsigned short onoffctrl=0; stat = (unsigned short)(psub->a); hsta = (unsigned short)(psub->b); psub->h = (double)( (stat & STAT_GOOD)>>STAT_GOOD_SHFT); psub->i = (double)( (stat & STAT_OK)>>STAT_OK_SHFT); psub->j = (double)( (stat & STAT_DEAD)>>STAT_DEAD_SHFT); psub->k = (double)( (stat & STAT_SICK)>>STAT_SICK_SHFT); psub->l = (double)( (stat & STAT_OFFLINE )>>STAT_OFFLINE_SHFT); psub->m = (double)( (stat & STAT_STDZOK)>>STAT_STDZOK_SHFT); psub->n = (double)( (stat & STAT_CALOK )>>STAT_CALBOK_SHFT); psub->o = (double)( (stat & STAT_DEGAUSOK)>>STAT_DRIFTING_SHFT); /* psub->p = (double)( (stat & STAT_DBERR)>>STAT_DBERR_SHFT); */ psub->p = (double)( (stat & STAT_TRIPPED)>>STAT_TRIPPED_SHFT); psub->q = (double)( (stat & STAT_DACERR)>>STAT_DACERR_SHFT); psub->r = (double)( (stat & STAT_ADCERR)>>STAT_ADCERR_SHFT); psub->s = (double)( (stat & STAT_BADCUR)>>STAT_BADCUR_SHFT); psub->t = (double)( (stat & STAT_OUTTOL)>>STAT_OUTTOL_SHFT ); psub->u = (double)( (stat & STAT_BADRIPL)>>STAT_BADRIPL_SHFT); psub->v = (double)( (stat & STAT_BADBACT)>>STAT_BADBACT_SHFT); if ( psub->d > 0.1 ) onoffctrl=1; mgntSlcStatMsg(stat,hsta,onoffctrl,&statmsg); psub->w = (double)statmsg; DEBUGPRINT(DP_DEBUG, mgntSubFlag, ("mgntStatDecode for %s: stat=0x%.4hx hsta=0x%.4hx statmsg=0x%.4hx\n", psub->name,stat,hsta,statmsg)); return(status); } /*============================================================================= Name: mgntRiplOK Abs: Calculates trim ramp rate for TRIMTYPE 3-linea Args: Type Name Access Description ------------------- ----------- ---------- ---------------------------- subRecord * psub read/write pointer to subroutine record Input: ------- INPA - $(DEV):IRIPL INPB - $(DEV):IDELTAS.J - CURR_TOL=ABS(CHCK_TOL) * DC_DB) = ABS( $(DEV):BDELTAS.J * $(DEV):BDES.L) D - used for factor of CURR_TOL=ABS(CHCK_TOL) * DC_DB) Output: ------- E = Calculated tolerance VAL =0 IRIPL not within itol*2 =1 IRIPL is within itol*2 Rem: Side: in magtrck.f86, a different algorithm for LGPS is used Ret: int 0 - Successful 1 - Invalid ==============================================================================*/ static long mgntRiplOK (subRecord *psub) { long status=SUCCESS; double curr_tol; curr_tol = psub->b; if (curr_tol<0) curr_tol *= -1; if (!curr_tol) psub->val = 1; /* success */ else { if (psub->d>0) psub->e = psub->d * curr_tol; else psub->e = 2.0 * curr_tol; if (psub->a > psub->e) psub-> val = 0; /* failure */ else psub-> val = 1; /* success */ } return(status); } /*============================================================================= Name: mgntDrifting Abs: Determine if the magnet field has changed significantely Args: Type Name Access Description ------------------- ----------- ---------- ---------------------------- subRecord * psub read/write pointer to subroutine record Rem: Init Subroutine for PRIM:LOCA:UNIT:DRIFTCHECK Input: -------- INPA = :BDES Desired B-field INPB = :BACT Actual B-field INPC = :FBCK Feedback enabled (0=disabled, 1=enabled, 2=not available) INPD = :PAU Pattern aware flag (0=disabled, 1=enabled) INPE = :BTRIMTOL Absolute warning tolerance on B-field INPF = :BTRIMTOLR Relative (fractional) warning tolerance on B-field INPG = :STATE.RVAL Power Supply on/off status (0=off, 1=on) INPH = :OUTOFSERVICE Device is out-of-service (0=in-service, 1=out-of-service) INPI = :FBCKENABLE.RVAL Matlab feedback (0=disabled, 1=enabled) SDIS = :SELECTEN If control function has been selected, then SELECTEN=Busy (1) and PV will be disabled, until control function has completed Output: -------- VALA = :DRIFTING VALB = :BACTPREV VALC = abs(b-field tolerance) VALD = abs(bact - prev_bact) Side: None Ret: long 0 - Successful -1 - Failure, due to error ==============================================================================*/ long mgntDrifting(aSubRecord *psub) { long status = SUCCESS; /* * If this is the first pass then set prev adc * before exiting. */ if (psub->udf) { *(double *)psub->valb = *(double *)psub->b; return(status); } /* * If the power supply is off or the device is out-of-service or * then clear drifting flag, set the prev adc and exit */ if ((*(epicsUInt32 *)psub->g==PSOFF) || *(epicsUInt32 *)psub->h) { *(unsigned short *)psub->vala = 0; /* clear drifting flag */ *(double *)psub->valb = *(double *)psub->b; /* save bact for next time around */ *(double *)psub->valc = 0; /* clear signal tolerance */ *(double *)psub->vald = 0; return(status); } /* * If fast feedback, pattern aware or matlab feedback are enabled, then use bact to * calculate signal tolerance, since bdes is usually not updated regularly. */ if ((*(unsigned short *)psub->c==1) || *(unsigned short *)psub->d || *(epicsUInt32 *)psub->i) { *(double *)psub->valc = abs(*(double *)psub->f * (*(double *)psub->b)); /* b-tolerance, relative */ *(double *)psub->vald = abs(*(double *)psub->b - *(double *)psub->valb); /* abs(bact-bact_prev) */ } else { *(double *)psub->valc = abs(*(double *)psub->f * (*(double *)psub->a)); /* b-tolerance, relative */ *(double *)psub->vald = abs(*(double *)psub->a - *(double *)psub->b); /* abs(bact-bdes) */ } /* Is the absolute b-tolerance larger? If so, then use that */ if (*(double *)psub->valc < *(double *)psub->e) *(double *)psub->valc = *(double *)psub->e; /* If the b-field has changed significantly, the field is drifting */ if (*(double *)psub->vald > *(double *)psub->valc) *(unsigned short *)psub->vala = 1; /* drifting */ else *(unsigned short *)psub->vala = 0; /* not drifting */ /* Save the readback */ *(double *)psub->valb = *(double *)psub->b; return(status); } /*============================================================================= Name: mgntStdzLost Abs: Determine if standardize has been lost Args: Type Name Access Description ------------------- ----------- ---------- ---------------------------- aSubRecord * psub read/write pointer to subroutine record Rem: Init Subroutine for PRIM:LOCA:UNIT:DRIFTCHECK Input: -------- INPA = :STDZOK Standardize flag (0=not stardize, 1=standardized) INPB = :STDZDISABLE.RVAL Standarized function permit (0=enabled, 1=disabled) INPB = :IACT Actual Current INPC = :ICTRL Current Set INPD = :FBCK Feedback enabled (0=disabled, 1=enabled, 2=not available) INPE = :PAU Pattern aware flag (0=disabled, 1=enabled) INPF = :FBCKENABLE.RVAL Matlab feedback (0=disabled, 1=enabled) INPG = :STATE.RVAL Power Supply on/off status (0=off, 1=on) SDIS = :SELECTEN If control function has been selected, then SELECTEN=Busy (1) and PV will be disabled, until control function has completed Output: -------- VALA = status 0=no change, 1=lost VALB = stdzok status VALC = time stamp string Side: None Ret: long 0 - Successful -1 - Failure, due to error ==============================================================================*/ long mgntStdzLost(aSubRecord *psub) { long status = SUCCESS; epicsTimeStamp timestamp; /* Initialize outputs */ *(epicsUInt32 *)psub->vala = 0; *(unsigned short *)psub->valb = *(unsigned short *)psub->a; epicsTimeGetCurrent(×tamp); epicsTimeToStrftime((char *)psub->valc,MAX_STRING_SIZE,TIME_FORMAT,×tamp); /* If device not standardize, then exit */ if (*(unsigned short *)psub->a==0) return(status); /* * If the standardize function is disabled,or the power supply is off * then clear stdzok flag and set the stdz lost time */ if (*(epicsUInt32 *)psub->b || (*(epicsUInt32 *)psub->g==PSOFF)) { *(epicsUInt32 *)psub->vala = 1; *(unsigned short *)psub->valb = 0; } /* check if the magnet current has moved since the last time */ return(status); } /* scondam: 2-Jun-2022: The following two subroutines subPSAlarmDelta and subPSWarnDelta are used only in SPEAR */ /*============================================================================= Proto: not required and not used. All functions called by the subroutine record get passed one argument: psub Pointer to the subroutine record data. Use: pointer Type: struct subRecord * Acc: read/write Mech: reference All functions return a long integer. 0 = OK, -1 = ERROR. The subroutine record ignores the status returned by the Init routines. For the calculation routines, the record status (STAT) is set to SOFT_ALARM (unless it is already set to LINK_ALARM due to severity maximization) and the severity (SEVR) is set to psub->brsv (BRSV - set by the user in the database though it is expected to be invalid). Auth: 08-Jan-2004, Stephanie Allison ==============================================================================*/ /*============================================================================= * Calculate alarm limits from desired deltas and reference. * * Name: subPSAlarmDelta * Function: Alarm Limit Delta and Absolute Limits * Inputs: * A = Reference * B = Delta for Alarm Limits (HIHI, LOLO) * C = Delta for Warning Limits (HIGH, LOW) * D = Enable/disable limits state * E = Enable/disable flag * 0 = When D==0, enable limits. * 1 = When D==0, disable limits. * Outputs: * H = Delta for Warning Limits * I = HIHI value * J = HIGH value * K = LOW value * L = LOLO value * VAL = Delta for Alarm Limits ==============================================================================*/ long subPSAlarmDelta(struct subRecord *psub) { if (((psub->e > 0.5) && (psub->d < 0.5)) || ((psub->e < 0.5) && (psub->d > 0.5))) { psub->val = 1000000.0; psub->h = 1000000.0; } else { psub->val = psub->b; psub->h = psub->c; } psub->i = psub->a + psub->val; psub->l = psub->a - psub->val; psub->j = psub->a + psub->h; psub->k = psub->a - psub->h; return 0; } /*============================================================================= * Calculate warning and alarm deltas from gold value or setpoint. * If the alarms are disabled or the setpoint is currently changing, * then set deltas to large values to disable alarms. * * Name: subPSWarnDelta * Function: Warning Limit Delta * Inputs: * A = Current Setpoint * B = Setpoint above which % is used and * below which delta is used (must be positive) * C = Gold Setpoint * D = Warning Delta * E = Multiplier for Alarm Limits (must be > 1) * F = Setpoint currently changing? (0=no, 1=yes) * (0=calc limits, 1=disable limits) * G = State (0=off, 1=on) * (1=calc limits, 0=disable limits) * H = Limits State * (0=disable limits, 1=use gold, 2=use setpoint) * I = Warning Fraction * Outputs: * K = Reference (gold or setpoint) * L = Delta for Alarm Limits * VAL = Delta for Warning Limits ==============================================================================*/ long subPSWarnDelta(struct subRecord *psub) { /* If setpoint is changing or the power supply is off, set deltas to large numbers to disabling alarming. */ if ((psub->f > 0.5) || (psub->g < 0.5) || (psub->h < 0.5)) { psub->val = 1000000.0; psub->l = 1000000.0; psub->k = 0.0; } else { /* Set reference value based on limits state. */ if (psub->h < 1.5) psub->k = psub->c; else psub->k = psub->a; /* Calculate warning limits tolerance. Use either fraction or absolute value depending on current setpoint value. */ if (psub->b < 0) psub->b = -psub->b; if (((psub->k >= 0.0) && (psub->k > psub->b)) || ((psub->k < 0.0) && (psub->k < -psub->b))) { psub->val = psub->k * psub->i; } else { psub->val = psub->d; } /* Calculate alarm limits tolerance using a multiplier. */ psub->l = psub->val * psub->e; /* Tolerances must be positive. */ if (psub->val < 0.0) psub->val = -psub->val; if (psub->l < 0.0) psub->l = -psub->l; } return 0; } /*============================================================================= */ epicsRegisterFunction(mgntInit); epicsRegisterFunction(mgntDegaussInit); epicsRegisterFunction(mgntExplodeInit); epicsRegisterFunction(mgntIVBInit); epicsRegisterFunction(mgntCalbLimitsInit); epicsRegisterFunction(mgntStdzInit); epicsRegisterFunction(mgntInitPoly); epicsRegisterFunction(mgntDegauss); epicsRegisterFunction(mgntStdz); epicsRegisterFunction(mgntIVB); epicsRegisterFunction(mgntNumPolyCoef); epicsRegisterFunction(mgntPoly); epicsRegisterFunction(mgntReversePoly); epicsRegisterFunction(mgntPhyDeltas); epicsRegisterFunction(mgntRawDeltas); epicsRegisterFunction(mgntLimits); epicsRegisterFunction(mgntSlcStat); epicsRegisterFunction(mgntBCONLimits); epicsRegisterFunction(mgntMpsLimits); epicsRegisterFunction(mgntCalbLimits); epicsRegisterFunction(mgntExplode); epicsRegisterFunction(mgntHstaDecode); epicsRegisterFunction(mgntHstaEncode); epicsRegisterFunction(mgntStatDecode); epicsRegisterFunction(mgntRiplOK); epicsRegisterFunction(mgntMcorLimits); epicsRegisterFunction(mgntDrifting); epicsRegisterFunction(mgntStdzLost); /* scondam: 2-Jun-2022: The following two subroutines subPSAlarmDelta and subPSWarnDelta are used only in SPEAR */ epicsRegisterFunction(subPSAlarmDelta); epicsRegisterFunction(subPSWarnDelta); /* Note - when adding a funciton, also add to mgntSub.dbd */