Exemple #1
0
 def CompressSegments(self):
     from MDSplus import Tree,DateToQuad,ZERO,Int32,Int32Array,Int64Array,Range
     with Tree(self.tree,self.shot+9,'NEW') as ptree:
         node = ptree.addNode('S')
         node.compress_on_put = False
         ptree.write()
     ptree.cleanDatafile()
     ptree.normal()
     te = DateToQuad("now")
     sampperseg = 50
     data = ZERO(Int32Array([sampperseg]),Int32(0))
     numsegs = 128
     for i in range(numsegs):
         t0=te+1;te=t0+sampperseg-1
         node.makeSegment(t0,te,Int64Array(range(t0,te+1)),data+Int32(i))
     node.compress_segments=True
     ptree.createPulse(self.shot+11)
     Tree.compressDatafile(self.tree,self.shot+11)
     ptree1 = Tree(self.tree,self.shot+11)
     node1  = ptree1.S
     self.assertEqual(True,(node.record==node1.record).all())
     self.assertEqual(True,ptree.getDatafileSize()>ptree1.getDatafileSize())
     for i in range(numsegs):
         srt,end = node.getSegmentLimits(i)
         dim = Range(srt,end)
         node.updateSegment(srt,end,dim,i)
         if i%16==0:
             self.assertEqual(dim.decompile(),node.getSegmentDim(i).decompile())
     ptree.compressDatafile()
     ptree.readonly()
     self.assertEqual(numsegs,node1.getNumSegments())
     self.assertEqual(True,ptree.getDatafileSize()<ptree1.getDatafileSize())
     for i in range(numsegs):
         self.assertEqual(node.getSegmentDim(i).data().tolist(),node1.getSegmentDim(i).data().tolist())
Exemple #2
0
 def test():
     from MDSplus import Tree, Int32, Int64, Dimension, Range, Window, DIVIDE, ADD, MULTIPLY
     from numpy import arange, ones, int16, int64
     slp = 3.3
     off = 1.1
     trg = -1000000
     clk = 1000000
     with Tree(self.tree, self.shot, 'NEW') as ptree:
         sig = ptree.addNode('SIG').record = ADD(
             MULTIPLY(ptree.addNode('RAW'), ptree.addNode('SLP')),
             ptree.addNode('OFF'))
         ptree.addNode('TRG').record = Int64(trg)
         ptree.addNode('CLK').record = Int32(clk)
         ptree.write()
     ptree = Tree(self.tree, self.shot)
     trig = ptree.TRG
     raw = ptree.RAW
     sig = ptree.SIG
     dt = DIVIDE(Int64(1e9), ptree.CLK)
     rng = Range(None, None, dt)
     wnd = Window(None, None, trig)
     ptree.SLP.record = slp
     ptree.OFF.record = off
     length, seglen = 100, 10
     dat = ones(seglen, dtype=int16)
     for i0 in range(0, length, seglen):
         i1 = i0 + seglen - 1
         wnd[0], wnd[1] = Int64(i0), Int64(i1)
         dim = Dimension(wnd, rng)
         d0 = Int64(i0 * dt + trig)
         d1 = Int64(i1 * dt + trig)
         self.assertEqual(dim.data()[0], d0.data())
         self.assertEqual(dim.data()[-1], d1.data())
         raw.makeSegment(d0, d1, dim, dat)
     self.assertEqual(
         str(raw.getSegment(0)),
         "Build_Signal(Word([1,1,1,1,1,1,1,1,1,1]), *, Build_Dim(Build_Window(0Q, 9Q, TRG), * : * : 1000000000Q / CLK))"
     )
     self.assertEqual(str(sig.record), "RAW * SLP + OFF")
     self.assertTrue(sig.dim_of().tolist(),
                     (arange(0, length, dtype=int64) * int(1e9 / clk) +
                      trg).tolist())
     self.assertTrue(
         (abs(sig.data() -
              (ones(length, dtype=int16) * slp + off)) < 1e-5).all(),
         "Stored data does not match expected array")
     #        ptree.close()
     #        ptree.compressDatafile() # this will break the functionality of updateSegment
     #        ptree.open()
     trig.record = 0
     for i in range(int(length / seglen)):
         dim = raw.getSegmentDim(i)
         raw.updateSegment(dim.data()[0], dim.data()[-1], dim, i)
     self.assertEqual(
         str(raw.getSegment(0)),
         "Build_Signal(Word([1,1,1,1,1,1,1,1,1,1]), *, Build_Dim(Build_Window(0Q, 9Q, TRG), * : * : 1000000000Q / CLK))"
     )
     self.assertTrue(sig.dim_of().tolist(),
                     (arange(0, length, dtype=int64) *
                      int(1e9 / clk)).tolist())
Exemple #3
0
        def sync(self):
            from MDSplus import Data, TreeNode, TreeNodeArray, Compound, Int32
            from MDSplus import TreeNODATA, TreeBADRECORD, TreeNNF
            master = self.master
            mnids = Int32(master.conglomerate_nids).data().tolist()

            def relink(val):
                if val is None: return None
                if isinstance(val, (Compound, )):
                    for i in range(val.getNumDescs()):
                        ans = val.getDescAt(i)
                        if isinstance(ans, (Data, TreeNode)):
                            val.setDescAt(i, relink(ans))
                    return val
                if isinstance(val, (TreeNodeArray, )):
                    for i in len(val):
                        val[i] = relink(val[i])
                    return val
                if isinstance(val, (TreeNode, )):
                    if not val.nid in mnids:
                        try:
                            return self.tree.getNode(val.minpath)
                        except:
                            pass
                    return relink(val.getRecord(None))
                return val

            def transfer(src, dst):
                dst.write_once = False
                try:
                    dst.record = relink(src.getRecord())
                except TreeNODATA:
                    dst.record = None
                finally:
                    dst.write_once = True

            for to in range(3):
                try:
                    master = self.master
                    for name in self.part_names:
                        dst = self.head.getNode(name)
                        if dst.no_write_shot: continue
                        try:
                            src = master.getNode(name)
                        except TreeNNF:
                            continue
                        else:
                            transfer(src, dst)
                except TreeBADRECORD:
                    time.sleep(1)
                else:
                    break
Exemple #4
0
 def test():
     from MDSplus import Tree, DateToQuad, ZERO, Int32, Int32Array, Int64Array, Range
     with Tree('seg_tree', self.shot, 'NEW') as ptree:
         node = ptree.addNode('S')
         node.compress_on_put = False
         ptree.write()
     ptree.normal()
     ptree.compressDatafile()
     te = DateToQuad("now")
     sampperseg = 50
     data = ZERO(Int32Array([sampperseg]), Int32(0))
     for i in range(513):
         t0 = te + 1
         te = t0 + sampperseg - 1
         node.makeSegment(t0, te, Int64Array(range(t0, te + 1)),
                          data + Int32(i))
     node.compress_segments = True
     ptree.createPulse(self.shot + 1)
     Tree.compressDatafile(self.tree, self.shot + 1)
     ptree1 = Tree(self.tree, self.shot + 1)
     node1 = ptree1.S
     self.assertEqual(True, (node.record == node1.record).all())
     self.assertEqual(
         True,
         ptree.getDatafileSize() > ptree1.getDatafileSize())
     for i in range(node.getNumSegments()):
         str, end = node.getSegmentLimits(i)
         node.updateSegment(str, end, Range(str, end), i)
     ptree.close()
     ptree.compressDatafile()
     ptree.readonly()
     self.assertEqual(
         True,
         ptree.getDatafileSize() < ptree1.getDatafileSize())
     for i in range(node1.getNumSegments()):
         self.assertEqual(
             node.getSegmentDim(i).data().tolist(),
             node1.getSegmentDim(i).data().tolist())
Exemple #5
0
    def start_store(self):

        try:
            self.restoreInfo()
        except:
            Data.execute('DevLogErr($1,$2)', self.getNid(),
                         'FAU device not initialized')
            raise mdsExceptions.TclFAILED_ESSENTIAL

        try:
            tsmpFreq = self.tsmp_freq.data()
            tickFreqCode = self.tsmpDict[tsmpFreq]
        except:
            Data.execute('DevLogErr($1,$2)', self.getNid(),
                         'Read FAU time stamp frequency error. Set to 40MHz')
            tsmpFreq = 40000000
            tickFreqCode = 0
            self.tsmp_freq.putData(Int32(tsmpFreq))

        treePtr = c_void_p(0)
        CRIO_FAU.niInterfaceLib.openTree(c_char_p(self.getTree().name),
                                         c_int(self.getTree().shot),
                                         byref(treePtr))

        self.worker = self.AsynchStore()
        self.worker.daemon = True
        self.worker.stopReq = False

        self.worker.configure(self, tsmpFreq, treePtr)

        trigMode = self.trig_mode.data()
        print "Trigg mode ", trigMode
        if (trigMode == "INTERNAL"):
            status = CRIO_FAU.niInterfaceLib.startFauAcquisition(self.session)
            print "Start FAU acquisition"
            if status < 0:
                Data.execute('DevLogErr($1,$2)', self.getNid(),
                             'FAU start acquisition device error.')
                raise mdsExceptions.TclFAILED_ESSENTIAL

        sleep(1)

        acqState = c_short()
        CRIO_FAU.niInterfaceLib.getFauAcqState(self.session, byref(acqState))
        print "Acquisition State ", acqState.value

        self.saveWorker()
        self.worker.start()

        return 1
Exemple #6
0
 def CompressTimestampedSegments(self):
     from MDSplus import Tree, Int32, Int64
     with Tree(self.tree,self.shot+10,'NEW') as ptree:
         s = ptree.addNode('s', 'SIGNAL')
         ptree.write()
     ptree.normal()
     for i in range(2):  # time is even, data is odd
         data = [i*10+j*2 for j in range(5)]
         s.makeTimestampedSegment(Int64(data), Int32(data)+1)
     before = s.record
     ptree.compressDatafile()
     ptree.readonly()
     after = s.record
     self.assertEqual(True,(before.data()==after.data()).all(), "%r != %r" % (before.value, after.value) )
     self.assertEqual(True,(before.dim_of().data()==after.dim_of().data()).all(), "%r != %r" % (before.dim_of(), after.dim_of()))
def DevAddPythonDevice(path, model, nidout=None):
    """Add a python device to the tree by:
    1) finding the model in the list defined by
       the tdi function, MdsDevices.
    2) try importing the package for the model and calling its Add method.

    Both the path and model are passed in as Ident instances.
    The StringArray returned by MdsDevices() contains String instances
    containing blank filled values containing an \0 character embedded.
    These Strings have to be manipulated to produce simple str() values.
    """
    model = str(model.data()).strip()
    path = str(path.data()).strip()
    try:
        node = Device.PyDevice(model).Add(Tree(), path)
        if isinstance(nidout, (Ident, )):
            Data.execute("$=$", nidout, Int32(node.nid))
        return TreeNORMAL.status
    except MDSplusException:
        return sys.exc_info()[1].status
    except:
        print("Error adding device instance of %s: %s" %
              (model, sys.exc_info()[1]))
        return MDSplusERROR.status
Exemple #8
0
    def store(self):
        self.restoreInfo()
        vmeAddress = 0
        # Stop device
        status = CAENDT5720.caenLib.CAENVME_WriteCycle(
            self.handle, c_int(vmeAddress + 0x8100), byref(c_int(0)),
            c_int(self.cvA32_S_DATA), c_int(self.cvD32))
        if status != 0:
            Data.execute('DevLogErr($1,$2)', self.getNid(),
                         'Error stopping device')
            raise mdsExceptions.TclFAILED_ESSENTIAL
    #need to wait a while
        sleep(0.1)
        acqMode = self.acq_mode.data()
        if acqMode == 'CONTINUOUS' or acqMode == 'CONTINUOUS WITH COUNTER':
            self.stop_store(0)
            return

        try:
            clock = self.clock_source.evaluate()
            dt = clock.getDelta().data()
        except:
            Data.execute('DevLogErr($1,$2)', self.getNid(),
                         'Error evaluating clock source')
            raise mdsExceptions.TclFAILED_ESSENTIAL
        try:
            trig = self.trig_source.data()
        except:
            Data.execute('DevLogErr($1,$2)', self.getNid(),
                         'Error evaluating trigger source')
            raise mdsExceptions.TclFAILED_ESSENTIAL
        try:
            startIdx = self.start_idx.data()
            endIdx = self.end_idx.data()
        except:
            Data.execute('DevLogErr($1,$2)', self.getNid(),
                         'Error evaluating start or end idx')
            raise mdsExceptions.TclFAILED_ESSENTIAL
        try:
            pts = self.pts.data()
        except:
            Data.execute('DevLogErr($1,$2)', self.getNid(),
                         'Error evaluating Post Trigger Samples')
            raise mdsExceptions.TclFAILED_ESSENTIAL

    # Read number of buffers
        actSegments = c_int(0)
        status = CAENDT5720.caenLib.CAENVME_ReadCycle(
            self.handle, c_int(vmeAddress + 0x812C), byref(actSegments),
            c_int(self.cvA32_S_DATA), c_int(self.cvD32))
        if status != 0:
            Data.execute('DevLogErr($1,$2)', self.getNid(),
                         'Error reading number of acquired segments')
            raise mdsExceptions.TclFAILED_ESSENTIAL

        if actSegments.value == 0:
            return

    #Compute Segment Size
        try:
            nSegments = self.num_segments.data()
            segmentSamples = 1048576 / nSegments
        except:
            Data.execute('DevLogErr($1,$2)', self.getNid(),
                         'Error reading max number of segments')
            raise mdsExceptions.TclFAILED_ESSENTIAL

    # Get Active channels
        chanMask = c_int(0)
        status = CAENDT5720.caenLib.CAENVME_ReadCycle(
            self.handle, c_int(vmeAddress + 0x8120), byref(chanMask),
            c_int(self.cvA32_S_DATA), c_int(self.cvD32))
        nActChans = 0
        chanMask = chanMask.value
        numChannels = self.num_channels.data()
        for chan in range(0, numChannels):
            if (chanMask & (1 << chan)) != 0:
                nActChans = nActChans + 1
        if nActChans == 0:
            print('No active groups')
            return

        segmentSize = 16 + 2 * segmentSamples * nActChans

        class DT5720Data(Structure):
            _fields_ = [("eventSize", c_int), ("boardGroup", c_int),
                        ("counter", c_int), ("time", c_int),
                        ("data", c_short * (segmentSize / 2))]

        actSegments = actSegments.value

        currStartIdx = segmentSamples - pts + startIdx
        currEndIdx = segmentSamples - pts + endIdx
        currChanSamples = Int32(currEndIdx - currStartIdx + 0.5).data()
        triggers = []
        deltas = []
        channels = [None] * numChannels
        for chan in range(numChannels):
            channels[chan] = ndarray(currChanSamples * actSegments)
        for segmentIdx in range(0, actSegments):
            segment = DT5720Data()
            retLen = c_int(0)
            status = CAENDT5720.caenLib.CAENVME_FIFOBLTReadCycle(
                self.handle, c_int(vmeAddress), byref(segment),
                c_int(segmentSize), c_int(self.cvA32_S_DATA),
                c_int(self.cvD64), byref(retLen))
            if status != 0:
                Data.execute('DevLogErr($1,$2)', self.getNid(),
                             'Error reading data segment')
                raise mdsExceptions.TclFAILED_ESSENTIAL

            actSize = 4 * (segment.eventSize & 0x0fffffff)
            if actSize != segmentSize:
                Data.execute(
                    'DevLogErr($1,$2)', self.getNid(),
                    'Expected event size different from expected size')
                raise mdsExceptions.TclFAILED_ESSENTIAL
            counter = segment.time / 2
            triggers.append(counter * dt)
            deltas.append(dt)
            sizeInInts = (segment.eventSize & 0x0fffffff) - 4
            chanSizeInInts = sizeInInts / nActChans
            chanSizeInShorts = chanSizeInInts * 2
            #chanOffset = 0
            for chan in range(numChannels):
                if (chanMask & (1 << chan)) != 0:
                    channels[chan][segmentIdx * currChanSamples:segmentIdx *
                                   currChanSamples + currEndIdx -
                                   currStartIdx] = segment.data[
                                       chan * chanSizeInShorts +
                                       currStartIdx:chan * chanSizeInShorts +
                                       currEndIdx]
            #endfor  chan in range(numChannels)
        #endfor segmentIdx in range(actSegments):
        if len(self.trig_source.getShape()) > 0:
            dim = Dimension(
                Window(startIdx,
                       endIdx + (actSegments - 1) * (endIdx - startIdx),
                       trig[0]),
                Range(
                    Float64Array(trig) + Float64(startIdx * dt),
                    Float64Array(trig) + Float64(endIdx * dt),
                    Float64Array(deltas)))
        else:
            dim = Dimension(
                Window(startIdx,
                       endIdx + (actSegments - 1) * (endIdx - startIdx), trig),
                Range(
                    Float64Array(triggers) - Float64(triggers[0]) +
                    Float64(trig) + Float64(startIdx * dt),
                    Float64Array(triggers) - Float64(triggers[0]) +
                    Float64(trig) + Float64(endIdx * dt),
                    Float64Array(deltas)))
        dim.setUnits("s")
        for chan in range(numChannels):
            if (chanMask & (1 << chan)) != 0:
                try:
                    offset = getattr(self, 'channel_%d_offset' % (chan + 1))
                except:
                    Data.execute('DevLogErr($1,$2)', self.getNid(),
                                 'Error reading channel offset')
                    raise mdsExceptions.TclFAILED_ESSENTIAL
                raw = Int16Array(channels[chan])
                raw.setUnits("counts")
                data = Data.compile("2*($VALUE - 2048)/4096.+$1", offset)
                data.setUnits("Volts")
                signal = Signal(data, raw, dim)
                try:
                    getattr(self,
                            'channel_%d_data' % (chan + 1)).putData(signal)
                except:
                    Data.execute('DevLogErr($1,$2)', self.getNid(),
                                 'Cannot write Signal in tree')
                    raise mdsExceptions.TclFAILED_ESSENTIAL
        #endfor chan in range(numChannels)
        return
Exemple #9
0
    def init(self):

        try:
            self.initializeInfo()
        except:
            Data.execute('DevLogErr($1,$2)', self.getNid(),
                         'Cannot open FAU device')
            raise mdsExceptions.TclFAILED_ESSENTIAL

        self.saveInfo()

        try:
            pteMask = self.pte_mask.data()
        except:
            Data.execute('DevLogErr($1,$2)', self.getNid(),
                         'Read FAU pulse train mask error. Set to 0')
            pteMask = 0

        try:
            pteFreq = self.pte_freq.data()
        except:
            Data.execute('DevLogErr($1,$2)', self.getNid(),
                         'Read FAU pulse train frequency error. Set to 50KHz')
            pteMask = 50000

        try:
            trigMode = self.trig_mode.data()
            print("Trigger Node = ", trigMode)
        except:
            Data.execute('DevLogErr($1,$2)', self.getNid(),
                         'Read FAU trigger mode error. Set to INTERNAL')
            trigMode = 'INTERNAL'
            self.trig_mode.putData(trigMode)

        try:
            tsmpFreq = self.tsmp_freq.data()
            tickFreqCode = self.tsmpDict[tsmpFreq]
        except:
            Data.execute('DevLogErr($1,$2)', self.getNid(),
                         'Read FAU time stamp frequency error. Set to 40MHz')
            tsmpFreq = 40000000
            tickFreqCode = 0
            self.tsmp_freq.putData(Int32(tsmpFreq))

        try:
            trigSource = self.trig_source.data()
        except:
            if (trigMode == 'EXTERNAL'):
                Data.execute('DevLogErr($1,$2)', self.getNid(),
                             'Cannot resolve Trigger source.')
                raise mdsExceptions.TclFAILED_ESSENTIAL
            else:
                trigSource = 0.
                self.trig_source.putData(Float32(trigSource))

        print("Trigger Source = ", trigSource)

        status = CRIO_FAU.niInterfaceLib.setFauAcqParam(
            self.session, c_short(pteMask), c_int(pteFreq),
            c_short(tickFreqCode))

        if status < 0:
            Data.execute('DevLogErr($1,$2)', self.getNid(),
                         'FAU acquisition device initialization error.')
            raise mdsExceptions.DevCANNOT_LOAD_SETTINGS

        status = CRIO_FAU.niInterfaceLib.startFauFpga(self.session)
        if status < 0:
            Data.execute('DevLogErr($1,$2)', self.getNid(),
                         'FAU start FPGA error.')
            raise mdsExceptions.DevCOMM_ERROR
Exemple #10
0
    def init(self):
        self.restoreInfo()
        vmeAddress = 0
        #Module Reset
        data = c_int(0)
        status = CAENDT5720.caenLib.CAENVME_WriteCycle(
            self.handle, c_int(vmeAddress + 0xEF24), byref(data),
            c_int(self.cvA32_S_DATA), c_int(self.cvD32))
        if status != 0:
            Data.execute('DevLogErr($1,$2)', self.getNid(),
                         'Error resetting V1740 Device')
            raise mdsExceptions.TclFAILED_ESSENTIAL

    #give some time
        sleep(0.1)

        #Module type
        devType = c_int(0)
        status = CAENDT5720.caenLib.CAENVME_ReadCycle(
            self.handle, c_int(vmeAddress + 0x8140), byref(devType),
            c_int(self.cvA32_S_DATA), c_int(self.cvD32))
        if status != 0:
            Data.execute('DevLogErr($1,$2)', self.getNid(),
                         'Error writing group configuration')
            raise mdsExceptions.TclFAILED_ESSENTIAL
        numChannels = devType.value >> 16
        print('NUM CHANNELS: ', numChannels)
        self.num_channels.putData(numChannels)

        #number of segments
        segmentDict = {
            1: 0,
            2: 1,
            4: 2,
            8: 3,
            16: 4,
            32: 5,
            64: 6,
            128: 7,
            256: 8,
            512: 9,
            1024: 10
        }
        try:
            nSegments = self.num_segments.data()
        except:
            Data.execute('DevLogErr($1,$2)', self.getNid(),
                         'Invalid Number of Segments')
            raise mdsExceptions.TclFAILED_ESSENTIAL
        segmentCode = segmentDict[nSegments]
        status = CAENDT5720.caenLib.CAENVME_WriteCycle(
            self.handle, c_int(vmeAddress + 0x800c), byref(c_int(segmentCode)),
            c_int(self.cvA32_S_DATA), c_int(self.cvD32))
        if status != 0:
            Data.execute('DevLogErr($1,$2)', self.getNid(),
                         'Error writing number of segments')
            raise mdsExceptions.TclFAILED_ESSENTIAL
#Global Channel Configuration
        trigModeDict = {'OVER THRESHOLD': 0, 'UNDER THRESHOLD': 1}
        try:
            trigMode = self.trig_mode.data()
        except:
            Data.execute('DevLogErr($1,$2)', self.getNid(),
                         'Invalid Trigger mode')
            raise mdsExceptions.TclFAILED_ESSENTIAL
        trigModeCode = trigModeDict[trigMode]
        conf = trigModeCode << 6
        conf = conf | 0x00000010
        status = CAENDT5720.caenLib.CAENVME_WriteCycle(
            self.handle, c_int(vmeAddress + 0x8000), byref(c_int(conf)),
            c_int(self.cvA32_S_DATA), c_int(self.cvD32))
        if status != 0:
            Data.execute('DevLogErr($1,$2)', self.getNid(),
                         'Error writing group configuration')
            raise mdsExceptions.TclFAILED_ESSENTIAL

#Channel configurations
        trigEnableCode = 0
        chanEnableCode = 0
        enabledDict = {'ENABLED': 1, 'DISABLED': 0}
        numChannels = self.num_channels.data()
        for chan in range(0, numChannels):
            #threshold level
            threshold = getattr(self,
                                'channel_%d_thresh_level' % (chan + 1)).data()
            status = CAENDT5720.caenLib.CAENVME_WriteCycle(
                self.handle, c_int(vmeAddress + 0x1080 + chan * 0x100),
                byref(c_int(threshold)), c_int(self.cvA32_S_DATA),
                c_int(self.cvD32))
            if status != 0:
                Data.execute('DevLogErr($1,$2)', self.getNid(),
                             'Error writing threshold level')
                raise mdsExceptions.TclFAILED_ESSENTIAL
#threshold samples
            threshSamples = getattr(self, 'channel_%d_thresh_sampl' %
                                    (chan + 1)).data()
            status = CAENDT5720.caenLib.CAENVME_WriteCycle(
                self.handle, c_int(vmeAddress + 0x1084 + chan * 0x100),
                byref(c_int(threshSamples)), c_int(self.cvA32_S_DATA),
                c_int(self.cvD32))
            if status != 0:
                Data.execute('DevLogErr($1,$2)', self.getNid(),
                             'Error writing threshold samples')
                raise mdsExceptions.TclFAILED_ESSENTIAL
#offset
            offset = getattr(self, 'channel_%d_offset' % (chan + 1)).data()
            if (offset > 1):
                offset = 1.
            if (offset < -1):
                offset = -1
            offset = (offset / 1.) * 32767
            status = CAENDT5720.caenLib.CAENVME_WriteCycle(
                self.handle, c_int(vmeAddress + 0x1098 + chan * 0x100),
                byref(c_int(int(offset + 0x08000))), c_int(self.cvA32_S_DATA),
                c_int(self.cvD32))
            if status != 0:
                Data.execute('DevLogErr($1,$2)', self.getNid(),
                             'Error writing DAC offset')
                raise mdsExceptions.TclFAILED_ESSENTIAL
#states
            state = getattr(self, 'channel_%d_state' % (chan + 1)).data()
            chanEnableCode = chanEnableCode | (enabledDict[state] << chan)
            trigState = getattr(self,
                                'channel_%d_trig_state' % (chan + 1)).data()
            trigEnableCode = trigEnableCode | (enabledDict[trigState] << chan)

#endfor chan in range(0,numChannels)

#Set channel enabled mask
        status = CAENDT5720.caenLib.CAENVME_WriteCycle(
            self.handle, c_int(vmeAddress + 0x8120),
            byref(c_int(chanEnableCode)), c_int(self.cvA32_S_DATA),
            c_int(self.cvD32))
        if status != 0:
            Data.execute('DevLogErr($1,$2)', self.getNid(),
                         'Error writing Channel enable register')
            raise mdsExceptions.TclFAILED_ESSENTIAL
        status = CAENDT5720.caenLib.CAENVME_WriteCycle(
            self.handle, c_int(vmeAddress + 0x810C),
            byref(c_int(trigEnableCode)), c_int(self.cvA32_S_DATA),
            c_int(self.cvD32))
        if status != 0:
            Data.execute('DevLogErr($1,$2)', self.getNid(),
                         'Error writing Channel trigger enable register')
            raise mdsExceptions.TclFAILED_ESSENTIAL

#Set trigger enabling
        trigExt = self.trig_ext.data()
        trigEnableCode = trigEnableCode | (enabledDict[trigExt] << 30)
        trigSoft = self.trig_soft.data()
        trigEnableCode = trigEnableCode | (enabledDict[trigSoft] << 31)
        status = CAENDT5720.caenLib.CAENVME_WriteCycle(
            self.handle, c_int(vmeAddress + 0x810C),
            byref(c_int(trigEnableCode)), c_int(self.cvA32_S_DATA),
            c_int(self.cvD32))
        if status != 0:
            Data.execute('DevLogErr($1,$2)', self.getNid(),
                         'Error writing trigger configuration')
            raise mdsExceptions.TclFAILED_ESSENTIAL

#Front Panel trigger out setting set TRIG/CLK to TTL
        data = 1
        status = CAENDT5720.caenLib.CAENVME_WriteCycle(
            self.handle, c_int(vmeAddress + 0x811C), byref(c_int(data)),
            c_int(self.cvA32_S_DATA), c_int(self.cvD32))

        #trigger source
        try:
            trigSource = self.trig_source.data()
            #if trigger is expressed as an array, consider only the first element
            if len(self.trig_source.getShape()) > 0:
                trigSource = trigSource[0]
        except:
            Data.execute('DevLogErr($1,$2)', self.getNid(),
                         'Cannot resolve Trigger source')
            raise mdsExceptions.TclFAILED_ESSENTIAL

#Clock source
        clockMode = self.clock_mode.data()
        if clockMode == 'EXTERNAL':
            try:
                clockSource = self.clock_source()
            except:
                Data.execute('DevLogErr($1,$2)', self.getNid(),
                             'Cannot resolve Clock source')
                raise mdsExceptions.TclFAILED_ESSENTIAL
        else:
            clockSource = Range(None, None, Float64(1 / 250E6))
            self.clock_source.putData(clockSource)

#Post Trigger Samples
        try:
            pts = self.pts.data()
        except:
            Data.execute('DevLogErr($1,$2)', self.getNid(),
                         'Cannot resolve PTS Samples')
            raise mdsExceptions.TclFAILED_ESSENTIAL
        segmentSize = 1048576 / nSegments
        if pts > segmentSize:
            Data.execute('DevLogErr($1,$2)', self.getNid(),
                         'PTS Larger than segmentSize')
            raise mdsExceptions.TclFAILED_ESSENTIAL
        status = CAENDT5720.caenLib.CAENVME_WriteCycle(
            self.handle, c_int(vmeAddress + 0x8114), byref(c_int(pts >> 2)),
            c_int(self.cvA32_S_DATA), c_int(self.cvD32))

        #Time management
        useTime = self.use_time.data()
        if useTime == 'YES':
            try:
                startTime = self.start_time.data()
                endTime = self.end_time.data()
            except:
                Data.execute('DevLogErr($1,$2)', self.getNid(),
                             'Cannot Read Start or End time')
                raise mdsExceptions.TclFAILED_ESSENTIAL
            if endTime > 0:
                endIdx = Data.execute(
                    'x_to_i($1, $2)',
                    Dimension(Window(0, segmentSize, trigSource), clockSource),
                    Float64(endTime + trigSource))
            else:
                endIdx = -Data.execute(
                    'x_to_i($1,$2)',
                    Dimension(Window(0, segmentSize, trigSource + endTime),
                              clockSource), Float64(trigSource))
            self.end_idx.putData(Int32(endIdx + 0.5))
            if startTime > 0:
                startIdx = Data.execute(
                    'x_to_i($1, $2)',
                    Dimension(Window(0, segmentSize, trigSource), clockSource),
                    startTime + trigSource)
            else:
                startIdx = -Data.execute(
                    'x_to_i($1,$2)',
                    Dimension(Window(0, segmentSize, trigSource + startTime),
                              clockSource), trigSource)
            self.start_idx.putData(Int32(startIdx + 0.5))
#Internal/External clock
#      print 'startIdx: ', startIdx
#      print 'endIdx: ', endIdx
#      print 'SEGMENT SIZE: ', segmentSize, pts
#      print 'PTS: ', pts
        currStartIdx = segmentSize - pts + startIdx.data()
        #      print 'currStartIdx: ', currStartIdx
        if currStartIdx < 0:
            Data.execute('DevLogErr($1,$2)', self.getNid(),
                         'Invalid segment size/pre-trigger samples')
            raise mdsExceptions.TclFAILED_ESSENTIAL

        currEndIdx = segmentSize - pts + endIdx.data()
        #      print 'segmentSize: ', segmentSize
        #      print 'PTS: ', pts
        #      print 'endIdx: ', endIdx
        #      print 'currEndIdx: ', currEndIdx
        if currEndIdx >= segmentSize:
            Data.execute('DevLogErr($1,$2)', self.getNid(),
                         'Invalid segment size/post-trigger samples')
            raise mdsExceptions.TclFAILED_ESSENTIAL

        acqMode = self.acq_mode.data()
        if acqMode == 'CONTINUOUS' or acqMode == 'CONTINUOUS WITH COUNTER':
            irqEvents = self.irq_events.data()
            irqEvents = irqEvents - 1
            if irqEvents < 1:
                irqEvents = 1
            status = CAENDT5720.caenLib.CAENVME_WriteCycle(
                self.handle, c_int(vmeAddress + 0xEF18),
                byref(c_int(irqEvents)), c_int(self.cvA32_S_DATA),
                c_int(self.cvD32))
            if status != 0:
                Data.execute('DevLogErr($1,$2)', self.getNid(),
                             'Error setting IRQ events')
                raise mdsExceptions.TclFAILED_ESSENTIAL
            status = CAENDT5720.caenLib.CAENVME_WriteCycle(
                self.handle, c_int(vmeAddress + 0xEF00), byref(c_int(0x09)),
                c_int(self.cvA32_S_DATA), c_int(self.cvD32))
            if status != 0:
                Data.execute('DevLogErr($1,$2)', self.getNid(),
                             'Error setting IRQ line')
                raise mdsExceptions.TclFAILED_ESSENTIAL
            status = CAENDT5720.caenLib.CAENVME_IRQEnable(
                self.handle, c_int(0x01))
            if status != 0:
                Data.execute('DevLogErr($1,$2)', self.getNid(),
                             'Error Enabling IRQ')
                raise mdsExceptions.TclFAILED_ESSENTIAL
#Start asynchronous readout
            self.start_store()
        #endif acqMode == 'CONTINUOUS SAMPLING'
# Run device
        runCommand = 4
        if clockMode == 'EXTERNAL':
            runCommand = runCommand | 0x00000040
        status = CAENDT5720.caenLib.CAENVME_WriteCycle(
            self.handle, c_int(vmeAddress + 0x8100), byref(c_int(4)),
            c_int(self.cvA32_S_DATA), c_int(self.cvD32))
        self.saveInfo()
        return
Exemple #11
0
    def init(self):

        self.debugPrint('================= 11 PXI 6259 Init ===============')


#Module in acquisition check
        if self.restoreInfo() == self.DEV_IS_OPEN :
            try:
               self.restoreWorker()
               if self.worker.isAlive():
                  print 'stop Store'
                  self.stop_store()
               self.restoreInfo()
            except:
               pass

        aiConf = c_void_p(0)
        NI6259AI.niInterfaceLib.pxi6259_create_ai_conf_ptr(byref(aiConf))
        try:
            inputMode = self.inputModeDict[self.input_mode.data()]
        except:
            Data.execute('DevLogErr($1,$2)', self.getNid(), 'Invalid Input Mode')
            raise DevBAD_PARAMETER
        if(inputMode == self.AI_CHANNEL_TYPE_DIFFERENTIAL):
            numChannels = 16
        else:
            numChannels = 32

#Channel configuration
        activeChan = 0;
        for chan in range(0, numChannels):
                    
            #Empy the node which will contain  the segmented data   
            getattr(self, 'channel_%d_data_raw'%(chan+1)).deleteData()

            getattr(self, 'channel_%d_data_raw'%(chan+1)).setCompressOnPut(False)
            try:
                enabled = self.enableDict[getattr(self, 'channel_%d_state'%(chan+1)).data()]
                polarity = self.polarityDict[getattr(self, 'channel_%d_polarity'%(chan+1)).data()]
                gain = self.gainDict[getattr(self, 'channel_%d_range'%(chan+1)).data()]
 
                data = Data.compile("NIpxi6259analogInputScaled(build_path($), build_path($), $ )", getattr(self, 'channel_%d_data_raw'%(chan+1)).getPath(),  getattr(self, 'channel_%d_calib_param'%(chan+1)).getPath(), gain )
                data.setUnits("Volts")
                getattr(self, 'channel_%d_data'%(chan+1)).putData(data)
            except Exception as e:
                self.debugPrint (estr(e))
                Data.execute('DevLogErr($1,$2)', self.getNid(), 'Invalid Configuration for channel '+str(chan + 1))
                raise DevBAD_PARAMETER
            if(enabled):
                if(inputMode == self.AI_CHANNEL_TYPE_DIFFERENTIAL):
                    currChan = self.diffChanMap[chan]
                else:
                    currChan = chan
                #self.debugPrint 'POLARITY: ' + str(polarity) + ' GAIN: ' + str(gain) + ' INPUT MODE: ' + str(inputMode)
                status = NI6259AI.niLib.pxi6259_add_ai_channel(aiConf, c_byte(currChan), polarity, gain, inputMode, c_byte(0))
                if(status != 0):
                    Data.execute('DevLogErr($1,$2)', self.getNid(), 'Cannot add channel '+str(currChan + 1))
                    raise DevBAD_PARAMETER
                #self.debugPrint('PXI 6259 CHAN '+ str(currChan+1) + ' CONFIGURED')
                activeChan = activeChan + 1
        #endfor

        """
        try:
            nSamples = self.num_samples.data()
        except:
            nSamples = -1
        """

#Acquisition management
        try:
            acqMode = self.acq_mode.data()
        except:
            Data.execute('DevLogErr($1,$2)', self.getNid(), 'Cannot resolve acquisition mode management')
            raise DevBAD_PARAMETER

#trigger mode
        try:
            trigMode = self.trig_mode.data()
            self.debugPrint('PXI 6259 Trigger mode: ', trigMode)
            if(trigMode == 'EXTERNAL_PFI1' or  trigMode == 'EXTERNAL_RTSI1' or trigMode == 'EXT_PFI1_R_RTSI1'):
                #self.debugPrint "AI_START_SELECT ", self.AI_START_SELECT
                #self.debugPrint "aiConf ", aiConf
                #self.debugPrint "AI_START_SELECT_PFI1 ", self.AI_START_SELECT_PFI1
                #self.debugPrint "niLib ", NI6259AI.niLib
                #self.debugPrint "AI_START_POLARITY ", self.AI_START_POLARITY
                #self.debugPrint "AI_START_POLARITY_RISING_EDGE ", self.AI_START_POLARITY_RISING_EDGE

                if(acqMode == 'TRANSIENT REC.'):
                    """
                    status = NI6259AI.niLib.pxi6259_set_ai_attribute(aiConf, self.AI_START_SELECT, self.AI_START_SELECT_PULSE)
                    self.debugPrint "status ", status
                    if( status == 0 ):
                        status = NI6259AI.niLib.pxi6259_set_ai_attribute(aiConf, self.AI_REFERENCE_SELECT, self.AI_REFERENCE_SELECT_PFI1)
                        self.debugPrint "status ", status
                    if( status == 0 ):
                        status = NI6259AI.niLib.pxi6259_set_ai_attribute(aiConf, self.AI_REFERENCE_POLARITY, self.AI_REFERENCE_POLARITY_RISING_EDGE)
                        self.debugPrint "status ", status
                    if( status != 0 ):
                        self.debugPrint "status ", status
                        Data.execute('DevLogErr($1,$2)', self.getNid(), 'Cannot set external trigger')
                        raise mdsExceptions.TclFAILED_ESSENTIAL
                    """
                    if( trigMode == 'EXTERNAL_PFI1' or trigMode == 'EXT_PFI1_R_RTSI1' ):
                        status = NI6259AI.niLib.pxi6259_set_ai_attribute(aiConf, self.AI_START_SELECT, self.AI_START_SELECT_PFI1)
                        self.debugPrint('AI_START_SELECT_PFI1 %d'%(status) ) 
                    else:
                        self.debugPrint("1 OK AI_START_SELECT_RTSI1")
                        status = NI6259AI.niLib.pxi6259_set_ai_attribute(aiConf, self.AI_START_SELECT, self.AI_START_SELECT_RTSI1)
                    if( status == 0 ):
                        status = NI6259AI.niLib.pxi6259_set_ai_attribute(aiConf, self.AI_START_POLARITY, self.AI_START_POLARITY_RISING_EDGE)
                        self.debugPrint('AI_START_POLARITY_RISING_EDGE %d'%(status) ) 
                    if( status != 0 ):
                        Data.execute('DevLogErr($1,$2)', self.getNid(), 'Cannot set external trigger')
                        raise DevBAD_PARAMETER                    
                    
                else:
                    if( trigMode == 'EXT_PFI1_R_RTSI1' ):
                         status = NI6259AI.niLib.pxi6259_set_ai_attribute(aiConf, self.AI_START_SELECT, self.AI_START_SELECT_PFI1)
                    else:
                         self.debugPrint("2 OK AI_START_SELECT_RTSI1")
                         status = NI6259AI.niLib.pxi6259_set_ai_attribute(aiConf, self.AI_START_SELECT, self.AI_START_SELECT_RTSI1)

                    if( status == 0 ):
                        status = NI6259AI.niLib.pxi6259_set_ai_attribute(aiConf, self.AI_START_POLARITY, self.AI_START_POLARITY_RISING_EDGE)
                    if( status != 0 ):
                        Data.execute('DevLogErr($1,$2)', self.getNid(), 'Cannot set external trigger')
                        raise DevBAD_PARAMETER


                if( trigMode == 'EXT_PFI1_R_RTSI1' ):
                    status = NI6259AI.niLib.pxi6259_export_ai_signal( aiConf, self.PXI6259_AI_START_TRIGGER,  self.PXI6259_RTSI1 )
                    if( status != 0 ):
                        Data.execute('DevLogErr($1,$2)', self.getNid(), 'Cannot route PFI1 signal to RTSI1')
                        raise DevBAD_PARAMETER
            else:
                #self.debugPrint "AI_START_SELECT ", self.AI_START_SELECT
                #self.debugPrint "aiConf ", aiConf
                #self.debugPrint "AI_START_SELECT_PFI1 ", self.AI_START_SELECT_PFI1
                #self.debugPrint "niLib ", NI6259AI.niLib
                #self.debugPrint "AI_START_POLARITY ", self.AI_START_POLARITY
                #self.debugPrint "AI_START_POLARITY_RISING_EDGE ", self.AI_START_POLARITY_RISING_EDGE
                #self.debugPrint "acqMode ", acqMode

                if(acqMode == 'TRANSIENT REC.'):
                    #status = NI6259AI.niLib.pxi6259_set_ai_attribute(aiConf, self.AI_START_SELECT, self.AI_START_SELECT_PULSE)
                    #if( status == 0 ):
                    status = NI6259AI.niLib.pxi6259_set_ai_attribute(aiConf, self.AI_REFERENCE_SELECT, self.AI_REFERENCE_SELECT_PULSE)
                    #if( status == 0 ):
                    #    status = NI6259AI.niLib.pxi6259_set_ai_attribute(aiConf, self.AI_REFERENCE_POLARITY, self.AI_REFERENCE_POLARITY_RISING_EDGE)
                    if( status != 0 ):
                        Data.execute('DevLogErr($1,$2)', self.getNid(), 'Cannot set external trigger')
                        raise DevBAD_PARAMETER

        except:
            traceback.print_exc(file=sys.stdout)
            Data.execute('DevLogErr($1,$2)', self.getNid(), 'Invalid triger mode definition')
            raise DevBAD_PARAMETER

#trigger source
        try:
            if(trigMode == 'EXTERNAL_PFI1' or trigMode == 'EXTERNAL_RTSI1' or trigMode == 'SW_RTSI1'):
                trigSource = self.trig_source.data()
            else:
                try:
                    trigSource = self.trig_source.data()
		except:
		    trigSource = 0;
            self.debugPrint('PXI 6259 Trigger source: ',trigSource)
        except:
            Data.execute('DevLogErr($1,$2)', self.getNid(), 'Cannot resolve Trigger source')
            raise DevBAD_PARAMETER

#clock mode
        try:
            clockMode = self.clock_mode.data()
            if(clockMode == 'INTERNAL'):
                frequency = self.clock_freq.data()
                if( ( activeChan == 1 and frequency > 1250000 ) or ( activeChan > 1 and frequency > 1000000./activeChan ) ):
                    self.debugPrint('PXI 6259 Frequency out of limits')
                    if( activeChan == 1 ):
                        frequency = 1250000.
                    else:
                        frequency = 1000000./activeChan
                    self.clock_source.putData(frequency)


                divisions = int(20000000./frequency)
                status = NI6259AI.niLib.pxi6259_set_ai_sample_clk(aiConf, c_int(divisions), c_int(3), self.AI_SAMPLE_SELECT_SI_TC, self.AI_SAMPLE_POLARITY_RISING_EDGE)
                if(status != 0):
                    Data.execute('DevLogErr($1,$2)', self.getNid(), 'Cannot Set Sample Clock')
                    raise DevBAD_PARAMETER
                """
                if nSamples > 0:
                    clockSource = Range(Float64(0), Float64(nSamples * divisions/20000000.) , Float64(divisions/20000000.))
                else:
                    clockSource = Range(Float64(0), Float64(3600), Float64(divisions/20000000.))
                """
                clockSource = Range(None, None, Float64(divisions/20000000.))
                self.debugPrint('PXI 6259 CLOCK: ', clockSource)
                self.clock_source.putData(clockSource)
            else:
                clockSource = self.clock_source.evaluate()
                status = NI6259AI.niLib.pxi6259_set_ai_sample_clk(aiConf, c_int(16), c_int(3), self.AI_SAMPLE_SELECT_PFI0, self.AI_SAMPLE_POLARITY_RISING_EDGE)
                if(status != 0):
                    Data.execute('DevLogErr($1,$2)', self.getNid(), 'Cannot configure device clock')
                    raise DevBAD_PARAMETER

            convClk = self.conv_clk.data()
            if ( activeChan == 1 and convClk == 20 ) :
                convClk = 16  


            status = NI6259AI.niLib.pxi6259_set_ai_convert_clk(aiConf, c_int(convClk), c_int(3), self.AI_CONVERT_SELECT_SI2TC, self.AI_CONVERT_POLARITY_RISING_EDGE)
            if(status != 0):
                Data.execute('DevLogErr($1,$2)', self.getNid(), 'Cannot Set Convert Clock')
                raise DevBAD_PARAMETER
        except:
            Data.execute('DevLogErr($1,$2)', self.getNid(), 'Invalid clock definition')
            raise DevBAD_PARAMETER

#Time management
        if acqMode == 'TRANSIENT REC.':
            try:
                useTime = self.use_time.data()

            except:
                Data.execute('DevLogErr($1,$2)', self.getNid(), 'Cannot resolve time or samples management')
                raise DevBAD_PARAMETER

            if useTime == 'YES':
                try:
                    startTime = self.start_time.data()
                    endTime = self.end_time.data()

                    self.debugPrint('PXI 6259 startTime = ', startTime)
                    self.debugPrint('PXI 6259 endTime   = ', endTime)
                    self.debugPrint('PXI 6259 trigSource   = ', trigSource)


                except:
                    Data.execute('DevLogErr($1,$2)', self.getNid(), 'Cannot Read Start or End time')
                    raise DevBAD_PARAMETER


                startIdx = Data.execute('x_to_i($1, $2)', Dimension(Window(0, None, trigSource), clockSource), startTime)

                endIdx = Data.execute('x_to_i($1, $2)', Dimension(Window(0, None, trigSource), clockSource), endTime)


                """
                if endTime > 0:
                    endIdx = Data.execute('x_to_i($1, $2)', Dimension(Window(0, None, trigSource), clockSource), endTime + trigSource)
                else:
                    endIdx = -Data.execute('x_to_i($1,$2)', Dimension(Window(0, None, trigSource + endTime), clockSource), trigSource)

                self.debugPrint 'endIdx   = ', Int32(int(endIdx))
                self.end_idx.putData(Int32(int(endIdx)))

                if startTime > 0:
                    startIdx = Data.execute('x_to_i($1, $2)', Dimension(Window(0, None, trigSource), clockSource), startTime + trigSource)
                else:
                    startIdx = -Data.execute('x_to_i($1,$2)', Dimension(Window(0, None, trigSource + startTime), clockSource), trigSource)
                """
                self.debugPrint('PXI 6259 startIdx = ', Int32(int(startIdx + 0.5)))
                self.start_idx.putData(Int32(int(startIdx + 0.5)))

                self.debugPrint('PXI 6259 endIdx   = ', Int32(int(endIdx + 0.5)))
                self.end_idx.putData(Int32(int(endIdx + 0.5)))


                #self.prts.putData(Int32(int(preTrigger)))
                #self.num_samples.putData(Int32(int(postTrigger)))

            else:
                endIdx = self.end_idx.data()
                startIdx = self.start_idx.data()

                """
                postTrigger = nSamples;
                preTrigger = 0
                try:
                    preTrigger = self.prts.data()
                except:
                    preTrigger = 0
                    nSamples =  postTrigger + preTrigger
                """


            nSamples = endIdx - startIdx + 1

            postTrigger = nSamples + startIdx
            #preTrigger  = nSamples - endIdx

            if startIdx >= 0:
                    status = NI6259AI.niLib.pxi6259_set_ai_number_of_samples(aiConf, c_int(startIdx + nSamples), 0, 0)
            else:
                if trigSource > startTime:
                    self.debugPrint('PXI 6259 Acquire only post trigger')
                    nSamples = postTrigger
                    startIdx = 0
                    self.start_idx.putData(Int32(int(0)))
                    self.start_time.putData(Float32(trigSource))
                    status = NI6259AI.niLib.pxi6259_set_ai_number_of_samples(aiConf, c_int(nSamples), 0, 0)

            """
            nSamples = endIdx - startIdx + 1
            postTrigger = nSamples + startIdx
            preTrigger = nSamples - endIdx
            """
            self.debugPrint('PXI 6259 nSamples   = ', Int32(int(nSamples)))
            self.seg_length.putData(Int32(int(nSamples)))

#           status = NI6259AI.niLib.pxi6259_set_ai_number_of_samples(aiConf, c_int(postTrigger), c_int(preTrigger), 0)

        else: #Continuous Acquisition
            nSamples = -1
            #if nSamples > 0:
            #    status = NI6259AI.niLib.pxi6259_set_ai_number_of_samples(aiConf, c_int(nSamples), 0, 0)

        if(status != 0):
            Data.execute('DevLogErr($1,$2)', self.getNid(), 'Cannot Set Number of Samples')
            raise DevBAD_PARAMETER

        status = NI6259AI.niLib.pxi6259_load_ai_conf(c_int(self.fd), aiConf)
        if(status != 0):
            Data.execute('DevLogErr($1,$2)', self.getNid(), 'Cannot load configuration')
            raise DevBAD_PARAMETER

        """
        if acqMode == 'TRANSIENT REC.':
            status = niLib.pxi6259_start_ai(c_int(self.fd))
            #status = 0

            if(status != 0):
                Data.execute('DevLogErr($1,$2)', self.device.getNid(), 'Cannot Start Acquisition ')
                return
        """
        self.saveInfo()
        self.debugPrint("===============================================")
        return 1
Exemple #12
0
 def nciInfo(self):
     with Tree('pytree',self.shot+7,'new') as pytree:
         pytree.addNode('pytreesub','subtree').include_in_pulse=True
         Device.PyDevice('TestDevice').Add(pytree,'TESTDEVICE')
         Device.PyDevice('CYGNET4K').Add(pytree,'CYGNET4K').on=False
         pytree.write()
     with Tree('pytreesub',self.shot+7,'new') as pytreesub:
         ip=pytreesub.addNode('ip','signal')
         ip.record=Signal(Int32(range(10)),None,Range(1.,10.))
         ip.tag='MAG_PLASMA_CURRENT'
         ip.tag='MAGNETICS_PLASMA_CURRENT'
         ip.tag='MAG_IP'
         ip.tag='MAGNETICS_IP'
         ip.tag='IP'
         ip.setExtendedAttribute('ATT1',100)
         ip.setExtendedAttribute('ATT2',Range(1,200))
         ip.setExtendedAttribute('ATT3','this is ip')
         ip.setExtendedAttribute('ATT3','this is plasma current')
         self.assertEqual(str(ip.getExtendedAttribute('ATT1')),'100')
         self.assertEqual(str(ip.getExtendedAttribute('ATT2')),'1 : 200 : *')
         self.assertEqual(str(ip.getExtendedAttribute('ATT3')),'this is plasma current')
         exattr = ip.getExtendedAttributes()
         self.assertEqual(exattr['ATT1'],100)
         self.assertEqual(str(exattr['ATT2']),'1 : 200 : *')
         self.assertEqual(exattr['ATT3'],'this is plasma current')
         for i in range(3):
             node=pytreesub.addNode('child%02d' % (i,),'structure')
             node.addDevice('dt200_%02d' % (i,),'dt200').on=False
         pytreesub.write()
     pytree.readonly()
     self.assertEqual(pytree.TESTDEVICE.__class__,Device.PyDevice('TESTDEVICE'))
     self.assertEqual(pytree.CYGNET4K.__class__,Device.PyDevice('CYGNET4K'))
     pytree.CYGNET4K.persistent = {}
     pytree.CYGNET4K.persistent['a'] = 1
     self.assertEqual(pytree.getNode('CYGNET4K').frames.persistent['a'], 1)
     ip=pytree.getNode('\\ip')
     self.assertEqual(ip.getUsage(),'SIGNAL')
     self.assertEqual(ip.usage,ip.getUsage())
     try: # do not continue and print when no match
         self.assertEqual(ip.getClass(),'CLASS_R')
     except AssertionError:
         print( "ip.nid=%d" % (ip.nid,))
         print( "Error with ip in %s" % (str(ip.tree),))
         raise
     self.assertEqual(ip.class_str,'CLASS_R')
     self.assertEqual(ip.compressible,False)
     self.assertEqual(ip.compressible,ip.isCompressible())
     self.assertEqual(ip.compress_on_put,True)
     self.assertEqual(ip.compress_on_put,ip.isCompressOnPut())
     self.assertEqual(ip.data_in_nci,False)
     self.assertEqual(ip.on,True)
     self.assertEqual(ip.on,ip.isOn())
     self.assertEqual(ip.do_not_compress,False)
     self.assertEqual(ip.do_not_compress,ip.isDoNotCompress())
     self.assertEqual(ip.dtype_str,'DTYPE_SIGNAL')
     self.assertEqual(ip.dtype_str,ip.getDtype())
     self.assertEqual(ip.essential,False)
     self.assertEqual(ip.essential,ip.isEssential())
     mhdtree=pytree.getNode('\\PYTREESUB::TOP')
     self.assertEqual(mhdtree.include_in_pulse,True)
     self.assertEqual(mhdtree.include_in_pulse,mhdtree.isIncludeInPulse())
     self.assertEqual(ip.length,int(Data.execute('getnci($,"LENGTH")',ip)))
     self.assertEqual(ip.length,ip.getLength())
     self.assertEqual(ip.no_write_shot,False)
     self.assertEqual(ip.no_write_shot,ip.isNoWriteShot())
     self.assertEqual(ip.no_write_model,False)
     self.assertEqual(ip.no_write_model,ip.isNoWriteModel())
     self.assertEqual(ip.write_once,False)
     self.assertEqual(ip.write_once,ip.isWriteOnce())
     pydev = pytree.TESTDEVICE
     part = pydev.conglomerate_nids[1]
     self.assertEqual(part.PART_NAME(),':ACTIONSERVER')
     self.assertEqual(part.original_part_name,':ACTIONSERVER')
     self.assertEqual(str(Data.execute('GETNCI($,"ORIGINAL_PART_NAME")',part)),':ACTIONSERVER')
     self.assertEqual(pydev.__class__,Device.PyDevice('TestDevice'))
     devs = pytree.getNodeWild('\\PYTREESUB::TOP.***','DEVICE')
     part = devs[0].conglomerate_nids[3]
     self.assertEqual(part.original_part_name,':COMMENT')
     self.assertEqual(part.original_part_name,str(Data.execute('GETNCI($,"ORIGINAL_PART_NAME")',part)))
     self.assertEqual(ip.owner_id,ip.getOwnerId())
     self.assertEqual(ip.rlength,136)
     self.assertEqual(ip.rlength,ip.getCompressedLength())
     self.assertEqual(ip.setup_information,False)
     self.assertEqual(ip.setup_information,ip.isSetup())
     self.assertEqual(ip.status,0)
     self.assertEqual(ip.status,ip.getStatus())
     self.assertEqual((ip.tags==Array(['IP','MAGNETICS_IP','MAG_IP','MAGNETICS_PLASMA_CURRENT','MAG_PLASMA_CURRENT'])).all(),True)
     self.assertEqual((ip.tags==ip.getTags()).all(),True)
     self.assertEqual(ip.time_inserted,ip.getTimeInserted())
Exemple #13
0
    def init(self):

        if self.restoreInfo() == 0:
            Data.execute('DevLogErr($1,$2)', self.getNid(),
                         'Cannot open DT5720 Device')
            return 0

        vmeAddress = 0

        #Module Reset
        data = c_int(0)
        status = CAENDT5720.caenLib.CAENVME_WriteCycle(
            self.handle, c_int(vmeAddress + 0xEF24), byref(data),
            c_int(self.cvA32_S_DATA), c_int(self.cvD32))
        if status != 0:
            Data.execute('DevLogErr($1,$2)', self.getNid(),
                         'Error resetting DT5720 Device')
            CAENDT5720.caenLib.CAENVME_End(self.handle)
            return 0

        #give some time
        sleep(0.1)

        #Module type
        devType = c_int(0)
        status = CAENDT5720.caenLib.CAENVME_ReadCycle(
            self.handle, c_int(vmeAddress + 0x8140), byref(devType),
            c_int(self.cvA32_S_DATA), c_int(self.cvD32))
        if status != 0:
            Data.execute('DevLogErr($1,$2)', self.getNid(),
                         'Error reading board info')
            CAENDT5720.caenLib.CAENVME_End(self.handle)
            return 0

        if (devType.value & 0x000000FF) != 0 and (devType.value
                                                  & 0x000000FF) != 0x3:
            Data.execute('DevLogErr($1,$2)', self.getNid(),
                         'Invalid board type. Device must be DT5720 model')
            return 0

        if (devType.value & 0x000000FF) == 0:
            if (devType.value & 0x0000FF00) >> 8 == 0x01:
                self.chanMemory = self.MEM_512kS
            else:
                self.chanMemory = self.MEM_4MS

        if (devType.value & 0x000000FF) == 0x3:
            if (devType.value & 0x0000FF00) >> 8 == 0x2:
                #self.chanMemory = self.MEM_1_25MS
                self.chanMemory = self.MEM_1MS
            else:
                self.chanMemory = self.MEM_10MS

        print('Channel Memory: ', self.chanMemory)

        numChannels = devType.value >> 16
        print('DevType code: ', devType.value)
        print('NUM CHANNELS: ', numChannels)
        print('Channel Memory: ', self.chanMemory)
        self.num_channels.putData(numChannels)
        """
      print "write decimation factor. Not Yet implemented"
      status = CAENDT5720.caenLib.CAENVME_WriteCycle(self.handle, c_int(vmeAddress + 0x8044), byref(c_int(0x2)), c_int(self.cvA32_S_DATA), c_int(self.cvD32))
      if status != 0:
        Data.execute('DevLogErr($1,$2)', self.getNid(), 'Error writing decimation' )
        return 0
      """

        #Number of segments
        segmentDict = {
            1: 0,
            2: 1,
            4: 2,
            8: 3,
            16: 4,
            32: 5,
            64: 6,
            128: 7,
            256: 8,
            512: 9,
            1024: 10
        }
        try:
            nSegments = self.num_segments.data()
        except:
            Data.execute('DevLogErr($1,$2)', self.getNid(),
                         'Invalid Number of Segments')
            return 0
        segmentCode = segmentDict[nSegments]
        status = CAENDT5720.caenLib.CAENVME_WriteCycle(
            self.handle, c_int(vmeAddress + 0x800c), byref(c_int(segmentCode)),
            c_int(self.cvA32_S_DATA), c_int(self.cvD32))
        #print "Buffer Organization 0x800C ", segmentCode
        if status != 0:
            Data.execute('DevLogErr($1,$2)', self.getNid(),
                         'Error writing number of segments')
            return 0

        #Global Channel Configuration
        trigModeDict = {'OVER THRESHOLD': 0, 'UNDER THRESHOLD': 1}
        try:
            trigMode = self.trig_mode.data()
        except:
            Data.execute('DevLogErr($1,$2)', self.getNid(),
                         'Invalid Trigger mode')
            return 0
        trigModeCode = trigModeDict[trigMode]
        conf = trigModeCode << 6
        conf = conf | 0x00000010
        status = CAENDT5720.caenLib.CAENVME_WriteCycle(
            self.handle, c_int(vmeAddress + 0x8000), byref(c_int(conf)),
            c_int(self.cvA32_S_DATA), c_int(self.cvD32))
        if status != 0:
            Data.execute('DevLogErr($1,$2)', self.getNid(),
                         'Error writing group configuration')
            return 0

        #Channel configurations
        trigEnableCode = 0
        chanEnableCode = 0
        enabledDict = {'ENABLED': 1, 'DISABLED': 0}
        numChannels = self.num_channels.data()
        for chan in range(0, numChannels):

            #Empy the node which will contain  the segmented data
            getattr(self, 'channel_%d_seg_raw' % (chan + 1)).deleteData()

            #Set threshold level
            threshold = getattr(self,
                                'channel_%d_thresh_level' % (chan + 1)).data()
            status = CAENDT5720.caenLib.CAENVME_WriteCycle(
                self.handle, c_int(vmeAddress + 0x1080 + chan * 0x100),
                byref(c_int(threshold)), c_int(self.cvA32_S_DATA),
                c_int(self.cvD32))
            if status != 0:
                Data.execute('DevLogErr($1,$2)', self.getNid(),
                             'Error writing threshold level')
                return 0

            #Set threshold samples
            threshSamples = getattr(self, 'channel_%d_thresh_sampl' %
                                    (chan + 1)).data()
            status = CAENDT5720.caenLib.CAENVME_WriteCycle(
                self.handle, c_int(vmeAddress + 0x1084 + chan * 0x100),
                byref(c_int(threshSamples)), c_int(self.cvA32_S_DATA),
                c_int(self.cvD32))
            if status != 0:
                Data.execute('DevLogErr($1,$2)', self.getNid(),
                             'Error writing threshold samples')
                return 0

            #Read FIRMWARE info
            """
        firmware = c_uint(0)
        status = CAENDT5720.caenLib.CAENVME_ReadCycle(self.handle, c_int(vmeAddress + 0x108C + chan * 0x100), byref(firmware), c_int(self.cvA32_S_DATA), c_int(self.cvD32))
        print "firmware  AMC FPGA Addr ", hex(vmeAddress + 0x108C + chan * 0x100), hex((firmware.value >> 16) & 0x0000ffff), " Version ", hex((firmware.value >> 8) & 0x000000ff), ".", hex((firmware.value ) & 0x000000ff)
        """
            dac_offset = getattr(self,
                                 'channel_%d_dac_offset' % (chan + 1)).data()

            #Channel offset compensation
            try:
                offset = getattr(self, 'channel_%d_offset' % (chan + 1)).data()
            except:
                offset = 0

            #Set offset
            offset = offset + dac_offset
            print('Ch ', chan, 'Offset Volt = ', offset)
            if (offset > 1.125):
                offset = 1.125
            if (offset < -1.125):
                offset = -1.125
            offset = (offset / 1.125) * 32767
            print('Ch ', chan, 'Offset Val. =', int(offset))

            status = CAENDT5720.caenLib.CAENVME_WriteCycle(
                self.handle, c_int(vmeAddress + 0x1098 + chan * 0x100),
                byref(c_int(int(offset + 0x08000))), c_int(self.cvA32_S_DATA),
                c_int(self.cvD32))
            if status != 0:
                Data.execute('DevLogErr($1,$2)', self.getNid(),
                             'Error writing DAC offset')
                return 0

            #Enable channel
            state = getattr(self, 'channel_%d_state' % (chan + 1)).data()
            chanEnableCode = chanEnableCode | (enabledDict[state] << chan)

            #Enable Trigger
            trigState = getattr(self,
                                'channel_%d_trig_state' % (chan + 1)).data()
            trigEnableCode = trigEnableCode | (enabledDict[trigState] << chan)

            #END channel configuration loop

        #Set channel enabled mask
        status = CAENDT5720.caenLib.CAENVME_WriteCycle(
            self.handle, c_int(vmeAddress + 0x8120),
            byref(c_int(chanEnableCode)), c_int(self.cvA32_S_DATA),
            c_int(self.cvD32))
        if status != 0:
            Data.execute('DevLogErr($1,$2)', self.getNid(),
                         'Error writing Channel enable register')
            return 0

        #Set channel trigger mask
        status = CAENDT5720.caenLib.CAENVME_WriteCycle(
            self.handle, c_int(vmeAddress + 0x810C),
            byref(c_int(trigEnableCode)), c_int(self.cvA32_S_DATA),
            c_int(self.cvD32))
        if status != 0:
            Data.execute('DevLogErr($1,$2)', self.getNid(),
                         'Error writing Channel trigger enable register')
            return 0

        #Set trigger enabling
        trigExt = self.trig_ext.data()
        trigEnableCode = trigEnableCode | (enabledDict[trigExt] << 30)
        trigSoft = self.trig_soft.data()
        trigEnableCode = trigEnableCode | (enabledDict[trigSoft] << 31)
        status = CAENDT5720.caenLib.CAENVME_WriteCycle(
            self.handle, c_int(vmeAddress + 0x810C),
            byref(c_int(trigEnableCode)), c_int(self.cvA32_S_DATA),
            c_int(self.cvD32))
        if status != 0:
            Data.execute('DevLogErr($1,$2)', self.getNid(),
                         'Error writing trigger configuration')
            return 0

        #Front Panel trigger out setting set TRIG/CLK to TTL
        data = 1
        status = CAENDT5720.caenLib.CAENVME_WriteCycle(
            self.handle, c_int(vmeAddress + 0x811C), byref(c_int(data)),
            c_int(self.cvA32_S_DATA), c_int(self.cvD32))

        #Configure trigger source
        """
      try:
        trigSource = self.trig_source.data()
        #Trigger source must be an array, consider only the first element as triggerSource time
        if len(self.trig_source.getShape()) > 0:
          trigSource = trigSource[0]
      except:
        Data.execute('DevLogErr($1,$2)', self.getNid(), 'Cannot resolve Trigger source')
        return 0
      """

        #Configure clock source
        # The clock source can be only INTERNAL
        clockMode = self.clock_mode.data()
        if clockMode == 'EXTERNAL':
            try:
                clockSource = self.clock_source()
            except:
                Data.execute('DevLogErr($1,$2)', self.getNid(),
                             'Cannot resolve Clock source')
                return 0
        else:
            clockSource = Range(None, None,
                                Float64(1 / self.InternalFrequency))
            self.clock_source.putData(clockSource)

        #Configure Post Trigger Samples
        try:
            pts = int(self.pts.data())
        except:
            Data.execute('DevLogErr($1,$2)', self.getNid(),
                         'Cannot resolve PTS Samples')
            return 0
        segmentSize = self.chanMemory / nSegments
        if pts > segmentSize:
            Data.execute('DevLogErr($1,$2)', self.getNid(),
                         'PTS Larger than segmentSize')
            return 0
        status = CAENDT5720.caenLib.CAENVME_WriteCycle(
            self.handle, c_int(vmeAddress + 0x8114), byref(c_int(pts >> 1)),
            c_int(self.cvA32_S_DATA), c_int(self.cvD32))

        #Time management compute endIdx and startIdx
        useTime = self.use_time.data()
        if useTime == 'YES':
            try:
                #Start and End Index acquisition burst calculation is prfomend with trigger time set to 0
                trigSource = 0.
                startTime = self.start_time.data()
                endTime = self.end_time.data()
            except:
                Data.execute('DevLogErr($1,$2)', self.getNid(),
                             'Cannot Read Start or End time')
                return 0
            if endTime > 0:
                endIdx = Data.execute(
                    'x_to_i($1, $2)',
                    Dimension(Window(0, segmentSize, trigSource), clockSource),
                    Float64(endTime + trigSource))
            else:
                endIdx = -Data.execute(
                    'x_to_i($1,$2)',
                    Dimension(Window(0, segmentSize, trigSource + endTime),
                              clockSource), Float64(trigSource))
            self.end_idx.putData(Int32(int(endIdx + 0.5)))
            if startTime > 0:
                startIdx = Data.execute(
                    'x_to_i($1, $2)',
                    Dimension(Window(0, segmentSize, trigSource), clockSource),
                    startTime + trigSource)
            else:
                startIdx = -Data.execute(
                    'x_to_i($1,$2)',
                    Dimension(Window(0, segmentSize, trigSource + startTime),
                              clockSource), trigSource)
            self.start_idx.putData(Int32(int(startIdx + 0.5)))

        currStartIdx = int(segmentSize - pts + startIdx.data())
        if currStartIdx < 0:
            Data.execute('DevLogErr($1,$2)', self.getNid(),
                         'Invalid segment size/pre-trigger samples')
            return 0

        currEndIdx = int(segmentSize - pts + endIdx.data())
        if currEndIdx >= segmentSize:
            Data.execute('DevLogErr($1,$2)', self.getNid(),
                         'Invalid segment size/post-trigger samples')
            return 0

        print('startIdx      : ', int(startIdx))
        print('endIdx        : ', int(endIdx))
        print('SEGMENT SIZE  : ', int(segmentSize))
        print('PTS           : ', pts)
        print('currStartIdx  : ', currStartIdx)
        print('currEndIdx    : ', currEndIdx)

        usbLink = (self.board_id.data() >= 10)
        acqMode = self.acq_mode.data()
        if not usbLink and (acqMode == 'CONTINUOUS'
                            or acqMode == 'CONTINUOUS WITH COUNTER'
                            or acqMode == 'TRANSIENT RECORDER'):

            irqEvents = self.irq_events.data()
            irqEvents = irqEvents - 1
            if irqEvents < 1:
                irqEvents = 1

            status = CAENDT5720.caenLib.CAENVME_WriteCycle(
                self.handle, c_int(vmeAddress + 0xEF18),
                byref(c_int(irqEvents)), c_int(self.cvA32_S_DATA),
                c_int(self.cvD32))
            if status != 0:
                Data.execute('DevLogErr($1,$2)', self.getNid(),
                             'Error setting IRQ events')
                return 0

            status = CAENDT5720.caenLib.CAENVME_WriteCycle(
                self.handle, c_int(vmeAddress + 0xEF00), byref(c_int(0x09)),
                c_int(self.cvA32_S_DATA), c_int(self.cvD32))
            if status != 0:
                Data.execute('DevLogErr($1,$2)', self.getNid(),
                             'Error setting IRQ line')
                return 0

            status = CAENDT5720.caenLib.CAENVME_IRQEnable(
                self.handle, c_int(0x01))
            if status != 0:
                Data.execute('DevLogErr($1,$2)', self.getNid(),
                             'Error Enabling IRQ')
                return 0
            #Start asynchronous readout thread
            #self.start_store()
            #endif acqMode == 'CONTINUOUS SAMPLING'

        self.saveInfo()

        return 1
Exemple #14
0
    def init(self):

        try:
            fifoDepthSize = self.fifo_depth.data();
        except:
            Data.execute('DevLogErr($1,$2)', self.getNid(), 'Fifo depth undefined, value set to defaul 40000')
            fifoDepthSize = 40000
            self.fifo_depth.putData(Int32(fifoDepthSize))

        try:
            boardId = self.board_id.data();
            boardIdDev='RIO%d'%(int(boardId))  
            print ('-------->'+boardIdDev)
        except:
            Data.execute('DevLogErr($1,$2)', self.getNid(), 'Board Identifier undefined')
            raise DevBAD_PARAMETER

        try:

            if self.restoreInfo() == self.DEV_IS_OPEN :
               if self.restoreWorker():
                  if self.worker.isAlive():
                      print ('stop Store')
                      self.stop_store()
                      self.wait_store()
               self.closeInfo()
               sleep(1)

            self.initializeInfo(boardIdDev, fifoDepthSize)
        except Exception as ex:
            Data.execute('DevLogErr($1,$2)', self.getNid(), 'Cannot open MPAG device : %s'%(str(ex)))
            raise mdsExceptions.TclFAILED_ESSENTIAL


        self.saveInfo()

        try:
            bufferSize = self.buf_size.data();
        except:
            Data.execute('DevLogErr($1,$2)', self.getNid(), 'Acquisition Buffer size undefined, value set to defaul 1000')
            bufferSize = 1000
            self.buf_size.putData(Int32(bufferSize))


        try:
            segmentLength = self.seg_length.data();
        except:
            Data.execute('DevLogErr($1,$2)', self.getNid(), 'Acquisition Segment length undefined, value set to defaul 10000')
            segmentLength = 10000
            self.seg_size.putData(Int32(segmentLength))



#clock mode
        try:
            clockMode = self.clock_mode.data()
            print ('ClockMode -------->'+clockMode)
            if clockMode == 'INTERNAL' :
                frequency = self.clock_freq.data()
                print (frequency)
                if( frequency > self.MAX_ACQ_FREQUENCY ):
                    frequency = self.MAX_ACQ_FREQUENCY
                    self.debugPrint('cRIO MPAG Frequency out of limits. Set to max frequency value : %f' %(self.MAX_ACQ_FREQUENCY))
                    self.clock_freq.putData(frequency)

                clockSource = Range(None, None, Float64(1./frequency))
                print (clockSource)
                self.debugPrint('cRIO MPAG CLOCK: ', clockSource)
                self.clock_source.putData(clockSource)
            else:
                clockSource = self.clock_source.evaluate()
                print (clockSource)
                frequency = self.clock_freq.data()
        except Exception as ex:
            Data.execute('DevLogErr($1,$2)', self.getNid(), 'Invalid clock definition : '+str(ex))
            raise DevBAD_PARAMETER

#trigger source
        try:
            trigMode = self.trig_mode.data()
            print ('Trig --------> '+trigMode)
            if trigMode == 'EXTERNAL':
                trigSource = self.trig_source.data()
            else:
                try:
                    trigSource = self.trig_source.data()
                except:
                    trigSource = 0;
                    self.trig_source.putData(Float32(trigSource))
            self.debugPrint('cRIO MPAG Trigger source: ',trigSource)
        except Exception as ex:
            Data.execute('DevLogErr($1,$2)', self.getNid(), 'Cannot resolve Trigger source : '+str(ex))
            raise DevBAD_PARAMETER


#Time management
        """
        try:
            acqMode = self.acq_mode.data()
        except:
            Data.execute('DevLogErr($1,$2)', self.getNid(), 'Acquisition Mode undefined')
            raise DevBAD_PARAMETER
        """
        acqMode = 'CONTINUOUS'
        if acqMode == 'TRANSIENT REC.':
            try:
                useTime = self.use_time.data()
            except:
                Data.execute('DevLogErr($1,$2)', self.getNid(), 'Cannot resolve time or samples management')
                raise DevBAD_PARAMETER

            if useTime == 'YES':
                try:
                    startTime = self.start_time.data()
                    endTime   = self.end_time.data()

                    self.debugPrint('cRIO MPAG startTime    = ', startTime)
                    self.debugPrint('cRIO MPAG endTime      = ', endTime)
                    self.debugPrint('cRIO MPAG trigSource   = ', trigSource)
                except:
                    Data.execute('DevLogErr($1,$2)', self.getNid(), 'Cannot Read Start or End time')
                    raise DevBAD_PARAMETER

                startIdx = Data.execute('x_to_i($1, $2)', Dimension(Window(0, None, trigSource), clockSource), startTime)
                endIdx   = Data.execute('x_to_i($1, $2)', Dimension(Window(0, None, trigSource), clockSource), endTime)


                self.debugPrint('cRIO MPAG  startIdx = ', Int32(int(startIdx + 0.5)))
                self.start_idx.putData(Int32(int(startIdx + 0.5)))

                self.debugPrint('cRIO MPAG  endIdx   = ', Int32(int(endIdx + 0.5)))
                self.end_idx.putData(Int32(int(endIdx + 0.5)))

            else:
                endIdx   = self.end_idx.data()
                startIdx = self.start_idx.data()

            #Solo acquisizione continua per il momento
            nSamples = -1

        else: #Continuous Acquisition
            nSamples = -1
 

#Channel configuration
        #activeChan = 0
        #chanState = []
        #chanNid = []
        #resNid = []

        mapToAO_Array =c_int32*16
        mapToAO = mapToAO_Array()

        for slave in ['a','b','c']:
            for chan in range(1, self.NUM_SLAVE_CHANNEL+1):                   
                #Empy the node which will contain  the segmented data   
                dataRawNode = getattr(self, 'slave_crio_%c_channel_%02d_data_raw'%(slave, chan))
                dataRawNode.deleteData()
                dataRawNode.setCompressOnPut(False)
                dataResNode = getattr(self, 'slave_crio_%c_channel_%02d_res_raw'%(slave, chan))  
                dataResNode.deleteData()
                dataResNode.setCompressOnPut(False)

        for adcIdx in ['1','2']:
            for chan in range(1, self.NUM_9220_CHANNEL+1):                   
                #Empy the node which will contain  the segmented data   
                dataRawNode = getattr(self, 'ni_9220_%c_channel_%02d_data_raw'%(adcIdx, chan))
                dataRawNode.deleteData()
                dataRawNode.setCompressOnPut(False)
                dataResNode = getattr(self, 'ni_9220_%c_channel_%02d_res_raw'%(adcIdx, chan))  
                dataResNode.deleteData()
                dataResNode.setCompressOnPut(False)


        #Da definire in base alla frequenza di acquisizione impostata

        #highStrobeTick = 50 
        highStrobeTick = int(1e6/frequency)*6 

        status = CRIO_MPAG.niInterfaceLib.setMpagAcqParam(self.session, c_float(frequency), c_uint16(highStrobeTick), mapToAO) 
        if status < 0 :
            Data.execute('DevLogErr($1,$2)', self.getNid(), 'cRIO MPAG acquisition device initialization error.')
            return 0

        """
        status = CRIO_MPAG.niInterfaceLib.startMpagFpga(self.session)
        if status < 0 :
            Data.execute('DevLogErr($1,$2)', self.getNid(), 'cRIO MPAG start FPGA error.')
            return 0
        """

        return 1
Exemple #15
0
class CAENDT5724(Device):
    Int32(1).setTdiVar('_PyReleaseThreadLock')
    """CAEN DT5724 4 Channels 14 Bit 100MS/S Digitizer"""
    parts=[{'path':':BOARD_ID', 'type':'numeric', 'value':0},
      {'path':':COMMENT', 'type':'text'},
      {'path':':TRIG_MODE', 'type':'text', 'value':'OVER THRESHOLD'},
      {'path':':TRIG_SOFT', 'type':'text', 'value':'ENABLED'},
      {'path':':TRIG_EXT', 'type':'text', 'value':'ENABLED'},
      {'path':':TRIG_SOURCE', 'type':'numeric'},
      {'path':':CLOCK_MODE', 'type':'text', 'value':'250 MHz'},
      {'path':':CLOCK_SOURCE', 'type':'numeric'},
      {'path':':NUM_SEGMENTS', 'type':'numeric','value':1024},
      {'path':':USE_TIME', 'type':'text', 'value':'YES'},
      {'path':':PTS', 'type':'numeric','value':1024},
      {'path':':START_IDX', 'type':'numeric','value':0},
      {'path':':END_IDX', 'type':'numeric','value':1024},
      {'path':':START_TIME', 'type':'numeric','value':0},
      {'path':':END_TIME', 'type':'numeric','value':1E-6},
      {'path':':ACQ_MODE', 'type':'text','value':'TRANSIENT RECORDER'},
      {'path':':IRQ_EVENTS', 'type':'numeric','value':0}]
    for i in range(0,4):
        parts.append({'path':'.CHANNEL_%d'%(i+1), 'type':'structure'})
        parts.append({'path':'.CHANNEL_%d:STATE'%(i+1), 'type':'text', 'value':'ENABLED'})
        parts.append({'path':'.CHANNEL_%d:TRIG_STATE'%(i+1), 'type':'text', 'value':'DISABLED'})
        parts.append({'path':'.CHANNEL_%d:OFFSET'%(i+1), 'type':'numeric', 'value':0})
        parts.append({'path':'.CHANNEL_%d:DAC_OFFSET'%(i+1), 'type':'numeric', 'value':0})
        parts.append({'path':'.CHANNEL_%d:THRESH_LEVEL'%(i+1), 'type':'numeric', 'value':0})
        parts.append({'path':'.CHANNEL_%d:THRESH_SAMPL'%(i+1), 'type':'numeric', 'value':0})
        parts.append({'path':'.CHANNEL_%d:DATA'%(i+1), 'type':'signal'})
        parts.append({'path':'.CHANNEL_%d:SEG_RAW'%(i+1), 'type':'signal'})
    del i
    parts.append({'path':':INIT_ACTION','type':'action',
	  'valueExpr':"Action(Dispatch('PXI_SERVER','INIT',50,None),Method(None,'init',head))",
	  'options':('no_write_shot',)})
    parts.append({'path':':START_ACTION','type':'action',
	  'valueExpr':"Action(Dispatch('PXI_SERVER','STORE',50,None),Method(None,'start_store',head))",
	  'options':('no_write_shot',)})
    parts.append({'path':':STOP_ACTION','type':'action',
	  'valueExpr':"Action(Dispatch('PXI_SERVER','STORE',50,None),Method(None,'stop_store',head))",
	  'options':('no_write_shot',)})
    parts.append({'path':':NUM_CHANNELS', 'type':'numeric','value':0})

    cvV1718 = 0L                    # CAEN V1718 USB-VME bridge    
    cvV2718 = 1L                    # V2718 PCI-VME bridge with optical link       
    cvA2818 = 2L                    # PCI board with optical link                  
    cvA2719 = 3L                    # Optical link piggy-back                      
    cvA32_S_DATA = 0x0D             # A32 supervisory data access                  */
    cvD32 = 0x04		    # D32
    cvD64 = 0x08
    IRQw = 0
    cv = 0
    #readCv = 1234
    worker = 0    
    handle = 0

    MEM_512kS = 524288
    MEM_4MS   = 4194304
    InternalFrequency = 100E6
    #chanMemory = 0

    HANDLE_RESTORE = 1L
    HANDLE_OPEN  = 2L


#Support Class for IRQ Wait
    class IRQWait(Thread):
      def configure(self, handle, cv, readCv):
        self.handle = handle
        self.cv = cv
        self.readCv = readCv
      def run(self):
        import time
        from ctypes import CDLL, c_int, c_short, c_long, byref, Structure
        global caenLib
        while 0 == 0:
          self.readCv.acquire()
          self.readCv.wait()
          self.readCv.release()
          #print 'waiting IRQ'
          status = caenLib.CAENVME_IRQWait(self.handle, c_long(0x01), c_long(1000000))
          #print 'IRQ Received'
          self.cv.acquire()
          self.cv.notify()
          self.cv.release()
    #end class IRQWait        
    
#Support class for continuous store
    class AsynchStore(Thread):
      import time;
      stopReq = False
      startIdx = 0
      endIdx = 0;
      pts = 0
      actChannels = 0
      trigTime = 0
      dt = 0
      boardId = 0
      cvV1718 = 0L                    # CAEN V1718 USB-VME bridge    
      cvV2718 = 1L                    # V2718 PCI-VME bridge with optical link       
      cvA2818 = 2L                    # PCI board with optical link                  
      cvA2719 = 3L                    # Optical link piggy-back                      
      cvA32_S_DATA = 0x0D             # A32 supervisory data access                 
      cvD32 = 0x04		      # D32
      cvD64 = 0x08


      #startTimeArray = []
      #endTimeArray = []
      dtArray = []
      segmentCounter = 0
      
      def configure(self, handle, acqMode, startIdx, endIdx, pts, actChans, nActChans, dt, trigTime, triggerSourceNid, segmentSamples, segmentSize, chanMask, nid, device, cv, readCv, useCounter, irqEvents):

        self.handle   = handle
        self.startIdx = startIdx
        self.endIdx   = endIdx
        self.acqMode = acqMode
        self.pts      = pts
        self.actChans = actChans
        self.nActChans = nActChans
        self.dt = dt
        self.trigTime = trigTime
        self.segmentSamples = segmentSamples
        self.segmentSize = segmentSize
        self.chanMask = chanMask
        self.nid = nid
        self.device = device
        self.cv = cv
        self.readCv = readCv
        self.useCounter = useCounter
        self.irqEvents = irqEvents
        self.triggerSourceNid = triggerSourceNid
        self.saveList = c_void_p(0)


      def run(self):
        global caenLib
        global caenInterfaceLib

        class DT5720Data(Structure):
          _fields_ = [("eventSize", c_int), ("boardGroup", c_int), ("counter", c_int), ("time", c_int), ("data", c_short * (self.segmentSamples * self.nActChans))]


        treePtr = c_void_p(0)
        status = caenInterfaceLib.openTree(c_char_p(self.device.getTree().name), c_int(self.device.getTree().shot), byref(treePtr))

        caenInterfaceLib.startSave(byref(self.saveList))


        vmeAddress = 0
 
        currStartIdx    = self.segmentSamples - self.pts + self.startIdx
        currEndIdx      = self.segmentSamples - self.pts + self.endIdx
        currChanSamples = currEndIdx - currStartIdx
        numChannels     = self.device.num_channels.data()
        clockNid        = self.device.clock_source.getNid()
        triggNid        = self.device.trig_source.getNid()
        numTrigger      = 0


        channels = [] 
        chanNid  = []

        if self.acqMode == "TRANSIENT RECORDER":
           numTrigger = len(self.device.trig_source.getData())
	else:
           #continuous
           numTrigger = -1
        
        for chan in range(0,numChannels):
          channels.append([])
          chanNid.append( getattr(self.device, 'channel_%d_seg_raw'%(chan+1)).getNid() )   

        chanNid_c = (c_int * len(chanNid) )(*chanNid)

        currSegmentIdx = 0
        segmentCounter = 0
        self.dtArray = []	

        while not self.stopReq:
          self.readCv.acquire()
          self.readCv.notify()
          self.readCv.release()
          self.cv.acquire()
          print 'WAIT CONDITION'
          self.cv.wait()
          self.cv.release()
          print 'CONDITION ISSUED'

	  # Read number of buffers 
	  actSegments = c_int(0)
	  status = caenLib.CAENVME_ReadCycle(self.handle, c_int(vmeAddress + 0x812C), byref(actSegments), c_int(self.cvA32_S_DATA), c_int(self.cvD32))
	  if status != 0:
	     print 'Error reading number of acquired segments' 
             continue


          segmentCounter = caenInterfaceLib.readAndSaveSegments(self.handle, c_int(vmeAddress), c_int(numChannels), c_int(self.nActChans), c_int(self.segmentSamples), c_int(self.segmentSize), 
                                            c_int(self.startIdx), c_int(self.endIdx), c_int(self.pts),  c_int(self.useCounter),  c_int(self.chanMask), c_int(segmentCounter), 
                                            c_int(numTrigger), chanNid_c, clockNid, triggNid, treePtr, self.saveList)



          if self.acqMode == "TRANSIENT RECORDER" and segmentCounter == numTrigger :
            print 'Transient Recoder acquisition completed!!!!'
            return 0

          if self.stopReq :
            print 'ASYNCH STORE EXITED!!!!'
            return 0
          status = caenLib.CAENVME_IRQEnable(self.handle, c_int(0x01));
        #endwhile self.stopReq == 0:

        return 0
        
      def stop(self):
        global caenInterfaceLib

        self.stopReq = True
        self.cv.acquire()
        self.cv.notify()
        self.cv.release()

        #need to wait a while
        time.sleep(0.5)

        caenInterfaceLib.stopSave(self.saveList)
        self.saveList = c_void_p(0)
        
    #end class AsynchStore

    def saveInfo(self):
      global caenHandles
      global caenCvs
      global caenReadCvs
      global caenWorkers
      global caenNids
      try:
        caenHandles
      except:
	caenHandles = []
        caenCvs     = []
        caenReadCvs = []
        caenWorkers = []
        caenNids    = []
      try:
        idx = caenNids.index(self.getNid())
      except:
        caenHandles.append(self.handle)
        caenCvs.append(self.cv)
        caenReadCvs.append(self.readCv)
        caenWorkers.append(self.worker)
        caenNids.append(self.nid)
        return
      caenHandles[idx] = self.handle
      caenCvs[idx] = self.cv
      caenReadCvs[idx] = self.readCv
      if caenWorkers[idx] != 0:
         caenWorkers[idx].stop()
         caenWorkers[idx].stopReq = True
      caenWorkers[idx] = self.worker
      return

    def saveWorker(self):
      global caenWorkers
      global caenNids

      idx = caenNids.index(self.getNid())
      caenWorkers[idx] = self.worker


    def restoreInfo(self):
      global caenHandles
      global caenCvs
      global caenWorkers
      global nids
      global caenLib
      global caenInterfaceLib
      from ctypes import CDLL, c_int, c_short, c_long, byref, Structure
      try:
        caenLib
      except:
        caenLib = CDLL("libCAENVME.so")

      try:
        caenLib
      except:
          print 'Error loading library libCAENVME.so' 
          return 0
        
      try:
        caenInterfaceLib
      except:
        caenInterfaceLib = CDLL("libCaenInterface.so")

      try:
        caenInterfaceLib
      except:
          print 'Error loading library libCaenInterface.so' 
          return 0
        
      try:
        idx = caenNids.index(self.getNid())
        self.handle = caenHandles[idx]
        self.cv = caenCvs[idx]
        self.readCv = caenReadCvs[idx]
        self.worker = caenWorkers[idx]
        return self.HANDLE_RESTORE
      except:
        try:
          boardId = self.board_id.data()
        except:
          Data.execute('DevLogErr($1,$2)', self.getNid(), 'Invalid Board ID specification')
          return 0
        self.handle = c_long(0)
        print 'HANDLE NON TROVATO ADESSO INIZIALIZZO DRIVER'
        status = caenLib.CAENVME_Init(c_int(self.cvV2718), c_int(0), c_int(boardId), byref(self.handle))
        if status != 0:
          print 'Error initializing CAENVME' 
          return 0
        
        self.cv     = Condition()
        self.readCv = Condition()
        print "recsv", self.readCv 
        IRQw = self.IRQWait()
        IRQw.daemon = True
        IRQw.configure(self.handle, self.cv, self.readCv)
        IRQw.start()
        
      return self.HANDLE_OPEN
 


################################# INIT ###############################
    def init(self):
      global caenLib
 
      if self.restoreInfo() == 0 : 
        Data.execute('DevLogErr($1,$2)', self.getNid(), 'Cannot open DT5724 Device' )
        return 0

      vmeAddress = 0
  
      #Module Reset
      data = c_int(0)
      status = caenLib.CAENVME_WriteCycle(self.handle, c_int(vmeAddress + 0xEF24), byref(data), c_int(self.cvA32_S_DATA), c_int(self.cvD32))
      if status != 0:
        Data.execute('DevLogErr($1,$2)', self.getNid(), 'Error resetting DT5724 Device' )
        return 0
	
      #give some time
      time.sleep(0.1)

      #Module type
      devType = c_int(0)
      status = caenLib.CAENVME_ReadCycle(self.handle, c_int(vmeAddress + 0x8140), byref(devType), c_int(self.cvA32_S_DATA), c_int(self.cvD32))
      if status != 0:
        Data.execute('DevLogErr($1,$2)', self.getNid(), 'Error reading board info')
        return 0

      if (devType.value & 0x000000FF) != 0 :
        Data.execute('DevLogErr($1,$2)', self.getNid(), 'Invalid board type. Device must be DT5724 model')
        return 0

      print "self", self

      if (devType.value & 0x0000FF00) >> 8 == 0x01 :
        print 'mem: ', self.MEM_512kS
        self.chanMemory = self.MEM_512kS
      else:
        print 'mem: ', self.MEM_4MS
        self.chanMemory = self.MEM_4MS
        print 'Channel Memory: ', self.chanMemory
 
      #self.chanMemory = chanMemory
      numChannels = devType.value >> 16
      print 'DevType code: ', devType.value
      print 'NUM CHANNELS: ', numChannels
      print 'Channel Memory: ', self.chanMemory
      self.num_channels.putData(numChannels)

      """      
      print "write decimation factor. Not Yet implemented"  	
      status = caenLib.CAENVME_WriteCycle(self.handle, c_int(vmeAddress + 0x8044), byref(c_int(0x2)), c_int(self.cvA32_S_DATA), c_int(self.cvD32))
      if status != 0:
        Data.execute('DevLogErr($1,$2)', self.getNid(), 'Error writing decimation' )
        return 0
      """

      #Number of segments
      segmentDict = {1:0, 2:1, 4:2, 8:3, 16:4, 32:5, 64:6, 128:7, 256:8, 512:9, 1024:10}
      try:
        nSegments=self.num_segments.data()
      except:
        Data.execute('DevLogErr($1,$2)', self.getNid(), 'Invalid Number of Segments')
        return 0
      segmentCode = segmentDict[nSegments]
      status = caenLib.CAENVME_WriteCycle(self.handle, c_int(vmeAddress + 0x800c), byref(c_int(segmentCode)), c_int(self.cvA32_S_DATA), c_int(self.cvD32))
      #print "Buffer Organization 0x800C ", segmentCode
      if status != 0:
        Data.execute('DevLogErr($1,$2)', self.getNid(), 'Error writing number of segments' )
        return 0

      #Global Channel Configuration
      trigModeDict = {'OVER THRESHOLD':0, 'UNDER THRESHOLD':1}
      try:
        trigMode = self.trig_mode.data()
      except:
        Data.execute('DevLogErr($1,$2)', self.getNid(), 'Invalid Trigger mode')
        return 0
      trigModeCode = trigModeDict[trigMode]
      conf = trigModeCode << 6
      conf = conf | 0x00000010
      status = caenLib.CAENVME_WriteCycle(self.handle, c_int(vmeAddress + 0x8000), byref(c_int(conf)), c_int(self.cvA32_S_DATA), c_int(self.cvD32))
      if status != 0:
        Data.execute('DevLogErr($1,$2)', self.getNid(), 'Error writing group configuration')
        return 0

      #Channel configurations
      trigEnableCode = 0L
      chanEnableCode = 0L
      enabledDict = {'ENABLED':1, 'DISABLED':0}
      numChannels = self.num_channels.data()
      for chan in range(0,numChannels):
        #Set threshold level
        threshold = getattr(self, 'channel_%d_thresh_level'%(chan+1)).data()
        status = caenLib.CAENVME_WriteCycle(self.handle, c_int(vmeAddress + 0x1080 + chan * 0x100), byref(c_int(threshold)), c_int(self.cvA32_S_DATA), c_int(self.cvD32))
        if status != 0:
          Data.execute('DevLogErr($1,$2)', self.getNid(), 'Error writing threshold level')
          return 0

        #Set threshold samples
        threshSamples = getattr(self, 'channel_%d_thresh_sampl'%(chan+1)).data()
        status = caenLib.CAENVME_WriteCycle(self.handle, c_int(vmeAddress + 0x1084 + chan * 0x100), byref(c_int(threshSamples)), c_int(self.cvA32_S_DATA), c_int(self.cvD32))
        if status != 0:
          Data.execute('DevLogErr($1,$2)', self.getNid(), 'Error writing threshold samples')
          return 0

        #Read FIRMWARE info
        """
        firmware = c_uint(0)
        status = caenLib.CAENVME_ReadCycle(self.handle, c_int(vmeAddress + 0x108C + chan * 0x100), byref(firmware), c_int(self.cvA32_S_DATA), c_int(self.cvD32))
        print "firmware  AMC FPGA Addr ", hex(vmeAddress + 0x108C + chan * 0x100), hex((firmware.value >> 16) & 0x0000ffff), " Version ", hex((firmware.value >> 8) & 0x000000ff), ".", hex((firmware.value ) & 0x000000ff)
        """
        
        dac_offset = getattr(self, 'channel_%d_dac_offset'%(chan+1)).data()

	#Channel offset compensation
        try:        
          offset = getattr(self, 'channel_%d_offset'%(chan+1)).data()	  
        except:
          offset = 0;
	
        #Set offset
        offset = offset + dac_offset
        print 'Offset V ',offset
        if(offset > 1.125):
          offset = 1.125
        if(offset < -1.125):
          offset = -1.125
        offset = (offset / 1.125) * 32767
        print 'Offset ',offset


        status = caenLib.CAENVME_WriteCycle(self.handle, c_int(vmeAddress + 0x1098 + chan * 0x100), byref(c_int(int(offset + 0x08000))), c_int(self.cvA32_S_DATA), c_int(self.cvD32))
        if status != 0:
          Data.execute('DevLogErr($1,$2)', self.getNid(), 'Error writing DAC offset')
          return 0

        #Enable channel
        state = getattr(self, 'channel_%d_state'%(chan+1)).data()
        chanEnableCode = chanEnableCode | (enabledDict[state] << chan)

        #Enable Trigger
        trigState = getattr(self, 'channel_%d_trig_state'%(chan+1)).data()
        trigEnableCode = trigEnableCode | (enabledDict[trigState] << chan)

        #END channel configuration loop
      
      #Set channel enabled mask
      status = caenLib.CAENVME_WriteCycle(self.handle, c_int(vmeAddress + 0x8120), byref(c_int(chanEnableCode)), c_int(self.cvA32_S_DATA), c_int(self.cvD32))
      if status != 0:
        Data.execute('DevLogErr($1,$2)', self.getNid(), 'Error writing Channel enable register')
        return 0


      #Set channel trigger mask
      status = caenLib.CAENVME_WriteCycle(self.handle, c_int(vmeAddress + 0x810C), byref(c_int(trigEnableCode)), c_int(self.cvA32_S_DATA), c_int(self.cvD32))
      if status != 0:
        Data.execute('DevLogErr($1,$2)', self.getNid(), 'Error writing Channel trigger enable register')
        return 0

      #Set trigger enabling
      trigExt = self.trig_ext.data()
      trigEnableCode = trigEnableCode | (enabledDict[trigExt] << 30)
      trigSoft = self.trig_soft.data()
      trigEnableCode = trigEnableCode | (enabledDict[trigSoft] << 31)
      status = caenLib.CAENVME_WriteCycle(self.handle, c_int(vmeAddress + 0x810C), byref(c_int(trigEnableCode)), c_int(self.cvA32_S_DATA), c_int(self.cvD32))
      if status != 0:
        Data.execute('DevLogErr($1,$2)', self.getNid(), 'Error writing trigger configuration')
        return 0

      #Front Panel trigger out setting set TRIG/CLK to TTL
      data = 1
      status = caenLib.CAENVME_WriteCycle(self.handle, c_int(vmeAddress + 0x811C), byref(c_int(data)), c_int(self.cvA32_S_DATA), c_int(self.cvD32))

      #Configure trigger source
      try:
        trigSource = self.trig_source.data()
        #If trigger is expressed as an array, consider only the first element as triggerSource time
        if len(self.trig_source.getShape()) > 0:
          trigSource = trigSource[0]
      except:
        Data.execute('DevLogErr($1,$2)', self.getNid(), 'Cannot resolve Trigger source')
        return 0

      #Configure clock source
      # The clock source can be only INTERNAL
      clockMode = self.clock_mode.data()
      if clockMode == 'EXTERNAL':
        try:
          clockSource = self.clock_source()
        except:
          Data.execute('DevLogErr($1,$2)', self.getNid(), 'Cannot resolve Clock source')
          return 0
      else:
        clockSource = Range(None, None, Float64(1/self.InternalFrequency))
        self.clock_source.putData(clockSource)

      #Configure Post Trigger Samples
      try:
        pts = int( self.pts.data() )
      except:
        Data.execute('DevLogErr($1,$2)', self.getNid(), 'Cannot resolve PTS Samples')
        return 0
      segmentSize = self.chanMemory/nSegments 
      if pts > segmentSize:
        Data.execute('DevLogErr($1,$2)', self.getNid(), 'PTS Larger than segmentSize')
        return 0
      status = caenLib.CAENVME_WriteCycle(self.handle, c_int(vmeAddress + 0x8114), byref(c_int(pts>>1)), c_int(self.cvA32_S_DATA), c_int(self.cvD32))

     
      #Time management compute endIdx and startIdx
      useTime=self.use_time.data()
      if useTime == 'YES':
        try:
          print "trigsource [0]", trigSource
          startTime = self.start_time.data()
          endTime = self.end_time.data()
        except:
          Data.execute('DevLogErr($1,$2)', self.getNid(), 'Cannot Read Start or End time')
          return 0
        if endTime > 0:
          endIdx = Data.execute('x_to_i($1, $2)', Dimension(Window(0, segmentSize, trigSource), clockSource), Float64(endTime + trigSource))
        else:
          endIdx = -Data.execute('x_to_i($1,$2)', Dimension(Window(0, segmentSize, trigSource + endTime), clockSource), Float64(trigSource))
        self.end_idx.putData(Int32(int(endIdx + 0.5)))
        if startTime > 0:
          startIdx = Data.execute('x_to_i($1, $2)', Dimension(Window(0, segmentSize, trigSource), clockSource), startTime + trigSource)
        else:
          startIdx = -Data.execute('x_to_i($1,$2)', Dimension(Window(0, segmentSize, trigSource + startTime), clockSource), trigSource)
        self.start_idx.putData(Int32(int(startIdx + 0.5)))

      currStartIdx = int(segmentSize - pts + startIdx.data())
      if currStartIdx < 0:
          Data.execute('DevLogErr($1,$2)', self.getNid(), 'Invalid segment size/pre-trigger samples')
          return 0

      currEndIdx = int(segmentSize - pts + endIdx.data())
      if currEndIdx >= segmentSize:
          Data.execute('DevLogErr($1,$2)', self.getNid(), 'Invalid segment size/post-trigger samples')
          return 0

      print 'startIdx      : ', int(startIdx)
      print 'endIdx        : ', int(endIdx)
      print 'SEGMENT SIZE  : ', int(segmentSize)
      print 'PTS           : ', pts
      print 'currStartIdx  : ', currStartIdx
      print 'currEndIdx    : ', currEndIdx

      acqMode = self.acq_mode.data()
      if acqMode == 'CONTINUOUS' or acqMode == 'CONTINUOUS WITH COUNTER' or acqMode == 'TRANSIENT RECORDER':
        irqEvents = self.irq_events.data()
        irqEvents = irqEvents - 1
        if irqEvents < 1:
          irqEvents = 1
        status = caenLib.CAENVME_WriteCycle(self.handle, c_int(vmeAddress + 0xEF18), byref(c_int(irqEvents)), c_int(self.cvA32_S_DATA), c_int(self.cvD32))
        if status != 0:
          Data.execute('DevLogErr($1,$2)', self.getNid(), 'Error setting IRQ events')
          return 0
        status = caenLib.CAENVME_WriteCycle(self.handle, c_int(vmeAddress + 0xEF00), byref(c_int(0x09)), c_int(self.cvA32_S_DATA), c_int(self.cvD32))
        if status != 0:
          Data.execute('DevLogErr($1,$2)', self.getNid(), 'Error setting IRQ line')
          return 0
        status = caenLib.CAENVME_IRQEnable(self.handle, c_int(0x01))
        if status != 0:
          Data.execute('DevLogErr($1,$2)', self.getNid(), 'Error Enabling IRQ')
          return 0
        #Start asynchronous readout thread
        #self.start_store()
      #endif acqMode == 'CONTINUOUS SAMPLING'

      self.saveInfo()
      print "Fine Init"

      return 1


################################ TRIGGER ###################################

    def trigger(self):
 
      if ( self.restoreInfo() != self.HANDLE_RESTORE and self.worker.stopReq == True ) :
        Data.execute('DevLogErr($1,$2)', self.getNid(), 'DT5724 Device not initialized' )
        return 0

      try:
        vmeAddress = 0
        #Module SW trigger
        data = c_int(0)
        status = caenLib.CAENVME_WriteCycle(self.handle, c_int(vmeAddress + 0x8108), byref(c_int(0L)), c_int(self.cvA32_S_DATA), c_int(self.cvD32))
        if status != 0:
          Data.execute('DevLogErr($1,$2)', self.getNid(), 'Error in sofware trigger DT5724 Device'  )
          return 0
        return 1
      except:
        Data.execute('DevLogErr($1,$2)', self.getNid(), 'Generic SW trigger Error'  )
        return 0


################################# START STORE ###############################
    def start_store(self):

      if ( self.restoreInfo() != self.HANDLE_RESTORE ) :
        Data.execute('DevLogErr($1,$2)', self.getNid(), 'DT5724 Device not initialized' )
        return 0

      vmeAddress = 0

      #Module type
      devType = c_int(0)
      status = caenLib.CAENVME_ReadCycle(self.handle, c_int(vmeAddress + 0x8140), byref(devType), c_int(self.cvA32_S_DATA), c_int(self.cvD32))
      if status != 0:
        Data.execute('DevLogErr($1,$2)', self.getNid(), 'Error reading board info')
        return 0

      if (devType.value & 0x000000FF) != 0 :
        Data.execute('DevLogErr($1,$2)', self.getNid(), 'Invalid board type. Device must be DT5724 model')
        return 0

      if (devType.value & 0x0000FF00) >> 8 == 0x01 :
        self.chanMemory = self.MEM_512kS
      else:
        self.chanMemory = self.MEM_4MS

      try:
        boardId = self.board_id.data()
      except:
        Data.execute('DevLogErr($1,$2)', self.getNid(), 'Invalid Board ID specification')
        return 0
      try:
        clock = self.clock_source.evaluate()
        dt = clock.getDelta().data()
      except:
        Data.execute('DevLogErr($1,$2)', self.getNid(), 'Error evaluating clock source' )
        return 0
      try:
        triggerSourceNid = TreePath(self.trig_source.getFullPath())
        trigTime = self.trig_source.data()
      except:
        Data.execute('DevLogErr($1,$2)', self.getNid(), 'Error evaluating trigger source' )
        return 0
      try:
        startIdx = self.start_idx.data()
        endIdx = self.end_idx.data()
      except:
        Data.execute('DevLogErr($1,$2)', self.getNid(), 'Error evaluating start or end idx')
        return 0
      try:
        pts = self.pts.data()
      except:
        Data.execute('DevLogErr($1,$2)', self.getNid(), 'Error evaluating Post Trigger Samples' )
        return 0
    
      #Compute Segment Size
      try:
        nSegments = self.num_segments.data()
        segmentSamples = self.chanMemory/nSegments
      except: 
        Data.execute('DevLogErr($1,$2)', self.getNid(), 'Error reading max number of segments' )
        return 0
      currStartIdx = segmentSamples - pts + startIdx
      currEndIdx = segmentSamples - pts + endIdx
    
      #Get Active channels
      chanMask = c_int(0)
      status = caenLib.CAENVME_ReadCycle(self.handle, c_int(vmeAddress + 0x8120), byref(chanMask), c_int(self.cvA32_S_DATA), c_int(self.cvD32))
      nActChans = 0
      chanMask = chanMask.value
      numChannels = self.num_channels.data()
      for chan in range(0,numChannels):
        if (chanMask & (1 << chan)) != 0:
          nActChans = nActChans + 1
      if nActChans == 0:
        print 'No active groups' 
        return 1
      segmentSize = 16 + 2 * segmentSamples * nActChans
      acqMode = self.acq_mode.data()
      
      for chan in range(0,numChannels):
        if (chanMask & (1 << chan)) != 0:
          try:        
            dac_offset = getattr(self, 'channel_%d_dac_offset'%(chan+1)).data()	  
          except:
            Data.execute('DevLogErr($1,$2)', self.getNid(), 'Error reading channel DAC offset')		  
            return 0
          if acqMode == 'CONTINUOUS WITH COUNTER':
            useCounter = True
            data = Data.compile("2.25*($1 - 8192)/16384.+$2", TreePath(getattr(self, 'channel_%d_seg_raw'%(chan+1)).getFullPath()), dac_offset);
          else:
            useCounter = False
            segRawPath = TreePath(getattr(self, 'channel_%d_seg_raw'%(chan+1)).getFullPath())
            data = Data.compile("(2.25*( $ - 8192)/16384. + $ )", segRawPath, Float32(dac_offset) )
          try:
            getattr(self, 'channel_%d_data'%(chan+1)).putData(data) 
          except:
            Data.execute('DevLogErr($1,$2)', self.getNid(), 'Error Writing data' )
            return 0
      #endfor chan in range(0,numChannels):
    
      self.worker = self.AsynchStore()        
      self.worker.daemon = True 
      self.worker.stopReq = False

      print "segmentSamples   ", segmentSamples

      self.worker.configure(self.handle, acqMode, startIdx, endIdx, pts, chanMask, nActChans, dt, trigTime, triggerSourceNid, segmentSamples, segmentSize, chanMask, self.getNid(), self, self.cv, self.readCv, useCounter, self.irq_events.data() + 1)
      self.worker.start()

      try:
        runCommand = 4
        """
          #External cllock not yet implemented 
          if clockMode == 'EXTERNAL':
          runCommand = runCommand | 0x00000040
        """
        #Module SW trigger
        data = c_int(0)
        status = caenLib.CAENVME_WriteCycle(self.handle, c_int(vmeAddress + 0x8100), byref(c_int(runCommand)), c_int(self.cvA32_S_DATA), c_int(self.cvD32))
        if status != 0:
          Data.execute('DevLogErr($1,$2)', self.getNid(), 'Error starting acquisition on DT5724 Device'  )
          return 0
      except:
        Data.execute('DevLogErr($1,$2)', self.getNid(), 'Cannot starting acquisition on DT5724 Device SW exception'  )
        return 0

      
      try:
        if  acqMode == 'TRANSIENT RECORDER':
          trigSoft = self.trig_soft.data()
          if trigSoft == 'ENABLED':
             trigSource = self.trig_source.data()
             t0 = trigSource[0]
             time.sleep(t0)
	     print "SW Trigger ", trigSource[0]
             status = caenLib.CAENVME_WriteCycle(self.handle, c_int(vmeAddress + 0x8108), byref(c_int(0L)), c_int(self.cvA32_S_DATA), c_int(self.cvD32))
             if status != 0:
               Data.execute('DevLogErr($1,$2)', self.getNid(), 'Error in sofware trigger DT5724 Device'  )
               return 0

             if len(trigSource) == 1 :
               time.sleep( 1 )
               status = caenLib.CAENVME_WriteCycle(self.handle, c_int(vmeAddress + 0x8108), byref(c_int(0L)), c_int(self.cvA32_S_DATA), c_int(self.cvD32))
               if status != 0:
                 Data.execute('DevLogErr($1,$2)', self.getNid(), 'Error in sofware trigger(1) DT5724 Device'  )
                 return 0

             for delay in trigSource[1 : ] :
               time.sleep( delay - t0 )
               t0 = delay
	       print "SW Trigger ", delay
               status = caenLib.CAENVME_WriteCycle(self.handle, c_int(vmeAddress + 0x8108), byref(c_int(0L)), c_int(self.cvA32_S_DATA), c_int(self.cvD32))
               if status != 0:
                 Data.execute('DevLogErr($1,$2)', self.getNid(), 'Error in sofware trigger DT5724 Device'  )
                 return 0
      except:
        Data.execute('DevLogErr($1,$2)', self.getNid(), 'Cannot starting acquisition on DT5724 Device SW exception'  )
        return 0
      

      self.saveWorker()

      return 1


#################################### STOP STORE ###################################
    def stop_store(self):

      print "Stop Store"

      if self.restoreInfo() != self.HANDLE_RESTORE :
        Data.execute('DevLogErr($1,$2)', self.getNid(), 'DT5724 Device not initialized' )
        return 0

      vmeAddress = 0
      #Stop device 
      status = caenLib.CAENVME_WriteCycle(self.handle, c_int(vmeAddress + 0x8100), byref(c_int(0L)), c_int(self.cvA32_S_DATA), c_int(self.cvD32))
      if status != 0:
        Data.execute('DevLogErr($1,$2)', self.getNid(), 'Error stopping device')
        return 0
      #need to wait a while
      time.sleep(0.5)

      self.worker.stop()
      del self.worker
 
      print "Fine Stop Store"

      return 1
Exemple #16
0
 def requests(self, c, idx):
     args = [Int32(i + idx + 10) for i in range(10)]
     for _ in range(20):
         self.assertEqual(
             c.get("[$,$,$,$,$,$,$,$,$,$]", *args).tolist(), args)
Exemple #17
0
    def init(self,arg):
      from MDSplus import Tree, TreeNode, Int16Array, Float64Array, Int32, Int64, Float32, Float64, Signal, Data, Dimension, Window, Range
      from ctypes import CDLL, c_int, c_short, c_long, byref, Structure
      import time
      caenLib = CDLL("libCAENVME.so")
      handle = c_long(0)
      status = caenLib.CAENVME_Init(c_int(self.cvV2718), c_int(0), c_int(0), byref(handle))
      if status != 0:
	print 'Error initializing CAENVME' 
	return 0

      try:
	baseNid = self.node.getNid()
 
   	boardId = TreeNode(baseNid + self.N_BOARD_ID).data()
    	print 'BOARD ID: ', boardId
    	vmeAddress = TreeNode(baseNid + self.N_VME_ADDRESS).data()
    	print 'VME ADDRESS: ', vmeAddress
  #Module Reset
    	data = c_int(0)
    	status = caenLib.CAENVME_WriteCycle(handle, c_int(vmeAddress + 0xEF24), byref(data), c_int(self.cvA32_S_DATA), c_int(self.cvD32))
    	if status != 0:
	    print 'Error resetting V1740 Device' 
	    caenLib.CAENVME_End(handle)
	    return 0
	
    #give some time
    	time.sleep(0.01)

#number of segments
    	segmentDict = {1:0, 2:1, 4:2, 8:3, 16:4, 32:5, 64:6, 128:7, 256:8, 512:9, 1024:10}
    	nSegments=TreeNode(baseNid+self.N_NUM_SEGMENTS).data()
    	segmentCode = segmentDict[nSegments]
    	status = caenLib.CAENVME_WriteCycle(handle, c_int(vmeAddress + 0x800c), byref(c_int(segmentCode)), c_int(self.cvA32_S_DATA), c_int(self.cvD32))
    	if status != 0:
	    print 'Error writing number of segments' 
	    caenLib.CAENVME_End(handle)
	    return 0
#Global Group Configuration
    	trigModeDict = {'OVER THRESHOLD':0, 'UNDER THRESHOLD':1}
    	trigMode = TreeNode(baseNid + self.N_TRIG_MODE).data()
    	trigModeCode = trigModeDict[trigMode]
    	conf = trigModeCode << 6
    	conf = conf | 0x00000010;
    	status = caenLib.CAENVME_WriteCycle(handle, c_int(vmeAddress + 0x8000), byref(c_int(conf)), c_int(self.cvA32_S_DATA), c_int(self.cvD32))
    	if status != 0:
	    print 'Error writing group configuration' 
	    caenLib.CAENVME_End(handle)
	    return 0

#Group configurations
    	trigEnableCode = 0L
    	chanEnableCode = 0L
    	enabledDict = {'ENABLED':1, 'DISABLED':0}
    	for group in range(0,8):
#threshold level
#	threshold = TreeNode(baseNid+self.N_CHANNEL_0 + group * K_NODES_PER_CHANNEL + self.N_CHAN_TRIG_THRESH_LEV).data()
#   	status = caenLib.CAENVME_WriteCycle(handle, c_int(vmeAddress + 0x1080 + group * 0x100), byref(c_int(threshold)), c_int#(self.cvA32_S_DATA), c_int(self.cvD32))
#    	if status != 0:
#	    print 'writing threshold level'
#	    caenLib.CAENVME_End(handle)
#	    return 0
#offset
	    offset = TreeNode(baseNid+self.N_CHANNEL_0 + group * self.K_NODES_PER_CHANNEL + self.N_CHAN_OFFSET).data()
	    if(offset > 1):
	    	offset = 1.
	    if(offset < -1):
	    	offset = -1
	    offset = (offset / 1.) * 32767
   	    status = caenLib.CAENVME_WriteCycle(handle, c_int(vmeAddress + 0x1098 + group * 0x100), byref(c_int(int(offset + 0x08000))), c_int(self.cvA32_S_DATA), c_int(self.cvD32))
    	    if status != 0:
	    	print 'Error writing DAC offset'
	    	caenLib.CAENVME_End(handle)
	    	return 0
#states
	    state = TreeNode(baseNid+self.N_CHANNEL_0 + group * self.K_NODES_PER_CHANNEL + self.N_CHAN_STATE).data()
	    chanEnableCode = chanEnableCode | (enabledDict[state] << group)
	    trigState = TreeNode(baseNid+self.N_CHANNEL_0 + group * self.K_NODES_PER_CHANNEL + self.N_CHAN_TRIG_STATE).data()
	    trigEnableCode = trigEnableCode | (enabledDict[trigState] << group)
#endfor group in range(0,8)

    	trigExt = TreeNode(baseNid + self.N_TRIG_EXT).data()
    	trigEnableCode = trigEnableCode | (enabledDict[trigExt] << 30)
    	trigSoft = TreeNode(baseNid + self.N_TRIG_SOFT).data()
    	trigEnableCode = trigEnableCode | (enabledDict[trigSoft] << 31)
    	status = caenLib.CAENVME_WriteCycle(handle, c_int(vmeAddress + 0x810C), byref(c_int(trigEnableCode)), c_int(self.cvA32_S_DATA), c_int(self.cvD32))
    	if status != 0:
	    print 'Error writing trigger configuration'
	    caenLib.CAENVME_End(handle)
	    return 0
    	status = caenLib.CAENVME_WriteCycle(handle, c_int(vmeAddress + 0x8120), byref(c_int(chanEnableCode)), c_int(self.cvA32_S_DATA), c_int(self.cvD32))
    	if status != 0:
	    print 'Error writing channel enabling'
	    caenLib.CAENVME_End(handle)
	    return 0

#Front Panel trigger out setting set TRIG/CLK to TTL
    	data = 1
    	status = caenLib.CAENVME_WriteCycle(handle, c_int(vmeAddress + 0x811C), byref(c_int(data)), c_int(self.cvA32_S_DATA), c_int(self.cvD32))

    	try:
    	    trigSource = TreeNode(baseNid + self.N_TRIG_SOURCE).data()
	
#if trigger is expressed as an array, consider only the first element
    	    print 'Trigger source: ', trigSource
	    if len(TreeNode(baseNid + self.N_TRIG_SOURCE).getShape()) > 0:
	    	trigSource = trigSource[0]
    	except:
	    print 'Cannot resolve Trigger source'
	    caenLib.CAENVME_End(handle)
	    return 0

#Clock source	
    	clockMode = TreeNode(baseNid + self.N_CLOCK_MODE).data()
    	if clockMode == 'EXTERNAL':
	    try:
   	    	clockSource = TreeNode(baseNid + self.N_CLOCK_SOURCE).getData()
    	    	print 'Clock source: ', clockSource
    	    except:
	    	print 'Cannot resolve Clock source'
	    	caenLib.CAENVME_End(handle)
	    	return 0
    	else:
	    
	    clockSource = Range(None, None, Float64(1/62.5E6))
    	    TreeNode(baseNid + self.N_CLOCK_SOURCE).putData(clockSource)

#Post Trigger Samples
    	try:
	    pts = TreeNode(baseNid + self.N_PTS).data()
    	except:
	    print 'Cannot resolve PTS samples'
	    caenLib.CAENVME_End(handle)
	    return 0
   	segmentSize = 196608/nSegments
    	if pts > segmentSize:
	    print 'PTS Larger than segmentSize'
	    caenLib.CAENVME_End(handle)
	    return 0
    	status = caenLib.CAENVME_WriteCycle(handle, c_int(vmeAddress + 0x8114), byref(c_int(pts)), c_int(self.cvA32_S_DATA), c_int(self.cvD32))

#Time management
    	useTime=TreeNode(baseNid+self.N_USE_TIME).data()
    	if useTime == 'YES':
	    try:
    	    	startTime = TreeNode(baseNid+self.N_START_TIME).data()
	    	endTime = TreeNode(baseNid+self.N_END_TIME).data()
	    except:
	    	print 'Cannot Read Start or End time'
	    	caenLib.CAENVME_End(handle)
	    	return 0
	    if endTime > 0:
	    	endIdx = Data.execute('x_to_i($1, $2)', Dimension(Window(0, None, trigSource), clockSource), endTime + trigSource)
	    else:
	    	endIdx = -Data.execute('x_to_i($1,$2)', Dimension(Window(0, None, trigSource + endTime), clockSource), trigSource)
   	    TreeNode(baseNid + self.N_END_IDX).putData(Int32(endIdx))

	    if startTime > 0:
	    	startIdx = Data.execute('x_to_i($1, $2)', Dimension(Window(0, None, trigSource), clockSource), startTime + trigSource)
	    else:
	    	startIdx = -Data.execute('x_to_i($1,$2)', Dimension(Window(0, None, trigSource + startTime), clockSource), trigSource)
   	    TreeNode(baseNid + self.N_START_IDX).putData(Int32(startIdx))

# Run device 
    	status = caenLib.CAENVME_WriteCycle(handle, c_int(vmeAddress + 0x8100), byref(c_int(4)), c_int(self.cvA32_S_DATA), c_int(self.cvD32))
    	caenLib.CAENVME_End(handle)
    	return 1
      except:
	print 'Generic Error' 
	caenLib.CAENVME_End(handle)
	return 0
Exemple #18
0
    def init(self):
        if CAENV1740.caenLib is None:
            CAENV1740.caenLib = CDLL("libCAENVME.so")
        handle = c_long(0)
        status = CAENV1740.caenLib.CAENVME_Init(c_int(self.cvV2718), c_int(0),
                                                c_int(0), byref(handle))
        if status != 0:
            print('Error initializing CAENVME')
        raise mdsExceptions.TclFAILED_ESSENTIAL

        try:
            boardId = self.board_id.data()
            print('BOARD ID: ', boardId)
            vmeAddress = self.vme_address.data()
            print('VME ADDRESS: ', vmeAddress)
            #Module Reset
            data = c_int(0)
            status = CAENV1740.caenLib.CAENVME_WriteCycle(
                handle, c_int(vmeAddress + 0xEF24), byref(data),
                c_int(self.cvA32_S_DATA), c_int(self.cvD32))
            if status != 0:
                print('Error resetting V1740 Device')
                CAENV1740.caenLib.CAENVME_End(handle)
                raise mdsExceptions.TclFAILED_ESSENTIAL

#give some time
            sleep(0.01)

            #number of segments
            segmentDict = {
                1: 0,
                2: 1,
                4: 2,
                8: 3,
                16: 4,
                32: 5,
                64: 6,
                128: 7,
                256: 8,
                512: 9,
                1024: 10
            }
            nSegments = self.num_segments.data()
            segmentCode = segmentDict[nSegments]
            status = CAENV1740.caenLib.CAENVME_WriteCycle(
                handle, c_int(vmeAddress + 0x800c), byref(c_int(segmentCode)),
                c_int(self.cvA32_S_DATA), c_int(self.cvD32))
            if status != 0:
                print('Error writing number of segments')
                CAENV1740.caenLib.CAENVME_End(handle)
                raise mdsExceptions.TclFAILED_ESSENTIAL
#Global Group Configuration
            trigModeDict = {'OVER THRESHOLD': 0, 'UNDER THRESHOLD': 1}
            trigMode = self.trig_mode.data()
            trigModeCode = trigModeDict[trigMode]
            conf = trigModeCode << 6
            conf = conf | 0x00000010
            status = CAENV1740.caenLib.CAENVME_WriteCycle(
                handle, c_int(vmeAddress + 0x8000), byref(c_int(conf)),
                c_int(self.cvA32_S_DATA), c_int(self.cvD32))
            if status != 0:
                print('Error writing group configuration')
                CAENV1740.caenLib.CAENVME_End(handle)
                raise mdsExceptions.TclFAILED_ESSENTIAL

#Group configurations
            trigEnableCode = 0
            chanEnableCode = 0
            enabledDict = {'ENABLED': 1, 'DISABLED': 0}
            for group in range(0, 8):
                #threshold level
                #             threshold = self.__dict__['group_%d_tr_tresh_lev'%(group+1)].data()
                #             status = CAENV1740.caenLib.CAENVME_WriteCycle(handle, c_int(vmeAddress + 0x1080 + group * 0x100), byref(c_int(threshold)), c_int#(self.cvA32_S_DATA), c_int(self.cvD32))
                #             if status != 0:
                #                 print 'writing threshold level'
                #                 CAENV1740.caenLib.CAENVME_End(handle)
                #                 raise mdsExceptions.TclFAILED_ESSENTIAL
                #offset
                offset = self.__dict__['group_%d_offset' % (group + 1)].data()
                if (offset > 1):
                    offset = 1.
                if (offset < -1):
                    offset = -1
                offset = (offset / 1.) * 32767
                status = CAENV1740.caenLib.CAENVME_WriteCycle(
                    handle, c_int(vmeAddress + 0x1098 + group * 0x100),
                    byref(c_int(int(offset + 0x08000))),
                    c_int(self.cvA32_S_DATA), c_int(self.cvD32))
                if status != 0:
                    print('Error writing DAC offset')
                    CAENV1740.caenLib.CAENVME_End(handle)
                    raise mdsExceptions.TclFAILED_ESSENTIAL
#states
                state = self.__dict__['group_%d_state' % (group + 1)].data()
                chanEnableCode = chanEnableCode | (enabledDict[state] << group)
                trigState = self.__dict__['group_%d_trig_state' %
                                          (group + 1)].data()
                trigEnableCode = trigEnableCode | (
                    enabledDict[trigState] << group)
                #endfor group in range(0,8)

                trigExt = self.trig_ext.data()
                trigEnableCode = trigEnableCode | (enabledDict[trigExt] << 30)
                trigSoft = self.trig_soft.data()
                trigEnableCode = trigEnableCode | (enabledDict[trigSoft] << 31)
                status = CAENV1740.caenLib.CAENVME_WriteCycle(
                    handle, c_int(vmeAddress + 0x810C),
                    byref(c_int(trigEnableCode)), c_int(self.cvA32_S_DATA),
                    c_int(self.cvD32))
                if status != 0:
                    print('Error writing trigger configuration')
                    CAENV1740.caenLib.CAENVME_End(handle)
                    raise mdsExceptions.TclFAILED_ESSENTIAL
                status = CAENV1740.caenLib.CAENVME_WriteCycle(
                    handle, c_int(vmeAddress + 0x8120),
                    byref(c_int(chanEnableCode)), c_int(self.cvA32_S_DATA),
                    c_int(self.cvD32))
                if status != 0:
                    print('Error writing channel enabling')
                    CAENV1740.caenLib.CAENVME_End(handle)
                    raise mdsExceptions.TclFAILED_ESSENTIAL

#Front Panel trigger out setting set TRIG/CLK to TTL
                data = 1
                status = CAENV1740.caenLib.CAENVME_WriteCycle(
                    handle, c_int(vmeAddress + 0x811C), byref(c_int(data)),
                    c_int(self.cvA32_S_DATA), c_int(self.cvD32))

                try:
                    trigSource = self.trig_source.data()

                    #if trigger is expressed as an array, consider only the first element
                    print('Trigger source: ', trigSource)
                    if len(self.trig_source.getShape()) > 0:
                        trigSource = trigSource[0]
                except:
                    print('Cannot resolve Trigger source')
                    CAENV1740.caenLib.CAENVME_End(handle)
                    raise mdsExceptions.TclFAILED_ESSENTIAL

#Clock source
                clockMode = self.clock_mode.data()
                if clockMode == 'EXTERNAL':
                    try:
                        clockSource = self.clock_source.getData()
                        if Device.debug: print('Clock source: ', clockSource)
                    except:
                        print('Cannot resolve Clock source')
                        CAENV1740.caenLib.CAENVME_End(handle)
                        raise mdsExceptions.TclFAILED_ESSENTIAL
                else:
                    clockSource = Range(None, None, Float64(1 / 62.5E6))
                    self.clock_source.putData(clockSource)

#Post Trigger Samples
                try:
                    pts = self.pts.data()
                except:
                    print('Cannot resolve PTS samples')
                    CAENV1740.caenLib.CAENVME_End(handle)
                    raise mdsExceptions.TclFAILED_ESSENTIAL
                segmentSize = 196608 / nSegments
                if pts > segmentSize:
                    print('PTS Larger than segmentSize')
                    CAENV1740.caenLib.CAENVME_End(handle)
                    raise mdsExceptions.TclFAILED_ESSENTIAL
                status = CAENV1740.caenLib.CAENVME_WriteCycle(
                    handle, c_int(vmeAddress + 0x8114), byref(c_int(pts)),
                    c_int(self.cvA32_S_DATA), c_int(self.cvD32))

                #Time management
                useTime = self.use_time.data()
                if useTime == 'YES':
                    try:
                        startTime = self.start_time.data()
                        endTime = self.end_time.data()
                    except:
                        print('Cannot Read Start or End time')
                        CAENV1740.caenLib.CAENVME_End(handle)
                        raise mdsExceptions.TclFAILED_ESSENTIAL
                if endTime > 0:
                    endIdx = Data.execute(
                        'x_to_i($1, $2)',
                        Dimension(Window(0, None, trigSource), clockSource),
                        endTime + trigSource)
                else:
                    endIdx = -Data.execute(
                        'x_to_i($1,$2)',
                        Dimension(Window(0, None, trigSource + endTime),
                                  clockSource), trigSource)
                self.end_idx.putData(Int32(endIdx))

                if startTime > 0:
                    startIdx = Data.execute(
                        'x_to_i($1, $2)',
                        Dimension(Window(0, None, trigSource), clockSource),
                        startTime + trigSource)
                else:
                    startIdx = -Data.execute(
                        'x_to_i($1,$2)',
                        Dimension(Window(0, None, trigSource + startTime),
                                  clockSource), trigSource)
                self.start_idx.putData(Int32(startIdx))

                # Run device
                status = CAENV1740.caenLib.CAENVME_WriteCycle(
                    handle, c_int(vmeAddress + 0x8100), byref(c_int(4)),
                    c_int(self.cvA32_S_DATA), c_int(self.cvD32))
                CAENV1740.caenLib.CAENVME_End(handle)
                return
        except:
            print('Generic Error')
            CAENV1740.caenLib.CAENVME_End(handle)
            raise mdsExceptions.TclFAILED_ESSENTIAL
Exemple #19
0
    def init(self):

        self.debugPrint('=================  BMC2835 Init ===============')

        # Module in acquisition check
        if self.restoreInfo() == self.DEV_IS_OPEN:
            try:
                self.restoreWorker()
                if self.worker.isAlive():
                    print('stop Store')
                    self.stop_store()
                self.restoreInfo()
            except:
                pass

# Channel configuration
        activeChan = 0
        for chan in range(0, 4):
            # Empy the node which will contain  the segmented data
            getattr(self, 'channel_%d_data_raw' % (chan + 1)).deleteData()
            getattr(self,
                    'channel_%d_data_raw' % (chan + 1)).setCompressOnPut(False)
            getattr(self, 'channel_%d_res_raw' % (chan + 1)).deleteData()
            getattr(self,
                    'channel_%d_res_raw' % (chan + 1)).setCompressOnPut(False)
            try:
                data = Data.compile(
                    "$1 * $2 + $3",
                    getattr(self, 'channel_%d_data_raw' % (chan + 1)),
                    getattr(self, 'channel_%d_gain' % (chan + 1)),
                    getattr(self, 'channel_%d_offset' % (chan + 1)))
                data.setUnits("Volts")
                getattr(self, 'channel_%d_data' % (chan + 1)).putData(data)
            except Exception as e:
                self.debugPrint(estr(e))
                Data.execute(
                    'DevLogErr($1,$2)', self.getNid(),
                    'Invalid Configuration for channel ' + str(chan + 1))
                raise DevBAD_PARAMETER
        # endfor
        """
        try:
            nSamples = self.num_samples.data()
        except:
            nSamples = -1
        """

        # Acquisition management
        try:
            acqMode = self.acq_mode.data()
        except:
            Data.execute('DevLogErr($1,$2)', self.getNid(),
                         'Cannot resolve acquisition mode management')
            raise DevBAD_PARAMETER

# trigger mode
        try:
            trigMode = self.trig_mode.data()
            self.debugPrint('BCM2835 Trigger mode: ', trigMode)
            if (trigMode == 'EXTERNAL'):
                if (acqMode == 'TRANSIENT REC.'):
                    print("External Trigger Transient recorder")
                else:
                    print("External Trigger Continuous recorder")
            else:
                if (acqMode == 'TRANSIENT REC.'):
                    print("Internal Trigger Transient recorder")
                else:
                    print("Internal Trigger Continuous recorder")
        except:
            traceback.print_exc(file=sys.stdout)
            Data.execute('DevLogErr($1,$2)', self.getNid(),
                         'Invalid triger mode definition')
            raise DevBAD_PARAMETER

# trigger source
        try:
            if (trigMode == 'EXTERNAL'):
                trigSource = self.trig_source.data()
            else:
                try:
                    trigSource = self.trig_source.data()
                except:
                    trigSource = 0
            self.debugPrint('BCM2835 Trigger source: ', trigSource)
        except:
            Data.execute('DevLogErr($1,$2)', self.getNid(),
                         'Cannot resolve Trigger source')
            raise DevBAD_PARAMETER

# clock mode
        try:
            clockMode = self.clock_mode.data()
            if (clockMode == 'INTERNAL'):
                frequency = self.clock_freq.data()
                if (frequency > 10000 or frequency <= 0):
                    self.debugPrint('BCM2835 Frequency out of limits')
                    frequency = 1000.
                    self.clock_source.putData(frequency)

                clockSource = Range(None, None, Float64(1. / frequency))
                self.debugPrint('BCM2835 CLOCK: ', clockSource)
                self.clock_source.putData(clockSource)
            else:
                clockSource = self.clock_source.evaluate()
                print("External clock")
        except:
            Data.execute('DevLogErr($1,$2)', self.getNid(),
                         'Invalid clock definition')
            raise DevBAD_PARAMETER

# Time management
        if acqMode == 'TRANSIENT REC.':
            try:
                useTime = self.use_time.data()
            except:
                Data.execute('DevLogErr($1,$2)', self.getNid(),
                             'Cannot resolve time or samples management')
                raise DevBAD_PARAMETER

            if useTime == 'YES':
                try:
                    startTime = self.start_time.data()
                    endTime = self.end_time.data()
                    self.debugPrint('BCM2835 startTime = ', startTime)
                    self.debugPrint('BCM2835 endTime   = ', endTime)
                    self.debugPrint('BCM2835 trigSource   = ', trigSource)
                except:
                    Data.execute('DevLogErr($1,$2)', self.getNid(),
                                 'Cannot Read Start or End time')
                    raise DevBAD_PARAMETER

                startIdx = Data.execute(
                    'x_to_i($1, $2)',
                    Dimension(Window(0, None, trigSource), clockSource),
                    startTime)
                endIdx = Data.execute(
                    'x_to_i($1, $2)',
                    Dimension(Window(0, None, trigSource), clockSource),
                    endTime)

                self.debugPrint('BCM2835 startIdx = ',
                                Int32(int(startIdx + 0.5)))
                self.start_idx.putData(Int32(int(startIdx + 0.5)))

                self.debugPrint('BCM2835 endIdx   = ',
                                Int32(int(endIdx + 0.5)))
                self.end_idx.putData(Int32(int(endIdx + 0.5)))

                # self.prts.putData(Int32(int(preTrigger)))
                # self.num_samples.putData(Int32(int(postTrigger)))

            else:
                endIdx = self.end_idx.data()
                startIdx = self.start_idx.data()

            nSamples = endIdx - startIdx + 1
            postTrigger = nSamples + startIdx
            if startIdx >= 0:
                self.debugPrint('BCM2835 Acquire pre and post trigger')
            else:
                if trigSource > startTime:
                    self.debugPrint('BCM2835 Acquire only post trigger')
                    nSamples = postTrigger
                    startIdx = 0
                    self.start_idx.putData(Int32(int(0)))
                    self.start_time.putData(Float32(trigSource))

            self.debugPrint('BCM2835 nSamples   = ', Int32(int(nSamples)))

        else:  # Continuous Acquisition
            nSamples = -1

        self.saveInfo()
        self.debugPrint("===============================================")
        return 1
Exemple #20
0
    def init(self):

        print('================= PXI 6259 Init ===============')

        self.restoreInfo()
        aiConf = c_void_p(0)
        NI6259AI.niInterfaceLib.pxi6259_create_ai_conf_ptr(byref(aiConf))
        try:
            inputMode = self.inputModeDict[self.input_mode.data()]
        except:
            Data.execute('DevLogErr($1,$2)', self.getNid(),
                         'Invalid Input Mode')
            raise mdsExceptions.TclFAILED_ESSENTIAL
        if (inputMode == self.AI_CHANNEL_TYPE_DIFFERENTIAL):
            numChannels = 16
        else:
            numChannels = 32

        activeChan = 0
        for chan in range(0, numChannels):
            getattr(self,
                    'channel_%d_data' % (chan + 1)).setCompressOnPut(False)
            try:
                enabled = self.enableDict[getattr(
                    self, 'channel_%d_state' % (chan + 1)).data()]
                polarity = self.polarityDict[getattr(
                    self, 'channel_%d_polarity' % (chan + 1)).data()]
                gain = self.gainDict[getattr(self, 'channel_%d_range' %
                                             (chan + 1)).data()]
            except:
                Data.execute(
                    'DevLogErr($1,$2)', self.getNid(),
                    'Invalid Configuration for channel ' + str(chan + 1))
                raise mdsExceptions.TclFAILED_ESSENTIAL
            if (enabled):
                if (inputMode == self.AI_CHANNEL_TYPE_DIFFERENTIAL):
                    currChan = self.diffChanMap[chan]
                else:
                    currChan = chan
                #print 'POLARITY: ' + str(polarity) + ' GAIN: ' + str(gain) + ' INPUT MODE: ' + str(inputMode)
                status = NI6259AI.niLib.pxi6259_add_ai_channel(
                    aiConf, c_byte(currChan), polarity, gain, inputMode,
                    c_byte(0))
                if (status != 0):
                    Data.execute('DevLogErr($1,$2)', self.getNid(),
                                 'Cannot add channel ' + str(currChan + 1))
                    raise mdsExceptions.TclFAILED_ESSENTIAL
                print('PXI 6259 CHAN ' + str(currChan + 1) + ' CONFIGURED')
                activeChan = activeChan + 1
        #endfor
        """
        try:
            nSamples = self.num_samples.data()
        except:
            nSamples = -1
        """

        #Acquisition management
        try:
            acqMode = self.acq_mode.data()
        except:
            Data.execute('DevLogErr($1,$2)', self.getNid(),
                         'Cannot resolve acquisition mode management')
            raise mdsExceptions.TclFAILED_ESSENTIAL

#trigger mode
        try:
            trigMode = self.trig_mode.data()
            print(trigMode)
            if (trigMode == 'EXTERNAL_PFI1' or trigMode == 'EXTERNAL_RTSI1'):
                #print "AI_START_SELECT ", self.AI_START_SELECT
                #print "aiConf ", aiConf
                #print "AI_START_SELECT_PFI1 ", self.AI_START_SELECT_PFI1
                #print "niLib ", niLib
                #print "AI_START_POLARITY ", self.AI_START_POLARITY
                #print "AI_START_POLARITY_RISING_EDGE ", self.AI_START_POLARITY_RISING_EDGE

                if (acqMode == 'TRANSIENT REC.'):
                    """
                    status = niLib.pxi6259_set_ai_attribute(aiConf, self.AI_START_SELECT, self.AI_START_SELECT_PULSE)
                    if( status == 0 ):
                        status = niLib.pxi6259_set_ai_attribute(aiConf, self.AI_REFERENCE_SELECT, self.AI_REFERENCE_SELECT_PFI1)
                    if( status == 0 ):
                        status = niLib.pxi6259_set_ai_attribute(aiConf, self.AI_REFERENCE_POLARITY, self.AI_REFERENCE_POLARITY_RISING_EDGE)
                    if( status != 0 ):
                        Data.execute('DevLogErr($1,$2)', self.getNid(), 'Cannot set external trigger')
                        raise mdsExceptions.TclFAILED_ESSENTIAL
                    """
                    # Sostituzione temporanea per gestire acquisizione a IPP trigger preso dal 6368
                    # status = niLib.pxi6259_set_ai_attribute(aiConf, self.AI_START_SELECT, self.AI_START_SELECT_PFI1)

                    if (trigMode == 'EXTERNAL_PFI1'):
                        status = NI6259AI.niLib.pxi6259_set_ai_attribute(
                            aiConf, self.AI_START_SELECT,
                            self.AI_START_SELECT_PFI1)
                    else:
                        print("1 OK AI_START_SELECT_RTSI1")
                        status = NI6259AI.niLib.pxi6259_set_ai_attribute(
                            aiConf, self.AI_START_SELECT,
                            self.AI_START_SELECT_RTSI1)

                    if (status == 0):
                        status = NI6259AI.niLib.pxi6259_set_ai_attribute(
                            aiConf, self.AI_START_POLARITY,
                            self.AI_START_POLARITY_RISING_EDGE)
                    if (status != 0):
                        Data.execute('DevLogErr($1,$2)', self.getNid(),
                                     'Cannot set external trigger')
                        raise mdsExceptions.TclFAILED_ESSENTIAL
                else:
                    # Sostituzione etmporanea per gestire acquisizione a IPP trigger preso dal 6368
                    # status = niLib.pxi6259_set_ai_attribute(aiConf, self.AI_START_SELECT, self.AI_START_SELECT_PFI1)

                    if (trigMode == 'EXTERNAL_PFI1'):
                        status = NI6259AI.niLib.pxi6259_set_ai_attribute(
                            aiConf, self.AI_START_SELECT,
                            self.AI_START_SELECT_PFI1)
                    else:
                        print("2 OK AI_START_SELECT_RTSI1")
                        status = NI6259AI.niLib.pxi6259_set_ai_attribute(
                            aiConf, self.AI_START_SELECT,
                            self.AI_START_SELECT_RTSI1)

                    if (status == 0):
                        status = NI6259AI.niLib.pxi6259_set_ai_attribute(
                            aiConf, self.AI_START_POLARITY,
                            self.AI_START_POLARITY_RISING_EDGE)
                    if (status != 0):
                        Data.execute('DevLogErr($1,$2)', self.getNid(),
                                     'Cannot set external trigger')
                        raise mdsExceptions.TclFAILED_ESSENTIAL

                if (trigMode == 'EXTERNAL_PFI1'):
                    status = NI6259AI.niLib.pxi6259_export_ai_signal(
                        aiConf, self.PXI6259_AI_START_TRIGGER,
                        self.PXI6259_RTSI1)
                    if (status != 0):
                        Data.execute('DevLogErr($1,$2)', self.getNid(),
                                     'Cannot route PFI1 signal to RTSI1')
                        raise mdsExceptions.TclFAILED_ESSENTIAL

            else:
                #print "AI_START_SELECT ", self.AI_START_SELECT
                #print "aiConf ", aiConf
                #print "AI_START_SELECT_PFI1 ", self.AI_START_SELECT_PFI1
                #print "niLib ", NI6259AI.niLib
                #print "AI_START_POLARITY ", self.AI_START_POLARITY
                #print "AI_START_POLARITY_RISING_EDGE ", self.AI_START_POLARITY_RISING_EDGE
                #print "acqMode ", acqMode

                if (acqMode == 'TRANSIENT REC.'):
                    #status = NI6259AI.niLib.pxi6259_set_ai_attribute(aiConf, self.AI_START_SELECT, self.AI_START_SELECT_PULSE)
                    #if( status == 0 ):
                    status = NI6259AI.niLib.pxi6259_set_ai_attribute(
                        aiConf, self.AI_REFERENCE_SELECT,
                        self.AI_REFERENCE_SELECT_PULSE)
                    #if( status == 0 ):
                    #    status = NI6259AI.niLib.pxi6259_set_ai_attribute(aiConf, self.AI_REFERENCE_POLARITY, self.AI_REFERENCE_POLARITY_RISING_EDGE)
                    if (status != 0):
                        Data.execute('DevLogErr($1,$2)', self.getNid(),
                                     'Cannot set external trigger')
                        raise mdsExceptions.TclFAILED_ESSENTIAL

        except:
            Data.execute('DevLogErr($1,$2)', self.getNid(),
                         'Invalid triger mode definition')
            raise mdsExceptions.TclFAILED_ESSENTIAL

#trigger source
        try:
            if (trigMode == 'EXTERNAL_PFI1' or trigMode == 'EXTERNAL_RTSI1'):
                trigSource = self.trig_source.data()
            else:
                trigSource = 0
            print('PXI 6259 Trigger source: ', trigSource)
        except:
            Data.execute('DevLogErr($1,$2)', self.getNid(),
                         'Cannot resolve Trigger source')
            raise mdsExceptions.TclFAILED_ESSENTIAL

#clock mode
        try:
            clockMode = self.clock_mode.data()
            if (clockMode == 'INTERNAL'):
                frequency = self.clock_freq.data()
                if ((activeChan == 1 and frequency > 1250000) or
                    (activeChan > 1 and frequency > 1000000. / activeChan)):
                    print('PXI 6259 Frequency out of limits')
                    if (activeChan == 1):
                        frequency = 1250000.
                    else:
                        frequency = 1000000. / activeChan
                    self.clock_source.putData(frequency)

                divisions = int(20000000. / frequency)
                status = NI6259AI.niLib.pxi6259_set_ai_sample_clk(
                    aiConf, c_int(divisions), c_int(3),
                    self.AI_SAMPLE_SELECT_SI_TC,
                    self.AI_SAMPLE_POLARITY_RISING_EDGE)
                if (status != 0):
                    Data.execute('DevLogErr($1,$2)', self.getNid(),
                                 'Cannot Set Sample Clock')
                    raise mdsExceptions.TclFAILED_ESSENTIAL
                """
                if nSamples > 0:
                    clockSource = Range(Float64(0), Float64(nSamples * divisions/20000000.) , Float64(divisions/20000000.))
                else:
                    clockSource = Range(Float64(0), Float64(3600), Float64(divisions/20000000.))
                """
                clockSource = Range(None, None, Float64(divisions / 20000000.))
                print('PXI 6259 CLOCK: ', clockSource)
                self.clock_source.putData(clockSource)
            else:
                clockSource = self.clock_source.evaluate()
                status = NI6259AI.niLib.pxi6259_set_ai_sample_clk(
                    aiConf, c_int(16), c_int(3), self.AI_SAMPLE_SELECT_PFI0,
                    self.AI_SAMPLE_POLARITY_RISING_EDGE)
                if (status != 0):
                    Data.execute('DevLogErr($1,$2)', self.getNid(),
                                 'Cannot configure device clock')
                    raise mdsExceptions.TclFAILED_ESSENTIAL

            status = NI6259AI.niLib.pxi6259_set_ai_convert_clk(
                aiConf, c_int(20), c_int(3), self.AI_CONVERT_SELECT_SI2TC,
                self.AI_CONVERT_POLARITY_RISING_EDGE)
            if (status != 0):
                Data.execute('DevLogErr($1,$2)', self.getNid(),
                             'Cannot Set Convert Clock')
                raise mdsExceptions.TclFAILED_ESSENTIAL
        except:
            Data.execute('DevLogErr($1,$2)', self.getNid(),
                         'Invalid clock definition')
            raise mdsExceptions.TclFAILED_ESSENTIAL

#Time management
        if acqMode == 'TRANSIENT REC.':
            try:
                useTime = self.use_time.data()

            except:
                Data.execute('DevLogErr($1,$2)', self.getNid(),
                             'Cannot resolve time or samples management')
                raise mdsExceptions.TclFAILED_ESSENTIAL

            if useTime == 'YES':
                try:
                    startTime = self.start_time.data()
                    endTime = self.end_time.data()

                    print('PXI 6259 startTime = ', startTime)
                    print('PXI 6259 endTime   = ', endTime)
                    print('PXI 6259 trigSource   = ', trigSource)

                except:
                    Data.execute('DevLogErr($1,$2)', self.getNid(),
                                 'Cannot Read Start or End time')
                    raise mdsExceptions.TclFAILED_ESSENTIAL

                startIdx = Data.execute(
                    'x_to_i($1, $2)',
                    Dimension(Window(0, None, trigSource), clockSource),
                    startTime)

                endIdx = Data.execute(
                    'x_to_i($1, $2)',
                    Dimension(Window(0, None, trigSource), clockSource),
                    endTime)
                """
                if endTime > 0:
                    endIdx = Data.execute('x_to_i($1, $2)', Dimension(Window(0, None, trigSource), clockSource), endTime + trigSource)
                else:
                    endIdx = -Data.execute('x_to_i($1,$2)', Dimension(Window(0, None, trigSource + endTime), clockSource), trigSource)

                print 'endIdx   = ', Int32(int(endIdx))
                self.end_idx.putData(Int32(int(endIdx)))

                if startTime > 0:
                    startIdx = Data.execute('x_to_i($1, $2)', Dimension(Window(0, None, trigSource), clockSource), startTime + trigSource)
                else:
                    startIdx = -Data.execute('x_to_i($1,$2)', Dimension(Window(0, None, trigSource + startTime), clockSource), trigSource)
                """
                print('PXI 6259 startIdx = ', Int32(int(startIdx + 0.5)))
                self.start_idx.putData(Int32(int(startIdx + 0.5)))

                print('PXI 6259 endIdx   = ', Int32(int(endIdx + 0.5)))
                self.end_idx.putData(Int32(int(endIdx + 0.5)))

                #self.prts.putData(Int32(int(preTrigger)))
                #self.num_samples.putData(Int32(int(postTrigger)))

            else:
                endIdx = self.end_idx.data()
                startIdx = self.start_idx.data()
                """
                postTrigger = nSamples;
                preTrigger = 0
                try:
                    preTrigger = self.prts.data()
                except:
                    preTrigger = 0
                    nSamples =  postTrigger + preTrigger
                """

            nSamples = endIdx - startIdx + 1

            postTrigger = nSamples + startIdx
            #preTrigger  = nSamples - endIdx

            if startIdx >= 0:
                status = NI6259AI.niLib.pxi6259_set_ai_number_of_samples(
                    aiConf, c_int(startIdx + nSamples), 0, 0)
            else:
                if trigSource > startTime:
                    print('PXI 6259 Acquire only post trigger')
                    nSamples = postTrigger
                    startIdx = 0
                    self.start_idx.putData(Int32(int(0)))
                    self.start_time.putData(Float32(trigSource))
                    status = NI6259AI.niLib.pxi6259_set_ai_number_of_samples(
                        aiConf, c_int(nSamples), 0, 0)
            """
            nSamples = endIdx - startIdx + 1
            postTrigger = nSamples + startIdx
            preTrigger = nSamples - endIdx
            """
            print('PXI 6259 nSamples   = ', Int32(int(nSamples)))
            self.seg_length.putData(Int32(int(nSamples)))

#           status = NI6259AI.niLib.pxi6259_set_ai_number_of_samples(aiConf, c_int(postTrigger), c_int(preTrigger), 0)

        else:  #Continuous Acquisition
            nSamples = -1
            #if nSamples > 0:
            #    status = NI6259AI.niLib.pxi6259_set_ai_number_of_samples(aiConf, c_int(nSamples), 0, 0)

        if (status != 0):
            Data.execute('DevLogErr($1,$2)', self.getNid(),
                         'Cannot Set Number of Samples')
            raise mdsExceptions.TclFAILED_ESSENTIAL

        status = NI6259AI.niLib.pxi6259_load_ai_conf(c_int(self.fd), aiConf)
        if (status != 0):
            Data.execute('DevLogErr($1,$2)', self.getNid(),
                         'Cannot load configuration')
            raise mdsExceptions.TclFAILED_ESSENTIAL
        """
        if acqMode == 'TRANSIENT REC.':
            status = niLib.pxi6259_start_ai(c_int(self.fd))
            #status = 0

            if(status != 0):
                Data.execute('DevLogErr($1,$2)', self.device.getNid(), 'Cannot Start Acquisition ')
                return
        """
        self.saveInfo()
        print("===============================================")
        return
Exemple #21
0
    def init(self):

        try:
            self.initializeInfo()
        except:
            Data.execute('DevLogErr($1,$2)', self.getNid(),
                         'Cannot open FAU device')
            raise mdsExceptions.TclFAILED_ESSENTIAL

        self.saveInfo()

        #try:
        #    pteMask = self.pte_mask.data();
        #except:
        #    Data.execute('DevLogErr($1,$2)', self.getNid(), 'Read FAU pulse train mask error. Set to 0')
        #    pteMask = 0

        try:
            pteFreqFast = self.pte_frq_fast.data()
        except:
            Data.execute(
                'DevLogErr($1,$2)', self.getNid(),
                'Read FAU pulse train fast frequency error. Set to 50kHz')
            pteFreqFast = 50000

        pteFastCount = int(self.TICK_40MHz / pteFreqFast + 100)

        try:
            pteFreqSlow = self.pte_frq_slow.data()
        except:
            Data.execute(
                'DevLogErr($1,$2)', self.getNid(),
                'Read FAU pulse train slow frequency error. Set to 50Hz')
            pteFreqSlow = 50

        pteSlowCount = int(self.TICK_40MHz / pteFreqSlow + 100)

        try:
            trigMode = self.trig_mode.data()
            print("Trigger Node = ", trigMode)
        except Exception as ex:
            Data.execute(
                'DevLogErr($1,$2)', self.getNid(),
                'Read FAU trigger mode error. Set to INTERNAL' + str(ex))
            trigMode = 'INTERNAL'
            self.trig_mode.putData(trigMode)

        try:
            tsmpFreq = self.tsmp_freq.data()
            tickFreqCode = self.tsmpDict[tsmpFreq]
        except:
            Data.execute('DevLogErr($1,$2)', self.getNid(),
                         'Read FAU time stamp frequency error. Set to 40MHz')
            tsmpFreq = 40000000
            tickFreqCode = 0
            self.tsmp_freq.putData(Int32(tsmpFreq))

        try:
            trigSource = self.trig_source.data()
        except:
            if (trigMode == 'EXTERNAL'):
                Data.execute('DevLogErr($1,$2)', self.getNid(),
                             'Cannot resolve Trigger source.')
                raise mdsExceptions.TclFAILED_ESSENTIAL
            else:
                trigSource = 0.
                self.trig_source.putData(Float32(trigSource))

        print("Trigger Source = ", trigSource)

        bit = 0
        pteEnaMask = long(0)
        pteSlowFastMask = long(0)
        for mod in range(0, 8):
            for ch in range(0, 8):
                pteModeCode = self.TPEModeDict[getattr(
                    self,
                    'module_%d_channel_%d_pte_mode' % (mod + 1, ch)).data()]
                pteEnaMask = pteEnaMask | ((pteModeCode & long(1) == 1) << bit)
                pteSlowFastMask = pteSlowFastMask | (
                    (pteModeCode & long(2) == 2) << bit)
                bit = bit + 1

        print('pteSlowFastMask ', pteSlowFastMask)
        status = CRIO_FAU.niInterfaceLib.setFauAcqParam(
            self.session, c_uint64(pteEnaMask), c_uint64(pteSlowFastMask),
            c_uint(pteSlowCount), c_uint(pteFastCount), c_short(tickFreqCode))

        if status < 0:
            Data.execute('DevLogErr($1,$2)', self.getNid(),
                         'FAU acquisition device initialization error.')
            return 0

        status = CRIO_FAU.niInterfaceLib.startFauFpga(self.session)
        if status < 0:
            Data.execute('DevLogErr($1,$2)', self.getNid(),
                         'FAU start FPGA error.')
            return 0

        acqState = c_short()
        CRIO_FAU.niInterfaceLib.getFauAcqState(self.session, byref(acqState))
        print("Acquisition State ", acqState.value)

        return 1
Exemple #22
0
    def init(self):

        self.debugPrint('=================  PXI 6368 Init ===============')

        # self.restoreInfo()

        # Acquisition in progress module check
        if self.restoreInfo() == self.DEV_IS_OPEN:
            try:
                self.restoreWorker()
                print('Check Start Store')
                if self.worker.isAlive():
                    print('stop Store')
                    self.stop_store()
                self.restoreInfo()
            except:
                pass

        aiConf = c_void_p(0)

        try:
            inputMode = self.inputModeDict[self.input_mode.data()]
        except:
            Data.execute('DevLogErr($1,$2)', self.getNid(),
                         'Invalid Input Mode')
            raise DevBAD_PARAMETER

        dev_fd = 0

        fileName = '/dev/pxie-6368.' + str(self.boardId)
        dev_fd = os.open(fileName, os.O_RDWR)
        #self.debugPrint('Open ai_fd: ', self.ai_fd)

        device_info = self.XSERIES_DEV_INFO(0, "", 0, 0, 0, 0, 0, 0, 0, 0, 0,
                                            0, 0, 0, 0, 0)

        # get card info
        status = NI6368AI.niInterfaceLib._xseries_get_device_info(
            c_int(dev_fd), byref(device_info))
        if status:
            Data.execute('DevLogErr($1,$2)', self.getNid(),
                         'Error reading card information')
            raise mdsExceptions.TclFAILED_ESSENTIAL

        os.close(dev_fd)

        try:
            self.serial_num.putData(device_info.serial_number)
        except:
            pass

        #self.debugPrint('OK xseries_get_device_info')

        # Stop the segment TODO is this necessary since the reset is next
        NI6368AI.niLib.xseries_stop_ai(c_int(self.ai_fd))

        # reset AI segment
        status = NI6368AI.niLib.xseries_reset_ai(c_int(self.ai_fd))
        if (status):
            errno = NI6368AI.niInterfaceLib.getErrno()
            Data.execute(
                'DevLogErr($1,$2)', self.getNid(),
                'Cannot reset AI segment: (%d) %s' %
                (errno, os.strerror(errno)))
            raise mdsExceptions.TclFAILED_ESSENTIAL

        # Check Acquisition Configuration
        try:
            bufSize = self.buf_size.data()
        except:
            Data.execute('DevLogErr($1,$2)', self.getNid(),
                         'Cannot resolve acquisition buffer size')
            raise DevBAD_PARAMETER

        try:
            segmentSize = self.seg_length.data()
        except:
            Data.execute('DevLogErr($1,$2)', self.getNid(),
                         'Cannot resolve acquisition segment size')
            raise DevBAD_PARAMETER

        # Acquisition management
        try:
            acqMode = self.acq_mode.data()
        except:
            Data.execute('DevLogErr($1,$2)', self.getNid(),
                         'Cannot resolve acquisition mode management')
            raise DevBAD_PARAMETER

        # trigger mode
        try:
            trigMode = self.trig_mode.data()
        except:
            Data.execute('DevLogErr($1,$2)', self.getNid(),
                         'Invalid triger mode definition')
            raise DevBAD_PARAMETER

        # trigger source
        try:
            trigSource = (self.trig_source.data())
        except:
            if (trigMode == 'EXTERNAL'):
                Data.execute('DevLogErr($1,$2)', self.getNid(),
                             'Cannot resolve Trigger source')
                raise DevBAD_PARAMETER
            else:
                trigSource = 0.
                self.trig_source.putData(Float32(trigSource))
        self.debugPrint('PXI 6368 Trigger source: ', trigSource)

        try:
            numTrigger = len(trigSource) - 1
            """
            Trigger time must be set to 0. in multi trigger
            acquisition for correct evaluation of the number
            of samples to acquire for each trigger
            """
            trigTime = 0.
        except:
            numTrigger = 1
            trigTime = trigSource
        #self.debugPrint('Trigger number: ', numTrigger)

        # clock mode
        try:
            clockMode = self.clock_mode.data()
            if (clockMode == 'INTERNAL'):
                frequency = self.clock_freq.data()
                if (frequency > 2000000.):
                    self.debugPrint('Frequency out of limits')
                    frequency = 2000000.

                clockSource = Range(None, None, Float64(1. / frequency))
                self.clock_source.putData(clockSource)
            else:
                # self.debugPrint('External')
                clockSource = self.clock_source.evaluate()
                self.debugPrint('PXI 6368 External CLOCK: ', clockSource)
        except:
            Data.execute('DevLogErr($1,$2)', self.getNid(),
                         'Invalid clock definition')
            raise mdsExceptions.TclFAILED_ESSENTIAL

        self.debugPrint('PXI 6368 CLOCK: ', clockSource)

        # Time management

        try:
            useTime = self.use_time.data()
        except:
            Data.execute('DevLogErr($1,$2)', self.getNid(),
                         'Cannot resolve time or samples management')
            raise mdsExceptions.TclFAILED_ESSENTIAL

        if acqMode == 'TRANSIENT REC.':
            if useTime == 'YES':
                try:
                    startTime = float(self.start_time.data())
                    endTime = float(self.end_time.data())
                    self.debugPrint('PXI 6368 startTime  = ', startTime)
                    self.debugPrint('PXI 6368 endTime    = ', endTime)
                    self.debugPrint('PXI 6368 trigTime   = ', trigTime)

                except:
                    Data.execute('DevLogErr($1,$2)', self.getNid(),
                                 'Cannot Read Start or End time')
                    raise mdsExceptions.TclFAILED_ESSENTIAL

                # Originale
                startIdx = Data.execute(
                    'x_to_i($1, $2)',
                    Dimension(Window(0, None, trigTime), clockSource),
                    startTime)
                # self.debugPrint("Originale startIdx ", startIdx
                endIdx = Data.execute(
                    'x_to_i($1, $2)',
                    Dimension(Window(0, None, trigTime), clockSource),
                    endTime) + 1
                #self.debugPrint("Originale endIdx ", endIdx)

                self.debugPrint('PXI 6368 startIdx = ', Int32(int(startIdx)))
                self.start_idx.putData(Int32(int(startIdx)))

                self.debugPrint('PXI 6368 endIdx   = ', Int32(int(endIdx)))
                self.end_idx.putData(Int32(int(endIdx)))

            else:
                endIdx = self.end_idx.data()
                startIdx = self.start_idx.data()

            nSamples = endIdx - startIdx

            postTrigger = nSamples + startIdx
            preTrigger = nSamples - endIdx

            self.debugPrint('PXI 6368 nSamples     = ', Int32(int(nSamples)))
            self.debugPrint('PXI 6368 seg_length   = ', self.seg_length.data())

        else:  # Continuous Acquisition
            if useTime == 'YES':
                try:
                    startTime = float(self.start_time.data())
                    self.debugPrint('PXI 6368 startTime  = ', startTime)
                    self.debugPrint('PXI 6368 trigTime = ', trigTime)

                    startIdx = Data.execute(
                        'x_to_i($1, $2)',
                        Dimension(Window(0, None, trigTime), clockSource),
                        startTime)

                except:
                    startIdx = 0
                self.start_idx.putData(Int32(int(startIdx)))
            else:
                startIdx = self.start_idx.data()
            nSamples = -1

        if acqMode == 'TRANSIENT REC.':
            if startIdx >= 0:
                NI6368AI.niInterfaceLib.xseries_create_ai_conf_ptr(
                    byref(aiConf), c_int(0), c_int(startIdx + nSamples),
                    (numTrigger))
                #niInterfaceLib.xseries_create_ai_conf_ptr(byref(aiConf), c_int(0), c_int(0), 0)
            else:
                self.debugPrint('PXI 6368 preTrigger   = ',
                                Int32(int(preTrigger)))
                self.debugPrint('PXI 6368 postTrigger   = ',
                                Int32(int(postTrigger)))
                if trigTime > startTime or trigMode == 'INTERNAL':
                    self.debugPrint(
                        'PXI 6368 Acquire only post trigger when triger time > start Time or trigger mode internal'
                    )
                    nSamples = postTrigger
                    startIdx = 0
                    self.start_idx.putData(Int32(int(0)))
                    self.start_time.putData(Float32(trigTime))
                    NI6368AI.niInterfaceLib.xseries_create_ai_conf_ptr(
                        byref(aiConf), c_int(-startIdx), c_int(nSamples),
                        (numTrigger))
                    #niInterfaceLib.xseries_create_ai_conf_ptr(byref(aiConf), c_int(0), c_int(0), 0)
        else:
            NI6368AI.niInterfaceLib.xseries_create_ai_conf_ptr(
                byref(aiConf), c_int(0), c_int(0), 0)

        #XSERIES_AI_DMA_BUFFER_SIZE = 0
        status = NI6368AI.niLib.xseries_set_ai_attribute(
            aiConf, c_int(0), c_int(80))
        if (status != 0):
            errno = NI6368AI.niInterfaceLib.getErrno()
            Data.execute(
                'DevLogErr($1,$2)', self.getNid(),
                'Set DMA buffer size : (%d) %s' % (errno, os.strerror(errno)))
            raise mdsExceptions.TclFAILED_ESSENTIAL

        # disable external gate
        status = NI6368AI.niLib.xseries_set_ai_external_gate(
            aiConf, self.XSERIES_AI_EXTERNAL_GATE_DISABLED,
            self.XSERIES_AI_POLARITY_ACTIVE_LOW_OR_FALLING_EDGE)
        if (status != 0):
            errno = NI6368AI.niInterfaceLib.getErrno()
            Data.execute(
                'DevLogErr($1,$2)', self.getNid(),
                'Cannot disable external gate!: (%d) %s' %
                (errno, os.strerror(errno)))
            raise mdsExceptions.TclFAILED_ESSENTIAL

        # SET trigger
        if (trigMode == 'EXTERNAL'):
            # if(acqMode == 'TRANSIENT REC.'):
            self.debugPrint(
                "PXI 6368 select start trigger External (START1 signal)")
            status = NI6368AI.niLib.xseries_set_ai_start_trigger(
                aiConf, self.XSERIES_AI_START_TRIGGER_PFI1,
                self.XSERIES_AI_POLARITY_ACTIVE_HIGH_OR_RISING_EDGE, 1)
            # test
            #status = niLib.xseries_set_ai_reference_trigger(aiConf, self.XSERIES_AI_START_TRIGGER_PFI1, self.XSERIES_AI_POLARITY_ACTIVE_HIGH_OR_RISING_EDGE ,1)

            if (status != 0):
                errno = NI6368AI.niInterfaceLib.getErrno()
                Data.execute(
                    'DevLogErr($1,$2)', self.getNid(),
                    'Cannot set external trigger: (%d) %s' %
                    (errno, os.strerror(errno)))
                raise mdsExceptions.TclFAILED_ESSENTIAL

        else:
            self.debugPrint(
                "PXI 6368 select start trigger Internal (START1 signal)")
            #status = niLib.xseries_set_ai_start_trigger(aiConf, self.XSERIES_AI_START_TRIGGER_SW_PULSE, self.XSERIES_AI_POLARITY_ACTIVE_LOW_OR_FALLING_EDGE, 0)
            status = NI6368AI.niLib.xseries_set_ai_start_trigger(
                aiConf, self.XSERIES_AI_START_TRIGGER_LOW,
                self.XSERIES_AI_POLARITY_ACTIVE_LOW_OR_FALLING_EDGE, 0)
            if (status != 0):
                errno = NI6368AI.niInterfaceLib.getErrno()
                Data.execute(
                    'DevLogErr($1,$2)', self.getNid(),
                    'Cannot set auto start trigger: (%d) %s' %
                    (errno, os.strerror(errno)))
                raise mdsExceptions.TclFAILED_ESSENTIAL

        # SET clock
        if (clockMode == 'INTERNAL'):
            period = int(100000000 / frequency)  # TB3 clock 100MHz
            self.debugPrint("PXI 6368 Internal CLOCK TB3 period ", period)

            status = NI6368AI.niLib.xseries_set_ai_scan_interval_counter(
                aiConf, self.XSERIES_SCAN_INTERVAL_COUNTER_TB3,
                self.XSERIES_SCAN_INTERVAL_COUNTER_POLARITY_RISING_EDGE,
                c_int(period), c_int(2))
            if (status != 0):
                errno = NI6368AI.niInterfaceLib.getErrno()
                Data.execute(
                    'DevLogErr($1,$2)', self.getNid(),
                    'Cannot Set internal sample clock: (%d) %s' %
                    (errno, os.strerror(errno)))
                raise mdsExceptions.TclFAILED_ESSENTIAL

        else:
            self.debugPrint(
                "PXI 6368 Program the sample clock (START signal) to start on a rising edge"
            )
            status = NI6368AI.niLib.xseries_set_ai_sample_clock(
                aiConf, self.XSERIES_AI_SAMPLE_CONVERT_CLOCK_PFI0,
                self.XSERIES_AI_POLARITY_ACTIVE_HIGH_OR_RISING_EDGE, c_int(1))
            if (status == 0):
                # Program the convert to be the same as START.
                status = NI6368AI.niLib.xseries_set_ai_convert_clock(
                    aiConf,
                    self.XSERIES_AI_SAMPLE_CONVERT_CLOCK_INTERNALTIMING,
                    self.XSERIES_AI_POLARITY_ACTIVE_HIGH_OR_RISING_EDGE)
                self.debugPrint(
                    "xseries_set_ai_convert_clock ",
                    self.XSERIES_AI_SAMPLE_CONVERT_CLOCK_INTERNALTIMING)
            if (status == 0):
                # Program the sample and convert clock timing specifications
                status = NI6368AI.niLib.xseries_set_ai_scan_interval_counter(
                    aiConf, self.XSERIES_SCAN_INTERVAL_COUNTER_TB3,
                    self.XSERIES_SCAN_INTERVAL_COUNTER_POLARITY_RISING_EDGE,
                    c_int(100), c_int(2))
                self.debugPrint("xseries_set_ai_scan_interval_counter ",
                                self.XSERIES_SCAN_INTERVAL_COUNTER_TB3)
            if (status != 0):
                errno = NI6368AI.niInterfaceLib.getErrno()
                Data.execute(
                    'DevLogErr($1,$2)', self.getNid(),
                    'Cannot configure external device clock: (%d) %s' %
                    (errno, os.strerror(errno)))
                raise mdsExceptions.TclFAILED_ESSENTIAL

        # Channel configuration
        numChannels = 16
        activeChan = 0
        for chan in range(1, numChannels + 1):
            try:
                # Empy the node which will contain  the segmented data
                getattr(self, 'channel_%d_data_raw' % (chan)).deleteData()

                getattr(self,
                        'channel_%d_data_raw' % (chan)).setCompressOnPut(False)
                enabled = self.enableDict[getattr(self, 'channel_%d_state' %
                                                  (chan)).data()]
                gain = self.gainDict[getattr(self, 'channel_%d_range' %
                                             (chan)).data()]
                data = self.getTree().tdiCompile(
                    "NIanalogInputScaled( build_path($), build_path($) )",
                    getattr(self, 'channel_%d_data_raw' % (chan)).getPath(),
                    getattr(self, 'channel_%d_calib_param' % (chan)).getPath())
                data.setUnits("Volts")
                getattr(self, 'channel_%d_data' % (chan)).putData(data)
            except:
                # self.debugPrint(sys.exc_info()[0])
                self.debugPrint(traceback.format_exc())
                Data.execute('DevLogErr($1,$2)', self.getNid(),
                             'Invalid Configuration for channel ' + str(chan))
                raise mdsExceptions.TclFAILED_ESSENTIAL
            if (enabled):
                # self.debugPrint(' GAIN: ' + str(gain) + ' INPUT MODE: ' + str(inputMode)
                status = NI6368AI.niLib.xseries_add_ai_channel(
                    aiConf, c_short(chan - 1), gain, inputMode, c_byte(1))
                if (status != 0):
                    Data.execute('DevLogErr($1,$2)', self.getNid(),
                                 'Cannot add channel ' + str(chan))
                    raise mdsExceptions.TclFAILED_ESSENTIAL
                #self.debugPrint ('PXI 6368 CHAN '+ str(chan) + ' CONFIGURED')
                activeChan = chan
            # else:
            #self.debugPrint ('PXI 6368 CHAN '+ str(chan) + ' DISABLED' )

        # endfor

        NI6368AI.niLib.xseries_stop_ai(c_int(self.ai_fd))

        try:
            status = NI6368AI.niInterfaceLib.xseries_set_ai_conf_ptr(
                c_int(self.ai_fd), aiConf)
            #status = NI6368AI.niLib.xseries_load_ai_conf( c_int(self.ai_fd), aiConf)
            if (status != 0):
                errno = NI6368AI.niInterfaceLib.getErrno()
                Data.execute(
                    'DevLogErr($1,$2)', self.getNid(),
                    'Cannot load ai configuration : (%d) %s' %
                    (errno, os.strerror(errno)))
                raise mdsExceptions.TclFAILED_ESSENTIAL
        except IOError:
            Data.execute(
                'DevLogErr($1,$2)', self.getNid(),
                'Exception: cannot load ai configuration: (%d) %s' %
                (errno, os.strerror(errno)))
            raise mdsExceptions.TclFAILED_ESSENTIAL

        self.saveInfo()

        self.debugPrint("===============================================")
Exemple #23
0
    def load_config(self):

        #print sys.version_info
        
        from openpyxl import load_workbook

        try:
            configurationFile = self.config_file.data()
        except Exception as e :
            Data.execute('DevLogErr($1,$2)', self.getNid(), 'Cannot read configuration file' + str(e) )
            raise mdsExceptions.TclFAILED_ESSENTIAL

        try:
            print ('Loading data from excel configuration file [%s] ...'%(configurationFile),  )          

            param='configurationFile'
            wb = load_workbook(configurationFile, data_only=True)

            sheet=wb['INFO']
            config_date = str(sheet['C1'].value)
            config_comment = str(sheet['C2'].value)
          
            sheet=wb['CONFIG']

            param = 'label_arr'
            #Set column range for all read column. Diect access, with value fild, on the first col value dosen't work
            col=sheet['B2:B%d'%(self.PROBES_NUM+1)]
            col=sheet['B']
            label_arr = [str( c.value if c != None else "") for c in col[1:len(col):1]]

            param = 'front_end_arr'
            col=sheet['C']
            front_end_arr = [str(  c.value if c.value != None else "" ) for c in col[1:len(col):1]]

            param = 'front_end_ch_arr'
            col=sheet['D']
            front_end_ch_arr = [str( c.value if  c.value != None else "") for c in col[1:len(col):1]]

            param = 'adc_slow_arr'
            col=sheet['E']
            adc_slow_arr = [str( c.value if c.value != None else "") for c in col[1:len(col):1]]

            param = 'adc_slow_con_arr'
            col=sheet['F']
            adc_slow_con_arr = [str( c.value if c.value != None else "") for c in col[1:len(col):1]]

            param = 'adc_fast_arr'
            col=sheet['G']
            adc_fast_arr = [str( c.value if  c.value != None else "") for c in col[1:len(col):1]]

            param = 'calib_RV_arr'
            col=sheet['H']
            calib_RV_arr = [float(c.value if c.value != None and (type(c.value) == long or type(c.value) == float) else -1) for c in col[1:len(col):1]]
            calib_RV_str_arr = [str( c.value if c.value != None and (type(c.value) == long or type(c.value) == float)  else "") for c in col[1:len(col):1]]

            param = 'calib_RI_high_arr'
            col=sheet['I']
            calib_RI_high_arr = [float(c.value if c.value != None and (type(c.value) == long or type(c.value) == float)  else -1) for c in col[1:len(col):1]]
            calib_RI_high_str_arr = [str( c.value if c.value != None and (type(c.value) == long or type(c.value) == float)  else "") for c in col[1:len(col):1]]

            param = 'calib_RI_low_arr'
            col=sheet['J']
            calib_RI_low_arr = [float(c.value if c.value != None and (type(c.value) == long or type(c.value) == float)  else -1) for c in col[1:len(col):1]]
            calib_RI_low_str_arr = [str( c.value if c.value != None and (type(c.value) == long or type(c.value) == float)  else "") for c in col[1:len(col):1]]

            param = 'note_arr'
            col=sheet['K']
            note_arr = [str( c.value if  c.value != None else "") for c in col[1:len(col):1]]

            wb.close()

            print (' data loaded')            


        except Exception as e :
            Data.execute('DevLogErr($1,$2)', self.getNid(), 'Cannot read or invalid probes param : [%s] configuration file : %s '%(param,str(e)) )
            raise mdsExceptions.TclFAILED_ESSENTIAL
        
        try:
            self.comment.putData(config_comment)
        except Exception as e :
            Data.execute('DevLogErr($1,$2)', self.getNid(), 'Error writing comment field ' + str(e) )
            raise mdsExceptions.TclFAILED_ESSENTIAL

        try:
            self.config_date.putData(config_date)
        except Exception as e :
            Data.execute('DevLogErr($1,$2)', self.getNid(), 'Error writing configuration date field ' + str(e) )
            raise mdsExceptions.TclFAILED_ESSENTIAL


        try:
            field = 'label'
            self.cfg_probes_label.putData(StringArray(label_arr))
            field = 'front_end'
            self.cfg_probes_front_end.putData(StringArray(front_end_arr))
            field = 'front_end_ch'
            self.cfg_probes_front_end_ch.putData(StringArray(front_end_ch_arr))
            field = 'adc_slow'
            self.cfg_probes_adc_slow.putData(StringArray(adc_slow_arr))
            field = 'adc_slow_con'
            self.cfg_probes_adc_slow_con.putData(StringArray(adc_slow_con_arr))
            field = 'adc_fast'
            self.cfg_probes_adc_fast.putData(StringArray(adc_fast_arr))
            field = 'calib_RV'
            self.cfg_probes_calib_rv.putData(StringArray(calib_RV_str_arr))
            field = 'calib_RI_high'
            self.cfg_probes_calib_ri_h.putData(StringArray(calib_RI_high_str_arr))
            field = 'calib_RI_low'
            self.cfg_probes_calib_ri_l.putData(StringArray(calib_RI_low_str_arr))
            field = 'note'
            self.cfg_probes_note.putData(StringArray(note_arr))
        except Exception as e :
            Data.execute('DevLogErr($1,$2)', self.getNid(), 'Error writing param %s probes : %s '%(field, str(e)) )
            raise mdsExceptions.TclFAILED_ESSENTIAL


        # Set off oll channel of the ADC module fast and slow defined in the configuration. 
        # ADC Channel is set ON if it is used. Thi is done to not acquire not usefull signals  

        adcSet = []
        for adc in adc_slow_arr :
            adc = adc.strip()
            if len(adc) == 0 :
                continue
            if not (adc in adcSet) :
                adcSet.append(adc)
                for i in range(1,33):
                    self.__setNodeState('\\%s.CHANNEL_%d'%(adc, i), False)
        del adcSet

        adcSet = []
        for adc in adc_fast_arr :
            adc = adc.strip()
            if len(adc) == 0 :
                continue
            if not (adc in adcSet) :
                adcSet.append(adc)
                for i in range(1,17):
                    self.__setNodeState('\\%s.CHANNEL_%d'%(adc, i), False)


        for i in range(0, self.PROBES_NUM):


            if  len( label_arr[i].strip() ) == 0 or label_arr[i].strip() == 'None' :
                continue

            print ('[%0.2d] Configuration for probe %s : '%(i+1, label_arr[i]),) 

            #print "Save probes %d %s"%(i+1, label_arr[i])

            try:
                getattr(self, 'probe_%02d_label'%(i+1)).putData(label_arr[i])
            except Exception as e :
                Data.execute('DevLogErr($1,$2)', self.getNid(), 'Error writing label field on probe %d : %s '%(i+1 , str(e)) )
                raise mdsExceptions.TclFAILED_ESSENTIAL


            try:
                getattr(self, 'probe_%02d_note'%(i+1)).putData(note_arr[i])
            except Exception as e :
                Data.execute('DevLogErr($1,$2)', self.getNid(), 'Error writing note field on probe %d : %s '%(i+1 , str(e)) )
                raise mdsExceptions.TclFAILED_ESSENTIAL


            if  len( front_end_arr[i].strip() ) == 0 or  front_end_arr[i].strip() == 'None':
                #print label_arr[i] + " probe reset data and set off"
                getattr(self, 'probe_%02d'%(i+1)).setOn(False)
                getattr(self, 'probe_%02d_front_end'%(i+1)).deleteData()
                getattr(self, 'probe_%02d_front_end_ch'%(i+1)).deleteData()
                getattr(self, 'probe_%02d_adc_slow'%(i+1)).deleteData()
                getattr(self, 'probe_%02d_adc_slow_con'%(i+1)).deleteData()
                getattr(self, 'probe_%02d_adc_fast'%(i+1)).deleteData()
                getattr(self, 'probe_%02d_calib_rv'%(i+1)).deleteData()
                getattr(self, 'probe_%02d_calib_ri_h'%(i+1)).deleteData()
                getattr(self, 'probe_%02d_calib_ri_l'%(i+1)).deleteData()
                getattr(self, 'probe_%02d_bias_source'%(i+1)).deleteData()
                getattr(self, 'probe_%02d_bias'%(i+1)).deleteData()
                getattr(self, 'probe_%02d_irange'%(i+1)).deleteData()
                getattr(self, 'probe_%02d_data_sv'%(i+1)).deleteData()
                getattr(self, 'probe_%02d_help_sv'%(i+1)).deleteData()
                getattr(self, 'probe_%02d_data_si'%(i+1)).deleteData()
                getattr(self, 'probe_%02d_help_si'%(i+1)).deleteData()
                getattr(self, 'probe_%02d_data_fv'%(i+1)).deleteData()
                getattr(self, 'probe_%02d_help_fv'%(i+1)).deleteData()
                getattr(self, 'probe_%02d_data_fi'%(i+1)).deleteData()
                getattr(self, 'probe_%02d_help_fi'%(i+1)).deleteData()

                try :
                   self.__getattr__('\\%sSV'%(label_arr[i]) ).setOn(False)
                   self.__getattr__('\\%sSI'%(label_arr[i]) ).setOn(False)
                   self.__getattr__('\\%sFV'%(label_arr[i]) ).setOn(False)
                   self.__getattr__('\\%sFI'%(label_arr[i]) ).setOn(False)
                except Exception :
                   print ('WARNING : The configuration excel file added the probe %s.\nThe updateSignalsProbes command MUST be execute'%(label_arr[i]) )  

                print ('[set OFF]')

                continue 
            else :
                print ('[set ON]')
                getattr(self, 'probe_%02d'%(i+1)).setOn(True)

            try:
                getattr(self, 'probe_%02d_front_end'%(i+1)).putData(front_end_arr[i])
            except Exception as e :
                Data.execute('DevLogErr($1,$2)', self.getNid(), 'Error writing front end field on probe %d : %s '%(i+1 , str(e)) )
                raise mdsExceptions.TclFAILED_ESSENTIAL

            try:
                getattr(self, 'probe_%02d_front_end_ch'%(i+1)).putData(Int32(int(front_end_ch_arr[i])))
            except Exception as e :
                Data.execute('DevLogErr($1,$2)', self.getNid(), '---Error writing front end channel field on probe %d : %s '%(i+1 , str(e)) )
                raise mdsExceptions.TclFAILED_ESSENTIAL

            try:                
                getattr(self, 'probe_%02d_adc_slow'%(i+1)).putData(adc_slow_arr[i])
            except Exception as e :
                Data.execute('DevLogErr($1,$2)', self.getNid(), 'Error writing adc slow field on probe %d : %s '%(i+1 , str(e)) )
                raise mdsExceptions.TclFAILED_ESSENTIAL

            try:
                if adc_slow_con_arr[i] == "CON_0" or adc_slow_con_arr[i] == "CON_1" : 
                    getattr(self, 'probe_%02d_adc_slow_con'%(i+1)).putData(adc_slow_con_arr[i])
                else:
                    Data.execute('DevLogErr($1,$2)', self.getNid(), 'Invalid value on adc slow connection field on probe %d, valid values CON_0, CON 1 '%(i+1) )
                    raise mdsExceptions.TclFAILED_ESSENTIAL
            except Exception as e :
                Data.execute('DevLogErr($1,$2)', self.getNid(), 'Error writing adc slow connection field on probe %d : %s '%(i+1 , str(e)) )
                raise mdsExceptions.TclFAILED_ESSENTIAL

            try:
                getattr(self, 'probe_%02d_adc_fast'%(i+1)).putData(adc_fast_arr[i])
            except Exception as e :
                Data.execute('DevLogErr($1,$2)', self.getNid(), 'Error writing adc fast field on probe %d : %s '%(i+1 , str(e)) )
                raise mdsExceptions.TclFAILED_ESSENTIAL

            try:
                getattr(self, 'probe_%02d_calib_rv'%(i+1)).putData(Float32(calib_RV_arr[i]))
            except Exception as e :
                Data.execute('DevLogErr($1,$2)', self.getNid(), 'Error writing resistence voltage calibration field on probe %d : %s '%(i+1 , str(e)) )
                raise mdsExceptions.TclFAILED_ESSENTIAL

            try:
                getattr(self, 'probe_%02d_calib_ri_h'%(i+1)).putData(Float32(calib_RI_high_arr[i]))
            except Exception as e :
                Data.execute('DevLogErr($1,$2)', self.getNid(), 'Error writing high current resistence calibration field on probe %d : %s '%(i+1 , str(e)) )
                raise mdsExceptions.TclFAILED_ESSENTIAL

            try:
                getattr(self, 'probe_%02d_calib_ri_l'%(i+1)).putData(Float32(calib_RI_low_arr[i]))
            except Exception as e :
                Data.execute('DevLogErr($1,$2)', self.getNid(), 'Error writing low current resistence calibration field on probe %d : %s '%(i+1 , str(e)) )
                raise mdsExceptions.TclFAILED_ESSENTIAL


            try:
               #Reset current link

               node = self.__getattr__('\\%s.CH_%02d:SOURCE'%(front_end_arr[i], int( front_end_ch_arr[i])));
               expr_val = Data.compile('build_path($)', node.getFullPath())	
               getattr(self, 'probe_%02d_bias_source'%(i+1)).putData( expr_val )
          
               """
               node = self.__getattr__('\\%s.CH_%02d:BIAS'%(front_end_arr[i], int( front_end_ch_arr[i])));
	       expr_val = Data.compile('build_path($)', node.getFullPath())	
               getattr(self, 'probe_%02d_bias'%(i+1)).putData( expr_val ) 
               """

               node = self.__getattr__('\\%s.CH_%02d:IRANGE'%(front_end_arr[i], int( front_end_ch_arr[i])));
               expr_val = Data.compile('build_path($)', node.getFullPath())
               irange_node = getattr(self, 'probe_%02d_irange'%(i+1)) 	
               irange_node.putData( expr_val )

               calib_rv_node = getattr(self, 'probe_%02d_calib_rv'%(i+1))
               calib_ri_high_node = getattr(self, 'probe_%02d_calib_ri_h'%(i+1))
               calib_ri_low_node = getattr(self, 'probe_%02d_calib_ri_l'%(i+1))
	
        
               if len( adc_slow_arr[i].strip() ) != 0 and adc_slow_arr[i].strip() != 'None' :

                   if adc_slow_con_arr[i] == "CON_0" :
                       adc_slow_i_node = self.__getattr__('\\%s.CHANNEL_%d:DATA'%(adc_slow_arr[i], int( front_end_ch_arr[i])) )
                       self.__setNodeState('\\%s.CHANNEL_%d'%(adc_slow_arr[i], int( front_end_ch_arr[i])), True)
                       adc_slow_v_node = self.__getattr__('\\%s.CHANNEL_%d:DATA'%(adc_slow_arr[i], int( front_end_ch_arr[i])+8 ))
                       self.__setNodeState('\\%s.CHANNEL_%d'%(adc_slow_arr[i], int( front_end_ch_arr[i])+8), True)
                   elif adc_slow_con_arr[i] == "CON_1" :
                       adc_slow_i_node = self.__getattr__('\\%s.CHANNEL_%d:DATA'%(adc_slow_arr[i], int( front_end_ch_arr[i])+16 ))
                       self.__setNodeState('\\%s.CHANNEL_%d'%(adc_slow_arr[i], int( front_end_ch_arr[i])+16), True)
                       adc_slow_v_node = self.__getattr__('\\%s.CHANNEL_%d:DATA'%(adc_slow_arr[i], int( front_end_ch_arr[i])+24 ))
                       self.__setNodeState('\\%s.CHANNEL_%d'%(adc_slow_arr[i], int( front_end_ch_arr[i])+24), True)
                   else:
                       Data.execute('DevLogErr($1,$2)', self.getNid(), 'Error invalid slow adc commector for probe %d (%s)'%(i+1, label_arr[i]) )
                       raise mdsExceptions.TclFAILED_ESSENTIAL



                   expr_slow_v = Data.compile('build_path($) *  build_path($)', calib_rv_node.getFullPath()  , adc_slow_v_node.getFullPath()) 
                   expr_slow_i = Data.compile("(build_path($) == 'LOW'  ?  build_path($) : build_path($) ) *  Build_path($)", irange_node.getFullPath() , calib_ri_low_node.getFullPath(), calib_ri_high_node.getFullPath()  , adc_slow_i_node.getFullPath()) 

                   getattr(self, 'probe_%02d_data_sv'%(i+1)).putData(expr_slow_v);
                   getattr(self, 'probe_%02d_help_sv'%(i+1)).putData('%s slow acquisition voltage'%(label_arr[i]));

                   getattr(self, 'probe_%02d_data_si'%(i+1)).putData(expr_slow_i);
                   getattr(self, 'probe_%02d_help_si'%(i+1)).putData('%s slow acquisition current'%(label_arr[i]));

                   getattr(self, 'probe_%02d_data_sv'%(i+1)).setOn(True)
                   getattr(self, 'probe_%02d_data_si'%(i+1)).setOn(True)

                   print ('[slow adc %s %s]'%(adc_slow_arr[i], adc_slow_con_arr[i]),)

                   try :
                      self.__getattr__('\\%sSV'%(label_arr[i]) ).setOn(True)
                      self.__getattr__('\\%sSI'%(label_arr[i]) ).setOn(True)
                   except Exception :
                      print ('\nWARNING : The configuration excel file added the probe %s.\nThe updateSignalsProbes command MUST be execute'%(label_arr[i]) )  

               else :
                   print (' ')
                   getattr(self, 'probe_%02d_data_sv'%(i+1)).deleteData()
                   getattr(self, 'probe_%02d_data_sv'%(i+1)).setOn(False)
                   getattr(self, 'probe_%02d_data_si'%(i+1)).deleteData()
                   getattr(self, 'probe_%02d_data_si'%(i+1)).setOn(False)
                   try :
                      self.__getattr__('\\%sSV'%(label_arr[i]) ).setOn(False)
                      self.__getattr__('\\%sSI'%(label_arr[i]) ).setOn(False)
                   except Exception :
                      print ('\nWARNING : The configuration excel file added the probe %s.\nThe updateSignalsProbes command MUST be execute'%(label_arr[i]))   


               if len( adc_fast_arr[i].strip() ) != 0 and adc_fast_arr[i].strip() != 'None' :


                   getattr(self, 'probe_%02d_data_fv'%(i+1)).setOn(True);
                   getattr(self, 'probe_%02d_data_fi'%(i+1)).setOn(True);

                   adc_fast_i_node = self.__getattr__('\\%s.CHANNEL_%d:DATA'%(adc_fast_arr[i], int( front_end_ch_arr[i]) ))
                   self.__setNodeState('\\%s.CHANNEL_%d'%(adc_fast_arr[i], int( front_end_ch_arr[i])), True)
                   adc_fast_v_node = self.__getattr__('\\%s.CHANNEL_%d:DATA'%(adc_fast_arr[i], int( front_end_ch_arr[i])+8 ))
                   self.__setNodeState('\\%s.CHANNEL_%d'%(adc_fast_arr[i], int( front_end_ch_arr[i])+8), True)

                   expr_fast_v = Data.compile('build_path($) *  build_path($)', calib_rv_node.getFullPath()  , adc_fast_v_node.getFullPath()) 
                   expr_fast_i = Data.compile("(build_path($) == 'LOW'  ?  build_path($) : build_path($) ) *  Build_path($)", irange_node.getFullPath() , calib_ri_low_node.getFullPath(), calib_ri_high_node.getFullPath()  , adc_fast_i_node.getFullPath()) 

                   getattr(self, 'probe_%02d_data_fv'%(i+1)).putData(expr_fast_v);
                   getattr(self, 'probe_%02d_help_fv'%(i+1)).putData('%s fast acquisition voltage'%(label_arr[i]));

                   getattr(self, 'probe_%02d_data_fi'%(i+1)).putData(expr_fast_i);
                   getattr(self, 'probe_%02d_help_fi'%(i+1)).putData('%s fast acquisition current'%(label_arr[i]));

                   print ('[fast adc %s]'%(adc_fast_arr[i]))

                   try :
                      self.__getattr__('\\%sFV'%(label_arr[i]) ).setOn(True)
                      self.__getattr__('\\%sFI'%(label_arr[i]) ).setOn(True)
                   except Exception :
                      print ('\nWARNING : The configuration excel file added the probe %s.\nThe updateSignalsProbes command MUST be execute'%(label_arr[i]))   

               else :
                   print (' ')
                   getattr(self, 'probe_%02d_data_fv'%(i+1)).deleteData();
                   getattr(self, 'probe_%02d_data_fv'%(i+1)).setOn(False);
                   getattr(self, 'probe_%02d_data_fi'%(i+1)).deleteData();
                   getattr(self, 'probe_%02d_data_fi'%(i+1)).setOn(False);
                   try :
                      self.__getattr__('\\%sFV'%(label_arr[i]) ).setOn(False)
                      self.__getattr__('\\%sFI'%(label_arr[i]) ).setOn(False)
                   except Exception :
                      print ('WARNING : The configuration excel file added the probe %s.\nThe updateSignalsProbes command MUST be execute'%(label_arr[i]) ) 

            except Exception as e:
                traceback.print_exc()
                Data.execute('DevLogErr($1,$2)', self.getNid(), 'Error setting link for probe %d (%s) to Front End %s ch %s : %s'%(i+1, label_arr[i], front_end_arr[i], front_end_ch_arr[i] ,str(e)))
                raise mdsExceptions.TclFAILED_ESSENTIAL

        return 1