/* BLDMCast.c */ #include #include #include #include #include #include #include #include #include #include #include #include #include #include "epicsVersion.h" #include "epicsExport.h" #include "epicsEvent.h" #include "epicsMutex.h" #include "cadef.h" #include "dbDefs.h" #include "dbScan.h" #include "db_access.h" #include "drvSup.h" #include "alarm.h" #include "cantProceed.h" #include "errlog.h" #include "epicsExit.h" #include "epicsThread.h" #include "evrTime.h" #include "evrPattern.h" #include /* This is MVME6100/5500 only */ #include "BLDMCast.h" #define FETCH_PULSE_PVS /* Otherwise we monitor pulse PVs */ #define USE_CA_ADD_EVENT /* ca_create_subscription seems buggy */ #define MULTICAST /* Use multicast interface */ int BLD_MCAST_ENABLE = 1; epicsExportAddress(int, BLD_MCAST_ENABLE); int BLD_MCAST_DEBUG = 0; epicsExportAddress(int, BLD_MCAST_DEBUG); int DELAY_FROM_FIDUCIAL = 5000; /* in microseconds */ epicsExportAddress(int, DELAY_FROM_FIDUCIAL); int DELAY_FOR_CA = 60; /* in seconds */ epicsExportAddress(int, DELAY_FOR_CA); /* Share with device support */ EBEAMINFO ebeamInfo; int bldAllPVsConnected = FALSE; int bldInvalidAlarmCount = 0; int bldUnmatchedTSCount = 0; IOSCANPVT ioscan; /* Trigger EPICS record */ epicsMutexId mutexLock = NULL; /* Protect staticPVs' values */ /* Share with device support */ /*==========================================================*/ static in_addr_t mcastIntfIp = 0; static void evr_timer_isr(void *arg); static int BLDMCastTask(void * parg); static void BLDMCastTaskEnd(void * parg); static epicsEventId EVRFireEvent = NULL; static EBEAMINFO ebeamInfoToSend; /* With little endian for receiver */ int BLDMCastStart(int enable, const char * NIC) {/* This funciton will be called in st.cmd after iocInit() */ /* 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; } scanIoInit(&ioscan); mutexLock = epicsMutexMustCreate(); /******************************************************************* Setup high resolution timer ***************************************************************/ /* you need to setup the timer only once (to connect ISR) */ BSP_timer_setup( 0 /* use first timer */, 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)); } void EVRFire(void) {/* This funciton will be registered with EVR callback */ epicsUInt32 rate_mask = MOD5_30HZ_MASK|MOD5_10HZ_MASK|MOD5_5HZ_MASK|MOD5_1HZ_MASK|MOD5_HALFHZ_MASK; /* can be 30HZ,10HZ,5HZ,1HZ,HALFHZ */ /* get the current pattern data - check for good status */ evrModifier_ta modifier_a; epicsTimeStamp time_s; 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\n"); if (!status) {/* check for LCLS beam and rate-limiting */ if ((modifier_a[4] & MOD5_BEAMFULL_MASK) && (modifier_a[4] & rate_mask)) {/* ... do beam-sync rate-limited processing here ... */ /* call 'BSP_timer_start()' to set/arm the hardware */ uint64_t delayFromFiducial = 0; /* This is 30Hz. So printf might screw timing */ if(BLD_MCAST_DEBUG >= 3) errlogPrintf("Timer Starts\n"); delayFromFiducial = BSP_timer_clock_get(0) * DELAY_FROM_FIDUCIAL; /* delay from fiducial in us */ BSP_timer_start( 0, (uint32_t) (delayFromFiducial / 1000000) ); } } 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); } #if 0 static void accessRightsCallback(struct access_rights_handler_args args) { chid pvChId = args.chid; if(BLD_MCAST_DEBUG >= 2) printChIdInfo(pvChId,"accessRightsCallback"); } static void connectionCallback(struct connection_handler_args args) { chid pvChId = args.chid; if(BLD_MCAST_DEBUG >= 2) printChIdInfo(pvChId,"connectionCallback"); } #endif 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(mutexLock); if (args.status == ECA_NORMAL) { memcpy(pPV->pTD, args.dbr, dbr_size_n(args.type, args.count)); if(pPV->pTD->severity >= INVALID_ALARM) /* We don't care timestamp for staticPVs. As long as it is not invalid, they are ok */ pPV->dataAvailable = FALSE; else pPV->dataAvailable = TRUE; 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 { pPV->dataAvailable = FALSE; } epicsMutexUnlock(mutexLock); } #ifndef vxWorks static void binvert(char * pBuf, int nBytes) { int loop; char temp; for(loop=0;loop= 2) { struct sockaddr_in sockaddrName; #ifdef __linux__ unsigned int iLength = sizeof(sockaddrName); #elif defined(__rtems__) socklen_t iLength = sizeof(sockaddrName); #else int iLength = sizeof(sockaddrName); #endif if(getsockname(sFd, (struct sockaddr*)&sockaddrName, &iLength) == 0) printf( "Local addr: %s Port %u\n", inet_ntoa(sockaddrName.sin_addr), ntohs(sockaddrName.sin_port)); } mcastTTL = MCAST_TTL; if (setsockopt(sFd, IPPROTO_IP, IP_MULTICAST_TTL, (char*)&mcastTTL, sizeof(unsigned char) ) < 0 ) { perror("Set TTL failed\n"); errlogPrintf("Failed to set TTL for multicast\n"); close(sFd); epicsMutexDestroy(mutexLock); return -1; } if (mcastIntfIp) { struct in_addr address; address.s_addr = mcastIntfIp; if(setsockopt(sFd, IPPROTO_IP, IP_MULTICAST_IF, (char*)&address, sizeof(struct in_addr) ) < 0) { errlogPrintf("Failed to set interface for multicast\n"); close(sFd); epicsMutexDestroy(mutexLock); return -1; } } #endif /************************************************************************* Prepare CA *************************************************************************/ 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 */ for(loop=0; loop 1) { SEVCHK(ca_add_array_event(DBR_TIME_DOUBLE, staticPVs[loop].nElems, staticPVs[loop].pvChId, eventCallback, &(staticPVs[loop]), 0.0, 0.0, 0.0, NULL), "ca_add_array_event"); } else { SEVCHK(ca_add_event(DBR_TIME_DOUBLE, staticPVs[loop].pvChId, eventCallback, &(staticPVs[loop]), NULL), "ca_add_event"); } #else SEVCHK(ca_create_subscription(DBR_TIME_DOUBLE, staticPVs[loop].nElems, staticPVs[loop].pvChId, DBE_VALUE|DBE_ALARM, eventCallback, &(staticPVs[loop]), NULL), "ca_create_subscription"); #endif } ca_flush_io(); /* ca_pend_event(2.0); */ /* We only fetch pulse PVs */ for(loop=0; loop 1) { SEVCHK(ca_add_array_event(DBR_TIME_DOUBLE, pulsePVs[loop].nElems, pulsePVs[loop].pvChId, eventCallback, &(pulsePVs[loop]), 0.0, 0.0, 0.0, NULL), "ca_add_array_event"); } else { SEVCHK(ca_add_event(DBR_TIME_DOUBLE, pulsePVs[loop].pvChId, eventCallback, &(pulsePVs[loop]), NULL), "ca_add_event"); } #else SEVCHK(ca_create_subscription(DBR_TIME_DOUBLE, pulsePVs[loop].nElems, pulsePVs[loop].pvChId, DBE_VALUE|DBE_ALARM, eventCallback, &(pulsePVs[loop]), NULL), "ca_create_subscription"); #endif } ca_flush_io(); #endif /* All ready to go, create event and register with EVR */ EVRFireEvent = epicsEventMustCreate(epicsEventEmpty); /* Register EVRFire */ evrTimeRegister((REGISTRYFUNCTION)EVRFire); bldAllPVsConnected = TRUE; printf("All PVs are successfully connected!\n"); while(bldAllPVsConnected) { int status; status = epicsEventWaitWithTimeout(EVRFireEvent, DEFAULT_EVR_TIMEOUT); if(status != epicsEventWaitOK) { if(status == epicsEventWaitTimeout) { if(BLD_MCAST_DEBUG >= 3) errlogPrintf("Wait EVR timeout, check timing?\n"); continue; } else { errlogPrintf("Wait EVR Error, what happened? Let's sleep 2 seconds.\n"); epicsThreadSleep(2.0); continue; } } #ifdef FETCH_PULSE_PVS /* Timer fires ok, let's then get pulse PVs */ /* This is 30Hz. So printf might screw timing */ if(BLD_MCAST_DEBUG >= 3) errlogPrintf("Do work!\n"); rtncode = ECA_NORMAL; for(loop=0; loop 1) { rtncode = ca_array_get(DBR_TIME_DOUBLE, pulsePVs[loop].nElems, pulsePVs[loop].pvChId, (void *)(pulsePVs[loop].pTD)); } else { rtncode = ca_get(DBR_TIME_DOUBLE, pulsePVs[loop].pvChId, (void *)(pulsePVs[loop].pTD)); } } rtncode = ca_pend_io(DEFAULT_CA_TIMEOUT); if (rtncode != ECA_NORMAL) { if(BLD_MCAST_DEBUG) errlogPrintf("Something wrong when fetch pulse-by-pulse PVs.\n"); ebeamInfo.uDamageMask = 0xffffffff; /* no information available */ ebeamInfo.uDamage = ebeamInfo.uDamage2 = EBEAM_INFO_ERROR; } #endif else {/* Got all PVs, do calculation including checking severity and timestamp */ memcpy((void *)&ebeamInfo, (void *)&ebeamInfoPreFill, sizeof(EBEAMINFO)); /* Assume the first timestamp is right */ ebeamInfo.timestamp = pulsePVs[BMCHARGE].pTD->stamp; ebeamInfo.uFiducialId = (ebeamInfo.timestamp.nsec & 0x1FFFF); for(loop=0; loopseverity >= INVALID_ALARM ) { pulsePVs[loop].dataAvailable = FALSE; bldInvalidAlarmCount++; if(BLD_MCAST_DEBUG) errlogPrintf("%s has severity %d\n", pulsePVs[loop].name, pulsePVs[loop].pTD->severity); } if( 0 != memcmp(&(ebeamInfo.timestamp), &(pulsePVs[loop].pTD->stamp), sizeof(epicsTimeStamp)) ) { pulsePVs[loop].dataAvailable = FALSE; bldUnmatchedTSCount++; if(BLD_MCAST_DEBUG) errlogPrintf("%s has unmatched timestamp.nsec [0x%08X,0x%08X]\n", pulsePVs[loop].name, ebeamInfo.timestamp.nsec, pulsePVs[loop].pTD->stamp.nsec); } } epicsMutexLock(mutexLock); ebeamInfo.uDamage = ebeamInfo.uDamage2 = 0; ebeamInfo.uDamageMask = 0; /* Calculate beam charge */ if(pulsePVs[BMCHARGE].dataAvailable) { ebeamInfo.ebeamCharge = pulsePVs[BMCHARGE].pTD->value * 1.602e-10; } else { ebeamInfo.uDamage = ebeamInfo.uDamage2 = EBEAM_INFO_ERROR; ebeamInfo.uDamageMask |= 0x1; } /* Calculate beam energy */ if(pulsePVs[BMENERGY1X].dataAvailable && pulsePVs[BMENERGY2X].dataAvailable && staticPVs[DSPR1].dataAvailable && staticPVs[DSPR2].dataAvailable && staticPVs[E0BDES].dataAvailable) { double tempD; tempD = pulsePVs[BMENERGY1X].pTD->value/(1000.0 * staticPVs[DSPR1].pTD->value); tempD += pulsePVs[BMENERGY2X].pTD->value/(1000.0 * staticPVs[DSPR2].pTD->value); tempD = tempD/2.0 + 1.0; tempD *= staticPVs[E0BDES].pTD->value * 1000.0; ebeamInfo.ebeamL3Energy = tempD; } else { ebeamInfo.uDamage = ebeamInfo.uDamage2 = EBEAM_INFO_ERROR; ebeamInfo.uDamageMask |= 0x2; } /* Calculate beam position */ if(pulsePVs[BMPOSITION1X].dataAvailable && pulsePVs[BMPOSITION1Y].dataAvailable && pulsePVs[BMPOSITION2X].dataAvailable && pulsePVs[BMPOSITION2Y].dataAvailable && pulsePVs[BMPOSITION3X].dataAvailable && pulsePVs[BMPOSITION3Y].dataAvailable && pulsePVs[BMPOSITION4X].dataAvailable && pulsePVs[BMPOSITION4Y].dataAvailable && staticPVs[FMTRX].dataAvailable) { dbr_double_t *pMatrixValue; double tempDA[4]; int i,j; pMatrixValue = &(staticPVs[FMTRX].pTD->value); for(i=0;i<4;i++) { tempDA[i] = 0.0; for(j=0;j<8;j++) tempDA[i] += pMatrixValue[i*8+j] * pulsePVs[BMPOSITION1X+j].pTD->value; } ebeamInfo.ebeamLTUPosX = tempDA[0]; ebeamInfo.ebeamLTUPosY = tempDA[1]; ebeamInfo.ebeamLTUAngX = tempDA[2]; ebeamInfo.ebeamLTUAngY = tempDA[3]; } else { ebeamInfo.uDamage = ebeamInfo.uDamage2 = EBEAM_INFO_ERROR; ebeamInfo.uDamageMask |= 0x3C; } /* Copy bunch length */ if(pulsePVs[BMBUNCHLEN].dataAvailable) { ebeamInfo.ebeamBunchLen = pulsePVs[BMBUNCHLEN].pTD->value; } else { ebeamInfo.uDamage = ebeamInfo.uDamage2 = EBEAM_INFO_ERROR; ebeamInfo.uDamageMask |= 0x40; } memcpy((void *)&ebeamInfoToSend, (void *)&ebeamInfo, sizeof(EBEAMINFO)); epicsMutexUnlock(mutexLock); scanIoRequest(ioscan); } #ifdef MULTICAST /* do MultiCast */ if(BLD_MCAST_ENABLE) { int ipos; for(ipos=0;ipos<16;ipos++) binvert( ((char *)&ebeamInfoToSend)+ipos*4, 4); for(ipos=8;ipos<15;ipos++) binvert( ((char *)&ebeamInfoToSend)+ipos*8, 8); if(-1 == sendto(sFd, (void *)&ebeamInfoToSend, sizeof(struct EBEAMINFO), 0, (const struct sockaddr *)&sockaddrDst, sizeof(struct sockaddr_in))) { if(BLD_MCAST_DEBUG) perror("Multicast sendto failed\n"); } } #endif } /*Should never return from following call*/ /*SEVCHK(ca_pend_event(0.0),"ca_pend_event");*/ return(0); } /**************************************************************************************************/ /* Here we supply the driver report function for epics */ /**************************************************************************************************/ static long BLD_EPICS_Init(); static long BLD_EPICS_Report(int level); const struct drvet drvBLD = {2, /*2 Table Entries */ (DRVSUPFUN) BLD_EPICS_Report, /* Driver Report Routine */ (DRVSUPFUN) BLD_EPICS_Init}; /* Driver Initialization Routine */ epicsExportAddress(drvet,drvBLD); /* implementation */ static long BLD_EPICS_Init() { BLDMCastStart(1, MCAST_LOCAL_IP); return 0; } static long BLD_EPICS_Report(int level) { printf("\n"BLD_DRV_VERSION"\n\n"); return 0; }