#include #include "padProto.h" #include #include #include #include #include #include #include #include #include #include #include #include #include #undef __STRICT_ANSI__ #include #include #include #include #include #include #include #include #include /* If ENABLE_SIMULATOR == 1 * then every write to the SIM PV will transmit * input values to the PAD simulators but * the PAD will not send a simulated reply back. * Instead, the PAD will generate a simulated * waveform on each HW trigger. * * If ENABLE_SIMULATOR == 2 * ('off-line' mode w/o EVR) the pad immediately * generates a simulated waveform as a response * to a simulate request. */ #define ENABLE_SIMULATOR 0 #if ENABLE_SIMULATOR #define fidHasBeam() (1) #else #include #endif /* obtain last values */ /* Assignment of signals to ADC channels (by AFE wiring) */ #define ADC_MAP_AFE_SIGNAL { RED, YLO, BLU, GRN } /* RED CAL cycle; we look only at blue and green */ #define ADC_MAP_AFE_CAL_RED { -1, -1, BLU, GRN } /* GRN CAL cycle; we look only at red and yellow */ #define ADC_MAP_AFE_CAL_GRN { RED, YLO, -1, -1 } #if 0 #define PAD_OVERRANGE(x) abs((x)) > CLIP_THRESHOLD #define CLIP_THRESHOLD 32000 #else /* PAD has ADC overrange flag encoded in data LSB */ #define PAD_OVERRANGE(x) ((x)&1) #endif #define NumberOf(arr) (sizeof((arr))/sizeof((arr)[0])) #define IIR128(old, new) ((old)*(1.0-1.0/128.) + (new)/128.) #ifndef PI #define PI 3.1415926535897932385 #endif #define RAD ((PI)/180.0) /* have these match the 'kind' so that we can index * the bpmGainRatios arrays either way */ #define GAIN_GRNOVERRED PadDataBpm #define GAIN_GRNOVERBLU PadDataCalRed #define GAIN_REDOVERYLO PadDataCalGrn #define NUM_DATA_KINDS 3 /* We calculate single-precision for now */ typedef float BpmNumber; /* Buffer the last couple of packets received */ static UdpCommPkt lastPkt[MAX_BPM][NUM_DATA_KINDS] = { {0, 0, 0} }; /* TODO: ??? */ typedef uint32_t TimeStamp; #ifdef __PPC__ uint32_t roundtripMax = 0; uint32_t roundtripAvg = 0; uint32_t totTimeMax = 0; uint32_t totTimeAvg = 0; #endif uint32_t drvPadUdpCommDebug = 0; /* Error stati can be OREd */ #define BPM_AMPL_OK 0 /* Overrange detected */ #define BPM_AMPL_OVR_GRN (1<<0) #define BPM_AMPL_OVR_RED (1<<1) #define BPM_AMPL_OVR_BLU (1<<2) #define BPM_AMPL_OVR_YLO (1<<3) #define BPM_AMPL_OVR_MSK (0xf<<0) /* Underrange detected */ #define BPM_AMPL_UDR_GRN (1<<4) #define BPM_AMPL_UDR_RED (1<<5) #define BPM_AMPL_UDR_BLU (1<<6) #define BPM_AMPL_UDR_YLO (1<<7) #define BPM_AMPL_UDR_MSK (0xf<<4) #define BPM_AMPL_RNG_MSK(chnl) \ ( ~(BPM_AMPL_OVR_MSK|BPM_AMPL_UDR_MSK) \ | (chnl >=0 ? (BPM_AMPL_OVR_GRN<<(chnl)) : 0) \ | (chnl >=0 ? (BPM_AMPL_UDR_GRN<<(chnl)) : 0) ) #define BPM_AMPL_TIMEDOUT (1<<8) #define BPM_AMPL_INVALID (1<<9) /* #define BPM_AMPL_SKIPPED (1<<10) #define BPM_AMPL_OLD (2<<10) #define BPM_AMPL_SEQMSK (3<<10) */ #define GRN 0 #define RED 1 #define BLU 2 #define YLO 3 typedef struct BpmRawAmplitudesRec_ { BpmNumber grn,red,blu,ylo; /* grn MUST be the first one [occasional casting to array ] */ BpmNumber tMax[4]; /* tMax MUST follow [occasional casting to array] */ uint32_t status; /* MUST follow 8 numbers [or change INP field in status record */ TimeStamp timeStamp; uint8_t pad[(1<<6)-sizeof(TimeStamp) - 8*sizeof(BpmNumber) - sizeof(uint32_t)]; } BpmRawAmplitudesRec, *BpmRawAmplitudes; #if MAX_BPM > 31 #error "too many channels -- don't fit in 32-bit mask" #endif volatile uint32_t bpmUpToDate[NUM_DATA_KINDS] = { 0, 0, 0}; volatile uint32_t drvPadUdpCommBpmInUse = 0; /* [slowly varying] online calibrator gain ratios */ volatile BpmNumber bpmGainRatios[MAX_BPM][NUM_DATA_KINDS]; volatile BpmNumber bpmGainRatioSlopes[MAX_BPM][NUM_DATA_KINDS]; volatile int bpmGainRatiosOK[MAX_BPM][NUM_DATA_KINDS]; int bpmStatus[MAX_BPM]; /* u,v,correction,x,y,tmit */ #define RES_U 0 #define RES_V 1 #define RES_C 2 #define RES_X 3 #define RES_Y 4 #define RES_T 5 BpmNumber bpmResults[MAX_BPM][6]; /* Cached rotation matrix coefficients */ #define ROT_UU 0 #define ROT_UV 1 #define ROT_VU 2 #define ROT_VV 3 BpmNumber bpmRot[MAX_BPM][PADRPLY_STRM_NCHANNELS]; /* Cached inter-axes angle parameter */ BpmNumber bpmCosPsi[MAX_BPM]; BpmNumber bpmSinPsi[MAX_BPM]; /* 1st index matches PadDataKind */ static int adcMaps[NUM_DATA_KINDS][4] = { ADC_MAP_AFE_SIGNAL, /* PadDataBpm */ ADC_MAP_AFE_CAL_RED, /* PadDataCalRed */ ADC_MAP_AFE_CAL_GRN /* PadDataCalGrn */ }; /* Simulated BPMs */ volatile struct { PadRequestRec req; PadSimCommandRec simbpm[MAX_BPM]; } padSimulateCmd; struct { PadRequestRec req; PadStrmCommandRec cmd[MAX_BPM]; } padStrmCmd; static epicsMutexId padStrmCmdLock; /* This is actually optimized away by gcc */ static int isbe() { union { uint8_t b[2]; uint16_t test; } endian = { b: {0xbe, 00 } }; return endian.test == 0xbe00; } static void strmCmdInit() { int i; padStrmCmd.req.version = PADPROTO_VERSION1; padStrmCmd.req.nCmds = MAX_BPM; padStrmCmd.req.cmdSize = sizeof(padStrmCmd.cmd[0]); for ( i=0; i= MAX_BPM ) return -1; key = epicsInterruptLock(); drvPadUdpCommBpmInUse &= ~(1<= MAX_BPM ) return -1; epicsMutexLock(padStrmCmdLock); padStrmCmd.cmd[channel].type = PADCMD_STRM | PADCMD_QUIET; scmd = padStrmCmd.cmd[channel]; epicsMutexUnlock(padStrmCmdLock); rval = padRequest(drvPadUdpCommSd, channel, PADCMD_STRM, drvPadUdpCommGetXid(), &scmd, 0, drvPadUdpCommTimeout); key = epicsInterruptLock(); drvPadUdpCommBpmInUse |= (1< 32 #error "MAX_BPM too big for current bitmask implementation" #endif volatile uint32_t bpmRawAmplitudesPending = 0; /* Operate on the bitmask */ /* Check if new data for 'channel' is pending */ static __inline__ int bpmRawAmplitudePending(unsigned channel) { int rval, key; key = epicsInterruptLock(); rval = (1<status |= BPM_AMPL_SKIPPED; } else { /* mark as old */ oa->status |= BPM_AMPL_OLD; oa = a; } ampFreeNonl(oa); } bpmRawAmplitudesPending |= msk; epicsInterruptUnlock(key); return rval ? 1 : 0; } #else BpmRawAmplitudesRec ampBuffers[MAX_BPM]; static __inline__ BpmRawAmplitudes ampAlloc(unsigned chnl) { return &Buffers[chnl]; } static __inline__ void ampInit() { int i; memset(ampBuffers, 0, sizeof(ampBuffers)); for ( i=0; i= MAX_BPM || kind < PadDataBpm || kind > PadDataCalGrn ) return p; key = epicsInterruptLock(); oldp = lastPkt[slot][kind]; lastPkt[slot][kind] = p; epicsInterruptUnlock(key); return oldp; } /* may return 0 if no data is * available (=> READ_ALARM) * * If a non-null item is returned, * the user must free it with * padDataFree(); */ void * padDataGet(unsigned slot, PadDataKind kind) { return padDataSwap(slot, kind, 0); } PadReply padReplyFind(void *data_p) { return data_p ? (PadReply)udpCommBufPtr(data_p) : 0; } void padDataFree(void *item) { udpCommFreePacket(item); } static int padDataSave(unsigned slot, PadDataKind kind, UdpCommPkt p) { int rval; UdpCommPkt oldp; if ( !p ) return -1; oldp = padDataSwap(slot, kind, p); /* failure -- invalid arguments */ rval = ( oldp == p ) ? -1 : 0; padDataFree(oldp); return rval; } static long padUdpCommReport(int level) { epicsPrintf("Udp Communication with PAD\n"); return 0; } uint32_t drvPadUdpCommGetXid() { static volatile uint32_t xid = 0; uint32_t rval; int key; key = epicsInterruptLock(); rval = xid++; epicsInterruptUnlock(key); return rval; } int drvPadUdpCommGetNsamples() { return 128; } int drvPadUdpCommSendStartCmd(int nsamples, uint32_t xid, int channel) { PadStrmCommandRec scmd; scmd.type = PADCMD_STRM; scmd.flags = (!isbe()) ? PADCMD_STRM_FLAG_LE : 0; scmd.port = htons(drvPadUdpCommPort + 1); scmd.nsamples = htonl(nsamples); /* Dont ask for a reply if we broadcast */ if ( channel < 0 ) scmd.type |= PADCMD_QUIET; return padRequest(drvPadUdpCommSd, channel, scmd.type, xid, &scmd, 0, drvPadUdpCommTimeout); } int drvPadUdpCommSendStartAll(epicsTimeStamp *ts_p) { int rval; epicsMutexLock(padStrmCmdLock); padStrmCmd.req.xid = htonl(drvPadUdpCommGetXid()); if ( ts_p ) { padStrmCmd.req.timestampHi = htonl(ts_p->secPastEpoch); padStrmCmd.req.timestampLo = htonl(ts_p->nsec); } else { padStrmCmd.req.timestampHi = htonl(0xdeadbeef); padStrmCmd.req.timestampLo = htonl(0xdeadbeef); } rval = udpCommSend(drvPadUdpCommSd, &padStrmCmd, sizeof(padStrmCmd)); epicsMutexUnlock(padStrmCmdLock); return rval; } /* Detection algorithm; * compute signal amplitudes, moment ( sum( amplitude[n] * n ) / sum(amplitude[n]) ), * and check for underflow/overflow. * * Also, the routine maps ADC channels into GRN/RED/BLU/YLO, i.e., * Channel 0 -> pacc[map[0]] * Channel 1 -> pacc[map[1]] * ... * If a 'map' entry is < 0 then the associated channel is skipped. * * RETURNS: bitset of over/underrange channels. */ uint8_t drvPadDetectEnergy(BpmNumber *pacc, BpmNumber *ptim, int16_t *p, int *map, int nsamples) { int i,j,x,x2; uint8_t clipped; BpmNumber s1, m1, s2, s1t, s2t, xf, N; clipped = 0; for ( j=0; j sum(n=0..N-1)/N = (N-1)/2; * */ N = (BpmNumber)nsamples; m1 = s1/N; s2 -= m1*s1; s2t = (s2t - 2 * s1t * m1) + m1*s1*(N-1.)/2.; /* TODO: subtract noise pedestal */ /* normalize */ s2t /= s2; /* Signal under-range if we have less than 64 * noise * contribution. If we have noise of ~2.5 bits then the * integrated energy is 2^5 = 32 * N */ if ( s2 < (nsamples<<11) ) clipped |= (BPM_AMPL_UDR_GRN << j); else s2 = sqrtf(s2); pacc[map[j]] = s2; ptim[map[j]] = s2t; } return clipped; } static int padBpmDataNoCook(PadReply rply) { int chnl = rply->chnl; volatile BpmRawAmplitudes a = ampAlloc(chnl); int key; /* just pet up-to-date status */ key = epicsInterruptLock(); bpmUpToDate[PadDataBpm] |= (1<status &= ~BPM_AMPL_TIMEDOUT; bpmGainRatiosOK[chnl][GAIN_GRNOVERRED] &= ~BPM_AMPL_TIMEDOUT; epicsInterruptUnlock(key); bpmRawAmplitudesPut(chnl, a, 0); return 0; } /* trivial 'energy' detection algorithm */ static int padBpmDataCook(PadReply rply, int nsamples) { BpmNumber max[PADRPLY_STRM_NCHANNELS]; BpmNumber acc[PADRPLY_STRM_NCHANNELS]; int i; uint8_t clipped; int chnl = rply->chnl; volatile BpmRawAmplitudes a = ampAlloc(chnl); if (!a) { /* no buffers [???] don't bother working */ errlogPrintf("drvPadUdpComm: cook got no pan [out of buffers]\n"); return -1; } clipped = drvPadDetectEnergy( acc, max, (int16_t*)rply->data, adcMaps[PadDataBpm], nsamples); /* Calibration */ /* gainRatios 0 is GRN/BLU -> BLU has to be multiplied * by GRN/BLU, YLO has to be multiplied by RED/YLO which * is gain ration [1] * * Apply the slope (cached value of corresponding AI record's ASLO) * here - don't factor it into the gain ratios because the AI read * routine applies ASLO... */ acc[BLU] *= bpmGainRatios[chnl][GAIN_GRNOVERBLU] * bpmGainRatioSlopes[chnl][GAIN_GRNOVERBLU]; acc[YLO] *= bpmGainRatios[chnl][GAIN_REDOVERYLO] * bpmGainRatioSlopes[chnl][GAIN_REDOVERYLO]; /* We use an invariant property of 'opposite' strips. * 'Opposite' means the the strips have to be opposite * to each other if the 2D domain of the vacuum chamber * is mapped conformally onto a circle. * * In this case, 1/a + 1/b is approximately * * 2/Q/Ggrn (1+r^2)/(1-r^2) * * which is invariant to a rotation about the origin * * hence: (1/c + 1/d) / (1/a+1/b) = Ggrn/Gred */ { BpmNumber r; if ( !clipped ) { int key; r = (1./acc[RED] + 1./acc[YLO])/(1./acc[GRN]+1./acc[BLU]); key = epicsInterruptLock(); r = IIR128(bpmGainRatios[chnl][GAIN_GRNOVERRED], r); bpmGainRatios[chnl][GAIN_GRNOVERRED] = r; epicsInterruptUnlock(key); } else { r = 0.; } bpmGainRatiosOK[chnl][GAIN_GRNOVERRED] = clipped; if ( r > 0.5 ) { acc[RED]*=r; acc[YLO]*=r; } } i = epicsInterruptLock(); a->grn = acc[0]; a->red = acc[1]; a->blu = acc[2]; a->ylo = acc[3]; a->timeStamp = (TimeStamp)(uint32_t)ntohl(rply->timestampLo); a->status = BPM_AMPL_OK | clipped ; a->tMax[0] = max[0]; a->tMax[1] = max[1]; a->tMax[2] = max[2]; a->tMax[3] = max[3]; bpmUpToDate[PadDataBpm] |= (1<data, adcMaps[kind], nsamples); /* TODO: sanity check on 1st moment */ if ( 0 == (bpmGainRatiosOK[rply->chnl][kind] = clipped) ) { ocalr = bpmGainRatios[rply->chnl][kind]; if ( PadDataCalRed == kind ) calr = acc[GRN]/acc[BLU]; else calr = acc[RED]/acc[YLO]; bpmGainRatios[rply->chnl][kind] = IIR128(ocalr, calr); } key = epicsInterruptLock(); bpmUpToDate[kind] |= (1<chnl); epicsInterruptUnlock(key); return 0; } static void drvPadUdpCommListener(void *arg) { int sd; UdpCommPkt p = 0; PadReply rply; PadDataKind kind; unsigned chan; unsigned nsamples; /* Open a socket for incoming streamed data */ sd = udpCommSocket(PADPROTO_STRM_PORT); if ( sd < 0 ) { epicsPrintf("drvPadUdpCommListener -- unable to create socket: %s\n", strerror(-sd)); return; } while ( 1 ) { /* release old buffer */ padDataFree(p); /* keep sending start command until we receive something */ while ( !( p = udpCommRecv(sd, drvPadUdpCommTimeout)) ) drvPadUdpCommSendStartAll(0); rply = padReplyFind(p); #ifdef __PPC__ { uint32_t tbl; __asm__ __volatile__ ("mftb %0":"=r"(tbl)); tbl -= ntohl(rply->timestampLo); if ( tbl > roundtripMax ) roundtripMax = tbl; /* to read AVG, divide by 16 */ roundtripAvg += (tbl - (roundtripAvg >> 4)); } #endif chan = rply->chnl; nsamples = PADRPLY_STRM_NSAMPLES(ntohs(rply->nBytes)); if ( chan >= MAX_BPM ) { /* drop invalid channels */ errlogPrintf("drvPadUdpCommListener: invalid BPM channel #%i\n", chan); continue; } /* We assume Row-major format */ if ( rply->strm_cmd_flags & PADCMD_STRM_FLAG_CM ) { errlogPrintf("drvPadUdpCommListener: bad data format -- row-major expected\n"); continue; } if ( isbe() != !(rply->strm_cmd_flags & PADCMD_STRM_FLAG_LE) ) { errlogPrintf("drvPadUdpCommListener: bad data endianness\n"); continue; } kind = PADRPLY_STRM_FLAG_TYPE_GET(rply->strm_cmd_flags); if ( drvPadUdpCommDebug & 1 ) { errlogPrintf("STRM: C %2u N %3u K %1u TS: 0x%08"PRIx32" XID: 0x%08"PRIx32"\n", chan, nsamples, kind, ntohl(rply->timestampLo), ntohl(rply->xid)); } /* TODO: find out what kind of cycle this is */ switch ( kind ) { case PadDataBpm: if ( fidHasBeam() ) { padBpmDataCook(rply, nsamples); } else { padBpmDataNoCook(rply); continue; } break; case PadDataCalRed: case PadDataCalGrn: padBpmCalCook(rply, nsamples, kind); break; default: errlogPrintf("drvPadUdpCommListener: bad data kind (0x%x) from channel %i\n", kind, chan); continue; } /* send buffer for waveforms to pick up */ if ( 0 == padDataSave(chan, kind, p) ) p = 0; /* Scan lists only on the beam pulse. Waveforms * listening to the cal pulses will also be on * the same scanlist. */ if ( PadDataBpm == kind ) { scanIoRequest(scanlist[chan]); } } } static BpmNumber cbpm(BpmNumber x, BpmNumber y, BpmNumber fi0, BpmNumber del) { BpmNumber sdel, cdel, xx, r2; r2 = x*x + y*y; if ( del != 0. ) { cdel = cosf(del); sdel = sinf(del); } else { sdel = 1.0; cdel = 1.0; } xx = (1-r2)*sdel / ((1+r2)*cdel - 2 * ( x * cos(fi0) + y * sin(fi0) ) ); return ( del != 0. ? 2*atanf( xx) : xx ) / 2. / PI; } int drvPadUdpCommSimulatePos(unsigned pad, float x, float y, float q, float phi, float psi, float w) { BpmNumber r = hypotf(x,y); int grn, red, blu, ylo, key; if ( pad >= MAX_BPM ) return -1; if ( q > 0.0 ) { if ( r > 1.0 ) { x=x/r; y=y/r; } grn = cbpm(x, y, -phi*RAD , w*PI)*q; red = cbpm(x, y, (-phi+psi)*RAD , w*PI)*q; blu = cbpm(x, y, -phi*RAD+PI , w*PI)*q; ylo = cbpm(x, y, (-phi+psi)*RAD+PI, w*PI)*q; key = epicsInterruptLock(); padSimulateCmd.simbpm[pad].a = htonl(grn); padSimulateCmd.simbpm[pad].b = htonl(red); padSimulateCmd.simbpm[pad].c = htonl(blu); padSimulateCmd.simbpm[pad].d = htonl(ylo); padSimulateCmd.simbpm[pad].type = PADCMD_SIM | PADCMD_QUIET; #if ENABLE_SIMULATOR == 1 padSimulateCmd.simbpm[pad].flags = PADCMD_SIM_FLAG_NOSEND; #endif epicsInterruptUnlock(key); } else { /* Switch simulate mode off */ padSimulateCmd.simbpm[pad].type = PADCMD_NOP | PADCMD_QUIET; } #if ENABLE_SIMULATOR == 1 udpCommSend( drvPadUdpCommSd, (void*)&padSimulateCmd.req, sizeof(padSimulateCmd)); #endif return 0; } static void drvPadUdpCommSimulator(void *arg) { int i, err = 0; #if ENABLE_SIMULATOR > 1 int xid = 0; #endif /* Initialize the simulator command */ padSimulateCmd.req.version = PADPROTO_VERSION1; padSimulateCmd.req.nCmds = MAX_BPM; padSimulateCmd.req.cmdSize = sizeof(padSimulateCmd.simbpm[0]); for ( i=0; i 1 /* TODO: add timestamps */ padSimulateCmd.req.timestampHi = htonl(0); #ifdef __PPC__ {uint32_t tbl; __asm__ __volatile__("mftb %0":"=r"(tbl)); padSimulateCmd.req.timestampLo = htonl(tbl); } #else padSimulateCmd.req.timestampLo = htonl(0); #endif padSimulateCmd.req.xid = htonl(xid++); err = udpCommSend( drvPadUdpCommSd, (void*)&padSimulateCmd.req, sizeof(padSimulateCmd)); #endif for ( j=0; j>=1, i++ ) { if ( t & 1 ) { key = epicsInterruptLock(); if ( PadDataBpm == j ) ampBuffers[i].status = BPM_AMPL_TIMEDOUT; bpmGainRatiosOK[i][j] = BPM_AMPL_TIMEDOUT; epicsInterruptUnlock(key); } } } /* Scan the channels that had any kind of timeout */ for ( i=0; s; s>>=1, i++ ) { if ( s & 1 ) { scanIoRequest(scanlist[i]); } } if ( err < 0 ) { errlogPrintf("drvPadUdpCommSimulator: sending simulator data failed\n"); epicsThreadSleep(10.0); } epicsThreadSleep(drvPadUdpCommStrmTimeout); } } static long padUdpCommInit(void) { int err,i; in_addr_t ipaddr; if ( !drvPadUdpCommPeerIp || INADDR_NONE == (ipaddr = inet_addr(drvPadUdpCommPeerIp)) ) { epicsPrintf("drvPadUdpComm -- invalid or unset peer IP; set drvPadUdpCommPeerIp to a string in 'dot' notation...\n"); return -1; } if ( (drvPadUdpCommSd = udpCommSocket(drvPadUdpCommPort)) < 0 ) { epicsPrintf("drvPadUdpComm -- unable to create socket: %s\n", strerror(-drvPadUdpCommSd)); return -1; } if ( (err=udpCommConnect(drvPadUdpCommSd, ipaddr, drvPadUdpCommPort)) ) { epicsPrintf("drvPadUdpComm -- unable to connect socket: %s\n", strerror(-err)); udpCommClose(drvPadUdpCommSd); drvPadUdpCommSd = -1; return -1; } strmCmdInit(); for ( i=0; idpvt; if ( dpvt->channel >= MAX_BPM ) return -1; *ppvt = scanlist[dpvt->channel]; return 0; } int drvPadUdpCommDpvtInit(DrvPadUdpCommDpvt padUdpCommPart, unsigned channel) { padUdpCommPart->channel = channel; return 0; } long drvPadUdpCommBpmCalc(subRecord *psub) { unsigned c = psub->l; BpmNumber u,v,s1,s2,t,cpsi,spsi,pcmm,uoff,voff,pinc; BpmNumber *prot; int err; if ( c >= MAX_BPM ) { psub->pact=TRUE; errlogPrintf("drvPadUdpComm -- drvPadUdpCommBpmCalc - invalid channel # %i (INPL)\n", c); return -1; } prot = bpmRot[c]; #define PHI (psub->e) #define PSI (psub->f) err = ampBuffers[c].status; if ( err & BPM_AMPL_RNG_MSK(-1) ) { bpmStatus[c] = READ_ALARM; } else if ( err & (BPM_AMPL_OVR_MSK) ) { bpmStatus[c] = HIHI_ALARM; } else if ( err & (BPM_AMPL_UDR_MSK) ) { bpmStatus[c] = LOLO_ALARM; /* clear TMIT for underrange channels */ bpmResults[c][RES_T] = 0.; } else { bpmStatus[c] = 0; } /* Did one of the angles change */ if ( PHI != psub->le || PSI != psub->lf ) { bpmCosPsi[c] = cos(PSI*RAD); bpmSinPsi[c] = sin(PSI*RAD); if ( bpmSinPsi[c] < 0.5 ) { /* Invalid */ bpmStatus[c] = CALC_ALARM; recGblSetSevr(psub, CALC_ALARM, INVALID_ALARM); psub->udf = TRUE; return 0; } /* uu */ prot[ROT_UU] = sin((PSI-PHI)*RAD)/bpmSinPsi[c]; prot[ROT_UV] = sin(PHI*RAD) /bpmSinPsi[c]; prot[ROT_VU] = -cos((PSI-PHI)*RAD)/bpmSinPsi[c]; prot[ROT_VV] = cos(PHI*RAD) /bpmSinPsi[c]; psub->le = PHI; psub->lf = PSI; } if ( (err=bpmStatus[c]) ) { recGblSetSevr(psub, err, INVALID_ALARM); psub->udf = TRUE; return 0; } cpsi = bpmCosPsi[c]; spsi = bpmSinPsi[c]; /* Calculate differences over sums */ s1 = (psub->a + psub->c); s2 = (psub->b + psub->d); u = (psub->a - psub->c)/s1/2.; v = (psub->b - psub->d)/s2/2.; pcmm = psub->g; uoff = psub->h; voff = psub->i; /* Turns out that 1 / ( 1/(a+c) + 1/(b+d) ) * is 4th order in r -> better than a+b+c+d. t = s1*s2/(s1+s2); * However: the simple formula is only correct if * the strips are Pi/2 apart. For (opposite) strips * with other separation angles, the expression: * * 1/tmit = 1/(g+b) + 1/(r+y) + 4 cos(psi) u v (1/g+1/b+1/r+1/y) * * is invariant to rotation about the origin (pure 'R' dependency) * * However: it is easier to just remove the 'R' dependency from * the 'second order' formula 4/tmit = (1/g+1/b+1/r+1/y) * */ /* they ask for pincushion correction ? */ if ( psub->k != 0. ) { BpmNumber r2 = (u*u+v*v-2*u*v*cpsi)/(spsi*spsi); /* 'pinc' -> 1+r^2 */ if ( r2 < 1.0E-6 ) { pinc = 1.0 + r2; } else { pinc = (0.5 - sqrtf(0.25 - r2))/r2; } t = 4./(1./psub->a+1./psub->b+1./psub->c+1./psub->d)*pinc/(2.0-pinc); } else { pinc = 1.0; /* use simple formula */ t = s1*s2/(s1+s2); } u *= pinc; v *= pinc; bpmResults[c][RES_U] = u; bpmResults[c][RES_V] = v; bpmResults[c][RES_C] = pinc; bpmResults[c][RES_T] = t; u = u*pcmm+uoff; v = v*pcmm+voff; /* Scale + Rotate */ bpmResults[c][RES_X] = prot[ROT_UU]*u + prot[ROT_UV]*v; bpmResults[c][RES_Y] = prot[ROT_VU]*u + prot[ROT_VV]*v; return 0; } epicsRegisterFunction(drvPadUdpCommBpmCalc); long drvPadUdpComm_read_raw_ai_stripl(aiRecord *pai) { unsigned c = pai->inp.value.vmeio.card; unsigned s = pai->inp.value.vmeio.signal; TimeStamp ts; uint32_t st = 0; uint32_t umsk = 0, omsk = 0; int err = 0; if ( c >= MAX_BPM ) { pai->pact = TRUE; errlogPrintf("drvPadUdpComm -- read_raw_ai_strip - invalid channel # %i\n", c); return -1; } if ( s < PADRPLY_STRM_NCHANNELS * 2 ) { /* They want to read stripline signals */ int key = epicsInterruptLock(); /* get cached copies */ st = ampBuffers[c].status; pai->val = ((BpmNumber*)&Buffers[c].grn)[s]; ts = ampBuffers[c].timeStamp; epicsInterruptUnlock(key); omsk = BPM_AMPL_OVR_GRN << s; umsk = BPM_AMPL_UDR_GRN << s; } else if ( (s-=PADRPLY_STRM_NCHANNELS * 2) < NumberOf(bpmGainRatios[0]) ) { /* Push ASLO into cache */ bpmGainRatioSlopes[c][s] = pai->aslo == 0. ? 1. : pai->aslo; /* Supply them with the value */ pai->val = bpmGainRatios[c][s]; st = bpmGainRatiosOK[c][s]; /* filter status bits depending on cal. mode */ switch ( s ) { default: case GAIN_GRNOVERRED: umsk = BPM_AMPL_UDR_MSK; omsk = BPM_AMPL_OVR_MSK; break; case GAIN_GRNOVERBLU: umsk = BPM_AMPL_UDR_GRN | BPM_AMPL_UDR_BLU; omsk = BPM_AMPL_OVR_GRN | BPM_AMPL_OVR_BLU; break; case GAIN_REDOVERYLO: umsk = BPM_AMPL_UDR_RED | BPM_AMPL_UDR_YLO; omsk = BPM_AMPL_OVR_RED | BPM_AMPL_OVR_YLO; break; } } else if ( (s-=NumberOf(bpmGainRatios[0])) < NumberOf(bpmResults[0]) ) { pai->val = bpmResults[c][s]; err = bpmStatus[c]; #ifdef __PPC__ if ( 5 == s ) { uint32_t tbl; __asm__ __volatile__ ("mftb %0":"=r"(tbl)); tbl -= ampBuffers[c].timeStamp; if ( tbl > totTimeMax ) totTimeMax = tbl; /* to read AVG, divide by 16 */ totTimeAvg += (tbl - (totTimeAvg >> 4)); } #endif } else { pai->pact = TRUE; errlogPrintf("drvPadUdpComm -- read_raw_ai_strip - invalid signal # %i\n", pai->inp.value.vmeio.signal); return -1; } /* map status bits into alarm */ if ( st ) { if ( st & omsk ) { err = HIHI_ALARM; } else if ( st & umsk ) { err = LOLO_ALARM; } else { err = READ_ALARM; } } if ( err ) { recGblSetSevr(pai, err, INVALID_ALARM); pai->udf = TRUE; } else { /* Linear transformation just with ASLO/AOFF */ if ( pai->aslo ) pai->val *= pai->aslo; pai->val += pai->aoff; pai->udf = isnan(pai->val); } return 2; } static struct { long number; DRVSUPFUN report; DRVSUPFUN init; } drvPadUdpComm = { 2, padUdpCommReport, padUdpCommInit }; epicsExportAddress(drvet,drvPadUdpComm); static const struct iocshArg arg1 = { "peer ", /* iocshArgPersistentString is broken (3.14.8) - * it doesn't check for an empty string before * duplicating :-( */ iocshArgString }; static const struct iocshArg *bloatp[] = { &arg1, 0 }; struct iocshFuncDef drvPadUdpCommSetupDesc = { "drvPadUdpCommSetup", 1, bloatp }; void drvPadUdpCommSetup(const char *arg) { char *col, *str; if ( !(str=strdup(arg)) ) { epicsPrintf("drvPadUdpCommSetup: not enough memory for strdup\n"); return; } if ( (col = strchr(str, ':')) ) *col++=0; if ( INADDR_NONE == inet_addr(str) ) { epicsPrintf("drvPadUdpCommSetup: invalid IP address '%s'\n", str); } else { drvPadUdpCommPeerIp = str; } if ( col && 1 != sscanf(col, "%i", &drvPadUdpCommPort) ) { epicsPrintf("drvPadUdpCommSetup: invalid port number: '%s'\n", col); drvPadUdpCommPort = PADPROTO_PORT; } if ( 0 == drvPadUdpCommPort ) drvPadUdpCommPort = PADPROTO_PORT; /* Register the 'in use' mask with devBusMapped */ devBusMappedRegister("bpmRaw", &Buffers); } void drvPadUdpCommSetupFunc(const iocshArgBuf *args) { if ( !args[0].sval ) { epicsPrintf("usage: drvPadUdpCommSetup(\"peer_ip:port\")\n"); return; } drvPadUdpCommSetup(args[0].sval); } static void drvPadUdpCommRegistrar(void) { iocshRegister(&drvPadUdpCommSetupDesc, drvPadUdpCommSetupFunc); } epicsExportRegistrar(drvPadUdpCommRegistrar);