/* $Id: drvBpmCavity.c,v 1.26 2016/06/02 08:42:03 strauman Exp $ */ #define _ISOC99_SOURCE #undef __STRICT_ANSI__ #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #ifndef NAN #define NAN (0./0.) #endif #ifndef PI #define PI 3.1415926535897932385 #endif #define RAD ((PI)/180.0) #define CMULT(y,a,b) do { \ float r__ = a##_re * b##_re - a##_im * b##_im ; \ float i__ = a##_re * b##_im + a##_im * b##_re ; \ y##_re = r__; y##_im = i__; \ } while (0) #define adcRMap(c) (3-(c)) /* VME digitizer has order reversed */ /* These indices must match the corresponding record's VME 'signal' (S) number */ #define REF 0 #define U_RE 1 #define V_RE 2 #define TDEL 4 #define U_IM 5 #define V_IM 6 #define PDEL 7 /* Note: for now, we don't flag underrange/overrange status on this one */ #define NUM_RAWPARMS BPM_NUM_VALS /* one unused for now; MUST be equal to BPM_NUM_VALS */ typedef struct CavDiagParmsRec_ { TimeStamp timeStamp; float vals[NUM_RAWPARMS]; unsigned status; } CavDiagParmsRec, *CavDiagParms; #define OVR_RAW(i) (1<<(i)) #define OVR_RAW_MSK ((1<out.type ) { epicsPrintf("phase_init_ao(%s): invalid OUT link type; must be VME_IO\n", pao->name); pao->pact = 1; return -1; } chnl = pao->out.value.vmeio.card; kind = pao->out.value.vmeio.signal; if ( chnl >= MAX_BPM || kind >= 2 ) { epicsPrintf("phase_init_ao(%s): OUT link card or signal # too big (>= #C%u S%u)\n", pao->name, MAX_BPM, 2); pao->pact = 1; return -1; } if ( (dpvt = &cavPhases[chnl][kind])->pao ) { epicsPrintf("phase_init_ao(%s): OUT link of record %s already registered here\n", pao->name, dpvt->pao->name); pao->pact = 1; return -1; } pao->dpvt = dpvt; dpvt->pao = pao; dpvt->cfi = cosf(pao->val*RAD); dpvt->sfi = sinf(pao->val*RAD); dpvt->N = N_PHI_SHOTS; return 2; /* no convert */ } static long phase_write_ao(aoRecord *pao) { CavPhaseAoDpvt dpvt = pao->dpvt; int key; float c,s; int drvPosted; int valOOR; if ( ! (valOOR = (pao->val > 360. || pao->val < -360.)) ) { c = cosf(pao->val*RAD); s = sinf(pao->val*RAD); } /* Is this an update requested by the driver task * or are we pushing out a value put in by the user? */ key = epicsInterruptLock(); if ( (drvPosted = dpvt->drvPosted) ) { /* requested by record -- it is possible * that we get here when the driver + user * posted simultaneously; in this case the * driver wins which is unfortunate but * it is very easy to implement and the race * condition is extremely unlikely */ dpvt->drvPosted = 0; c = dpvt->cfi; s = dpvt->sfi; } else { /* requested by user */ if ( valOOR ) { /* value out-of-range; they want to start the * auto-algorithm */ dpvt->N = N_PHI_SHOTS; } else { dpvt->N = 0; /* stop auto-algorithm */ dpvt->cfi = c; dpvt->sfi = s; } } epicsInterruptUnlock(key); if ( drvPosted ) { pao->val = atan2f(s,c)/RAD; } return 0; } struct { long number; DEVSUPFUN report; DEVSUPFUN init; DEVSUPFUN init_record; DEVSUPFUN get_ioint_info; DEVSUPFUN write_ao; DEVSUPFUN special_linconv; }devAoCavPhase={ 6, 0, 0, phase_init_ao, 0, phase_write_ao, 0}; epicsExportAddress(dset,devAoCavPhase); static void computePhase(CavPhaseAoDpvt p, float rr, float ii) { int key; float p_re, p_im, A; /* auto-compute */ #if N_PHI_SHOTS > 1 #error "fit to straight line not implemented yet" #endif A = hypotf(rr,ii); p_re = rr/A; p_im = -ii/A; key = epicsInterruptLock(); if ( p->N > 0 ) { p->N--; p->cfi = p_re; p->sfi = p_im; p->drvPosted = 1; } epicsInterruptUnlock(key); if ( p->pao ) scanOnce((dbCommon*)p->pao); } static int computeFilter(BpmCavFilter f, float *Hre, float *Him, int nsamples) { int i; double fc, bw, max, re, im, A2; /* allocate space for coefficients */ if ( bpmCavCoeffsAlloc(&f->coeffs) ) { return -1; } /* calculate fc and bw (ignoring DC component) */ for ( fc=bw=max=0., i=1; i max ) max = A2; } /* NOTE: We ignore the Fourier-coefficient at fs/2 */ fc = fc/bw/(double)nsamples; bw = bw/max/(double)nsamples; /* Update the filter parameters */ if ( NO_FC(f->parms.fc) ) f->parms.fc = fc; /* Use twice the measured signal bandwidth for the filter * (arbitrary headroom) */ if ( NO_BW(f->parms.bw) ) f->parms.bw = 2.0*bw; /* Generate filter coefficients */ bpmCavGenerateFilter(f); return 0; } static int dataNoCook(PadReply rply) { int chnl = rply->chnl; volatile BpmRawAmplitudes a = bpmRawAmplitudesAlloc(chnl); int key; /* just pet up-to-date status */ key = epicsInterruptLock(); a->status &= ~BPM_AMPL_TIMEDOUT; cavDiagParms[chnl].status &= ~TMO_RAW; epicsInterruptUnlock(key); bpmRawAmplitudesPut(chnl, a, 0); return -1; } static int cavityCook(PadReply rply, int nsamples, int layout_cm, int kind, void *closure) { TimeStamp ts; int rval = PAD_UDPCOMM_COOK_STAT_NOSCAN_NOPOST; if ( !layout_cm ) { epicsPrintf("drvBpmCavity: wrong data layout; can only handle col-major for now\n"); return rval; } switch (kind) { default: /* unknown 'kind' -- may indicate there is no beam */ dataNoCook(rply); /* return positive value to flag this BPM as 'updated' */ return PAD_UDPCOMM_COOK_STAT_NOSCAN; case PadDataBpm: { unsigned chnl = rply->chnl; int nvecs = nsamples / (VECTSZ/sizeof(float)); int nFvecs = nvecs/2; /* dimension of spectra is half of nsamples*/ int updFlt = 0; BpmCavFilter filt; int stat_msk, diag_stat_msk, key; WavBuf fresp; double delPhi, delT, rms, tmp; float *pHre, *pHim; float raw_rms[4]; volatile BpmRawAmplitudes a; double u_re, u_im, v_re, v_im; float p_re, p_im; CavPhaseAoDpvt p; if ( chnl >= MAX_BPM ) { break; } if ( ! fidHasBeam() ) { dataNoCook(rply); /* return positive value to flag this BPM as 'updated' */ rval = PAD_UDPCOMM_COOK_STAT_NOSCAN; break; } filt = bpmCavFilterBank[chnl]; p = cavPhases[chnl]; if ( 0 != (((uintptr_t)rply->data) & (VECTALIGN-1)) ) { errlogPrintf("drvBpmCavity: Fatal Error: Packet data not vector-aligned! (%p)\n", rply->data); errlogFlush(); abort(); } /* * convert short-> float and check overflow bit; write * data in temp-buffer attached to 'closure' */ stat_msk = vec_cvtf_4arr(closure, (vShort*)rply->data, nsamples, raw_rms); if ( DIGI_NO_OVFL_SUP(chnl) ) stat_msk = 0; diag_stat_msk = stat_msk; /* FFT from temp-buffer into a wavBuf */ fresp = bpmCavFFT(closure, 2); if ( !fresp ) { break; } pHre = fresp->d_re; pHim = fresp->d_im; bpmCavFilterBankLock(); if ( 0 == filt[CAV_REF].coeffs.nsamples ) { /* No filter coefficients set; compute */ if ( computeFilter( &filt[CAV_REF], pHre + CAV_REF*fresp->stride, pHim + CAV_REF*fresp->stride, nsamples ) ) { bpmCavFilterBankUnlock(); u_re = u_im = v_re = v_im = rms = delT = delPhi = NAN; stat_msk = BPM_AMPL_INVALID; goto bail; } updFlt = 1; } /* We could be smarter when computing the * filters -- if X/Y signal level is too low * (centered beam) then we could hold off * the calculation until we see some signal. * However, this case is rare - especially * during commissioning where the filter * auto-update is intended to help... */ if ( 0 == filt[CAV_U].coeffs.nsamples ) { /* No filter coefficients set; compute */ if ( computeFilter( &filt[CAV_U], pHre + CAV_U*fresp->stride, pHim + CAV_U*fresp->stride, nsamples ) ) { bpmCavFilterBankUnlock(); u_re = u_im = v_re = v_im = rms = delT = delPhi = NAN; stat_msk = BPM_AMPL_INVALID; goto bail; } updFlt = 1; } if ( 0 == filt[CAV_V].coeffs.nsamples ) { /* No filter coefficients set; compute */ if ( computeFilter( &filt[CAV_V], pHre + CAV_V*fresp->stride, pHim + CAV_V*fresp->stride, nsamples ) ) { bpmCavFilterBankUnlock(); u_re = u_im = v_re = v_im = rms = delT = delPhi = NAN; stat_msk = BPM_AMPL_INVALID; goto bail; } updFlt = 1; } vec_tadj( &delPhi, &delT, &rms, (vFloat*)filt[CAV_REF].coeffs.Hre, (vFloat*)filt[CAV_REF].coeffs.Him, (vFloat*)(pHre+CAV_REF*fresp->stride), (vFloat*)(pHim+CAV_REF*fresp->stride), nFvecs ); /* Flag ref. signal under-range if we have signal energy * less than 64 * noise contribution. * If we have noise of ~2.5 bits then the = * rms is sqrt( 2^5 64 * nsamples ) = 2^(0.5*(5+6+7)) */ #if BPM_CAV_NSAMPLES != 128 #error "Need to fix hardcoded limit (approx. 2^(0.5*(11+BPM_CAV_NSAMPLES)))" #endif if ( rms < 128. ) stat_msk |= BPM_AMPL_UDR_R; if ( raw_rms[REF] < 128. ) { diag_stat_msk |= UDR_RAW_R; } else { raw_rms[CAV_U]/=raw_rms[CAV_REF]; raw_rms[CAV_V]/=raw_rms[CAV_REF]; } vec_filt( &u_re, &u_im, +delT, (vFloat*)filt[CAV_U].coeffs.Hre, (vFloat*)filt[CAV_U].coeffs.Him, (vFloat*)(pHre+CAV_U*fresp->stride), (vFloat*)(pHim+CAV_U*fresp->stride), nFvecs ); vec_filt( &v_re, &v_im, +delT, (vFloat*)filt[CAV_V].coeffs.Hre, (vFloat*)filt[CAV_V].coeffs.Him, (vFloat*)(pHre+CAV_V*fresp->stride), (vFloat*)(pHim+CAV_V*fresp->stride), nFvecs ); bpmCavFilterBankUnlock(); p_re = cosf((float)delPhi); p_im = +sinf((float)delPhi); CMULT(u,u,p); CMULT(v,v,p); key = epicsInterruptLock(); if ( p[PHASE_U].N ) { epicsInterruptUnlock(key); computePhase(&p[PHASE_U], u_re, u_im); key = epicsInterruptLock(); } p_re = p[PHASE_U].cfi; p_im = p[PHASE_U].sfi; epicsInterruptUnlock(key); CMULT(u,u,p); key = epicsInterruptLock(); if ( p[PHASE_V].N ) { epicsInterruptUnlock(key); computePhase(&p[PHASE_V], v_re, v_im); key = epicsInterruptLock(); } p_re = p[PHASE_V].cfi; p_im = p[PHASE_V].sfi; epicsInterruptUnlock(key); CMULT(v,v,p); /* scale u_re/u_im with 1/nsamples so that * reading doesn't change if nsamples is ever * changed. * However, multiply back by 128 so that the * original scale is maintained (the division * by nsamples was introduced after the software * went into production -- we don't want the * users to have to change their calibration * right now...) */ tmp = 128./((double)nsamples)/rms; u_re*= tmp; u_im*= tmp; v_re*= tmp; v_im*= tmp; bail: ts.nsec = ntohl(rply->timestampLo); ts.secPastEpoch = ntohl(rply->timestampHi); drvBpmCalcPos(chnl, u_re, v_re, rms, BPM_AMPL_OK | stat_msk, 1.0, &ts); a = bpmRawAmplitudesAlloc(chnl); key = epicsInterruptLock(); a->vals[U_RE] = u_re; a->vals[U_IM] = u_im; a->vals[V_RE] = v_re; a->vals[V_IM] = v_im; a->vals[REF] = rms; a->vals[TDEL] = delT; a->vals[PDEL] = delPhi; a->timeStamp = ts; a->status = BPM_AMPL_OK | stat_msk; cavDiagParms[chnl].timeStamp = a->timeStamp; cavDiagParms[chnl].vals[CAV_REF] = raw_rms[CAV_REF]; cavDiagParms[chnl].vals[CAV_U ] = raw_rms[CAV_U]; cavDiagParms[chnl].vals[CAV_V ] = raw_rms[CAV_V]; cavDiagParms[chnl].status = diag_stat_msk; epicsInterruptUnlock(key); bpmRawAmplitudesPut(chnl, a, 0); if ( fresp ) { wavBufPost(chnl, WB_KIND_F, fresp); /* post buffer to cplx-envelope computation only * if there were no errors. In particular, * we must not post if there are no filters. */ if ( BPM_AMPL_OK == stat_msk ) wavBufPost(chnl, WB_KIND_E, fresp); else wavBufFree(fresp); } /* notify waveform records etc. that we * modified the filter... */ if ( updFlt ) bpmCavLLFilterPostJob(chnl); } rval = PAD_UDPCOMM_COOK_STAT_OK; break; } DIGI_OVFL_SUP_TEST( rply ); return rval; } static void cavityWatchdog(int channel, int kind, void *closure) { int key; if ( channel < 0 || channel >= MAX_BPM ) return; if ( kind < 0 || kind >= NUM_DATA_KINDS ) return; bpmWatchdog(channel, kind, closure); key = epicsInterruptLock(); if ( PadDataBpm == kind ) { cavDiagParms[channel].status = TMO_RAW; } epicsInterruptUnlock(key); } static int cavityInit(DrvPadUdpCommCallbacks cbs) { int i; #if defined(__PPC__) || defined(__powerpc__) || defined(__POWERPC__) vec_task_enable(); altivec_nonC9xmode(); #endif bpmCavFilterInit(); for ( i=0; icookClosure = bpmCavFFTBufAlloc()) ? 0 : -1; } static int cavityGetPrefs(DrvPadUdpCommPrefs p) { p->nsamples = BPM_CAV_NSAMPLES; /* number of samples must not be changed at run-time */ p->nsamples_dynamic = 0; /* we need col-major layout */ p->col_major = 1; /* no d32 */ p->d32 = 0; p->nchannels_dynamic = 0; return 0; } static float pos_proj(float x, float y, float ang) { return cosf(ang) * x + sinf(ang) * y; } static int cavitySimPos(int32_t *vals_p, float x, float y, float q, float phi, float psi, void *parms) { vals_p[adcRMap(CAV_REF)] = q; vals_p[adcRMap(CAV_U) ] = q * pos_proj(x, y, (-phi )*RAD); vals_p[adcRMap(CAV_V) ] = q * pos_proj(x, y, (-phi+psi)*RAD); vals_p[adcRMap(CAV_SPR)] = 0; return 0; } static DrvPadUdpCommCallbacksRec cavityCb = { init: cavityInit, cookClosure: 0, cook: cavityCook, watchdogClosure: 0, watchdog: cavityWatchdog, watchKinds: (1<val = cavDiagParms[c].vals[s]; st = cavDiagParms[c].status; /* ts = cavDiagParms[c].timeStamp; */ epicsInterruptUnlock(key); omsk = OVR_RAW(REF) | OVR_RAW( (s % NUM_RAWPARMS) ); umsk = UDR_RAW(REF) | UDR_RAW( (s % NUM_RAWPARMS) ); err = drvBpm_map_status(st, omsk, umsk); } else { return -1; } return err; } long drvBpmCavity_read_raw_ai(aiRecord *pai) { return drvBpm_read_raw_ai_helper(pai, cav_cb); } static long bpmCavityReport(int level) { epicsPrintf("Cavity BPM Support\n"); return 0; } long bpmCavityInit(void) { return 0; } static struct { long number; DRVSUPFUN report; DRVSUPFUN init; } drvBpmCavity = { 2, bpmCavityReport, bpmCavityInit }; epicsExportAddress(drvet,drvBpmCavity); static void drvBpmCavityRegistrar(void) { registryAdd( (void*)drvPadUdpCommRegistryId, "drvBpmCavityCallbacks", &cavityCb ); } epicsExportRegistrar(drvBpmCavityRegistrar);