Exemple #1
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 #2
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 #3
0
    def storeftp(self, arg):

        try:
            from xml.marshal.generic import dumps, loads, load
        except:
            print(
                "you must install PyXML to use this deprecated device.  Please switch to acq216 device type"
            )

        debug = self.debug

        path = self.local_path
        tree = self.local_tree
        shot = self.tree.shot
        CPCIDataDir = os.getenv('CPCI_DATA_DIR')
        if not CPCIDataDir:
            raise 'CPCI_DATA_DIR environment variable must be defined'
        dataDir = "%s/%s/%s/%s" % (
            CPCIDataDir,
            tree,
            shot,
            path,
        )
        try:
            settingsf = open("%s/settings.xml" % (dataDir, ), "r")
        except:
            raise Exception("Could not open Settings file %s/settings.xml" %
                            (dataDir, ))
        try:
            settings = load(settingsf)
        except:
            settingsf.close()
            raise Exception("Could not parse XML settings")
        settingsf.close()
        numSampsStr = settings['getNumSamples']
        preTrig = self.getPreTrig(numSampsStr)
        postTrig = self.getPostTrig(numSampsStr)
        #        vins = makeArray(numpy.array(settings['get.vin'].split(',')).astype('float'))
        range_strs = settings['getVoltsRange'].split()[1].split('=')[1].split(
            ',')
        range_strs[0] = range_strs[0][:-1]
        range_strs[1] = range_strs[1][:-1]
        vins = makeArray(numpy.array(range_strs).astype('float32'))
        coefficent = (vins[1] - vins[0]) / (2**16 - 1)
        chanMask = settings['getChannelMask'].split('=')[-1]
        if not 'ACTIVE' in settings['get.ext_clk']:
            #intClkStr=settings['getInternalClock'].split()[0].split('=')[1]
            #intClock=int(intClikStr)
            intClock = float(settings['getInternalClock'].split()[1])
            delta = 1. / float(intClock)
        else:
            delta = 0

        #trigExpr = 'self.%s'% str(self.trig_src.record)
        #trig_src = eval(trigExpr.lower())
        trig_src = self.__getattr__(str(self.trig_src.record).lower())
        #
        # now store each channel
        #
        for chan in range(16):
            if debug:
                print("working on channel %d" % chan)
            #chan_node = eval('self.input_%2.2d' % (chan+1,))
            chan_node = self.__getattr__('input_%2.2d' % (chan + 1, ))
            if chan_node.on:
                if debug:
                    print("it is on so ...")
                if chanMask[chan:chan + 1] == '1':
                    try:
                        #start = max(eval('int(self.input_%2.2d:start_idx)'%(chan+1,)), preTrig)
                        start = max(
                            int(
                                self.__getattr__('input_%2.2d_startidx' %
                                                 (chan + 1, ))), -preTrig)
                    except:
                        start = -preTrig
                    try:
                        #end = min(eval('int(self.input_%2.2d:end_idx)'%(chan+1,)), postTrig)
                        end = min(
                            int(
                                self.__getattr__('input_%2.2d_endidx' %
                                                 (chan + 1, ))), postTrig - 1)
                    except:
                        end = postTrig - 1
                    try:
                        #inc =  max(eval('int(self.input_%2.2d:inc)'%(chan+1,)), 1)
                        inc = max(
                            int(
                                self.__getattr__('input_%2.2d_inc' %
                                                 (chan + 1, ))), 1)
                    except:
                        inc = 1
#
# could do the coeffs
#
                    chanFileName = "%s/%2.2d" % (
                        dataDir,
                        chan + 1,
                    )
                    buf = self.readRawData(chanFileName, preTrig, start, end,
                                           inc)
                    #                    try:
                    #                        buf = self.readRawData(chanFileName, start, end, inc)
                    #                    except:
                    #                        print "Error Reading Channel %d"%(chan+1,)
                    if delta != 0:
                        axis = Range(None, None, delta / inc)
                    else:
                        #clockExpr = 'self.%s'% str(self.clock_src.record)
                        #clock_src = eval(clockExpr.lower())
                        clock_src = self.__getattr__(
                            str(self.clock_src.record).lower())
                        axis = clock_src

                    if inc == 1:
                        dim = Dimension(Window(start, end, trig_src), axis)
                    else:
                        dim = Data.compile(
                            'Map($,$)',
                            Dimension(Window(start / inc, end / inc, trig_src),
                                      axis), Range(start, end, inc))
                    dat = Data.compile(
                        'build_signal(build_with_units( $*(0. + $value), "V") ,build_with_units($,"Counts"),$)',
                        coefficent, buf, dim)
                    exec('c=self.input_' + '%02d' % (chan + 1, ) +
                         '.record=dat')
        return 1
Exemple #4
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 #5
0
 def time(r):
     return Dimension(None, r).setUnits("time")
Exemple #6
0
    def storeftp(self, arg):

        try:
            from xml.marshal.generic import dumps, loads, load
        except:
            print "you must install PyXML to use this deprecated device.  Please switch to acq216 device type"

        debug = os.getenv("DEBUG_DEVICES")

        path = self.local_path
        tree = self.local_tree
        shot = self.tree.shot
        CPCIDataDir = os.getenv('CPCI_DATA_DIR')
        if not CPCIDataDir:
            raise 'CPCI_DATA_DIR environment variable must be defined'
        dataDir = "%s/%s/%s/%s" % (
            CPCIDataDir,
            tree,
            shot,
            path,
        )
        try:
            settingsf = open("%s/settings.xml" % (dataDir, ), "r")
        except:
            raise Exception, "Could not open Settings file %s/settings.xml" % (
                dataDir, )
        try:
            settings = load(settingsf)
        except:
            settingsf.close()
            raise Exception, "Could not parse XML settings"
        settingsf.close()
        if debug:
            print "xml is loaded\n"
        status = []
        cmds = self.status_cmds.record
        for cmd in cmds:
            cmd = cmd.strip()
            if debug:
                print "about to append answer for /%s/\n" % (cmd, )
                print "   which is /%s/\n" % (settings[cmd], )
            status.append(settings[cmd])
            if debug:
                print "%s returned %s\n" % (
                    cmd,
                    settings[cmd],
                )
        if debug:
            print "about to write board_status signal"
        self.board_status.record = Signal(cmds, None, status)

        numSampsStr = settings['getNumSamples']
        preTrig = self.getPreTrig(numSampsStr)
        postTrig = self.getPostTrig(numSampsStr)
        vins = makeArray(
            numpy.array(settings['get.vin'].split(',')).astype('float'))
        self.ranges.record = vins
        chanMask = settings['getChannelMask'].split('=')[-1]
        if self.clock_src.record.lower(
        ) == 'int' or self.clock_src.record.lower() == 'master':
            #intClkStr=settings['getInternalClock'].split()[0].split('=')[1]
            #intClock=int(intClikStr)
            intClock = float(settings['getInternalClock'].split()[1])
            delta = 1. / float(intClock)
        else:
            delta = 0

        trig_src = self.__getattr__(str(self.trig_src.record).lower())
        #
        # now store each channel
        #
        for chan in range(16):
            if debug:
                print "working on channel %d" % chan
            #chan_node = eval('self.input_%2.2d' % (chan+1,))
            chan_node = self.__getattr__('input_%2.2d' % (chan + 1, ))
            if chan_node.on:
                if debug:
                    print "it is on so ..."
                if chanMask[chan:chan + 1] == '1':
                    try:
                        start = max(
                            int(
                                self.__getattr__('input_%2.2d_startidx' %
                                                 (chan + 1, ))), -preTrig)
                    except:
                        start = -preTrig
                    try:
                        end = min(
                            int(
                                self.__getattr__('input_%2.2d_endidx' %
                                                 (chan + 1, ))), postTrig - 1)
                    except:
                        end = postTrig - 1
                    try:
                        inc = max(
                            int(
                                self.__getattr__('input_%2.2d_inc' %
                                                 (chan + 1, ))), 1)
                    except:
                        inc = 1
#
# could do the coeffs
#
                    chanFileName = "%s/%2.2d" % (
                        dataDir,
                        chan + 1,
                    )
                    buf = self.readRawData(chanFileName, preTrig, start, end,
                                           inc)
                    if delta != 0:
                        axis = Range(None, None, delta / inc)
                    else:
                        #clockExpr = 'self.%s'% str(self.clock_src.record)
                        #clock_src = eval(clockExpr.lower())
                        clock_src = self.__getattr__(
                            str(self.clock_src.record).lower())
                        axis = clock_src

                    if inc == 1:
                        dim = Dimension(Window(start, end, trig_src), axis)
                    else:
                        dim = Data.compile(
                            'Map($,$)',
                            Dimension(Window(start / inc, end / inc, trig_src),
                                      axis), Range(start, end, inc))
#                    dat = Data.compile('build_signal(build_with_units( $*(0. + $value), "V") ,build_with_units($,"Counts"),$)', coefficent, buf,dim)
                    dat = Data.compile(
                        '_v0=$, _v1=$, build_signal(build_with_units(( _v0+ (_v1-_v0)*($value - -32768)/(32767 - -32768 )), "V") ,build_with_units($,"Counts"),$)',
                        vins[chan * 2], vins[chan * 2 + 1], buf, dim)
                    exec('c=self.input_' + '%02d' % (chan + 1, ) +
                         '.record=dat')
        return 1
Exemple #7
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 #8
0
    def store(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
    	try:
	    clock = TreeNode(baseNid + self.N_CLOCK_SOURCE).evaluate()
	    dt = clock.getDelta().data()
    	except:
	    print 'Error evaluating clock source' 
	    caenLib.CAENVME_End(handle)
	    return 0
    	try:
	    trig = TreeNode(baseNid + self.N_TRIG_SOURCE).data()
    	except:
	    print 'Error evaluating trigger source' 
	    caenLib.CAENVME_End(handle)
	    return 0
    	try:
	    startIdx = TreeNode(baseNid + self.N_START_IDX).data()
	    endIdx = TreeNode(baseNid + self.N_END_IDX).data()
    	except:
	    print 'Error evaluating start or end idx' 
	    caenLib.CAENVME_End(handle)
	    return 0
        try:
    	    pts = TreeNode(baseNid + self.N_PTS).data()
        except:
    	    print 'Error evaluating Post Trigger Samples' 
    	    caenLib.CAENVME_End(handle)
    	    return 0
    
    
    # Stop device 
        status = caenLib.CAENVME_WriteCycle(handle, c_int(vmeAddress + 0x8100), byref(c_int(0L)), c_int(self.cvA32_S_DATA), c_int(self.cvD32))
        if status != 0:
    	    print 'Error stopping device' 
    	    caenLib.CAENVME_End(handle)
    	    return 0
    #need to wait a while
        time.sleep(0.1)
    
    
    # Read number of buffers */
        actSegments = c_int(0)
        status = caenLib.CAENVME_ReadCycle(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' 
    	    caenLib.CAENVME_End(handle)
    	    return 0
    
        print 'Acquired segments: ', actSegments.value
	if actSegments.value == 0:
    	    caenLib.CAENVME_End(handle)
    	    return 1

    
    #Compute Segment Size
        try:
            nSegments = TreeNode(baseNid + self.N_NUM_SEGMENTS).data()
            segmentSamples = 196608/nSegments
    	    print 'Segment samples: ', segmentSamples
        except: 
    	    print 'Error reading max number of segments' 
    	    caenLib.CAENVME_End(handle)
    	    return 0
    	
    
    # Get Active groups
        groupMask = c_int(0)
        status = caenLib.CAENVME_ReadCycle(handle, c_int(vmeAddress + 0x8120), byref(groupMask), c_int(self.cvA32_S_DATA), c_int(self.cvD32))
        nActGroups = 0
        groupMask = groupMask.value
        for group in range(0,8):
    	    if (groupMask & (1 << group)) != 0:
    	    	nActGroups = nActGroups + 1
            if nActGroups == 0:
    		print 'No active groups' 
    		caenLib.CAENVME_End(handle)
    		return 1
 
       	segmentSize = 16 + segmentSamples * nActGroups * 8 * 12 / 8
       	class V1740Data(Structure):
        	_fields_ = [("eventSize", c_int), ("boardGroup", c_int), ("counter", c_int), ("time", c_int), ("data", c_int * (segmentSamples * 64*12/(8*4)))]
    
        actSegments = actSegments.value
        currStartIdx = segmentSamples - pts + startIdx
        currEndIdx = segmentSamples - pts + endIdx
    
        DataArray = c_short * ((currEndIdx - currStartIdx + 1) * actSegments)
        triggers = []
        deltas = []
        channels = [] 
        for chan in range(0,64):
    	    channels.append([])
        for chan in range(0,64):
    	    channels[chan] = DataArray()
    
        c = []
        for i in range(0,64):
    	    c.append(0)
        for sample in range(0,actSegments):
    	    segment= V1740Data()
    	    retLen = c_int(0)
    	    status = caenLib.CAENVME_FIFOBLTReadCycle(handle, c_int(vmeAddress), byref(segment), c_int(segmentSize), 
    		c_int(self.cvA32_S_DATA), c_int(self.cvD64), byref(retLen))
            if status != 0:
    		print 'Error reading data segment' 
    	  	caenLib.CAENVME_End(handle)
    		return 0
      	    actSize = 4 * (segment.eventSize & 0x0fffffff)
    	    if actSize != segmentSize: 
    		print 'Expected event size different from expected size' 
    	  	caenLib.CAENVME_End(handle)
    		return 0
    	    counter = segment.time/2
    	    triggers.append(counter*dt)
    	    deltas.append(dt)
    	    sizeInInts = (segment.eventSize & 0x0fffffff) - 4;
    	    groupSize = sizeInInts/nActGroups;
    	    groupOffset = 0
            for group in range(0,8):
    	    	if (groupMask & (1 << group)) != 0:
    		    rpnt = 0
    		    sampleCount = 0;
    		    while rpnt < groupSize :
    		        if rpnt % 9 == 0:
    			    if sampleCount >= currStartIdx and sampleCount <= currEndIdx :
    			    	channels[group*8][c[group*8+0]] = segment.data[groupOffset+rpnt] & 0x00000FFF
    				c[group*8+0] = c[group*8+0]+1
    			    if sampleCount +1 >= currStartIdx and sampleCount + 1 <= currEndIdx :
    			    	channels[group*8][c[group*8+0]] = (segment.data[groupOffset+rpnt] & 0x00FFF000) >> 12
    				c[group*8+0] = c[group*8+0]+1
    			    if sampleCount +2 >= currStartIdx and sampleCount +2 <= currEndIdx :
    			    	channels[group*8][c[group*8+0]] = ((segment.data[groupOffset+rpnt] & 0xFF000000) >> 24) | ((segment.data[groupOffset+rpnt+1] & 0x0000000F) << 8)
    				c[group*8+0] = c[group*8+0]+1
    		        if rpnt % 9 == 1:
    			    if sampleCount >= currStartIdx and sampleCount <= currEndIdx :
    			    	channels[group*8+1][c[group*8+1]] = (segment.data[groupOffset+rpnt] & 0x0000FFF0) >> 4
    				c[group*8+1] = c[group*8+1]+1
    			    if sampleCount +1 >= currStartIdx and sampleCount + 1 <= currEndIdx :
    			    	channels[group*8+1][c[group*8+1]] = (segment.data[groupOffset+rpnt] & 0x0FFF0000) >> 16
    				c[group*8+1] = c[group*8+1]+1
    			    if sampleCount +2 >= currStartIdx and sampleCount +2 <= currEndIdx :
    			    	channels[group*8+1][c[group*8+1]] = ((segment.data[groupOffset+rpnt] & 0xF0000000) >> 28) | ((segment.data[groupOffset+rpnt+1] & 0x000000FF) << 4)
    				c[group*8+1] = c[group*8+1]+1
    		        if rpnt % 9 == 2:
    			    if sampleCount >= currStartIdx and sampleCount <= currEndIdx :
    			    	channels[group*8+2][c[group*8+2]] = (segment.data[groupOffset+rpnt] &   0x000FFF00) >> 8
    				c[group*8+2] = c[group*8+2]+1
    			    if sampleCount +1 >= currStartIdx and sampleCount + 1 <= currEndIdx :
    		    	    	channels[group*8+2][c[group*8+2]] = (segment.data[groupOffset+rpnt] & 0xFFF00000) >> 20
    				c[group*8+2] = c[group*8+2]+1
    		        if rpnt % 9 == 3:
    			    if sampleCount +2 >= currStartIdx and sampleCount +2 <= currEndIdx :
    		    	    	channels[group*8+2][c[group*8+2]] = segment.data[groupOffset+rpnt] &  0x00000FFF
    				c[group*8+2] = c[group*8+2]+1
    			    if sampleCount >= currStartIdx and sampleCount <= currEndIdx :
    		    	    	channels[group*8+3][c[group*8+3]] = (segment.data[groupOffset+rpnt]  & 0x00FFF000) >> 12
    				c[group*8+3] = c[group*8+3]+1
    			    if sampleCount +1 >= currStartIdx and sampleCount + 1 <= currEndIdx :
    		    	    	channels[group*8+3][c[group*8+3]] = ((segment.data[groupOffset+rpnt]  & 0xFF000000) >> 24) | ((segment.data[groupOffset+rpnt+1] & 0x0000000F) << 8)
    				c[group*8+3] = c[group*8+3]+1
    		        if rpnt % 9 == 4:
    			    if sampleCount +2 >= currStartIdx and sampleCount +2 <= currEndIdx :
    		    	    	channels[group*8+3][c[group*8+3]] = (segment.data[groupOffset+rpnt] & 0x0000FFF0) >> 4
    				c[group*8+3] = c[group*8+3]+1
   			    if sampleCount >= currStartIdx and sampleCount <= currEndIdx :
    		    	    	channels[group*8+4][c[group*8+4]] = (segment.data[groupOffset+rpnt] & 0x0FFF0000) >> 16
    				c[group*8+4] = c[group*8+4]+1
    			    if sampleCount +1 >= currStartIdx and sampleCount + 1 <= currEndIdx :
    		    	    	channels[group*8+4][c[group*8+4]] = ((segment.data[groupOffset+rpnt] & 0xF0000000) >> 28) | ((segment.data[groupOffset+rpnt+1] & 0x000000FF) << 4)
    				c[group*8+4] = c[group*8+4]+1
    		        if rpnt % 9 == 5:
    			    if sampleCount +2 >= currStartIdx and sampleCount +2 <= currEndIdx :
    		    	    	channels[group*8+4][c[group*8+4]] = (segment.data[groupOffset+rpnt]  & 0x000FFF00) >> 8
    				c[group*8+4] = c[group*8+4]+1
    			    if sampleCount >= currStartIdx and sampleCount <= currEndIdx :
    		    	    	channels[group*8+5][c[group*8+5]] = (segment.data[groupOffset+rpnt] & 0xFFF00000) >> 20
    				c[group*8+5] = c[group*8+5]+1
    		        if rpnt % 9 == 6:
    			    if sampleCount +1 >= currStartIdx and sampleCount + 1 <= currEndIdx :
    		    	    	channels[group*8+5][c[group*8+5]] = segment.data[groupOffset+rpnt]  & 0x00000FFF
    				c[group*8+5] = c[group*8+5]+1
    			    if sampleCount +2 >= currStartIdx and sampleCount +2 <= currEndIdx :
    		    	    	channels[group*8+5][c[group*8+5]] = (segment.data[groupOffset+rpnt] & 0x00FFF000) >> 12
    				c[group*8+5] = c[group*8+5]+1
    			    if sampleCount >= currStartIdx and sampleCount <= currEndIdx :
    		    	    	channels[group*8+6][c[group*8+6]] = ((segment.data[groupOffset+rpnt] & 0xFF000000) >> 24) | ((segment.data[groupOffset+rpnt+1] & 0x0000000F) << 8)
    				c[group*8+6] = c[group*8+6]+1
    		        if rpnt % 9 == 7:
    			    if sampleCount +1 >= currStartIdx and sampleCount + 1 <= currEndIdx :
    		    	    	channels[group*8+6][c[group*8+6]] = (segment.data[groupOffset+rpnt] & 0x0000FFF0) >> 4
    				c[group*8+6] = c[group*8+6]+1
    			    if sampleCount +2 >= currStartIdx and sampleCount +2 <= currEndIdx :
    		    	    	channels[group*8+6][c[group*8+6]] = (segment.data[groupOffset+rpnt] & 0x0FFF0000) >> 16
    				c[group*8+6] = c[group*8+6]+1
    			    if sampleCount >= currStartIdx and sampleCount <= currEndIdx :
    		    	    	channels[group*8+7][c[group*8+7]] = ((segment.data[groupOffset+rpnt] & 0xF0000000) >> 28) | ((segment.data[groupOffset+rpnt+1] & 0x000000FF) << 4)
    				c[group*8+7] = c[group*8+7]+1
    		        if rpnt % 9 == 8:
    			    if sampleCount +1 >= currStartIdx and sampleCount + 1 <= currEndIdx :
    		    	    	channels[group*8+7][c[group*8+7]] = (segment.data[groupOffset+rpnt] & 0x000FFF00) >> 8
    				c[group*8+7] = c[group*8+7]+1
    			    if sampleCount +2 >= currStartIdx and sampleCount +2 <= currEndIdx :
    		    	    	channels[group*8+7][c[group*8+7]] = (segment.data[groupOffset+rpnt] & 0xFFF00000) >> 20
    				c[group*8+7] = c[group*8+7]+1
    		        if rpnt % 9 == 8:
    		    	    sampleCount = sampleCount + 3
    		        rpnt = rpnt + 1
    		    #endwhile
    		    groupOffset = groupOffset + groupSize
    	        #endif 
            #endfor group in range(0:8)
        #endfor samples in range(0, actSegments)
    
    	
        if len(TreeNode(baseNid + self.N_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)))
    
        print 'DIM: ', dim
        dim.setUnits("s");
        chan0Nid = baseNid + self.N_CHANNEL_0
        data0Nid = baseNid + self.N_DATA_0
        for group in range(0,8):
    	    if groupMask & (1 << group):
        	try:
    	    	    offset = TreeNode(baseNid + self.N_CHANNEL_0 + group * self.N_CHAN_DATA + self.N_CHAN_OFFSET).data()
        	except:
    		    print 'Error evaluating group offset' 
    		    caenLib.CAENVME_End(handle)
    		    return 0
    	        for chan in range(0,8):
    		    raw = Int16Array(channels[group * 8 + chan])
    		    raw.setUnits("counts")
    		    data = Data.compile("2*($VALUE - 2048)/4096.+$1", offset);
    		    data.setUnits("Volts")
    		    signal = Signal(data, raw, dim)
    		    try:
    		    	TreeNode(baseNid + self.N_DATA_0 + group * 8 + chan).putData(signal)
        	    except:
    		    	print 'Cannot write Signal in the tree' 
    		    	caenLib.CAENVME_End(handle)
    		    	return 0
        	#endfor
    	    #endif
        #endfor
    
        caenLib.CAENVME_End(handle)
        return 1
      except:
	print 'Generic Error' 
	caenLib.CAENVME_End(handle)
	return 0
Exemple #9
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 #10
0
    def store(self, arg):
        """
        Store the data from the device
        Fetch and store the device status (firmware etc)
        If the device is finished
        For each channel that is on and active in the mask
        read the data
        store the data into the raw nodes
        store the expression into the data nodes
        """

        debug = os.getenv("DEBUG_DEVICES")
        try:
            boardip = self.check('str(self.boardip.record)',
                                 "Must specify a board ipaddress")
            UUT = acq200.Acq200(transport.factory(boardip))
            try:
                ans = []
                cmds = self.status_cmds.record
                for cmd in cmds:
                    print(cmd)
                    a = UUT.uut.acq2sh(cmd)
                    ans.append(a)
                self.board_status.record = Data.compile(
                    'build_signal($,*, $)', ans, cmds)
            except Exception:
                pass

            complete = 0
            tries = 0
            if UUT.get_state().split()[-1] == "ST_RUN":
                raise Exception(
                    "Device not Triggered \n device returned -%s-" %
                    UUT.get_state().split()[-1])
            if debug:
                print("about to get the vins\n")
            vins = self.getVins(UUT)
            self.ranges.record = vins
            (tot, pre, post, run) = UUT.get_numSamples()
            pre = int(pre)
            post = int(post)
            if pre == 0 and post == 0:
                return 662480266  # DT196B$_NO_SAMPLES
            mask = UUT.uut.acqcmd('getChannelMask').split('=')[-1]
            if debug:
                print("pre = %d, post = %d" % (
                    pre,
                    post,
                ))
            clock_src = self.check(
                'str(self.clock_src.record.getOriginalPartName())[1:]',
                "Clock source must be a string")
            if clock_src == 'INT_CLOCK':
                self.clock.record = Range(delta=1. /
                                          self.getInternalClock(UUT))
            else:
                self.clock.record = self.clock_src

            clock = self.clock.record
            if debug:
                print("about to start the script")

            (fd, fname) = mkstemp('.sh')
            f = open(fname, 'w')
            f.write("#!/bin/sh\n")
            f.write("touch /tmp/starting_%d\n" % self.boardip.tree.shot)
            f.write("acqcmd --until ST_STOP\n")
            f.write("mdsConnect %s\n" % str(self.hostip.record))
            cmd = "mdsValue \"job_start('%s', %d)\"" % (self.path,
                                                        self.tree.shot)
            cmd = cmd.replace('\\', '\\\\\\\\\\\\\\')
            f.write("%s\n" % (cmd, ))
            f.write("mdsOpen %s %d\n" % (
                self.boardip.tree.name,
                self.boardip.tree.shot,
            ))
            for chan in range(96):
                chan_node = eval('self.input_%2.2d' % (chan + 1, ))
                chan_raw_node = eval('self.input_%2.2d_raw' % (chan + 1, ))
                if chan_node.on:
                    if debug:
                        print("it is on so ...")
                    if mask[chan:chan + 1] == '1':
                        try:
                            start = eval("int(self.input_%2.2d_start_idx)" %
                                         (chan + 1))
                        except:
                            start = pre
                        try:
                            end = eval("int(self.input_%2.2d_end_idx" %
                                       (chan + 1))
                        except:
                            end = post - 1
                        try:
                            inc = eval("int(self.input_%2.2d_inc)" %
                                       (chan + 1))
                        except:
                            inc = 1
                        if debug:
                            print("build the command")
                        command = "mdsPutCh --field %s:raw --expr %%calsig --timebase %d,%d,%d %d\n" % (
                            chan_node.getFullPath(), int(start), int(end),
                            int(inc), chan + 1)
                        command = command.replace('\\', '\\\\')
                        if debug:
                            print("about to execute %s" % command)
                        f.write(command)
                        if inc > 1:
                            clk = None
                            delta = None
                            begin = None
                            ending = None
                            try:
                                clk = self.clock.evaluate()
                                delta = clk.delta
                                begin = clk.begin
                                ending = clk.ending
                            except:
                                pass
                            if delta:
                                axis = Range(begin, ending, delta * inc)
                                window = Window(start / inc, end / inc,
                                                self.trig_src)
                                dim = Dimension(window, axis)
                            else:
                                dim = Data.compile(
                                    'Map($,$)',
                                    Dimension(
                                        Window(start / inc, end / inc,
                                               trig_src), clock),
                                    Range(start, end, inc))
                            raw = Data.compile('data($)', chan_raw_node)
                            chan_node.record = eval('Signal(raw, "", dim)')
                        else:
                            raw = Data.compile('data($)', chan_raw_node)
                            chan_node.record = Signal(
                                raw, "",
                                Dimension(
                                    Window(start, end - 1, self.trig_src),
                                    clock))
            f.write('mdsClose %s\n' % (self.boardip.tree.name, ))
            f.write("touch /tmp/finished_%d\n" % self.boardip.tree.shot)
            cmd = "mdsValue \"job_finish('%s', %d)\"" % (self.path,
                                                         self.tree.shot)
            cmd = cmd.replace('\\', '\\\\\\\\\\\\\\')
            f.write("%s\n" % (cmd, ))
            f.write("rm $0\n")
            f.close()
            cmd = 'curl -s -T %s ftp://%s/%s' % (fname, boardip,
                                                 'post_shot.sh')
            pipe = os.popen(cmd)
            pipe.close()
            UUT.uut.acq2sh("chmod a+rx /home/ftp/post_shot.sh")
            UUT.uut.acq2sh("/home/ftp/post_shot.sh&")
        except Exception as e:
            print("Error storing DT196B Device\n%s" % (str(e), ))
            return 0

        return 1
Exemple #11
0
 def run(self):
     Tree.usePrivateCtx(True)
     try:  # test open Nodes
         tree = Tree(self.tree, self.shot)
         try:
             tree.getNode(self.pcb)
         except Exception as exc:
             error(exc)
             self.pcb = None
         try:
             tree.getNode(self.cmos)
         except Exception as exc:
             error(exc)
             self.cmos = None
     except Exception as exc:
         error(exc)
         error(
             'Cannot access trend tree. Check TREND:TREE and TREND_SHOT.'
         )
         raise mdsExceptions.TreeTNF
     if self.pcb is None and self.cmos is None:
         error(
             'Cannot access any node for trend. Check TREND:PCB, TREND:CMOS on. Nodes must exist on %s.'
             % repr(tree))
         raise mdsExceptions.TreeNNF
     if self.pcb is None:
         error(
             'Cannot access node for pcb trend. Check TREND:PCB. Continue with cmos trend.'
         )
     elif self.cmos is None:
         error(
             'Cannot access node for cmos trend. Check TREND:CMOS. Continue with pcb trend.'
         )
     print('started trend writing to %s - %s and %s every %fs' %
           (self.tree, self.pcb, self.cmos, self.period))
     self.running = True
     while (not self.stopReq):
         timeTillNextMeasurement = self.period - (time() % self.period)
         if timeTillNextMeasurement > 0.6:
             sleep(.5)  # listen to stopReq
         else:
             sleep(timeTillNextMeasurement)
             # wait remaining period unit self.period
             currTime = int(
                 int(time() / self.period + .1) * self.period * 1000)
             # currTime in steps of self.period
             if self.ns: currTime *= 1000000  # time in nano seconds
             try:
                 if self.shot == 0:
                     if Tree.getCurrent(self.tree) != tree.shot:
                         tree = Tree(self.tree, self.shot)
                 if self.pcb is not None:
                     pcbTemp = CYGNET4K.xclib.getPcbTemp()
                     tree.getNode(self.pcb).makeSegment(
                         currTime, currTime,
                         Dimension(None, Uint64Array(currTime)),
                         Float32Array(pcbTemp).setUnits('oC'), -1)
                 if self.cmos is not None:
                     cmosTemp = CYGNET4K.xclib.getCmosTemp()
                     tree.getNode(self.cmos).makeSegment(
                         currTime, currTime,
                         Dimension(None, Uint64Array(currTime)),
                         Uint16Array(cmosTemp), -1)
                 if Device.debug:
                     print(tree.tree, tree.shot, currTime, pcbTemp,
                           cmosTemp)
             except Exception:
                 error(exc_info()[1])
                 error('failure during temperature readout')
             sleep(0.01)
     self.running = False
     print('done')
Exemple #12
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 #13
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 #14
0
 def axis(r, idx):
     return Dimension(None, r).setUnits("dim_of(" + str(idx) + ")")
Exemple #15
0
    def store(self):
        #import required symbols from MDSSplus and ctypes packages

        #instantiate library object
        try:
            deviceLib = CDLL("libDemoAdcShr.so")
        except:
            print('Cannot link to device library')
            return 0

#get addr
        try:
            addr = self.addr.data()
#we expect to get a string in addr
        except:
            print('Missing Addr in device')
            return 0

#instantiate four short arrays with 65536 samples each. They will be passed to the acquire() external routine
        DataArray = c_short * 65536
        rawChan = []
        rawChan.append(DataArray())
        rawChan.append(DataArray())
        rawChan.append(DataArray())
        rawChan.append(DataArray())

        status = deviceLib.acquire(c_char_p(addr), byref(rawChan[0]),
                                   byref(rawChan[1]), byref(rawChan[2]),
                                   byref(rawChan[3]))
        if status == -1:
            print('Acquisition Failed')
            return 0

#at this point the raw signals are contained in rawChan1-4. We must now:
#1) reduce the dimension of the stored array using the start idx and end idx parameters for each channel, which define
#   the number of samples around the trigger which need to be stored in the pulse file (for this purpose the value of
#   post trigger samples is also required)
#2) build the appropriate timing information
#3) Put all together in a Signal object
#4) store the Signal object in the tree

#read PostTriggerSamples
        try:
            pts = self.pts.data()
        except:
            print('Missing or invalid Post Trigger Samples')
            return 0
#for each channel we read start idx and end idx
        startIdx = []
        endIdx = []
        try:
            for chan in range(0, 4):
                currStartIdx = self.__getattr__('channel_%d_start_idx' %
                                                (chan)).data()
                currEndIdx = self.__getattr__('channel_%d_end_idx' %
                                              (chan)).data()
                startIdx.append(currStartIdx)
                endIdx.append(currEndIdx)
        except:
            print('Cannot read start idx or end idx')
            return 0
#1)Build reduced arrays based on start idx and end idx for each channel
#recall that a transient recorder stores acquired data in a circular buffer and stops after acquiring
#PTS samples after the trigger. This means that the sample corresponding to the trigger is at offset PTS samples
#before the end of the acquired sample array.

#the total number of samples returned by routine acquire()
        totSamples = 65536

        #we read the time associated with the trigger. It is specified in the TRIG_SOURCE field of the device tree structure.
        #it will be required in order to associate the correct time with each acquired sample
        try:
            trigTime = self.trig_source.data()
        except:
            print('Missing or invalid Post Trigger Samples')
            return 0
#we need clock frequency as well
        try:
            clockFreq = self.clock_freq.data()
            clockPeriod = 1. / clockFreq
        except:
            print('Missing or invalid clock frequency')
            return 0

#the following steps are performed for each acquired channel
        for chan in range(0, 4):
            actStartIdx = totSamples - pts + startIdx[
                chan]  #first index of the part of interest of the sample array
            actEndIdx = totSamples - pts + endIdx[
                chan]  #last index of the part of interest of the sample array
            #make sure we do not exceed original array limits
            if actStartIdx < 0:
                actStartIdx = 0
            if actEndIdx > totSamples:
                actEndIdx = totSamples - 1
#build reshaped array
            reducedRawChan = rawChan[chan][actStartIdx:actEndIdx]

            #2)Build timing information. For this purpose we use a  MDSplus "Dimension" object which contains two fields:
            # "Window" and "Axis". Window object defines the start and end index of the associated data array and the time which is
            # associated with the sample at index 0. Several possible combination of start and end indexes are possible (the can also be
            #negative numbers). We adopt here the following convention: consider index 0 as the index of the sample corresponding
            #to the trigger, and therefore associated with the trigger time. From the way we have built the reduced raw sample array,
            #it turns out that the start idx and end idx defined
            #in the Window object are the same of the start and end indexes defined in the device configuration.
            #
            #The "Range" object describes a (possibly multispeed or busrt) clock. Its fields specify the clock period, the start and end time
            #for that clock frequency. In our case we need to describe a continuous single speed clock, so there is no need to
            #specify start and end times(it is a continuous, single speed clock).
            #
            #build the Dimension object in a single call
            dim = Dimension(Window(startIdx[chan], endIdx[chan], trigTime),
                            Range(None, None, clockPeriod))

            #3) Put all togenther in a "Signal" object. MDSplus Signal objects define three fields: samples, raw samples, dimension
            #   raw samples are contained in reducedRawChan. The computation required to convert the raw 16 bit sample into a +-10V
            #   value is: sample = 10.*rawSample/32768. We may compute a new float array containing such data and store it together
            #   with the raw sample (in the case we would like to reain also raw data. There is however a better way to do it
            #   by storing only the required information, i.e. the raw(16 bit) samples and the definition of the expression which
            #   converts raw data into actual voltage levels. Therefore, the first field of the Signal object will contain only the
            #   definition of an expression, which refers to the raw samples (the second field) of the same Signal object.
            #   The MDSplus syntax for this conversion is:  10.*$VALUE/32768.
            #   We shall use Data method compile() to build the MDSplus internal representation of this expression, and the stick it
            #   as the first field of the Signal object
            convExpr = Data.compile("10.* $VALUE/32768.")

            #use MDSplus Int16Array object to vest the short array reducedRawChan into the appropriate MDSplus type
            rawMdsData = Int16Array(reducedRawChan)

            #every MDSplus data type can have units associated with it
            rawMdsData.setUnits("Count")
            convExpr.setUnits("Volt")

            #build the signal object
            signal = Signal(convExpr, rawMdsData, dim)

            #write the signal in the tree
            try:
                self.__getattr__('channel_%d_data' % (chan)).putData(signal)
            except:
                print('Cannot write Signal in the tree')
                return 0

#endfor chan in range(0,4):

#return success (odd numbers in MDSplus)
        return 1
Exemple #16
0
    def store(self, arg):
        """
        Store the data from the device
        Fetch and store the device status (firmware etc)
        If the device is finished
        For each channel that is on and active in the mask
        read the data
        store the data into the raw nodes
        store the expression into the data nodes
        """

        debug = os.getenv("DEBUG_DEVICES")
        try:
            error = "Must specify a board ipaddress"
            boardip = str(self.boardip.record)
            error = None
            UUT = acq200.ACQ200(transport.factory(boardip))
            try:
                ans = []
                cmds = self.status_cmds.record
                for cmd in cmds:
                    print cmd
                    a = UUT.uut.acq2sh(cmd)
                    ans.append(a)
                self.board_status.record = Signal(makeArray(ans), None,
                                                  makeArray(cmds))
            except Exception, e:
                pass

            complete = 0
            tries = 0
            while not complete and tries < 60:
                if UUT.get_state().split()[-1] == "ST_POSTPROCESS":
                    tries += 1
                    sleep(1)
                else:
                    complete = 1
            if UUT.get_state().split()[-1] != "ST_STOP":
                raise Exception, "Device not Triggered \n device returned -%s-" % UUT.get_state(
                ).split()[-1]
            if debug:
                print "about to get the vins\n"
            vins = self.getVins(UUT)
            self.ranges.record = vins
            (tot, pre, post, run) = UUT.get_numSamples()
            pre = int(pre) * -1
            post = int(post) - 1
            mask = UUT.uut.acqcmd('getChannelMask').split('=')[-1]
            error = "Clock source must be a string"
            clock_src = self.clock_src.record.getOriginalPartName().getString(
            )[1:]
            error = None
            if clock_src == 'INT_CLOCK':
                self.clock.record = Range(delta=1. /
                                          self.getInternalClock(UUT))
            else:
                self.clock.record = self.clock_src

            clock = self.clock.record
            if debug:
                print "about to ask it to mdsconnect"
            UUT.uut.acq2sh("mdsConnect %s" % str(self.hostip.record))
            if debug:
                print "about to ask it to mdsopen"
            UUT.uut.acq2sh('mdsOpen %s %d' % (
                self.boardip.tree.name,
                self.boardip.tree.shot,
            ))
            for chan in range(32):
                if debug:
                    print "working on channel %d" % chan
                chan_node = self.__getattr__('input_%2.2d' % (chan + 1, ))
                chan_raw_node = self.__getattr__('input_%2.2d_raw' %
                                                 (chan + 1, ))
                if chan_node.on:
                    if debug:
                        print "it is on so ..."
                    if mask[chan:chan + 1] == '1':
                        try:
                            start = max(
                                int(
                                    self.__getattr__('input_%2.2d_start_idx' %
                                                     (chan + 1))), pre)
                            print "start = %d" % start
                        except:
                            start = pre
                        try:
                            end = min(
                                int(
                                    self.__getattr__('input_%2.2d_end_idx' %
                                                     (chan + 1))), post)
                            print "end = %d" % end
                        except:
                            end = post
                        try:
                            inc = int(
                                self.__getattr__('input_%2.2d_inc' %
                                                 (chan + 1)))
                            print "inc = %d" % inc
                        except:
                            inc = 1
                        if debug:
                            print "build the command"
                        command = "mdsPutCh --field %s:raw --expr %%calsig --timebase %d,%d,%d %d" % (
                            chan_node.getFullPath(), int(start - pre),
                            int(end - pre), int(inc), chan + 1)
                        command = command.replace('\\', '\\\\')
                        if debug:
                            print "about to execute %s" % command
                        UUT.uut.acq2sh(command)
                        if inc > 1:
                            clk = ''
                            delta = ''
                            begin = ''
                            end = ''
                            try:
                                clk = self.clock.evaluate()
                                delta = clk.delta
                                begin = clk.begin
                                ending = clk.end
                            except:
                                pass
                            if delta:
                                axis = Range(begin, ending, delta / inc)
                                window = Window(start / inc, end / inc,
                                                trigger)
                                dim = Dimension(window, axis)
                            else:
                                dim = Data.Compile(
                                    'Map($,$)',
                                    Dimension(
                                        Window(start / inc, end / inc,
                                               trigger), clock),
                                    Range(start, end, inc))
                                raw = Data.compile('data($)', chan_raw_node)
                                chan_node.record = Signal(raw, None, dim)
                        else:
                            raw = Data.compile('data($)', chan_raw_node)
                            chan_node.record = Signal(
                                raw, None,
                                Dimension(Window(start, end, self.trig_src),
                                          clock))

            UUT.uut.acq2sh('mdsClose %s' % (self.boardip.tree.name, ))
Exemple #17
0
	def store(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, c_char_p
		print '************ START STORE ************'
	# Get IP Address
		try:
			ipAddr = self.ip_addr.data()
		except:
			Data.execute('DevLogErr($1,$2)', self.nid, 'Invalid Remote IP Address')
			return 0
	# Get Base Address   
		try:
			baseAddr = self.base_addr.data()
		except: 
			Data.execute('DevLogErr($1,$2)', self.nid, 'Invalid Base Address specification')
			return 0
	# Get Scan Count
		try:
			scanCount = self.scan_count.data()
		except:
			Data.execute('DevLogErr($1,$2)', self.nid, 'Invalid Scan Count')
			return 0	  
		print 'Scan Count=',scanCount
	# Get LNE Mode
		lneModeDict = {'VME':0, 'CONTROL SIGNAL':1, 'INTERNAL 10MHZ':2, 'CHANNEL N':3, 'PRESET':4}
		try:
			lneMode = lneModeDict[self.lne_mode.data()]
		except:
			Data.execute('DevLogErr($1,$2)', self.nid, 'Invalid LNE Mode')
			return 0
		print 'LNE Mode=',lneMode
	# Get LNE Source
		try:
			lneSource = self.lne_source.data()
		except:
			Data.execute('DevLogErr($1,$2)', self.nid, 'Invalid LNE Source')
			return 0	  
		print 'LNE Source=',lneSource
	# Get Channels Setup
		channelMask = 0
		for a in range(0, 32):
			if a < 10:
				if getattr(self, 'channel_0%d'%(a)).isOn():
					print 'Channel_0' + str(a) + ' IS ON'
					channelMask = channelMask | (1 << a)
			else:
				if getattr(self, 'channel_%d'%(a)).isOn():
					print 'Channel_' + str(a) + ' IS ON'
					channelMask = channelMask | (1 << a)
		del a
		print 'Channel Mask= ', channelMask
	# Connect to SIS3820 via MDS IP
		status = Data.execute('MdsConnect("'+ ipAddr +'")')
		if status == 0:
			Data.execute('MdsDisconnect()')
			Data.execute('DevLogErr($1,$2)', self.nid, 'Cannot Connect to VME. See VME console for details')
			return 0
	# Wait End Acquisition
		status = Data.execute('MdsValue("SIS3820->sis3820_waitEndAcquisition(val($1), val($2))", $1, $2)', baseAddr, scanCount)
		if status <> 0:
			Data.execute('MdsDisconnect()')
			Data.execute('DevLogErr($1,$2)', self.nid, 'Cannot execute HW Acquisition. See VME console for details')
			return 0
	# Pre Store Fase
		status = Data.execute('MdsValue("SIS3820->sis3820_preStore(val($1), val($2))", $1, $2)', baseAddr, channelMask)
		if status <> 0:
			Data.execute('MdsDisconnect()')
			Data.execute('DevLogErr($1,$2)', self.nid, 'Cannot execute HW Acquisition. See VME console for details')
			return 0
		
		DataArray = c_int * scanCount		
		rawChan = []
		rawChan = DataArray()		

		if lneMode == 2:
			trigTime = 0
			clockPeriod = 10e-6
                else:
			try:
				clk = self.lne_source.evaluate()
				clockPeriod = clk.delta
				trigTime = clk.begin
				#ending = clk.end
			except:
				Data.execute('DevLogErr($1,$2)', self.nid, 'Invalid LNE Source')
				return 0	  
		
		for chan in range(0,32):
			if channelMask & ( 1 << chan ):
			# Read Chan Data
				rawChan = Data.execute('MdsValue("SIS3820->sis3820_readChData:dsc( val($1))", $1)', chan)
			# Build the Dimension object in a single call
				dim = Dimension(Window(0, scanCount, trigTime), Range(None, None, clockPeriod))
			# Put all togenther in a "Signal" object. 			
				convExpr = Data.compile("$VALUE")
			# Use MDSplus Int32Array object
				rawMdsData = Int32Array( rawChan )
			# Every MDSplus data type can have units associated with it
				rawMdsData.setUnits("Count")
				convExpr.setUnits("Count")
			# Build the signal object
				signal = Signal(convExpr, rawMdsData, dim)		
			# Write the signal in the tree 
				if chan < 10:
					try:
						self.__getattr__('channel_0%d_data'%(chan)).putData(signal)
					except:
						Data.execute('DevLogErr($1,$2)', self.nid, 'Cannot write Signal in the tree')
						print 'Cannot write Signal in the tree' 		
				else:
					try:
						self.__getattr__('channel_%d_data'%(chan)).putData(signal)
					except:
						Data.execute('DevLogErr($1,$2)', self.nid, 'Cannot write Signal in the tree')
						print 'Cannot write Signal in the tree' 		

		Data.execute('MdsDisconnect()')	
		del chan
		print '************ END STORE ************'
		return 1
########################################### END STORE #######################################	  
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('================= 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 #20
0
    def store(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:  # except line 508
            boardId = self.board_id.data()
            if Device.debug: print('BOARD ID: ', boardId)
            vmeAddress = self.vme_address.data()
            if Device.debug: print('VME ADDRESS: ', vmeAddress)
            try:
                clock = self.clock_source.evaluate()
                dt = clock.getDelta().data()
            except:
                print('Error evaluating clock source')
                CAENV1740.caenLib.CAENVME_End(handle)
                raise mdsExceptions.TclFAILED_ESSENTIAL
            try:
                trig = self.trig_source.data()
            except:
                print('Error evaluating trigger source')
                CAENV1740.caenLib.CAENVME_End(handle)
                raise mdsExceptions.TclFAILED_ESSENTIAL
            try:
                startIdx = self.start_idx.data()
                endIdx = self.end_idx.data()
            except:
                print('Error evaluating start or end idx')
                CAENV1740.caenLib.CAENVME_End(handle)
                raise mdsExceptions.TclFAILED_ESSENTIAL
            try:
                pts = self.pts.data()
            except:
                print('Error evaluating Post Trigger Samples')
                CAENV1740.caenLib.CAENVME_End(handle)
                raise mdsExceptions.TclFAILED_ESSENTIAL

        # Stop device
            status = CAENV1740.caenLib.CAENVME_WriteCycle(
                handle, c_int(vmeAddress + 0x8100), byref(c_int(0)),
                c_int(self.cvA32_S_DATA), c_int(self.cvD32))
            if status != 0:
                print('Error stopping device')
                CAENV1740.caenLib.CAENVME_End(handle)
                raise mdsExceptions.TclFAILED_ESSENTIAL
        #need to wait a while
            sleep(0.1)

            # Read number of buffers */
            actSegments = c_int(0)
            status = CAENV1740.caenLib.CAENVME_ReadCycle(
                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')
                CAENV1740.caenLib.CAENVME_End(handle)
                raise mdsExceptions.TclFAILED_ESSENTIAL

            if Device.debug: print('Acquired segments: ', actSegments.value)
            if actSegments.value == 0:
                CAENV1740.caenLib.CAENVME_End(handle)
                return

        #Compute Segment Size
            try:
                nSegments = self.num_segments.data()
                segmentSamples = 196608 / nSegments
                print('Segment samples: ', segmentSamples)
            except:
                print('Error reading max number of segments')
                CAENV1740.caenLib.CAENVME_End(handle)
                raise mdsExceptions.TclFAILED_ESSENTIAL

        # Get Active groups
            groupMask = c_int(0)
            status = CAENV1740.caenLib.CAENVME_ReadCycle(
                handle, c_int(vmeAddress + 0x8120), byref(groupMask),
                c_int(self.cvA32_S_DATA), c_int(self.cvD32))
            nActGroups = 0
            groupMask = groupMask.value
            for group in range(0, 8):
                if (groupMask & (1 << group)) != 0:
                    nActGroups = nActGroups + 1
            if nActGroups == 0:
                if Device.debug: print('No active groups')
                CAENV1740.caenLib.CAENVME_End(handle)
                return
            segmentSize = 16 + segmentSamples * nActGroups * 8 * 12 / 8

            class V1740Data(Structure):
                _fields_ = [("eventSize", c_int), ("boardGroup", c_int),
                            ("counter", c_int), ("time", c_int),
                            ("data",
                             c_int * (segmentSamples * 64 * 12 / (8 * 4)))]

            actSegments = actSegments.value
            currStartIdx = segmentSamples - pts + startIdx
            currEndIdx = segmentSamples - pts + endIdx

            DataArray = c_short * (
                (currEndIdx - currStartIdx + 1) * actSegments)
            triggers = []
            deltas = []
            channels = []
            for chan in range(0, 64):
                channels.append([])
            for chan in range(0, 64):
                channels[chan] = DataArray()
            c = []
            for i in range(0, 64):
                c.append(0)
            for sample in range(0, actSegments):
                segment = V1740Data()
                retLen = c_int(0)
                status = CAENV1740.caenLib.CAENVME_FIFOBLTReadCycle(
                    handle, c_int(vmeAddress), byref(segment),
                    c_int(segmentSize), c_int(self.cvA32_S_DATA),
                    c_int(self.cvD64), byref(retLen))
                if status != 0:
                    print('Error reading data segment')
                    CAENV1740.caenLib.CAENVME_End(handle)
                    raise mdsExceptions.TclFAILED_ESSENTIAL
                actSize = 4 * (segment.eventSize & 0x0fffffff)
                if actSize != segmentSize:
                    print('Expected event size different from expected size')
                    CAENV1740.caenLib.CAENVME_End(handle)
                    raise mdsExceptions.TclFAILED_ESSENTIAL
                counter = segment.time / 2
                triggers.append(counter * dt)
                deltas.append(dt)
                sizeInInts = (segment.eventSize & 0x0fffffff) - 4
                groupSize = sizeInInts / nActGroups
                groupOffset = 0
                for group in range(0, 8):
                    if (groupMask & (1 << group)) != 0:
                        rpnt = 0
                        sampleCount = 0
                        while rpnt < groupSize:
                            if rpnt % 9 == 0:
                                if sampleCount >= currStartIdx and sampleCount <= currEndIdx:
                                    channels[group * 8][
                                        c[group * 8 +
                                          0]] = segment.data[groupOffset +
                                                             rpnt] & 0x00000FFF
                                    c[group * 8 + 0] = c[group * 8 + 0] + 1
                                if sampleCount + 1 >= currStartIdx and sampleCount + 1 <= currEndIdx:
                                    channels[group * 8][c[group * 8 + 0]] = (
                                        segment.data[groupOffset + rpnt]
                                        & 0x00FFF000) >> 12
                                    c[group * 8 + 0] = c[group * 8 + 0] + 1
                                if sampleCount + 2 >= currStartIdx and sampleCount + 2 <= currEndIdx:
                                    channels[group * 8][c[group * 8 + 0]] = (
                                        (segment.data[groupOffset + rpnt]
                                         & 0xFF000000) >> 24
                                    ) | ((segment.data[groupOffset + rpnt + 1]
                                          & 0x0000000F) << 8)
                                    c[group * 8 + 0] = c[group * 8 + 0] + 1
                            if rpnt % 9 == 1:
                                if sampleCount >= currStartIdx and sampleCount <= currEndIdx:
                                    channels[group * 8 + 1][c[
                                        group * 8 +
                                        1]] = (segment.data[groupOffset + rpnt]
                                               & 0x0000FFF0) >> 4
                                    c[group * 8 + 1] = c[group * 8 + 1] + 1
                                if sampleCount + 1 >= currStartIdx and sampleCount + 1 <= currEndIdx:
                                    channels[group * 8 + 1][c[
                                        group * 8 +
                                        1]] = (segment.data[groupOffset + rpnt]
                                               & 0x0FFF0000) >> 16
                                    c[group * 8 + 1] = c[group * 8 + 1] + 1
                                if sampleCount + 2 >= currStartIdx and sampleCount + 2 <= currEndIdx:
                                    channels[group * 8 + 1][c[
                                        group * 8 + 1]] = (
                                            (segment.data[groupOffset + rpnt]
                                             & 0xF0000000) >> 28) | (
                                                 (segment.data[groupOffset +
                                                               rpnt + 1]
                                                  & 0x000000FF) << 4)
                                    c[group * 8 + 1] = c[group * 8 + 1] + 1
                            if rpnt % 9 == 2:
                                if sampleCount >= currStartIdx and sampleCount <= currEndIdx:
                                    channels[group * 8 + 2][c[
                                        group * 8 +
                                        2]] = (segment.data[groupOffset + rpnt]
                                               & 0x000FFF00) >> 8
                                    c[group * 8 + 2] = c[group * 8 + 2] + 1
                                if sampleCount + 1 >= currStartIdx and sampleCount + 1 <= currEndIdx:
                                    channels[group * 8 + 2][c[
                                        group * 8 +
                                        2]] = (segment.data[groupOffset + rpnt]
                                               & 0xFFF00000) >> 20
                                    c[group * 8 + 2] = c[group * 8 + 2] + 1
                            if rpnt % 9 == 3:
                                if sampleCount + 2 >= currStartIdx and sampleCount + 2 <= currEndIdx:
                                    channels[group * 8 + 2][
                                        c[group * 8 +
                                          2]] = segment.data[groupOffset +
                                                             rpnt] & 0x00000FFF
                                    c[group * 8 + 2] = c[group * 8 + 2] + 1
                                if sampleCount >= currStartIdx and sampleCount <= currEndIdx:
                                    channels[group * 8 + 3][c[
                                        group * 8 +
                                        3]] = (segment.data[groupOffset + rpnt]
                                               & 0x00FFF000) >> 12
                                    c[group * 8 + 3] = c[group * 8 + 3] + 1
                                if sampleCount + 1 >= currStartIdx and sampleCount + 1 <= currEndIdx:
                                    channels[group * 8 + 3][c[
                                        group * 8 + 3]] = (
                                            (segment.data[groupOffset + rpnt]
                                             & 0xFF000000) >> 24) | (
                                                 (segment.data[groupOffset +
                                                               rpnt + 1]
                                                  & 0x0000000F) << 8)
                                    c[group * 8 + 3] = c[group * 8 + 3] + 1
                            if rpnt % 9 == 4:
                                if sampleCount + 2 >= currStartIdx and sampleCount + 2 <= currEndIdx:
                                    channels[group * 8 + 3][c[
                                        group * 8 +
                                        3]] = (segment.data[groupOffset + rpnt]
                                               & 0x0000FFF0) >> 4
                                    c[group * 8 + 3] = c[group * 8 + 3] + 1
                                if sampleCount >= currStartIdx and sampleCount <= currEndIdx:
                                    channels[group * 8 + 4][c[
                                        group * 8 +
                                        4]] = (segment.data[groupOffset + rpnt]
                                               & 0x0FFF0000) >> 16
                                    c[group * 8 + 4] = c[group * 8 + 4] + 1
                                if sampleCount + 1 >= currStartIdx and sampleCount + 1 <= currEndIdx:
                                    channels[group * 8 + 4][c[
                                        group * 8 + 4]] = (
                                            (segment.data[groupOffset + rpnt]
                                             & 0xF0000000) >> 28) | (
                                                 (segment.data[groupOffset +
                                                               rpnt + 1]
                                                  & 0x000000FF) << 4)
                                    c[group * 8 + 4] = c[group * 8 + 4] + 1
                            if rpnt % 9 == 5:
                                if sampleCount + 2 >= currStartIdx and sampleCount + 2 <= currEndIdx:
                                    channels[group * 8 + 4][c[
                                        group * 8 +
                                        4]] = (segment.data[groupOffset + rpnt]
                                               & 0x000FFF00) >> 8
                                    c[group * 8 + 4] = c[group * 8 + 4] + 1
                                if sampleCount >= currStartIdx and sampleCount <= currEndIdx:
                                    channels[group * 8 + 5][c[
                                        group * 8 +
                                        5]] = (segment.data[groupOffset + rpnt]
                                               & 0xFFF00000) >> 20
                                    c[group * 8 + 5] = c[group * 8 + 5] + 1
                            if rpnt % 9 == 6:
                                if sampleCount + 1 >= currStartIdx and sampleCount + 1 <= currEndIdx:
                                    channels[group * 8 + 5][
                                        c[group * 8 +
                                          5]] = segment.data[groupOffset +
                                                             rpnt] & 0x00000FFF
                                    c[group * 8 + 5] = c[group * 8 + 5] + 1
                                if sampleCount + 2 >= currStartIdx and sampleCount + 2 <= currEndIdx:
                                    channels[group * 8 + 5][c[
                                        group * 8 +
                                        5]] = (segment.data[groupOffset + rpnt]
                                               & 0x00FFF000) >> 12
                                    c[group * 8 + 5] = c[group * 8 + 5] + 1
                                if sampleCount >= currStartIdx and sampleCount <= currEndIdx:
                                    channels[group * 8 + 6][c[
                                        group * 8 + 6]] = (
                                            (segment.data[groupOffset + rpnt]
                                             & 0xFF000000) >> 24) | (
                                                 (segment.data[groupOffset +
                                                               rpnt + 1]
                                                  & 0x0000000F) << 8)
                                    c[group * 8 + 6] = c[group * 8 + 6] + 1
                            if rpnt % 9 == 7:
                                if sampleCount + 1 >= currStartIdx and sampleCount + 1 <= currEndIdx:
                                    channels[group * 8 + 6][c[
                                        group * 8 +
                                        6]] = (segment.data[groupOffset + rpnt]
                                               & 0x0000FFF0) >> 4
                                    c[group * 8 + 6] = c[group * 8 + 6] + 1
                                if sampleCount + 2 >= currStartIdx and sampleCount + 2 <= currEndIdx:
                                    channels[group * 8 + 6][c[
                                        group * 8 +
                                        6]] = (segment.data[groupOffset + rpnt]
                                               & 0x0FFF0000) >> 16
                                    c[group * 8 + 6] = c[group * 8 + 6] + 1
                                if sampleCount >= currStartIdx and sampleCount <= currEndIdx:
                                    channels[group * 8 + 7][c[
                                        group * 8 + 7]] = (
                                            (segment.data[groupOffset + rpnt]
                                             & 0xF0000000) >> 28) | (
                                                 (segment.data[groupOffset +
                                                               rpnt + 1]
                                                  & 0x000000FF) << 4)
                                    c[group * 8 + 7] = c[group * 8 + 7] + 1
                            if rpnt % 9 == 8:
                                if sampleCount + 1 >= currStartIdx and sampleCount + 1 <= currEndIdx:
                                    channels[group * 8 + 7][c[
                                        group * 8 +
                                        7]] = (segment.data[groupOffset + rpnt]
                                               & 0x000FFF00) >> 8
                                    c[group * 8 + 7] = c[group * 8 + 7] + 1
                                if sampleCount + 2 >= currStartIdx and sampleCount + 2 <= currEndIdx:
                                    channels[group * 8 + 7][c[
                                        group * 8 +
                                        7]] = (segment.data[groupOffset + rpnt]
                                               & 0xFFF00000) >> 20
                                    c[group * 8 + 7] = c[group * 8 + 7] + 1
                            if rpnt % 9 == 8:
                                sampleCount = sampleCount + 3
                            rpnt = rpnt + 1
                        #endwhile
                        groupOffset = groupOffset + groupSize
                    #endif
                #endfor group in range(0:8)
            #endfor samples in range(0, 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)))

            print('DIM: ', dim)
            dim.setUnits("s")
            for group in range(0, 8):
                if groupMask & (1 << group):
                    try:
                        offset = self.__dict__['group_%d_offset' %
                                               (group + 1)].data()
                    except:
                        print('Error evaluating group offset')
                        CAENV1740.caenLib.CAENVME_End(handle)
                        raise mdsExceptions.TclFAILED_ESSENTIAL
                    for chan in range(0, 8):
                        raw = Int16Array(channels[group * 8 + chan])
                        raw.setUnits("counts")
                        data = Data.compile("2*($VALUE - 2048)/4096.+$1",
                                            offset)
                        data.setUnits("Volts")
                        signal = Signal(data, raw, dim)
                        try:
                            self.__dict__['data%02d' %
                                          ((group + 1) *
                                           (chan + 1), )].putData(signal)
                        except:
                            print('Cannot write Signal in the tree')
                            CAENV1740.caenLib.CAENVME_End(handle)
                            raise mdsExceptions.TclFAILED_ESSENTIAL
                    #endfor
                #endif
            #endfor

            CAENV1740.caenLib.CAENVME_End(handle)
            return
        except:  # try line 258
            print('Generic Error')
            CAENV1740.caenLib.CAENVME_End(handle)
            raise mdsExceptions.TclFAILED_ESSENTIAL
Exemple #21
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 #22
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