/* $Id: BLDMCast.c,v 1.51 2011/05/25 23:48:20 lpiccoli Exp $ */ #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include "epicsExport.h" #include "epicsEvent.h" #include "epicsMutex.h" #include "epicsThread.h" #include "cadef.h" #include "dbScan.h" #include "drvSup.h" #include "alarm.h" #include "cantProceed.h" #include "errlog.h" #include "epicsExit.h" #include "evrTime.h" #include "evrPattern.h" #include "fcom_api.h" #include "fcomUtil.h" #include "udpComm.h" #include "fcomLclsBpm.h" #include "fcomLclsBlen.h" #include /* This is MVME6100/5500 only */ #include "BLDMCast.h" #define BLD_DRV_VERSION "BLD driver $Revision: 1.51 $/$Name: $" #define CA_PRIORITY CA_PRIORITY_MAX /* Highest CA priority */ #define TASK_PRIORITY epicsThreadPriorityMax /* Highest EPICS thread priority */ #define DEFAULT_CA_TIMEOUT 0.04 /* Default CA timeout, for 30Hz */ #define DEFAULT_EVR_TIMEOUT 0.2 /* Default EVR event timeout, for 30Hz */ #define MCAST_TTL 8 /* T.S: I doubt that ca_create_subscription works any different. * ca_add_array_event is just a macro mapping to the * ca_add_masked_array_event() wrapper which calls * ca_create_subscription with the DBE_VALUE | DBE_ALARM mask ... */ #define BSPTIMER 0 /* Timer instance -- use first timer */ /* We monitor static PVs and update their value upon modification */ enum STATICPVSINDEX { DSPR1=0, DSPR2, E0BDES, FMTRX };/* the definition here must match the PV definition below */ /* We use caget to read pulse by pulse PVs when EVR triggers */ enum PULSEPVSINDEX { BMCHARGE=0, BMENERGY1X, BMENERGY2X, BMPOSITION1X, BMPOSITION2X, BMPOSITION3X, BMPOSITION4X, BMBUNCHLEN, BC2STATE, };/* the definition here must match the PV definition below, the order is critical as well */ /** Former PVAVAILMASK enum */ #define AVAIL_DSPR1 0x0001 #define AVAIL_DSPR2 0x0002 #define AVAIL_E0BDES 0x0004 #define AVAIL_FMTRX 0x0008 #define AVAIL_BMCHARGE 0x0010 #define AVAIL_BMENERGY1X 0x0020 #define AVAIL_BMENERGY2X 0x0040 #define AVAIL_BMPOSITION1X 0x0080 #define AVAIL_BMPOSITION2X 0x0100 #define AVAIL_BMPOSITION3X 0x0200 #define AVAIL_BMPOSITION4X 0x0400 #define AVAIL_BMPOSITION1Y 0x0800 #define AVAIL_BMPOSITION2Y 0x1000 #define AVAIL_BMPOSITION3Y 0x2000 #define AVAIL_BMPOSITION4Y 0x4000 #define AVAIL_BMBUNCHLEN 0x8000 #define AVAIL_BC2STATE 0x10000 /* Structure representing one PV (= channel) */ typedef struct BLDPV { const char * name; unsigned long nElems; /* type is always DOUBLE */ long availMask; chid pvChId; struct dbr_time_double * pTD; /* No need for eventId, never cancel subscription *\ evid pvEvId; \* No need for eventId, never cancel subscription */ /* No need to hold type, always double *\ long dbfType; long dbrType; \* No need to hold type, always double */ } BLDPV; typedef struct BLDBLOB { const char * name; FcomBlobRef blob; long aMsk; long validCounter; long unmatchedTSCount; long fcomGetErrs; long nullBlobCount; } BLDBLOB; /* [E0BDES] = {"BEND:LTU0:125:BDES", 1, AVAIL_E0BDES, NULL, NULL}, / * Energy in MeV */ BLDPV bldStaticPVs[]= { [DSPR1] = {"BLD:SYS0:500:DSPR1", 1, AVAIL_DSPR1, NULL, NULL}, /* For Energy */ [DSPR2] = {"BLD:SYS0:500:DSPR2", 1, AVAIL_DSPR2, NULL, NULL}, /* For Energy */ [E0BDES] = {"BLD:SYS0:500:DSPR1", 1, AVAIL_E0BDES, NULL, NULL}, /* Energy in MeV */ [FMTRX] = {"BLD:SYS0:500:FMTRX", 32, AVAIL_FMTRX, NULL, NULL} /* For Position */ }; #define N_STATIC_PVS (sizeof(bldStaticPVs)/sizeof(bldStaticPVs[0])) BLDBLOB bldPulseBlobs[] = { /** * Charge (nC) = BPMS:IN20:221:TMIT (Nel) * 1.602e-10 (nC/Nel) // [Nel = number electrons] */ [BMCHARGE] = { name: "BPMS:IN20:221:TMIT", blob: 0, aMsk: AVAIL_BMCHARGE, validCounter: 0, unmatchedTSCount: 0, fcomGetErrs: 0, nullBlobCount: 0}, /* Charge in Nel, 1.602e-10 nC per Nel*/ /** * Energy at L3 (MeV) = [ (BPM1x(MeV) + BPM2x(MeV))/2 ]*E0(MeV) + E0 (MeV) * where E0 is the final desired energy at the LTU (the magnet setting BEND:LTU0:125:BDES*1000) * dspr1,2 = Dx for the chosen dispersion BPMs (from design model database twiss parameters) (we can store these in BLD IOC PVs) * BPM1x = [BPMS:LTU1:250:X(mm)/(dspr1(m/Mev)*1000(mm/m))] * BPM2x = [BPMS:LTU1:450:X(mm)/(dspr2(m/Mev)*1000(mm/m))] */ [BMENERGY1X] = { name: "BPMS:LTU1:250:X", blob: 0, aMsk: AVAIL_BMENERGY1X, validCounter: 0, unmatchedTSCount: 0, fcomGetErrs: 0, nullBlobCount: 0}, /* Energy in MeV */ [BMENERGY2X] = { name: "BPMS:LTU1:450:X", blob: 0, aMsk: AVAIL_BMENERGY2X, validCounter: 0, unmatchedTSCount: 0, fcomGetErrs: 0, nullBlobCount: 0}, /* Energy in MeV */ /** * Position X, Y, Angle X, Y at LTU: * Using the LTU Feedback BPMs: BPMS:LTU1:720,730,740,750 * The best estimate calculation is a matrix multiply for the result vector p: * * [xpos(mm) [bpm1x //= BPMS:LTU1:720:X (mm) * p= ypos(mm) = [F]* bpm2x //= BPMS:LTU1:730:X * xang(mrad) bpm3x //= BPMS:LTU1:740:X * yang(mrad)] bpm4x //= BPMS:LTU1:750:X * bpm1y //= BPMS:LTU1:720:Y * bpm2y //= BPMS:LTU1:730:Y * bpm3y //= BPMS:LTU1:740:Y * bpm4y] //= BPMS:LTU1:750:Y * * Where F is the 4x8 precalculated fit matrix. F is approx. pinv(A), for Least Squares fit p = pinv(A)*x * * A = [R11 R12 R13 R14; //rmat elements for bpm1x * R11 R12 R13 R14; //rmat elements for bpm2x * R11 R12 R13 R14; //rmat elements for bpm3x * R11 R12 R13 R14; //rmat elements for bpm4x * R31 R32 R33 R34; //rmat elements for bpm1y * R31 R32 R33 R34; //rmat elements for bpm2y * R31 R32 R33 R34; //rmat elements for bpm3y * R31 R32 R33 R34] //rmat elements for bpm4y */ [BMPOSITION1X] = { name: "BPMS:LTU1:720:X", blob: 0, aMsk: AVAIL_BMPOSITION1X | AVAIL_BMPOSITION1Y, validCounter: 0, unmatchedTSCount: 0, fcomGetErrs: 0, nullBlobCount: 0}, /* Position in mm/mrad */ [BMPOSITION2X] = { name: "BPMS:LTU1:730:X", blob: 0, aMsk: AVAIL_BMPOSITION2X | AVAIL_BMPOSITION2Y, validCounter: 0, unmatchedTSCount: 0, fcomGetErrs: 0, nullBlobCount: 0}, /* Position in mm/mrad */ [BMPOSITION3X] = { name: "BPMS:LTU1:740:X", blob: 0, aMsk: AVAIL_BMPOSITION3X | AVAIL_BMPOSITION3Y, validCounter: 0, unmatchedTSCount: 0, fcomGetErrs: 0, nullBlobCount: 0}, /* Position in mm/mrad */ [BMPOSITION4X] = { name: "BPMS:LTU1:750:X", blob: 0, aMsk: AVAIL_BMPOSITION4X | AVAIL_BMPOSITION4Y, validCounter: 0, unmatchedTSCount: 0, fcomGetErrs: 0, nullBlobCount: 0}, /* Position in mm/mrad */ [BMBUNCHLEN] = { name: "BLEN:LI24:886:BIMAX", blob: 0, aMsk: AVAIL_BMBUNCHLEN, validCounter: 0, unmatchedTSCount: 0, fcomGetErrs: 0, nullBlobCount: 0}, /* Bunch Length in Amps */ [BC2STATE] = { name: "FBCK:FB03:TR04:STATES", blob: 0, aMsk: AVAIL_BC2STATE, validCounter: 0, unmatchedTSCount: 0, fcomGetErrs: 0, nullBlobCount: 0}, /* Longitudinal Feedback States, which includes BC2 Energy */ /* Actual Longitudinal location */ /* [BC2STATE] = { name: "FBCK:FB04:LG01:STATES", blob: 0, aMsk: AVAIL_BC2STATE, validCounter: 0, unmatchedTSCount: 0, fcomGetErrs: 0, nullBlobCount: 0}, *//* Longitudinal Feedback States, which includes BC2 Energy */ }; #define N_PULSE_BLOBS (sizeof(bldPulseBlobs)/sizeof(bldPulseBlobs[0])) FcomID bldPulseID[N_PULSE_BLOBS] = { 0 }; FcomBlobSetRef bldBlobSet = 0; static epicsInt32 bldUseFcomSet = 0; static long dataAvailable = 0; int BLD_MCAST_ENABLE = 1; epicsExportAddress(int, BLD_MCAST_ENABLE); int BLD_MCAST_DEBUG = 0; epicsExportAddress(int, BLD_MCAST_DEBUG); static uint32_t timer_delay_clicks = 10 /* just some value; true thing is written by EPICS record */; static uint32_t timer_delay_ms = 4 /* just some value; true thing is written by EPICS record */; int DELAY_FOR_CA = 0; /* in seconds */ epicsExportAddress(int, DELAY_FOR_CA); /* Share with device support */ volatile int bldAllPVsConnected = FALSE; volatile int bldConnectAbort = FALSE; epicsUInt32 bldInvalidAlarmCount[N_PULSE_BLOBS] = {0}; epicsUInt32 bldUnmatchedTSCount[N_PULSE_BLOBS] = {0}; EBEAMINFO bldEbeamInfo; EBEAMINFO bldEbeamInfoDump; IOSCANPVT bldIoscan; /* Trigger EPICS record */ epicsMutexId bldMutex = NULL; /* Protect bldStaticPVs' values */ epicsUInt32 bldFcomGetErrs[N_PULSE_BLOBS] = {0}; epicsUInt32 bldMcastMsgSent = 0; epicsUInt32 bldMinFcomDelayUs = -1; epicsUInt32 bldAvgFcomDelayUs = 0; epicsUInt32 bldMaxFcomDelayUs = 0; epicsUInt32 bldMaxPostDelayUs = 0; epicsUInt32 bldAvgPostDelayUs = 0; /* Share with device support */ /* Some debug counters */ long validBC2EnergyCounter = 0; /* Some debug counters */ /*==========================================================*/ static in_addr_t mcastIntfIp = 0; static epicsEventId EVRFireEvent = NULL; /* EPICS time has pulse ID in lower bits of nanoseconds; * for measuring high-resolution delays we also need * the real nano- or at least microseconds. */ epicsTimeStamp bldFiducialTime; struct timeval bldFiducialTimeHires; int tsCatch = -1; uint32_t tsMismatch[4]; static epicsUInt32 usSinceFiducial(void) { struct timeval now; gettimeofday( &now, 0 ); if ( now.tv_usec < bldFiducialTimeHires.tv_usec ) { now.tv_usec += 1000000; now.tv_sec--; } now.tv_usec = now.tv_usec - bldFiducialTimeHires.tv_usec; now.tv_usec += now.tv_sec - bldFiducialTimeHires.tv_sec; return (epicsUInt32)now.tv_usec; } static void evr_timer_isr(void *arg); static int BLDMCastTask(void * parg); static void BLDMCastTaskEnd(void * parg); /* This function will be called in st.cmd after iocInit() */ int BLDMCastStart(int enable, const char * NIC) { /* Do we need to use RTEMS task priority to get higher priority? */ BLD_MCAST_ENABLE = enable; if(NIC && NIC[0] != 0) mcastIntfIp = inet_addr(NIC); if(mcastIntfIp == (in_addr_t)(-1)) { errlogPrintf("Illegal MultiCast NIC IP\n"); return -1; } /****** Setup high resolution timer ***********************/ /* you need to setup the timer only once (to connect ISR) */ BSP_timer_setup( BSPTIMER, evr_timer_isr, 0, 0 /* do not reload timer when it expires */); epicsAtExit(BLDMCastTaskEnd, NULL); return (int)(epicsThreadMustCreate("BLDMCast", TASK_PRIORITY, 20480, (EPICSTHREADFUNC)BLDMCastTask, NULL)); } static int pvTimePulseIdMatches(epicsTimeStamp *p_ref, FcomBlobRef p_cmp) { epicsUInt32 idref, idcmp, diff; idref = PULSEID((*p_ref)); idcmp = p_cmp->fc_tsLo & LOWER_17_BIT_MASK; if ( idref == idcmp && idref != PULSEID_INVALID ) { /* Verify that seconds match to less that a few minutes */ diff = abs(p_ref->secPastEpoch - p_cmp->fc_tsHi ); if ( diff < 4*60 ) return 0; } return -1; } /* This function will be registered with EVR callback */ void EVRFire(void *use_sets) { epicsTimeStamp time_s; /* get the current pattern data - check for good status */ evrModifier_ta modifier_a; unsigned long patternStatus; /* see evrPattern.h for values */ int status = evrTimeGetFromPipeline(&time_s, evrTimeCurrent, modifier_a, &patternStatus, 0,0,0); /* This is 120Hz. So printf will screw timing */ if(BLD_MCAST_DEBUG >= 4) errlogPrintf("EVR fires (status %i, mod5 0x%08x)\n", status, (unsigned)modifier_a[4]); /* check for LCLS beam and rate-limiting */ if (!status) { if (/*(modifier_a[4] & MOD5_30HZ_MASK)*//*MOD5_HALFHZ_MASK)*//*MOD5_BEAMFULL_MASK)*/ (modifier_a[4] & MOD5_BEAMFULL_MASK) /* 120Hz ---*//* (modifier_a[1] & TIMESLOT1_MASK || modifier_a[1] & TIMESLOT4_MASK)*/ ) {/* ... do beam-sync rate-limited processing here ... */ /* call 'BSP_timer_start()' to set/arm the hardware */ bldFiducialTime = time_s; gettimeofday( &bldFiducialTimeHires, 0 ); /* This is 30Hz. So printf might screw timing */ if(BLD_MCAST_DEBUG >= 3) errlogPrintf("Timer Starts\n"); if ( ! use_sets ) { BSP_timer_start( BSPTIMER, timer_delay_clicks ); } else { epicsEventSignal(EVRFireEvent); } } } else { bldFiducialTime.nsec = PULSEID_INVALID; } return; } static void evr_timer_isr(void *arg) {/* post event/release sema to wakeup worker task here */ if(EVRFireEvent) { epicsEventSignal(EVRFireEvent); } /* This is 30Hz. So printk might screw timing */ if(BLD_MCAST_DEBUG >= 3) { printk("Timer fires\n"); } return; } static void printChIdInfo(chid pvChId, char *message) { errlogPrintf("\n%s\n",message); errlogPrintf("pv: %s type(%d) nelements(%ld) host(%s)", ca_name(pvChId),ca_field_type(pvChId),ca_element_count(pvChId),ca_host_name(pvChId)); errlogPrintf(" read(%d) write(%d) state(%d)\n", ca_read_access(pvChId),ca_write_access(pvChId),ca_state(pvChId)); } static void exceptionCallback(struct exception_handler_args args) { chid pvChId = args.chid; long stat = args.stat; /* Channel access status code*/ const char *channel; static char *noname = "unknown"; channel = (pvChId ? ca_name(pvChId) : noname); if(pvChId) printChIdInfo(pvChId,"exceptionCallback"); errlogPrintf("exceptionCallback stat %s channel %s\n", ca_message(stat),channel); } static void setBits(long *mask, long bits) { *mask |= bits; } static void clearBits(long *mask, long bits) { *mask &= ~bits; } static void eventCallback(struct event_handler_args args) { BLDPV * pPV = args.usr; if(BLD_MCAST_DEBUG >= 2) { errlogPrintf("Event Callback: %s, status %d\n", ca_name(args.chid), args.status); } epicsMutexLock(bldMutex); if (args.status == ECA_NORMAL) { memcpy(pPV->pTD, args.dbr, dbr_size_n(args.type, args.count)); /* We don't care timestamp for bldStaticPVs. As long as it is not invalid, they are ok */ if(pPV->pTD->severity >= INVALID_ALARM) { clearBits(&dataAvailable, pPV->availMask); } else { setBits(&dataAvailable, pPV->availMask); } if(BLD_MCAST_DEBUG >= 2) { errlogPrintf("Event Callback: %s, copy type %ld, elements %ld, bytes %d, severity %d\n", ca_name(args.chid), args.type, args.count, dbr_size_n(args.type, args.count), pPV->pTD->severity); errlogPrintf("Value is %f\n", pPV->pTD->value); } } else { clearBits(&dataAvailable, pPV->availMask); } epicsMutexUnlock(bldMutex); } static int connectCaPv(const char *name, chid *p_chid) { int rtncode; do { rtncode = ECA_NORMAL; /* No need for connectionCallback since we want to wait till connected */ if ( BLD_MCAST_DEBUG >= 1 ) { printf("creating channel..."); fflush(stdout); } SEVCHK(ca_create_channel(name, NULL/*connectionCallback*/, NULL, CA_PRIORITY , p_chid), "ca_create_channel"); if ( BLD_MCAST_DEBUG >= 1 ) { printf(" done\n"); } /* Not very necessary */ /* SEVCHK(ca_replace_access_rights_event(bldStaticPVs[loop].pvChId, accessRightsCallback), "ca_replace_access_rights_event"); */ /* We could do subscription in connetion callback. But in this case, better to enforce all connection */ if ( BLD_MCAST_DEBUG >= 1 ) { printf("pending for IO ..."); fflush(stdout); } rtncode = ca_pend_io(10.0); if ( BLD_MCAST_DEBUG >= 1 ) { printf(" done\n"); } if ( ECA_NORMAL != rtncode ) { ca_clear_channel(*p_chid); *p_chid = 0; if (rtncode == ECA_TIMEOUT) { errlogPrintf("Channel connect timed out: '%s' not found.\n", name); errlogPrintf("Continue to try -- set variable 'bldConnectAbort' to nonzero for aborting within 10s\n"); if ( ! bldConnectAbort ) { continue; } } else { errlogPrintf("ea_pend_io() returned %i\n", rtncode); } return -1; } } while ( ECA_TIMEOUT == rtncode ); return 0; } static int init_pvarray(BLDPV *p_pvs, int n_pvs, int subscribe) { int loop; unsigned long cnt; for(loop=0; loop 0 ) { printf("Delay %d seconds to wait CA ready!\n", DELAY_FOR_CA); for(loop=DELAY_FOR_CA;loop>0;loop--) { printf("\r%d seconds left!\n", loop); epicsThreadSleep(1.0); } printf("\n"); } SEVCHK(ca_context_create(ca_enable_preemptive_callback),"ca_context_create"); SEVCHK(ca_add_exception_event(exceptionCallback,NULL), "ca_add_exception_event"); /* TODO, clean up resource when fail */ /* Monitor static PVs */ if ( init_pvarray( bldStaticPVs, N_STATIC_PVS, 1 /* do subscribe */ ) ) { return -1; /* error message already printed */ } ca_flush_io(); /* ca_pend_event(2.0); */ return 0; } static void BLDMCastInitializeData() { bldEbeamInfo.uMBZ1 = __le32(0); bldEbeamInfo.uMBZ2 = __le32(0); bldEbeamInfo.uLogicalId = __le32(0x06000000); bldEbeamInfo.uPhysicalId = __le32(0); /* bldEbeamInfo.uDataType = __le32(0x1000f);*/ bldEbeamInfo.uDataType = __le32(0x2000f); /** This is the new version with BC2 ENERGY added */ bldEbeamInfo.uExtentSize = __le32(80 + 8); bldEbeamInfo.uLogicalId2 = __le32(0x06000000); bldEbeamInfo.uPhysicalId2= __le32(0); /* bldEbeamInfo.uDataType2 = __le32(0x1000f);*/ bldEbeamInfo.uDataType2 = __le32(0x2000f); /** This is the new version with BC2 ENERGY added */ bldEbeamInfo.uExtentSize2= __le32(80 + 8); } /** * Wait for an event to be received. * * @return 0 if event was received, -1 if there has been a timeout or * another error */ static int BLDMCastTaskWaitEvent() { int status = epicsEventWaitWithTimeout(EVRFireEvent, DEFAULT_EVR_TIMEOUT); if(status != epicsEventWaitOK) { if(status == epicsEventWaitTimeout) { if(BLD_MCAST_DEBUG >= 3) errlogPrintf("Wait EVR timeout, check timing?\n"); } else { errlogPrintf("Wait EVR Error, what happened? Let's sleep 2 seconds.\n"); epicsThreadSleep(2.0); } return -1; } return 0; } /** * Get a blob set from FCOM. * * @param got_mask returns a mask defining which blobs in the set * have data. * @return 0 if blobs can be used (must check the got_mask bits), * or -1 if there is an FCOM time out */ static int BLDMCastTaskFcomGetBlobSet(FcomBlobSetMask *got_mask) { int loop; int status; if ( bldBlobSet ) { status = fcomGetBlobSet( bldBlobSet, got_mask, (1< bldMaxFcomDelayUs ) { bldMaxFcomDelayUs = this_time; } if ( this_time < bldMinFcomDelayUs ) { bldMinFcomDelayUs = this_time; } /* Running average: fn+1 = 127/128 * fn + 1/128 * x = fn - 1/128 fn + 1/128 x */ bldAvgFcomDelayUs += ((int)(- bldAvgFcomDelayUs + this_time)) >> 8; } static void BLDMCastTaskCheckPostDelays() { epicsUInt32 this_time; this_time = usSinceFiducial(); if ( this_time > bldMaxPostDelayUs ) { bldMaxPostDelayUs = this_time; } /* Running average: fn+1 = 127/128 * fn + 1/128 * x = fn - 1/128 fn + 1/128 x */ bldAvgPostDelayUs += ((int) (- bldAvgPostDelayUs + this_time)) >> 8; } /** * This function calls fcomGetBlob() for each blob. The got_mask * parameter indicates whether data has been received. A pointer * to the blob is saved into the 'blob' field. If no new data * has been received the 'blob' field is set to 0. * * @param got_mask bitmask defining which blobs in the set * have data. */ static void BLDMCastTaskGetBlobs(FcomBlobSetMask got_mask) { FcomBlobRef b1; epicsTimeStamp *p_refTime; int rtncode; int loop; p_refTime = &bldFiducialTime; bldEbeamInfo.uDamageMask = __le32(0); for ( loop = 0; loop < N_PULSE_BLOBS; loop++, got_mask >>= 1 ) { setBits(&dataAvailable, bldPulseBlobs[loop].aMsk); if ( bldBlobSet ) { /* NOTE: this could be coded more elegantly but * we want to share as much of the code path * that doesn't use a 'set' as possible. */ rtncode = ! (got_mask & 1); bldPulseBlobs[loop].blob = bldBlobSet->memb[loop].blob; setBits(&dataAvailable, bldPulseBlobs[loop].aMsk); /* If there was no data then it was probably too late */ if ( rtncode ) { bldPulseBlobs[loop].blob = 0; bldUnmatchedTSCount[loop]++; } } else { /** Clear the blob reference before getting a new one... */ bldPulseBlobs[loop].blob = 0; rtncode = fcomGetBlob( bldPulseID[loop], &bldPulseBlobs[loop].blob, 0 ); if ( rtncode ) { bldPulseBlobs[loop].blob = 0; bldFcomGetErrs[loop]++; bldPulseBlobs[loop].fcomGetErrs++; } } if (/* rtncode &&*/ bldPulseBlobs[loop].blob == 0) { clearBits(&dataAvailable, bldPulseBlobs[loop].aMsk); bldPulseBlobs[loop].blob = 0; bldPulseBlobs[loop].nullBlobCount++; continue; } b1 = bldPulseBlobs[loop].blob; if ( b1->fc_stat ) { /* If status is not 0 then handle a few special, permissible cases */ switch ( loop ) { case BMCHARGE: if ( FC_STAT_BPM_REFLO == b1->fc_stat ) goto passed; break; case BMBUNCHLEN: if ( ! (FC_STAT_BLEN_INVAL_BIMAX_MASK & b1->fc_stat) ) goto passed; break; default: break; } bldInvalidAlarmCount[loop]++; clearBits(&dataAvailable, bldPulseBlobs[loop].aMsk); } passed: /* verify timestamp */ if ( 0 != pvTimePulseIdMatches( p_refTime, b1 ) ) { if ( loop == tsCatch ) { tsMismatch[0]=p_refTime->secPastEpoch; tsMismatch[1]=p_refTime->nsec; tsMismatch[2]=b1->fc_tsHi; tsMismatch[3]=b1->fc_tsLo; tsCatch = -1; } bldUnmatchedTSCount[loop]++; clearBits(&dataAvailable, bldPulseBlobs[loop].aMsk); bldPulseBlobs[loop].unmatchedTSCount++; /* if (loop==BC2STATE) { && ((bldPulseBlobs[loop].unmatchedTSCount > 3000 && bldPulseBlobs[loop].unmatchedTSCount < 3050) || (bldPulseBlobs[loop].unmatchedTSCount > 150 && bldPulseBlobs[loop].unmatchedTSCount < 160))) { epicsUInt32 idref, idcmp, diff; idref = PULSEID((*p_refTime)); idcmp = b1->fc_tsLo & LOWER_17_BIT_MASK; if ( idref == idcmp && idref != PULSEID_INVALID ) { } printf("BLD: %i; FF: %i\n", idref, idcmp); } */ } else { bldPulseBlobs[loop].validCounter++; } } __st_le32(&bldEbeamInfo.ts_sec, p_refTime->secPastEpoch); __st_le32(&bldEbeamInfo.ts_nsec, p_refTime->nsec); __st_le32(&bldEbeamInfo.uFiducialId, PULSEID((*p_refTime))); } /** * Calculate the current CHARGE and add to the outgoing * EbeamInfo data. */ static void BLDMCastTaskAddCharge(FcomBlobSetMask got_mask) {/*) {*/ if( (dataAvailable & AVAIL_BMCHARGE) ) { __st_le64(&bldEbeamInfo.ebeamCharge, (double)bldPulseBlobs[BMCHARGE].blob->fcbl_bpm_T * 1.602e-10); } else { bldEbeamInfo.uDamageMask |= __le32(BAD_CHARGE); } } /** * Calculate the current L3 energy and add to the outgoing * EbeamInfo data. */ static void BLDMCastTaskAddL3Energy() { #define AVAIL_L3ENERGY (AVAIL_BMENERGY1X | AVAIL_BMENERGY2X | AVAIL_DSPR1 | AVAIL_DSPR2 | AVAIL_E0BDES) /* Calculate beam energy */ if( AVAIL_L3ENERGY == (AVAIL_L3ENERGY & dataAvailable ) ) { double tempD; tempD = bldPulseBlobs[BMENERGY1X].blob->fcbl_bpm_X/(1000.0 * bldStaticPVs[DSPR1].pTD->value); tempD += bldPulseBlobs[BMENERGY2X].blob->fcbl_bpm_X/(1000.0 * bldStaticPVs[DSPR2].pTD->value); tempD = tempD/2.0 + 1.0; tempD *= bldStaticPVs[E0BDES].pTD->value * 1000.0; __st_le64(&bldEbeamInfo.ebeamL3Energy, tempD); } else { bldEbeamInfo.uDamageMask |= __le32(BAD_ENERGY);/*0x2);*/ } } /** * Calculate the current beam position and add to the outgoing * EbeamInfo data. */ static void BLDMCastTaskAddBeamPosition() { #define AVAIL_LTUPOS ( AVAIL_BMPOSITION1X | AVAIL_BMPOSITION1Y | \ AVAIL_BMPOSITION2X | AVAIL_BMPOSITION2Y | \ AVAIL_BMPOSITION3X | AVAIL_BMPOSITION3Y | \ AVAIL_BMPOSITION4X | AVAIL_BMPOSITION4Y | \ AVAIL_FMTRX ) /* Calculate beam position */ if( AVAIL_LTUPOS == (AVAIL_LTUPOS & dataAvailable) ) { dbr_double_t *pMatrixValue; double tempDA[4]; int i; pMatrixValue = &(bldStaticPVs[FMTRX].pTD->value); for ( i=0; i<4; i++, pMatrixValue+=8 ) { double acc = 0.0; acc += pMatrixValue[0] * bldPulseBlobs[BMPOSITION1X].blob->fcbl_bpm_X; acc += pMatrixValue[1] * bldPulseBlobs[BMPOSITION1X].blob->fcbl_bpm_Y; acc += pMatrixValue[2] * bldPulseBlobs[BMPOSITION2X].blob->fcbl_bpm_X; acc += pMatrixValue[3] * bldPulseBlobs[BMPOSITION2X].blob->fcbl_bpm_Y; acc += pMatrixValue[4] * bldPulseBlobs[BMPOSITION3X].blob->fcbl_bpm_X; acc += pMatrixValue[5] * bldPulseBlobs[BMPOSITION3X].blob->fcbl_bpm_Y; acc += pMatrixValue[6] * bldPulseBlobs[BMPOSITION4X].blob->fcbl_bpm_X; acc += pMatrixValue[7] * bldPulseBlobs[BMPOSITION4X].blob->fcbl_bpm_Y; tempDA[i] = acc; } __st_le64(&bldEbeamInfo.ebeamLTUPosX, tempDA[0]); __st_le64(&bldEbeamInfo.ebeamLTUPosY, tempDA[1]); __st_le64(&bldEbeamInfo.ebeamLTUAngX, tempDA[2]); __st_le64(&bldEbeamInfo.ebeamLTUAngY, tempDA[3]); } else { bldEbeamInfo.uDamageMask |= __le32(BAD_POS_X | BAD_POS_Y | BAD_ANG_X | BAD_ANG_Y);/*0x3C);*/ } } /** * Add bunch length information to the outgoing EbeamInfo data. */ static void BLDMCastTaskAddBunchLength() { if( (AVAIL_BMBUNCHLEN & dataAvailable) ) { __st_le64(&bldEbeamInfo.ebeamBunchLen, (double)bldPulseBlobs[BMBUNCHLEN].blob->fcbl_blen_bimax); } else { bldEbeamInfo.uDamage = bldEbeamInfo.uDamage2 = __le32(EBEAM_INFO_ERROR); bldEbeamInfo.uDamageMask |= __le32(BAD_BLEN);/*0x40);*/ } if ( __ld_le32( &bldEbeamInfo.uDamageMask ) ) { bldEbeamInfo.uDamage = bldEbeamInfo.uDamage2 = __le32(EBEAM_INFO_ERROR); } else { bldEbeamInfo.uDamage = bldEbeamInfo.uDamage2 = __le32(0); } } static void BLDMCastTaskAddBC2Energy() { if( (dataAvailable & AVAIL_BC2STATE) ) { __st_le64(&bldEbeamInfo.ebeamBC2Energy, (double)bldPulseBlobs[BC2STATE].blob->fc_flt[3]); validBC2EnergyCounter = validBC2EnergyCounter + 1; } else { bldEbeamInfo.uDamageMask |= __le32(BAD_BC2_ENERGY); } } static void BLDMCastTaskFillEbeamInfo(FcomBlobSetMask got_mask) {/*) {*/ BLDMCastTaskAddCharge(got_mask); BLDMCastTaskAddL3Energy(); BLDMCastTaskAddBeamPosition(); BLDMCastTaskAddBunchLength(); BLDMCastTaskAddBC2Energy(); } /** * Send the current EbeamInfo to listeners! * * @param sFd socket file descriptor used for the multicast */ static void BLDMCastTaskSend(int sFd) { int rtncode; if(BLD_MCAST_ENABLE) { rtncode = udpCommSend( sFd, &bldEbeamInfo, sizeof(bldEbeamInfo) ); if ( rtncode < 0 ) { if ( BLD_MCAST_DEBUG ) errlogPrintf("Sending multicast packet failed: %s\n", strerror(-rtncode)); } bldMcastMsgSent++; } } /** * Release all blobs acquired during the last cycle. * * @return 0 on success, -1 if one of the blobs could not be * released. */ static int BLDMCastReleaseBlobs() { int loop; int rtncode; if ( ! bldBlobSet ) { for ( loop = 0; loop < N_PULSE_BLOBS; loop++ ) { if ( bldPulseBlobs[loop].blob ) { rtncode = fcomReleaseBlob( & bldPulseBlobs[loop].blob ); if ( rtncode ) { errlogPrintf("Fatal Error: Unable to release blob (for %s): %s\n", bldPulseBlobs[loop].name, fcomStrerror(rtncode)); return -1; } bldPulseBlobs[loop].blob = 0; } } } return 0; } /** * Main loop of the BLDMCastTask. * * @param sFd socket file descriptor used for the multicast */ static int BLDMCastTaskRun(int sFd) { FcomBlobSetMask got_mask; while(bldAllPVsConnected) { /** If there is a valid EVR event received, process it */ if (BLDMCastTaskWaitEvent() == 0) { /** This is 30Hz. So printf might screw timing */ if(BLD_MCAST_DEBUG >= 3) errlogPrintf("Do work!\n"); /** * Use FCOM to obtaine pulse-by-pulse data and * save new data into the EBeamInfo struct. */ if (BLDMCastTaskFcomGetBlobSet(&got_mask) == 0) { BLDMCastTaskCheckFcomDelays(); epicsMutexLock(bldMutex); BLDMCastTaskGetBlobs(got_mask); BLDMCastTaskFillEbeamInfo(got_mask); epicsMutexUnlock(bldMutex); } scanIoRequest(bldIoscan); /* do MultiCast */ BLDMCastTaskSend(sFd); BLDMCastTaskCheckPostDelays(); if (BLDMCastReleaseBlobs() != 0) { return -1; } } } return 0; } /** * BLDMTask entry point */ static int BLDMCastTask(void * parg) { int loop; int rtncode; int sFd; /** Prepare MultiCast */ sFd = BLDMCastTaskPrepareMulticast(); if (sFd < 0) { return -1; } /** Prepare CA */ if (BLDMCastTaskPrepareCA() != 0) { return -1; } /* All ready to go, create event and register with EVR */ EVRFireEvent = epicsEventMustCreate(epicsEventEmpty); /* Register EVRFire */ evrTimeRegister(EVRFire, bldBlobSet); /*#undef bldBlobSet*/ bldAllPVsConnected = TRUE; printf("All PVs are successfully connected!\n"); /* Prefill EBEAMINFO with constant values */ BLDMCastInitializeData(); printf("#################### Entering main loop ########################\n"); if (BLDMCastTaskRun(sFd) != 0) { return -1; } udpCommClose( sFd ); if ( bldBlobSet ) { rtncode = fcomFreeBlobSet( bldBlobSet ); if ( rtncode ) fprintf(stderr, "Unable to destroy blob set: %s\n", fcomStrerror(rtncode)); bldBlobSet = 0; } for ( loop = 0; loop < N_PULSE_BLOBS; loop++ ) { rtncode = fcomUnsubscribe( bldPulseID[loop] ); if ( rtncode ) fprintf(stderr, "Unable to unsubscribe %s from FCOM: %s\n", bldPulseBlobs[loop].name, fcomStrerror(rtncode)); } /*Should never return from following call*/ /*SEVCHK(ca_pend_event(0.0),"ca_pend_event");*/ return(0); } void dumpEBeamInfo(FILE *f) { if ( !f ) f = stdout; if ( bldMutex ) epicsMutexLock( bldMutex ); memcpy(&bldEbeamInfoDump, &bldEbeamInfo, sizeof(bldEbeamInfo)); if ( bldMutex ) epicsMutexUnlock( bldMutex ); fprintf(f, "TS (sec) : %i\n", __ld_le32(&bldEbeamInfoDump.ts_sec)); fprintf(f, "TS (nsec) : %i\n", __ld_le32(&bldEbeamInfoDump.ts_nsec)); fprintf(f, "uMBZ1 : %i\n", __ld_le32(&bldEbeamInfoDump.uMBZ1)); fprintf(f, "FiducialId : %i\n", __ld_le32(&bldEbeamInfoDump.uFiducialId)); fprintf(f, "uMBZ2 : %i\n", __ld_le32(&bldEbeamInfoDump.uMBZ2)); /* Xtc Section 1 */ fprintf(f, "uDamage : %i\n", __ld_le32(&bldEbeamInfoDump.uDamage)); fprintf(f, "uLogicalId : %i\n", __ld_le32(&bldEbeamInfoDump.uLogicalId)); fprintf(f, "uPhysicalId : %i\n", __ld_le32(&bldEbeamInfoDump.uPhysicalId)); fprintf(f, "uDataType : %i\n", __ld_le32(&bldEbeamInfoDump.uDataType)); fprintf(f, "uExtentSize : %i\n", __ld_le32(&bldEbeamInfoDump.uExtentSize)); /* Xtc Section 2 */ fprintf(f, "uDamage2 : %i\n", __ld_le32(&bldEbeamInfoDump.uDamage2)); fprintf(f, "uLogicalId2 : %i\n", __ld_le32(&bldEbeamInfoDump.uLogicalId2)); fprintf(f, "uPhysicalId2 : %i\n", __ld_le32(&bldEbeamInfoDump.uPhysicalId2)); fprintf(f, "uDataType2 : %i\n", __ld_le32(&bldEbeamInfoDump.uDataType2)); fprintf(f, "uExtentSize2 : %i\n", __ld_le32(&bldEbeamInfoDump.uExtentSize2)); fprintf(f, "uDamageMask : %i\n", __ld_le32(&bldEbeamInfoDump.uDamageMask)); fprintf(f, "ebeamCharge : %f\n", __ld_le64(&bldEbeamInfoDump.ebeamCharge)); /* in nC */ fprintf(f, "ebeamL3Energy: %f\n", __ld_le64(&bldEbeamInfoDump.ebeamL3Energy)); /* in MeV */ fprintf(f, "ebeamLTUPosX : %f\n", __ld_le64(&bldEbeamInfoDump.ebeamLTUPosX)); /* in mm */ fprintf(f, "ebeamLTUPosY : %f\n", __ld_le64(&bldEbeamInfoDump.ebeamLTUPosY)); /* in mm */ fprintf(f, "ebeamLTUAngX : %f\n", __ld_le64(&bldEbeamInfoDump.ebeamLTUAngX)); /* in mrad */ fprintf(f, "ebeamLTUAngY : %f\n", __ld_le64(&bldEbeamInfoDump.ebeamLTUAngY)); /* in mrad */ fprintf(f, "ebeamBunchLen: %f\n", __ld_le64(&bldEbeamInfoDump.ebeamBunchLen)); /* in Amps */ fprintf(f, "ebeamBC2Energy: %f\n", __ld_le64(&bldEbeamInfoDump.ebeamBC2Energy)); /* in MeV */ } void dumpFcomStats(FILE *f) { int loop; if ( !f ) f = stdout; fprintf(f, "FCOM ID\t\t\t\tValid\tBad TS\tErrs\tNull\n"); for ( loop = 0; loop < N_PULSE_BLOBS; loop++ ) { fprintf(f, "%s\t\t", bldPulseBlobs[loop].name); if (strlen(bldPulseBlobs[loop].name) < 17) { fprintf(f, "\t"); } fprintf(f, "%li\t%li\t%li\t%li\n", bldPulseBlobs[loop].validCounter, bldPulseBlobs[loop].unmatchedTSCount, bldPulseBlobs[loop].fcomGetErrs, bldPulseBlobs[loop].nullBlobCount); } } void dumpTsMismatchStats(FILE *f, int reset) { int i; epicsUInt32 cnt [N_PULSE_BLOBS]; epicsUInt32 cnt1[N_PULSE_BLOBS]; epicsUInt32 cnt2[N_PULSE_BLOBS]; if ( bldMutex ) epicsMutexLock( bldMutex ); memcpy(cnt, bldUnmatchedTSCount, sizeof(cnt)); memcpy(cnt1, bldInvalidAlarmCount, sizeof(cnt1)); memcpy(cnt2, bldFcomGetErrs, sizeof(cnt1)); if ( bldMutex ) epicsMutexUnlock( bldMutex ); if ( !f ) f = stdout; fprintf(f,"FCOM Data arriving late:\n"); for ( i=0; i 0.004 ) { errlogPrintf("WARNING: system clock rate not high enough to timeout -- using asynchronous mode\n"); } else { if ( (rtncode = fcomAllocBlobSet( bldPulseID, sizeof(bldPulseID)/sizeof(bldPulseID[0]), &bldBlobSet)) ) { errlogPrintf("ERROR: Unable to allocate blob set: %s; trying asynchronous mode\n", fcomStrerror(rtncode)); bldBlobSet = 0; } else { bldUseFcomSet = 1; } } if ( devBusMappedRegisterIO("bld_timer_io", &timer_delay_io) ) errlogPrintf("ERROR: Unable to register I/O methods for timer delay\n" "SOFTWARE MAY NOT WORK PROPERLY\n"); check("bld_stat_bad_t", &bldUnmatchedTSCount); check("bld_stat_bad_d", &bldInvalidAlarmCount); check("bld_stat_bad_f", &bldFcomGetErrs); check("bld_stat_msg_s", &bldMcastMsgSent); check("bld_stat_min_f", &bldMinFcomDelayUs); check("bld_stat_max_f", &bldMaxFcomDelayUs); check("bld_stat_avg_f", &bldAvgFcomDelayUs); check("bld_stat_max_p", &bldMaxPostDelayUs); check("bld_stat_avg_p", &bldAvgPostDelayUs); check("bld_fcom_use_s", &bldUseFcomSet); scanIoInit(&bldIoscan); bldMutex = epicsMutexMustCreate(); BLDMCastStart(1, getenv("IPADDR1")); return 0; } static long BLD_EPICS_Report(int level) { printf("\n"BLD_DRV_VERSION"\n\n"); printf("Compiled with options:\n"); printf("FCOM :"); if ( bldBlobSet ) printf(" Uses a blob set to receive data synchronously\n"); else printf(" Delays (using a hardware timer) and reads data asynchronously\n"); return 0; }