#include #include #include #include #include #include #include #include /* for ntohs used by padProto macros */ #include #include "digiHasOvfl.h" /* Start out ignoring the overflow (if supported) */ volatile signed char digiHasOvfl[MAX_BPM]; static epicsMutexId mtx; static epicsMessageQueueId msgq; int digiHasOvflTestRequest(PadReply rply) { int chnl = rply->chnl; /* range check on rply->chnl has already been performed by DIGI_OVFL_SUP_TEST() macro * which is supposed to call this routine */ epicsMutexLock( mtx ); if ( DIGI_OVFL_SUP_INIT == digiHasOvfl[chnl] ) { digiHasOvfl[chnl] = DIGI_OVFL_SUP_UNKNOWN; } else { rply = 0; } epicsMutexUnlock( mtx ); if ( rply ) { padReplyRef( rply ); if ( epicsMessageQueueTrySend( msgq, &rply, sizeof(rply) ) ) { padReplyFree( rply ); } } return DIGI_HAS_OVFL_SUP( chnl ); } /* Heuristic test to find out if the digitizer uses the LSB to signal * an overflow condition */ int digiHasOvflTest(PadReply rply) { int i,sz,lsb,msb,n; if ( (1 << PADRPLY_STRM_LD_SZ(rply)) != (sz = sizeof(int16_t)) ) { epicsPrintf("digiHasOvfl: sample size != int16 not implemented; ignore OVFL FORCED\n"); return 0; } /* look for a sample which is not close to full-range but has LSB set */ if ( (rply->strm_cmd_flags & PADCMD_STRM_FLAG_LE) ) { msb = 1; lsb = 0; } else { msb = 0; lsb = 1; } for ( i=n=0; idata[i+msb]) <= 10 ) { n++; if ( (rply->data[i+lsb] & 1) ) { /* Found one; LSB is apparently NOT used to signal overflow */ return 0; } } } /* none found; if we checked at least 40 samples then we're good */ return n >= 40 ? 1 : DIGI_OVFL_SUP_INIT; } static void hasOvflThread(void *arg) { PadReply rply; int res; do { if ( epicsMessageQueueReceive( msgq, &rply, sizeof(rply) ) < 0 ) { cantProceed("hasOvflThread: epicsMessageQueueReceive() failed\n"); } res = digiHasOvflTest( rply ); epicsMutexLock( mtx ); digiHasOvfl[rply->chnl] = res; epicsMutexUnlock( mtx ); padReplyFree( rply ); /* We don't know how many channels there are so we don't have * a clear termination criteria. */ } while ( 1 ); epicsMessageQueueDestroy( msgq ); /* Destroying the mutex is not strictly legal here: * digiHasOvflTestRequest(): * - thread A could just have passed the first IF test and * then been suspended. * - thread B passes, takes mutex and schedules a job * - we execute finish, destroy the mutex * - thread A resumes and locks a dead mutex. */ } int digiHasOvflTestInit() { int i; mtx = epicsMutexMustCreate(); msgq = epicsMessageQueueCreate( MAX_BPM, sizeof(PadReply) ); if ( ! msgq ) { cantProceed("digiHasOvflTestInit(): unable to create message queue\n"); } for ( i=0; DIGI_VALID_CH(i); i++ ) { digiHasOvfl[i] = DIGI_OVFL_SUP_INIT; } epicsThreadMustCreate("hasOvflTest", epicsThreadPriorityLow, epicsThreadGetStackSize( epicsThreadStackSmall ), hasOvflThread, 0); return 0; }