コード例 #1
0
 def getValue(self):
     ans=Window()
     t=self.startIdx.get_text()
     if t == '':
         ans.startIdx=None
     else:
         try:
             ans.startIdx=Data.compile(self.startIdx.get_text())
         except Exception:
             msg="Invalid startIdx specified.\n\n%s" % (sys.exc_info(),)
             MDSplusErrorMsg('Invalid StartIdx',msg)
             raise
     t=self.endIdx.get_text()
     if t == '':
         ans.endIdx=None
     else:
         try:
             ans.endIdx=Data.compile(self.endIdx.get_text())
         except Exception:
             msg="Invalid endIdx specified.\n\n%s" % (sys.exc_info(),)
             MDSplusErrorMsg('Invalid EndIdx',msg)
             raise
     t=self.timeAt0.get_text()
     if t != '':
         try:
             ans.timeAt0=Data.compile(self.timeAt0.get_text())
         except Exception:
             msg="Invalid timeAt0 specified.\n\n%s" % (sys.exc_info(),)
             MDSplusErrorMsg('Invalid TimeAt0',msg)
             raise
     return ans
コード例 #2
0
ファイル: cp7452.py プロジェクト: LucyScott/mdsplus
 def init(self,arg):
     """Initialize digital outputs of CP7452 cpci board.
     Connects to the host and for each of the DIGITAL_OUTS nodes which are turned on, write the value to the digital output.
     """
     import os
     from MDSplus import Uint32
     debug=os.getenv("DEBUG_DEVICES")
     try:
         host=str(self.node.record.data())
     except:
         host='local'
     if Data.execute('mdsconnect($)',host) == 0:
         raise Exception,"Error connecting to host: "+host
     board=int(self.board.record)
     for i in range(4):
         do_nid=self.__getattr__('digital_outs_do%d'%(i,))
         if do_nid.on:
             try:
                 exp='MdsValue("_lun=fopen(\\\"/sys/module/cp7452_drv/parameters/format\\\",\\\"r+\\"); write(_lun,\\\"1\\\"); fclose(_lun);'
                 exp=exp+'_lun=fopen(\\\"/dev/cp7452.%d/DO%d\\\",\\\"r+\\\"); write(_lun,\\\"%x\\\"); fclose(_lun)")' % (board,i,int(Uint32(do_nid.record.data()).data()))
                 if debug:
                     print exp
                 Data.execute(exp)
             except Exception,e:
                 print "Error outputing to DO%d\n\t%s" % (i,str(e),)
コード例 #3
0
 def getValue(self):
     ans=Dispatch(dispatch_type=2)
     ans.ident=self.ident.get_text()
     try:
         ans.ident=Data.compile(ans.ident)
     except Exception:
         pass
     ans.phase=self.phase.get_text()
     try:
         ans.phase=Data.compile(ans.phase)
     except Exception:
         pass
     try:
         ans.when=Data.compile(self.sequence.get_text())
     except Exception:
         msg="Invalid sequence specified.\n\n%s" % (sys.exc_info()[1],)
         MDSplusErrorMsg('Invalid Sequence',msg)
         raise
     ans.completion=self.event.get_text()
     if ans.completion == '':
         ans.completion=None
     else:
         try:
             ans.completion=Data.compile(ans.event)
         except Exception:
             pass
     return ans
コード例 #4
0
ファイル: cp7452.py プロジェクト: LucyScott/mdsplus
 def store(self,arg):
     """Stores the digital input values into the tree.
     Connects to the host and for each of the DIGITAL_INS nodes which are turned on, read the digital input and store the value in the node.
     """
     import os
     debug=os.getenv("DEBUG_DEVICES")
     try:
         host=str(self.node.record.data())
     except:
         host='local'
     if Data.execute('mdsconnect($)',host) == 0:
         raise Exception,"Error connecting to host: "+host
     board=int(self.board.record)
     for i in range(4):
         di_nid=self.__getattr__('digital_ins_di%d'%(i,1))
         if di_nid.on:
             try:
                 exp='MdsValue("_lun=fopen(\\\"/sys/module/cp7452_drv/parameters/format\\\",\\\"r+\\\"); write(_lun,\\\"1\\\"); fclose(_lun);'
                 exp=exp+'_lun=fopen(\\\"/dev/cp7452.%d/DI%d\\\",\\\"r\\\"); _ans=read(_lun); fclose(_lun),_ans")' % (board,i)
                 if debug:
                     print exp
                 value=eval('0x'+str(Data.execute(exp)))
                 di_nid.record=value
             except Exception,e:
                 print "Error inputting from DI%d\n\t%s" % (i,str(e),)
コード例 #5
0
 def getValue(self):
     ans=Range()
     t=self.begin.get_text()
     if t == '':
         ans.begin=None
     else:
         try:
             ans.begin=Data.compile(self.begin.get_text())
         except Exception:
             msg="Invalid begin specified.\n\n%s" % (sys.exc_info()[1],)
             MDSplusErrorMsg('Invalid Begin',msg)
             raise
     t=self.ending.get_text()
     if t == '':
         ans.ending=None
     else:
         try:
             ans.ending=Data.compile(self.ending.get_text())
         except Exception:
             msg="Invalid ending specified.\n\n%s" % (sys.exc_info()[1],)
             MDSplusErrorMsg('Invalid Ending',msg)
             raise
     t=self.delta.get_text()
     if t != '':
         try:
             ans.delta=Data.compile(self.delta.get_text())
         except Exception:
             msg="Invalid delta specified.\n\n%s" % (sys.exc_info()[1],)
             MDSplusErrorMsg('Invalid Delta',msg)
             raise
     return ans
コード例 #6
0
 def getValue(self):
     ans=Routine()
     ans.image=self.image.get_text()
     try:
         ans.image=Data.compile(ans.image)
     except Exception,e:
         pass
コード例 #7
0
 def getValue(self):
     ans=Method()
     ans.method=self.method.get_text()
     try:
         ans.method=Data.compile(ans.method)
     except Exception,e:
         pass
コード例 #8
0
 def getValue(self):
     ans=Dispatch(dispatch_type=2)
     ans.ident=self.ident.get_text()
     try:
         ans.ident=Data.compile(ans.ident)
     except Exception,e:
         pass
コード例 #9
0
ファイル: tdipy.py プロジェクト: LucyScott/mdsplus
def execPy(varname=None,traceback=False):
    """Get array of python commands from tdi public variable ___TDI___cmds
    and execute them. The ___TDI___cmds variable should be either a scalar string
    or a string array. If varname is defined
    then set the tdi public variable ___TDI___answer to the value of the variable
    with the name specified in varname. If varname is not defined
    then set public variable ___TDI___answer to 1 if there is no exception. If there
    is an exception then set public variable ___TDI___exception to be the
    exception string.
    """
    from MDSplus import Data as ___TDI___Data,makeData as ___TDI___makeData,String as ___TDI___String
    try:
        cmds=list()
        for cmd in ___TDI___Data.getTdiVar('___TDI___cmds'):
            cmds.append(str(cmd))
        cmds="\n".join(cmds)
        isglobal=False
        try:
          if int(___TDI___Data.getTdiVar('___TDI___global_ns'))==1:
            isglobal=True
        except:
            pass
        ans=1
        if isglobal:
          exec( cmds) in globals()
          if varname is not None:
            if varname in globals():
              ans=globals()[varname]
            else:
              ans=None
        else:
       	  ns={}
          exec( cmds) in ns
          if varname is not None:
            if varname in ns:
              ans=ns[varname]
            else:
              ans=None

        ___TDI___makeData(ans).setTdiVar("___TDI___answer")
    except Exception:
        if traceback:
          _tb.print_exc()
        import sys
        e=sys.exc_info()[1]    
        ___TDI___String("Error: "+str(e)).setTdiVar("___TDI___exception")
コード例 #10
0
def do1darray(self):
    if len(self.path_parts) > 2:
        self.openTree(self.path_parts[1],self.path_parts[2])
    expr=self.args['expr'][-1]
    try:
        a=makeData(Data.execute(expr).data())
    except Exception,e:
        raise Exception("Error evaluating expression: '%s', error: %s" % (expr,e))
コード例 #11
0
def do1dsignal(self):
    if len(self.path_parts) > 2:
        self.openTree(self.path_parts[1],self.path_parts[2])
    expr=self.args['expr'][-1]
    try:
        sig=Data.execute(expr)
        y=makeData(sig.data())
        x=makeData(sig.dim_of().data())
    except Exception,e:
        raise Exception("Error evaluating expression: '%s', error: %s" % (expr,e))
コード例 #12
0
 def getValue(self):
     ans=Range()
     t=self.begin.get_text()
     if t == '':
         ans.begin=None
     else:
         try:
             ans.begin=Data.compile(self.begin.get_text())
         except Exception,e:
             msg="Invalid begin specified.\n\n%s" % (e,)
             MDSplusErrorMsg('Invalid Begin',msg)
             raise
コード例 #13
0
def doPlot(self):

    viewbox=[0,0,10000,10000];
    def scale(xmin,ymin,xmax,ymax,xmin_s,ymin_s,xmax_s,ymax_s,x,y):
        px=(x-xmin)*(xmax_s-xmin_s)/(xmax-xmin)
        py=(y-ymin)*(ymax_s-ymin_s)/(ymax-ymin)
        return " %d %d" % (int(round(px)),int(round(py)))

    def gridScaling(min_in,max_in,divisions,span):
        from math import log10,pow,fabs,ceil,floor,modf
        resdivlog = log10(fabs(max_in-min_in))
        if resdivlog < 0:
            res = pow(10,ceil(resdivlog) - 4)
        else:
            res = pow(10,floor(resdivlog) - 4)
        divlog = log10(fabs(max_in - min_in) / divisions)
        fractpart,wholepart = modf(divlog)
        intinc = pow(10,fabs(fractpart))
        if intinc < 1.3333333:
            intinc=1
        elif intinc < 2.857:
            intinc=2
        else:
            intinc=10
        if divlog < 0:
            val_inc = pow(10,-log10(intinc) + wholepart)
        else:
            val_inc = pow(10,log10(intinc) + wholepart)
        grid=ceil(min_in/val_inc) * val_inc
        divs_out = floor((max_in - grid + val_inc) / val_inc)
        if max_in > min_in:
            first_pix = span * ((grid - min_in) / (max_in - min_in))
            pix_inc = span * val_inc / (max_in - min_in);
            first_val = (first_pix * ((max_in - min_in)/span)) + min_in
        else:
            divs_out = 2
            first_pix = 0
            pix_inc = span
            val_inc = 0
        return {"divisions":divs_out,
                "first_pixel":first_pix, "pixel_increment":pix_inc, 
                "first_value":first_val, "value_increment":val_inc,
                "resolution":res}
          
    if len(self.path_parts) > 2:
        self.openTree(self.path_parts[1],self.path_parts[2])
    expr=self.args['expr'][-1]
    try:
        sig=Data.execute(expr)
        y=makeData(sig.data()).data()
        x=makeData(sig.dim_of().data()).data()
    except Exception,e:
        raise Exception("Error evaluating expression: '%s', error: %s" % (expr,e))
コード例 #14
0
 def getValue(self):
     ans=Window()
     t=self.startIdx.get_text()
     if t == '':
         ans.startIdx=None
     else:
         try:
             ans.startIdx=Data.compile(self.startIdx.get_text())
         except Exception,e:
             msg="Invalid startIdx specified.\n\n%s" % (e,)
             MDSplusErrorMsg('Invalid StartIdx',msg)
             raise
コード例 #15
0
 def getValue(self):
     ans=Method()
     ans.method=self.method.get_text()
     try:
         ans.method=Data.compile(ans.method)
     except Exception:
         pass
     try:
         ans.object=Data.compile(self.device.get_text())
     except Exception:
         msg="Invalid device specified.\n\n%s" % (sys.exc_info(),)
         MDSplusErrorMsg('Invalid Device',msg)
         raise
     if self.timeout.get_text() == '' or self.timeout.get_text() == '*':
         ans.timeout=None
     else:
         try:
             ans.timeout=Data.compile(self.timeout.get_text())
         except Exception:
             msg="Invalid timeout specified.\n\n%s" % (sys.exc_info(),)
             MDSplusErrorMsg('Invalid Timeout',msg)
             raise
     idx=len(self.args)-1
     found=False
     while idx >= 0:
         t = self.args[idx].get_text()
         if t == '':
             if found:
                 ans.setArgumentAt(idx,None)
         else:
             try:
                 a=Data.compile(t)
             except Exception:
                 msg="Invalid argument (%d) specified.\n\n%s" % (idx+1,sys.exc_info(),)
                 MDSplusErrorMsg('Invalid Argument',msg)
                 raise
             ans.setArgumentAt(idx,a)
             found=True
         idx=idx-1
     return ans
コード例 #16
0
 def getValue(self):
     ans=Routine()
     ans.image=self.image.get_text()
     try:
         ans.image=Data.compile(ans.image)
     except Exception:
         pass
     ans.routine=self.routine.get_text()
     try:
         ans.routine=Data.compile(ans.routine)
     except Exception:
         pass
     if self.timeout.get_text() == '' or self.timeout.get_text() == '*':
         ans.timeout=None
     else:
         try:
             ans.timeout=Data.compile(self.timeout.get_text())
         except Exception:
             msg="Invalid timeout specified.\n\n%s" % (sys.exc_info(),)
             MDSplusErrorMsg('Invalid Timeout',msg)
             raise
     idx=len(self.args)-1
     found=False
     while idx >= 0:
         t = self.args[idx].get_text()
         if t == '':
             if found:
                 ans.setArgumentAt(idx,None)
         else:
             try:
                 a=Data.compile(t)
             except Exception:
                 msg="Invalid argument specified.\n\n%s" % (sys.exc_info(),)
                 MDSplusErrorMsg('Invalid Argument',msg)
                 raise
             ans.setArgumentAt(idx,a)
             found=True
         idx=idx-1
     return ans
コード例 #17
0
ファイル: mdsplusdigchans.py プロジェクト: LucyScott/mdsplus
 def applyPart(self,channel,field,idx):
     value=channel[field].get_text()
     if value == '':
         value=None
     else:
         try:
             value=Data.compile(value)
         except Exception:
             MDSplusErrorMsg('Invalid value','Error compiling %s for channel %d\n\n%s\n\n%s' % (field,idx,value,sys.exc_info()))
             raise
     try:
         if channel[field+'Node'].compare(value) != 1:
             channel[field+'Node'].record=value
     except Exception:
         MDSplusErrorMsg('Error storing value','Error storing value %s for channel %d\n\n\%s' % (field,idx,sys.exc_info()))
コード例 #18
0
ファイル: do1darray.py プロジェクト: LucyScott/mdsplus
def do1darray(self):
    if len(self.path_parts) > 2:
        self.openTree(self.path_parts[1],self.path_parts[2])
    expr=self.args['expr'][-1]
    try:
        a=makeData(Data.execute(expr).data())
    except Exception:
        raise Exception("Error evaluating expression: '%s', error: %s" % (expr,sys.exc_info()))
    response_headers=list()
    response_headers.append(('Cache-Control','no-store, no-cache, must-revalidate'))
    response_headers.append(('Pragma','no-cache'))
    response_headers.append(('DTYPE',a.__class__.__name__))
    response_headers.append(('LENGTH',str(len(a))))
    if self.tree is not None:
        response_headers.append(('TREE',self.tree))
        response_headers.append(('SHOT',self.shot))
    output=str(a.data().data)
    status = '200 OK'
    return (status, response_headers, output)
コード例 #19
0
def doImage(self):
    if len(self.path_parts) > 2:
        self.openTree(self.path_parts[1],self.path_parts[2])
    expr=self.args['expr'][-1]
    try:
        d=Data.execute(expr)
        try:
            im=d.getImage()
        except:
            raise Exception("Expression does not evaluate to an image type")
        if im.format == "MPEG":
            response_headers=[('Content-type','video/mpeg'),('Content-Disposition','inline; filename="%s.mpeg"' % (expr,))]
        elif im.format == "GIF":
            response_headers=[('Content-type','image/gif'),('Content-Disposition','inline; filename="%s.gif"' % (expr,))]
        elif im.format == "JPEG":
            response_headers=[('Content-type','image/jpeg'),('Content-Disposition','inline; filename="%s.jpeg"' % (expr,))]
        else:
            raise Exception("not an known image type")
        output=str(d.getData().data().data)
    except Exception,e:
        raise Exception("Error evaluating expression: '%s', error: %s" % (expr,e))
コード例 #20
0
ファイル: CAENV1740.py プロジェクト: LucyScott/mdsplus
    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
コード例 #21
0
ファイル: NI6259EV.py プロジェクト: zack-vii/mdsplus
    def init(self):

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

        ##self.restoreInfo()

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

        aiConf = c_void_p(0)
        NI6259EV.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
        chanModes = []
        chanEvents = []
        chanPreTimes = []
        chanPostTimes = []

        for chan in range(0, numChannels):

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

            getattr(self,
                    'channel_%d_raw' % (chan + 1)).setCompressOnPut(False)
            mode = getattr(self, 'channel_%d_mode' % (chan + 1)).data()
            chanModes.append(mode)
            enabled = (mode != 'DISABLED')
            if not enabled:
                continue
            try:
                event = getattr(self,
                                'channel_%d_event_name' % (chan + 1)).data()
                chanEvents.append(event)
            except:
                chanEvents.append('')
            try:
                preTime = getattr(self,
                                  'channel_%d_start_time' % (chan + 1)).data()
                if preTime < 0:
                    Data.execute(
                        'DevLogErr($1,$2)', self.getNid(),
                        'Pre time for channel %d must be geater of equal to 0 '
                        + str(chan + 1))
                    raise DevBAD_PARAMETER

                postTime = getattr(self,
                                   'channel_%d_end_time' % (chan + 1)).data()
                if postTime < 0:
                    Data.execute(
                        'DevLogErr($1,$2)', self.getNid(),
                        'Post time for channel %d must be geater of equal to 0 '
                        + str(chan + 1))
                    raise DevBAD_PARAMETER
            except:
                if mode == 'BURST(FREQ1)' or mode == 'BURST(FREQ2)' or mode == (
                        'DUAL SPEED'):
                    Data.execute(
                        'DevLogErr($1,$2)', self.getNid(),
                        'Missing pre or post time for channel ' +
                        str(chan + 1))
                    raise DevBAD_PARAMETER
                else:
                    preTime = 0
                    postTime = 0

            chanPreTimes.append(preTime)
            chanPostTimes.append(postTime)

            try:
                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_raw' % (chan + 1)).getPath(),
                    getattr(self, 'channel_%d_calib' % (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 = NI6259EV.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
        nid = self.getNid()
        NI6259EV.ni6259chanModes[nid] = chanModes
        NI6259EV.ni6259chanEvents[nid] = chanEvents
        NI6259EV.ni6259chanPreTimes[nid] = chanPreTimes
        NI6259EV.ni6259chanPostTimes[nid] = chanPostTimes

        #Continuous acquisiton
        status = NI6259EV.niLib.pxi6259_set_ai_attribute(
            aiConf, self.AI_CONTINUOUS, c_int(1))
        if (status != 0):
            Data.execute('DevLogErr($1,$2)', self.getNid(),
                         'Cannot set continuous acquisition')
            raise DevBAD_PARAMETER
#PFI0 clock (per ora)

        status = NI6259EV.niLib.pxi6259_set_ai_sample_clk(
            aiConf, c_int(16), c_int(3), self.AI_SAMPLE_SELECT_PFI0,
            self.AI_SAMPLE_POLARITY_RISING_EDGE)
        #        status = NI6259EV.niLib.pxi6259_set_ai_sample_clk(aiConf, c_int(0), c_int(0), 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

        if activeChan == 1:
            convClk = 16
        else:
            convClk = 20
        status = NI6259EV.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

        status = NI6259EV.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

        self.saveInfo()
        self.debugPrint("===============================================")
        return 1
コード例 #22
0
ファイル: CAENV1740.py プロジェクト: LucyScott/mdsplus
    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
コード例 #23
0
ファイル: dtao32.py プロジェクト: LucyScott/mdsplus
            knots_x = [0., 1.]
           
            if ao_nid.on:
                try:
                    fit = str(self.__getattr__('ouput_%2.2d_fit'))
                except:
                    fit = 'LINEAR'
                try:
                    knots_y = ao_nid.record.data()
                    knots_x = ao_nid.record.getDimensionAt(0).data()
                except Exception,e:
                    knots_y = numpy.array([ 0.,  0.])
                    knots_x = numpy.array([ 0.,  1.])
                    print "Error reading data for channel %d - ZEROING ZEROING\n" % i
                if fit == 'SPLINE':
                    wave = Data.execute('SplineFit($,$,$)', knots_x, knots_y, dim)
                else:
                    wave = Data.execute('LinFit($,$,$)', knots_x, knots_y, dim)
                counts = wave.data() / 10.*2**15
                counts = numpy.int16(counts[:max_samples])
                self.WriteWaveform(hostname, board, i+1, counts)

        if not self.first:
            self.SendFiles(hostname, hostboard, board)
        else:
            raise Exception, 'No channels defined aborting'

        try:
            Dt200WriteMaster(hostboard, 'set.ao32 %d AO_MODE %s' % (board, mode), 1)
            Dt200WriteMaster(hostboard, 'set.ao32 %d AO_CLK  %s %d %s' % (board, clock_src, clock_div, clock_edge), 1) 
            Dt200WriteMaster(hostboard, 'set.ao32 %d AO_TRG %s %s' % (board, trig_src, trig_edge), 1)
コード例 #24
0
        self.value=value

    def getValue(self):
        ans=Dispatch(dispatch_type=2)
        ans.ident=self.ident.get_text()
        try:
            ans.ident=Data.compile(ans.ident)
        except Exception,e:
            pass
        ans.phase=self.phase.get_text()
        try:
            ans.phase=Data.compile(ans.phase)
        except Exception,e:
            pass
        try:
            ans.when=Data.compile(self.sequence.get_text())
        except Exception,e:
            msg="Invalid sequence specified.\n\n%s" % (e,)
            MDSplusErrorMsg('Invalid Sequence',msg)
            raise
        ans.completion=self.event.get_text()
        if ans.completion == '':
            ans.completion=None
        else:
            try:
                ans.completion=Data.compile(ans.event)
            except Exception,e:
                pass
        return ans
        
    def setValue(self,d):
コード例 #25
0
ファイル: doScope.py プロジェクト: MDSplus/Python-TDISHR
def doScope(self):
  response_headers=list()
  noCache(response_headers)
  if 'user' in self.args:
      user=self.args['user'][-1]
      response_headers.append(('Content-type','text/html'))
      outStr='<html><head><title>Scope Selection</title><body>'
      subdir=''
      if 'dir' in self.args and '..' not in self.args['dir'][-1]:
          file_list=getConfigFiles(user,'jScope' in self.args,self.args['dir'][-1])
      else:
          file_list=getConfigFiles(user,True,'')
          file_list.extend(getConfigFiles(user,False,''))
      if(len(file_list) == 0):
          outStr = outStr+'No Scope configuration file found</body></html>'            
          status = '200 OK'
          return (status, response_headers, outStr)
      file_list.sort(file_list_cmp)
      last_is_dir=False
      for f in file_list:
          if not f['notdir']:
              last_is_dir=True
              if f['jScope']:
                  jscope='&jScope=yes'
              else:
                  jscope=''
              outStr = outStr + '<a href="?user='******'&dir='+f['subdir']+'/'+f['file']+jscope+'">'+f['filespec']+'</a><br>'
          else:
              if last_is_dir:
                  outStr = outStr + '<br>'
              last_is_dir=False
              outStr = outStr + '<a href="scope?config='+f['filespec'] +'" target="_blank">'+f['filespec']+'</a><br>'
      outStr = outStr + '</body></html>'
      status = '200 OK'
      return (status, response_headers, outStr)
  elif 'configxml' in self.args:

#Handle direct configuration
    response_headers.append(('IS_CONFIG','YES'))
    response_headers.append(('Content-type','text/xml'))

    f = open(self.args['configxml'][-1],'r')
    lines = f.readlines()
    f.close()
    outStr = '<scope>'
    title=getValue(lines, 'Scope.title')
    if title:
      outStr = outStr + '<title><expression>'+encodeUrl(title)+'</expression>'
      event=getValue(lines,'Scope.update_event')
      if event:
        outStr = outStr + '<event>'+event+'</event>'
      outStr = outStr + '</title>'
    outStr = outStr + '<palette>'
    idx = 0
    GLOBAL_SHOT_IDX = 8
    GLOBAL_TREE_IDX = 7
    GLOBAL_XMIN_IDX = 12
    GLOBAL_XMAX_IDX = 13
    GLOBAL_YMIN_IDX = 14
    GLOBAL_YMAX_IDX = 15
    while True:
        color = getValue(lines, 'Scope.color_'+str(idx))
        if(color == None):
            break
        color = color.split(',')[0]
        if color == 'Blak':
            color = 'Black'
        outStr = outStr+'<color>'+color+'</color>'
        idx = idx + 1
#Handle missing color palette
    if (idx == 0):
        outStr = outStr+'<color>Black</color>'
    outStr = outStr+'</palette>'
    globalTree = getValue(lines, 'Scope.global_1_1.experiment')
    globalShot = getValue(lines, 'Scope.global_1_1.shot')
         
    globalXMin = getValue(lines, 'Scope.global_1_1.xmin')
    globalXMax = getValue(lines, 'Scope.global_1_1.xmax')
    globalYMin = getValue(lines, 'Scope.global_1_1.ymin')
    globalYMax = getValue(lines, 'Scope.global_1_1.ymax')
    globalXLabel = getValue(lines, 'Scope.global_1_1.x_label')
    globalYLabel = getValue(lines, 'Scope.global_1_1.y_label')  
    globalEvent = getValue(lines, 'Scope.global_1_1.event')
    numCols = int(getValue(lines, 'Scope.columns'))
    outStr = outStr+'<columns>'
    for colIdx in range(1, numCols+1):
      outStr = outStr+'<column>'
      numRows = int(getValue(lines, 'Scope.rows_in_column_'+str(colIdx)))
      for rowIdx in range(1, numRows+1):
        outStr = outStr + '<panel '
        globalDefs = int(getValue(lines, 'Scope.plot_'+str(rowIdx)+'_'+str(colIdx)+'.global_defaults'))
        if(globalDefs & (1 << GLOBAL_TREE_IDX)):
          tree = globalTree
        else:
          tree = getValue(lines, 'Scope.plot_'+str(rowIdx)+'_'+str(colIdx)+'.experiment')

        if(tree != None):
          outStr = outStr+' tree = "'+tree+'" ';
          if(globalDefs & (1 << GLOBAL_SHOT_IDX)):
            shotNum = '-2'
          else:
            shotNum = getValue(lines, 'Scope.plot_'+str(rowIdx)+'_'+str(colIdx)+'.shot')
          if(shotNum != None):
            outStr = outStr+' shot = "'+shotNum+'" '

        if(globalDefs & (1 << GLOBAL_XMIN_IDX)):
          xmin = globalXMin
        else:
          xmin = getValue(lines, 'Scope.plot_'+str(rowIdx)+'_'+str(colIdx)+'.xmin')
        if(xmin != None):
          outStr = outStr+' xmin = "'+encodeUrl(xmin)+'" '

        if(globalDefs & (1 << GLOBAL_XMAX_IDX)):
          xmax = globalXMax
        else:
          xmax = getValue(lines, 'Scope.plot_'+str(rowIdx)+'_'+str(colIdx)+'.xmax')
        if(xmax != None):
          outStr = outStr+' xmax = "'+encodeUrl(xmax)+'" '

        if(globalDefs & (1 << GLOBAL_YMIN_IDX)):
          ymin = globalYMin
        else:
          ymin = getValue(lines, 'Scope.plot_'+str(rowIdx)+'_'+str(colIdx)+'.ymin')
        if(ymin != None):
          outStr = outStr+' ymin = "'+encodeUrl(ymin)+'" '

        if(globalDefs & (1 << GLOBAL_YMAX_IDX)):
          ymax = globalYMax
        else:
          ymax = getValue(lines, 'Scope.plot_'+str(rowIdx)+'_'+str(colIdx)+'.ymax')
        if(ymax != None):
          outStr = outStr+' ymax = "'+encodeUrl(ymax)+'" '

        title = getValue(lines, 'Scope.plot_'+str(rowIdx)+'_'+str(colIdx)+'.title') 
        if(title != None):
          title = encodeUrl(title)
          title = title.replace('"', "'")
          outStr = outStr+' title = "'+title+'"'
        xlabel = getValue(lines,'Scope.plot_'+str(rowIdx)+'_'+str(colIdx)+'.x_label')
        if (xlabel == None):
          xlabel = globalXLabel
        if (xlabel != None):
          xlabel = encodeUrl(xlabel)
          xlabel = xlabel.replace('"',"'")
          outStr = outStr+' xlabel = "'+xlabel+'"'
        ylabel = getValue(lines,'Scope.plot_'+str(rowIdx)+'_'+str(colIdx)+'.y_label')
        if (ylabel == None):
          ylabel = globalYLabel
        if (ylabel != None):
          ylabel = encodeUrl(ylabel)
          ylabel = ylabel.replace('"',"'")
          outStr = outStr+' ylabel = "'+ylabel+'"'
        event = getValue(lines,'Scope.plot_'+str(rowIdx)+'_'+str(colIdx)+'.event')
        if (event == None):
          event = globalEvent
        if (event != None):
          outStr = outStr+' event = "'+event+'"'

        outStr = outStr + '>'
        numExprStr = getValue(lines, 'Scope.plot_'+str(rowIdx)+'_'+str(colIdx)+'.num_expr')
        if(numExprStr == None):
            numExpr = 1
        else: 
            numExpr = int(numExprStr) 
        for exprIdx in range(1, numExpr+1):
          outStr = outStr+'<signal'
          color = getValue(lines, 'Scope.plot_'+str(rowIdx)+'_'+str(colIdx)+'.color_'+str(exprIdx)+'_1')
          if(color != None):
            if color == 'Blak':
              color = 'Black'  #fix old config file typo
            outStr = outStr+' color="'+color+'"'
          else:
            outStr = outStr + ' color="Black"'
          mode = getValue(lines, 'Scope.plot_'+str(rowIdx)+'_'+str(colIdx)+'.mode_1D_'+str(exprIdx)+'_1')
          marker = getValue(lines, 'Scope.plot_'+str(rowIdx)+'_'+str(colIdx)+'.marker_'+str(exprIdx)+'_1')
          if(mode == 'Line' and marker == '0'):
            outStr = outStr+ ' mode="1"'
          elif(mode == 'Line' and marker != '0'):
            outStr = outStr+ ' mode="3"'
          elif(mode == 'Noline' and marker != '0'):
            outStr = outStr+ ' mode="2"'
          outStr = outStr+'>'
          yExpr = getValue(lines, 'Scope.plot_'+str(rowIdx)+'_'+str(colIdx)+'.y_expr_'+str(exprIdx))
          if(yExpr == None):
              yExpr = getValue(lines, 'Scope.plot_'+str(rowIdx)+'_'+str(colIdx)+'.y')
          xExpr = getValue(lines, 'Scope.plot_'+str(rowIdx)+'_'+str(colIdx)+'.x_expr_'+str(exprIdx))
          if(xExpr == None):
              xExpr = getValue(lines, 'Scope.plot_'+str(rowIdx)+'_'+str(colIdx)+'.x')
          if(xExpr == None):
            outStr = outStr+encodeUrl(yExpr)+'</signal>'
          else:
            outStr = outStr+'BUILD_SIGNAL('+encodeUrl(yExpr)+',,'+encodeUrl(xExpr)+')</signal>'
        outStr = outStr+'</panel>\n'
      outStr = outStr+'</column>\n\n'
    outStr = outStr+'</columns></scope>'
    output=str(outStr)
    status = '200 OK'
    return (status, response_headers, output)
  elif 'panel' in self.args:
    return doScopepanel(self)
  elif 'title' in self.args:
    response_headers.append(('Content-type','text/text'))
    try:
      output = str(Data.execute(self.args['title'][0]))
    except Exception:
      output = str(sys.exc_info()[1])+' expression was '+self.args['title'][0]
    return ('200 OK',response_headers, output)
  else:
    ans=('400 NOT FOUND',[('Content-type','text/text'),],'')
    try:
      f=open(os.path.dirname(__file__)+'/../html/scope.html',"r")
      contents=f.read()
      f.close()
      ans = ('200 OK',[('Content-type','text/html'),],contents)
    except:
      pass
    return ans
コード例 #26
0
ファイル: dt216b.py プロジェクト: LucyScott/mdsplus
    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, e:
                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)
            mask = UUT.uut.acqcmd('getChannelMask').split('=')[-1]
            if debug:
                print "pre = %d, post = %d" % (pre, post, )
            clock_src=self.check('self.clock_src.record.getOriginalPartName().getString()[1:]', "Clock source must be a string") 
            if clock_src == 'INT_CLOCK' or clock_src == 'MASTER' :
                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(16) :
                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
                        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-start+1), 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, 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&")
コード例 #27
0
    def load_config(self):

        #print sys.version_info
        
        from openpyxl import load_workbook

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

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

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

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

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

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

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

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

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

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

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

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

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

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

            wb.close()

            print (' data loaded')            


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

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


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


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

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

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


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


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

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

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

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


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


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

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

                print ('[set OFF]')

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

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

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

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

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

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

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

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

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


            try:
               #Reset current link

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

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

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

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



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

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

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

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

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

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

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


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


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

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

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

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

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

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

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

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

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

        return 1
コード例 #28
0
ファイル: NI6259AI.py プロジェクト: santorofer/mdsplus
    def init(self):

        self.debugPrint('================= PXI 6259 Init ===============')
        print('USE PRIVATE CTX: '+str(self.getTree().usingPrivateCtx()))

# 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)
            getattr(self, 'channel_%d_res_raw' % (chan+1)).deleteData()
            getattr(self, 'channel_%d_res_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)))

#           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("===============================================")
コード例 #29
0
ファイル: dt216.py プロジェクト: zack-vii/mdsplus
    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()
        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
コード例 #30
0
ファイル: tree_case.py プロジェクト: santorofer/mdsplus
 def nci(self):
     shot = self.shot + 6
     with Tree('pytree', shot, 'new') as pytree:
         pytree.addNode('pytreesub', 'subtree').include_in_pulse = True
         Device.PyDevice('TestDevice').Add(pytree, 'TESTDEVICE')
         Device.PyDevice('CYGNET4K').Add(pytree, 'CYGNET4K').on = False
         pytree.write()
     with Tree('pytreesub', shot, 'new') as pytreesub:
         ip = pytreesub.addNode('ip', 'signal')
         ip.record = Signal(Int32(range(10)), None, Range(1., 10.))
         ip.tag = 'MAG_PLASMA_CURRENT'
         ip.tag = 'MAGNETICS_PLASMA_CURRENT'
         ip.tag = 'MAG_IP'
         ip.tag = 'MAGNETICS_IP'
         ip.tag = 'IP'
         ip.setExtendedAttribute('ATT1', 100)
         ip.setExtendedAttribute('ATT2', Range(1, 200))
         ip.setExtendedAttribute('ATT3', att3)
         self.assertEqual(str(ip.getExtendedAttribute('ATT1')), '100')
         self.assertEqual(str(ip.getExtendedAttribute('ATT2')), att2)
         self.assertEqual(str(ip.getExtendedAttribute('ATT3')), att3)
         exattr = ip.getExtendedAttributes()
         self.assertEqual(exattr['ATT1'], 100)
         self.assertEqual(str(exattr['ATT2']), att2)
         self.assertEqual(exattr['ATT3'], att3)
         for i in range(3):
             node = pytreesub.addNode('child%02d' % (i, ), 'structure')
             node.addDevice('dt200_%02d' % (i, ), 'dt200').on = False
         pytreesub.write()
     pytree.readonly()
     self.assertEqual(pytree.TESTDEVICE.__class__,
                      Device.PyDevice('TESTDEVICE'))
     self.assertEqual(pytree.CYGNET4K.__class__,
                      Device.PyDevice('CYGNET4K'))
     pytree.CYGNET4K.persistent = {}
     pytree.CYGNET4K.persistent['a'] = 1
     self.assertEqual(pytree.getNode('CYGNET4K').frames.persistent['a'], 1)
     ip = pytree.getNode('\\ip')
     self.assertEqual(ip.getUsage(), 'SIGNAL')
     self.assertEqual(ip.usage, ip.getUsage())
     try:  # do not continue and print when no match
         self.assertEqual(ip.getClass(), 'CLASS_R')
     except AssertionError:
         print("ip.nid=%d" % (ip.nid, ))
         print("Error with ip in %s" % (str(ip.tree), ))
         raise
     self.assertEqual(ip.class_str, 'CLASS_R')
     self.assertEqual(ip.compressible, False)
     self.assertEqual(ip.compressible, ip.isCompressible())
     self.assertEqual(ip.compress_on_put, True)
     self.assertEqual(ip.compress_on_put, ip.isCompressOnPut())
     self.assertEqual(ip.data_in_nci, False)
     self.assertEqual(ip.on, True)
     self.assertEqual(ip.on, ip.isOn())
     self.assertEqual(ip.do_not_compress, False)
     self.assertEqual(ip.do_not_compress, ip.isDoNotCompress())
     self.assertEqual(ip.dtype_str, 'DTYPE_SIGNAL')
     self.assertEqual(ip.dtype_str, ip.getDtype())
     self.assertEqual(ip.essential, False)
     self.assertEqual(ip.essential, ip.isEssential())
     mhdtree = pytree.getNode('\\PYTREESUB::TOP')
     self.assertEqual(mhdtree.include_in_pulse, True)
     self.assertEqual(mhdtree.include_in_pulse, mhdtree.isIncludeInPulse())
     self.assertEqual(ip.length, int(Data.execute('getnci($,"LENGTH")',
                                                  ip)))
     self.assertEqual(ip.length, ip.getLength())
     self.assertEqual(ip.no_write_shot, False)
     self.assertEqual(ip.no_write_shot, ip.isNoWriteShot())
     self.assertEqual(ip.no_write_model, False)
     self.assertEqual(ip.no_write_model, ip.isNoWriteModel())
     self.assertEqual(ip.write_once, False)
     self.assertEqual(ip.write_once, ip.isWriteOnce())
     pydev = pytree.TESTDEVICE
     part = pydev.conglomerate_nids[1]
     self.assertEqual(part.PART_NAME(), ':ACTIONSERVER')
     self.assertEqual(part.original_part_name, ':ACTIONSERVER')
     self.assertEqual(
         str(Data.execute('GETNCI($,"ORIGINAL_PART_NAME")', part)),
         ':ACTIONSERVER')
     self.assertEqual(pydev.__class__, Device.PyDevice('TestDevice'))
     devs = pytree.getNodeWild('\\PYTREESUB::TOP.***', 'DEVICE')
     part = devs[0].conglomerate_nids[3]
     self.assertEqual(part.original_part_name, ':COMMENT')
     self.assertEqual(
         part.original_part_name,
         str(Data.execute('GETNCI($,"ORIGINAL_PART_NAME")', part)))
     self.assertEqual(ip.owner_id, ip.getOwnerId())
     self.assertEqual(ip.rlength, 136)
     self.assertEqual(ip.rlength, ip.getCompressedLength())
     self.assertEqual(ip.setup_information, False)
     self.assertEqual(ip.setup_information, ip.isSetup())
     self.assertEqual(ip.status, 0)
     self.assertEqual(ip.status, ip.getStatus())
     self.assertEqual((ip.tags == Array([
         'IP', 'MAGNETICS_IP', 'MAG_IP', 'MAGNETICS_PLASMA_CURRENT',
         'MAG_PLASMA_CURRENT'
     ])).all(), True)
     self.assertEqual((ip.tags == ip.getTags()).all(), True)
     self.assertEqual(ip.time_inserted, ip.getTimeInserted())
コード例 #31
0
ファイル: SPECTRO_CFG.py プロジェクト: santorofer/mdsplus
    def load_config(self):

        print(sys.version_info)

        from openpyxl import load_workbook

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

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

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

            sheet = wb['CONFIG']

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

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

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

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

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

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

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

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

            param = 'P0_str_arr'
            matrix = sheet['J2':'L%d' % (self.LOS_NUM + 1)]
            data_arr = [
                c.value for c in np.asarray(matrix).reshape(3 * self.LOS_NUM)
            ]
            P0_arr = np.array(data_arr, 'float32').reshape([self.LOS_NUM, 3])
            P0_str_arr = [str(c) for c in P0_arr]

            param = 'P1_str_arr'
            matrix = sheet['M2':'O%d' % (self.LOS_NUM + 1)]
            data_arr = [
                c.value for c in np.asarray(matrix).reshape(3 * self.LOS_NUM)
            ]
            P1_arr = np.array(data_arr, 'float32').reshape([self.LOS_NUM, 3])
            P1_str_arr = [str(c) for c in P1_arr]

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

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

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

            param = 'calib_flag_arr'
            col = sheet['S']
            calib_flag_arr = [
                str(c.value if c.value != None else "false").lower()
                for c in col[1:len(col):1]
            ]

            wb.close()

        except Exception as e:
            Data.execute(
                'DevLogErr($1,$2)', self.getNid(),
                'Cannot read or invalid spectro param %s configuration file : %s '
                % (param, str(e)))
            raise mdsExceptions.TclFAILED_ESSENTIAL

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

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

        try:
            field = 'label'
            self.config_los_label.putData(StringArray(label_arr))
            field = 'telescope'
            self.config_los_telescope.putData(StringArray(telescope_arr))
            field = 'a_patch'
            self.config_los_a_patch.putData(StringArray(a_patch_arr))
            field = 'b_patch'
            self.config_los_b_patch.putData(StringArray(b_patch_arr))
            field = 'c_patch'
            self.config_los_c_patch.putData(StringArray(c_patch_arr))
            field = 'or_pannel'
            self.config_los_or_pannel.putData(StringArray(or_pannel_arr))
            field = 'diameter'
            self.config_los_diameter.putData(StringArray(diameter_str_arr))
            field = 'diaphragm'
            self.config_los_diaphragm.putData(StringArray(diaphragm_str_arr))
            field = 'P0'
            self.config_los_p0.putData(StringArray(P0_str_arr))
            field = 'P1'
            self.config_los_p1.putData(StringArray(P1_str_arr))
            field = 'roi'
            self.config_los_roi.putData(StringArray(roi_str_arr))
            field = 'spectrometer'
            self.config_los_spectrometer.putData(StringArray(spec_arr))
            field = 'note'
            self.config_los_note.putData(StringArray(note_arr))
            field = 'calib_flag'
            self.config_los_calib_flag.putData(StringArray(calib_flag_arr))
        except Exception as e:
            Data.execute('DevLogErr($1,$2)', self.getNid(),
                         'Error writing %s on LoS  : %s ' % (field, str(e)))
            raise mdsExceptions.TclFAILED_ESSENTIAL

        spectrometer_list = []
        for i in range(0, self.LOS_NUM):

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

            try:
                getattr(self, 'los_%03d_telescope' % (i + 1)).putData(
                    telescope_arr[i])
            except Exception as e:
                Data.execute(
                    'DevLogErr($1,$2)', self.getNid(),
                    'Error writing telescope field on LoS %s ' % (i + 1) +
                    str(e))
                raise mdsExceptions.TclFAILED_ESSENTIAL

            try:
                getattr(self,
                        'los_%03d_c_patch' % (i + 1)).putData(c_patch_arr[i])
            except Exception as e:
                Data.execute(
                    'DevLogErr($1,$2)', self.getNid(),
                    'Error writing C patch field on LoS %s ' % (i + 1) +
                    str(e))
                raise mdsExceptions.TclFAILED_ESSENTIAL

            try:
                getattr(self,
                        'los_%03d_b_patch' % (i + 1)).putData(b_patch_arr[i])
            except Exception as e:
                Data.execute(
                    'DevLogErr($1,$2)', self.getNid(),
                    'Error writing B patch field on LoS %s ' % (i + 1) +
                    str(e))
                raise mdsExceptions.TclFAILED_ESSENTIAL

            try:
                getattr(self, 'los_%03d_or_pannel' % (i + 1)).putData(
                    or_pannel_arr[i])
            except Exception as e:
                Data.execute(
                    'DevLogErr($1,$2)', self.getNid(),
                    'Error writing OR pannel field on LoS %s ' % (i + 1) +
                    str(e))
                raise mdsExceptions.TclFAILED_ESSENTIAL

            try:
                getattr(self,
                        'los_%03d_a_patch' % (i + 1)).putData(a_patch_arr[i])
            except Exception as e:
                Data.execute(
                    'DevLogErr($1,$2)', self.getNid(),
                    'Error writing A patch field on LoS %s ' % (i + 1) +
                    str(e))
                raise mdsExceptions.TclFAILED_ESSENTIAL

            try:
                getattr(self,
                        'los_%03d_diameter' % (i + 1)).putData(diameter_arr[i])
            except Exception as e:
                Data.execute(
                    'DevLogErr($1,$2)', self.getNid(),
                    'Error writing diameter field on LoS %s ' % (i + 1) +
                    str(e))
                raise mdsExceptions.TclFAILED_ESSENTIAL

            try:
                getattr(self, 'los_%03d_diaphragm' % (i + 1)).putData(
                    diaphragm_arr[i])
            except Exception as e:
                Data.execute(
                    'DevLogErr($1,$2)', self.getNid(),
                    'Error writing diaphragm field on LoS %s ' % (i + 1) +
                    str(e))
                raise mdsExceptions.TclFAILED_ESSENTIAL

            try:
                getattr(self, 'los_%03d_p0' % (i + 1)).putData(
                    Float32Array(P0_arr[i]))
            except Exception as e:
                Data.execute(
                    'DevLogErr($1,$2)', self.getNid(),
                    'Error writing start point P0 field on LoS %s ' % (i + 1) +
                    str(e))
                raise mdsExceptions.TclFAILED_ESSENTIAL

            try:
                getattr(self, 'los_%03d_p1' % (i + 1)).putData(
                    Float32Array(P1_arr[i]))
            except Exception as e:
                Data.execute(
                    'DevLogErr($1,$2)', self.getNid(),
                    'Error writing end point P1 field on LoS %s ' % (i + 1) +
                    str(e))
                raise mdsExceptions.TclFAILED_ESSENTIAL

            try:
                getattr(self, 'los_%03d_roi' % (i + 1)).putData(roi_arr[i])
            except Exception as e:
                Data.execute(
                    'DevLogErr($1,$2)', self.getNid(),
                    'Error writing roi field on LoS %s ' % (i + 1) + str(e))
                raise mdsExceptions.TclFAILED_ESSENTIAL

            try:
                getattr(self,
                        'los_%03d_spectrometer' % (i + 1)).putData(spec_arr[i])
            except Exception as e:
                Data.execute(
                    'DevLogErr($1,$2)', self.getNid(),
                    'Error writing spectrometer field on LoS %s ' % (i + 1) +
                    str(e))
                raise mdsExceptions.TclFAILED_ESSENTIAL

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

            try:
                getattr(self, 'los_%03d_calib_flag' % (i + 1)).putData(
                    calib_flag_arr[i])
            except Exception as e:
                Data.execute(
                    'DevLogErr($1,$2)', self.getNid(),
                    'Error writing calib flag field on LoS %s ' % (i + 1) +
                    str(e))
                raise mdsExceptions.TclFAILED_ESSENTIAL

            try:
                if label_arr[i] == 'None':
                    continue

                if len(spec_arr[i].strip()) == 0:
                    print(self.bcolors.OKBLUE +
                          'Info LoS %d (%s) acquisition not configured ' %
                          (i + 1, label_arr[i]) + self.bcolors.ENDC)
                    continue

                if self.getDeviceName(self.__getattr__(
                        '\\%s' % (spec_arr[i]))) == 'PI_SCT320':
                    # Set link LOS_xxx spectra to ROI_xx spectrometer
                    try:
                        # Reset current link
                        getattr(self,
                                'los_%03d_spectra_ref' % (i + 1)).deleteData()
                        if len(spec_arr[i]) > 0 and not (spec_arr[i]
                                                         in spectrometer_list):
                            for r in range(1, 25):
                                self.__getattr__(
                                    '\\%s.ROIS.ROI_%02d:LOS_PATH' %
                                    (spec_arr[i], r)).deleteData()
                            # Register spectrometer already reset
                            spectrometer_list.append(spec_arr[i])

                        if roi_arr[i] == -1:
                            continue

                        spectraRoiNode = self.__getattr__(
                            '\\%s.ROIS.ROI_%02d:SPECTRA' %
                            (spec_arr[i], roi_arr[i]))
                        getattr(self, 'los_%03d_spectra_ref' %
                                (i + 1)).putData(spectraRoiNode)
                        self.__getattr__('\\%s.ROIS.ROI_%02d:LOS_PATH' %
                                         (spec_arr[i], roi_arr[i])).putData(
                                             label_arr[i])

                        print(
                            self.bcolors.OKGREEN +
                            'Info LoS %d (%s) SPECTRO acquisition configured on Spectrometer %s Roi %d'
                            % (i + 1, label_arr[i], spec_arr[i], roi_arr[i]) +
                            self.bcolors.ENDC)

                    except Exception as e:
                        Data.execute(
                            'DevLogErr($1,$2)', self.getNid(),
                            'Error setting link from LoS %d (%s) to ROI %d on spectrometer %s : %s'
                            % (i + 1, label_arr[i], roi_arr[i], spec_arr[i],
                               str(e)))

                # spec_arr for photodiode is the Front End device BOARD
                elif self.getDeviceName(
                        self.__getattr__('\\%s' % (spec_arr[i]))) == 'PLFE':
                    # Set link LOS_xxx photodiode to Front End
                    try:
                        # Reset photodiode acquisitio channel link
                        getattr(self,
                                'los_%03d_photodiode' % (i + 1)).deleteData()

                        # ROI for phothodiode is the Front End Board channel and adc channel coded as NXX
                        # where N is the BOARD channel 1 or 2 and XX is adc channel from 1 to 32
                        if roi_arr[i] == -1:
                            continue

                        # From FE board path retrives FE BOARD index form 1 to 6
                        feBoardIdx = int(spec_arr[i][-1:])
                        if feBoardIdx < 1 or feBoardIdx > 6:
                            raise Exception(
                                'Invalid board index, valid values from 1 to 6'
                            )
                        code = int(roi_arr[i])

                        feBoardCh = code / 100  # ROI for front end identify the FE board channl 1 or 2
                        if feBoardCh != 1 and feBoardCh != 2:
                            raise Exception(
                                'Invalid board channel, valid values 1 or 2')

                        adcChan = code - feBoardCh * 100
                        if adcChan < 1 or adcChan > 32:
                            raise Exception(
                                'Invalid adc channel number %d for adc device define in front end device, valid values are from 1 to 32'
                                % (adcChan))

                        fePath = self.getDevice(
                            self.__getattr__('\\%s' %
                                             (spec_arr[i]))).getMinPath()
                        adcPath = (self.__getattr__(
                            '%s:ADC' % (fePath))).getData().getMinPath()

                        expr = Data.compile(
                            '%s.CHANNEL_%d:DATA / (%s.BOARD_%02d.SETUP.CHANNEL_%02d.WR:GAIN * (%s.BOARD_%02d.SETUP.CHANNEL_%02d.WR:TRANS == 0 ? 1 : 100))'
                            % (adcPath, adcChan, fePath, feBoardIdx, feBoardCh,
                               fePath, feBoardIdx, feBoardCh))

                        getattr(self,
                                'los_%03d_photodiode' % (i + 1)).putData(expr)

                        print(
                            self.bcolors.OKGREEN +
                            'Info LoS %d (%s) PHOTODIODE acquisition configured on Adc %s ch %d Front End %s Board %d Ch %d'
                            % (i + 1, label_arr[i], adcPath, adcChan, fePath,
                               feBoardIdx, feBoardCh) + self.bcolors.ENDC)

                    except Exception as e:
                        Data.execute(
                            'DevLogErr($1,$2)', self.getNid(),
                            'Error setting link from LoS %d (%s) to front end board %s : %s'
                            % (i + 1, label_arr[i], spec_arr[i], str(e)))
                else:
                    Data.execute(
                        'DevLogErr($1,$2)', self.getNid(),
                        'Invalid definition of spectrometer/front-end device (%s) for LoS %d (%s)'
                        % (spec_arr[i], i + 1, label_arr[i]))
            except Exception as e:
                print(str(e))
                Data.execute(
                    'DevLogErr($1,$2)', self.getNid(),
                    'Error definition of spectrometer/front-end device (%s) for LoS %d (%s) : %s'
                    % (spec_arr[i], i + 1, label_arr[i], str(e)))
        return 1
コード例 #32
0
    def init(self):
        from array import array
        print("Init Femto Amplifier: reading data from traverser...")

        # Get Name
        try:
            name = self.name.data()
            print('Name=', name)
        except:
            Data.execute('DevLogErr($1,$2)', self.nid,
                         'WARNING: device with no name')
            #raise mdsExceptions.TclFAILED_ESSENTIAL

        # Get IP Address
        try:
            ipAddr = self.ip_addr.data()
            print('Remote Mode: IP address = ', ipAddr,
                  ';note: empty for Local Mode.')
        except:
            ipAddr = ""
            Data.execute('DevLogErr($1,$2)', self.nid,
                         'WARNING: Local Mode. Put a valid IP address.')

        # Get ComPort
        try:
            comPort = self.com_port.data()
            print('COM port = ', comPort)
        except:
            Data.execute('DevLogErr($1,$2)', self.nid,
                         'ERROR: No COM port. Put COMx in traverser.')
            raise mdsExceptions.TclFAILED_ESSENTIAL

        femto = array('B')

        gainDict = {
            "10^3": 0,
            "10^4": 1,
            "10^5": 2,
            "10^6": 3,
            "10^7": 4,
            "10^8": 5,
            "10^9": 6,
            "0": 0
        }
        acdcDict = {"AC": 0, "DC": 8, "0": 0}
        hslnDict = {"HS": 0, "LN": 16, "0": 0}

        for i in range(1, 66):
            try:
                gain = self.__getattr__('channel_%02d_gain' % (i)).data()
                #print 'gain=',gain
                gainVal = gainDict[gain]
                #print 'gainVal=',gainVal
            except:
                Data.execute(
                    'DevLogErr($1,$2)', self.nid,
                    'ERROR: Invalid gain setting in Femto %02d.' % (i))
                raise mdsExceptions.TclFAILED_ESSENTIAL

            try:
                acdc = self.__getattr__('channel_%02d_acdc' % (i)).data()
                #print 'acdc=',acdc
                acdcVal = acdcDict[acdc]
                #print 'acdcVal=',acdcVal
            except:
                Data.execute(
                    'DevLogErr($1,$2)', self.nid,
                    'ERROR: Invalid acdc setting in Femto %02d.' % (i))
                raise mdsExceptions.TclFAILED_ESSENTIAL

            try:
                hsln = self.__getattr__('channel_%02d_hsln' % (i)).data()
                #print 'hsln=',hsln
                hslnVal = hslnDict[hsln]
                #print 'hslnVal=',hslnVal
            except:
                Data.execute(
                    'DevLogErr($1,$2)', self.nid,
                    'ERROR: Invalid hsln setting in Femto %02d.' % (i))
                raise mdsExceptions.TclFAILED_ESSENTIAL

            try:
                conf = gainVal + acdcVal + hslnVal
                #print 'Femto %02d conf.='%(i),conf
                femto.append(conf)
            except:
                print("Error appending data to array.")
                raise mdsExceptions.TclFAILED_ESSENTIAL

        print("Init Femto Amplifier: data reading completed.")

        print("Init Femto Amplifier: writing data...")
        #LOCAL MODE
        if ipAddr == "":
            try:
                deviceLib = CDLL("RS232Lib.dll")
            except:
                print('ERROR: Cannot link to device library femto.dll')
                raise mdsExceptions.TclFAILED_ESSENTIAL
            try:
                femtostr = femto.tostring()
                #print 'femtostrtype=',type(femtostr),'val=',femtostr
            except:
                print('Error converting array to string.')
                raise mdsExceptions.TclFAILED_ESSENTIAL
            try:
                deviceLib.Femto232Write.argtypes = [c_char_p, c_char_p]
                deviceLib.Femto232Write(c_char_p(comPort), c_char_p(femtostr))
            except:
                print('Error doing Femto232Write() in .dll')
                raise mdsExceptions.TclFAILED_ESSENTIAL

        #REMOTE MODE
        else:
            # Connect via MdsIP
            status = Data.execute('MdsConnect("' + ipAddr + '")')
            if status == 0:
                Data.execute('MdsDisconnect()')
                Data.execute('DevLogErr($1,$2)', self.nid,
                             "Cannot Connect to specified IP ADDRESS: ",
                             ipAddr)
                raise mdsExceptions.TclFAILED_ESSENTIAL
            # init
            status = Data.execute(
                'MdsValue("RS232Lib->Femto232Write($1,$2)",$1,$2)', comPort,
                Int8Array(femto))
            for i in range(0, 65):
                print('Femto %02d-> ' % (i + 1), '%02x' % (femto[i]))
            del i
            if status == 0:
                Data.execute('MdsDisconnect()')
                Data.execute(
                    'DevLogErr($1,$2)', self.nid,
                    "ERROR doing MdsValue(femto->Femto232Write(...))")
                raise mdsExceptions.TclFAILED_ESSENTIAL
            # disconnect
            Data.execute('MdsDisconnect()')

        print('Init Femto Amplifier: end.')
        return
コード例 #33
0
ファイル: NI6259EV.py プロジェクト: zack-vii/mdsplus
    def start_store(self):

        self.debugPrint(
            '================= PXI 6259 EVstart store ===============')

        if self.restoreInfo() != self.DEV_IS_OPEN:
            Data.execute('DevLogErr($1,$2)', self.getNid(),
                         'Module not Initialized')
            raise mdsExceptions.TclFAILED_ESSENTIAL

#Module in acquisition check
        try:
            if self.restoreWorker():
                if self.worker.isAlive():
                    Data.execute('DevLogErr($1,$2)', self.getNid(),
                                 'Module is in acquisition')
                    return
        except:
            pass

        self.worker = self.AsynchStore()
        self.worker.daemon = True
        self.worker.stopReq = False
        NI6259EV.workers[self.nid] = self.worker

        chanMap = []
        stopAcq = c_void_p(0)
        NI6259EV.niInterfaceLib.getStopAcqFlag(byref(stopAcq))
        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
        for chan in range(0, numChannels):
            try:
                mode = getattr(self, 'channel_%d_mode' % (chan + 1)).data()
                if mode != 'DISABLED':
                    chanMap.append(chan)
            except:
                Data.execute('DevLogErr($1,$2)', self.getNid(),
                             'Invalid mode for channel ' + str(chan + 1))
                raise DevBAD_PARAMETER
        treePtr = c_void_p(0)
        NI6259EV.niInterfaceLib.openTree(c_char_p(self.getTree().name),
                                         c_int(self.getTree().shot),
                                         byref(treePtr))
        if (inputMode == self.AI_CHANNEL_TYPE_DIFFERENTIAL):
            self.worker.configure(self, self.fd, chanMap, self.diffChanMap,
                                  treePtr, stopAcq)
        else:
            self.worker.configure(self, self.fd, chanMap, self.nonDiffChanMap,
                                  treePtr, stopAcq)
        self.saveWorker()
        self.worker.start()

        time.sleep(2)

        if self.worker.hasError():
            raise mdsExceptions.TclFAILED_ESSENTIAL

        self.debugPrint(
            "======================================================")

        return 1
コード例 #34
0
ファイル: doScope.py プロジェクト: MDSplus/Python-TDISHR
def doScopepanel(self):
    def getStringExp(self,name,response_headers):
        if name in self.args:
            try:
                response_headers.append((name,str(Data.execute(self.args[name][-1]).data())))
            except Exception:
                response_headers.append((name,str(sys.exc_info()[1])))

    response_headers=list()
    response_headers.append(('Cache-Control','no-store, no-cache, must-revalidate'))
    response_headers.append(('Pragma','no-cache'))
    if 'tree' in self.args:
        Tree.usePrivateCtx()
        try:
            t=Tree(self.args['tree'][-1],int(self.args['shot'][-1].split(',')[0]))
        except:
            pass

    for name in ('title','xlabel','ylabel','xmin','xmax','ymin','ymax'):
        getStringExp(self,name,response_headers)

    sig_idx=0
    output=''
    if 'tree' in self.args:
        shots=self.args['shot'][-1].split(',')
        for shot in shots:
            y_idx=1
            y_idx_s='%d' % (y_idx,)
            while 'y'+y_idx_s in self.args:
                x_idx_s=y_idx_s
                sig_idx=sig_idx+1
                sig_idx_s='%d' % (sig_idx,)
                expr=self.args['y'+y_idx_s][-1]
                y_idx=y_idx+1
                y_idx_s='%d' % (y_idx,)
                try:
                    t=Tree(self.args['tree'][-1],int(shot))
                    response_headers.append(('SHOT'+sig_idx_s,str(t.shot)))
                except Exception:
                    response_headers.append(('ERROR'+sig_idx_s,'Error opening tree %s, shot %s, error: %s' % (self.args['tree'][-1],shot,sys.exc_info()[1])))
                    continue
                if 'default_node' in self.args:
                    try:
                        t.setDefault(t.getNode(self.args['default_node'][-1]))
                    except Exception:
                        response_headers.append(('ERROR'+sig_idx_s,'Error setting default to %s in tree %s, shot %s, error: %s' % (self.args['default_node'][-1],
                                                                                                                                    self.args['tree'][-1],shot,sys.exc_info()[1])))
                        continue
                try:
                    sig=Data.execute(expr)
                    y=makeData(sig.data())
                except Exception:
                    response_headers.append(('ERROR' + sig_idx_s,'Error evaluating expression: "%s", error: %s' % (expr,sys.exc_info()[1])))
                    continue
                if 'x'+x_idx_s in self.args:
                    expr=self.args['x'+x_idx_s][-1]
                    try:
                        x=Data.execute(expr)
                        x=makeData(x.data())
                    except Exception:
                        response_headers.append(('ERROR'+sig_idx_s,'Error evaluating expression: "%s", error: %s' % (expr,sys.exc_info()[1])))
                        continue
                else:
                    try:
                        x=makeData(sig.dim_of().data())
                    except Exception:
                        response_headers.append(('ERROR'+sig_idx_s,'Error getting x axis of %s: "%s", error: %s' % (expr,sys.exc_info()[1])))
                        continue
                response_headers.append(('X'+sig_idx_s+'_DATATYPE',x.__class__.__name__))
                response_headers.append(('Y'+sig_idx_s+'_DATATYPE',y.__class__.__name__))
                response_headers.append(('X'+sig_idx_s+'_LENGTH',str(len(x))))
                response_headers.append(('Y'+sig_idx_s+'_LENGTH',str(len(y))))
                output=output+str(x.data().data)+str(y.data().data)
    else:            
        y_idx=1
        y_idx_s='%d' % (y_idx,)
        while 'y'+y_idx_s in self.args:
            x_idx_s = y_idx_s
            expr=self.args['y'+y_idx_s][-1]
            y_idx=y_idx+1
            y_idx_s='%d' % (y_idx,)
            sig_idx=sig_idx+1
            sig_idx_s='%d' % (sig_idx,)
            try:
                sig=Data.execute(expr)
                y=makeData(sig.data())
            except Exception:
                response_headers.append(('ERROR' + sig_idx_s,'Error evaluating expression: "%s", error: %s' % (expr,sys.exc_info()[1])))
                continue
            if 'x'+x_idx_s in self.args:
                expr=self.args['x'+x_idx_s][-1]
                try:
                    x=Data.execute(expr)
                    x=makeData(x.data())
                except Exception:
                    response_headers.append(('ERROR'+sig_idx_s,'Error evaluating expression: "%s", error: %s' % (expr,sys.exc_info()[1])))
                    continue
            else:
                try:
                    x=makeData(sig.dim_of().data())
                except Exception:
                    response_headers.append(('ERROR'+sig_idx_s,'Error getting x axis of %s: "%s", error: %s' % (expr,sys.exc_info()[1])))
                    continue
            response_headers.append(('X'+sig_idx_s+'_DATATYPE',x.__class__.__name__))
            response_headers.append(('Y'+sig_idx_s+'_DATATYPE',y.__class__.__name__))
            response_headers.append(('X'+sig_idx_s+'_LENGTH',str(len(x))))
            response_headers.append(('Y'+sig_idx_s+'_LENGTH',str(len(y))))
            output=output+str(x.data().data)+str(y.data().data)
    return ('200 OK', response_headers, output)
コード例 #35
0
ファイル: doScope.py プロジェクト: AndreaRigoni/mdsplus
def doScopepanel(self):
    def getStringExp(self, name, response_headers, t):
        if name in self.args:
            try:
                if t == None:
                    response_headers.append(
                        (name, str(Data.execute(self.args[name][-1]).data())))
                else:
                    response_headers.append(
                        (name, str(t.tdiExecute(self.args[name][-1]).data())))
            except Exception:
                response_headers.append((name + '_error', str(sys.exc_info())))

    def manageContinuousUpdate(self, x):
        if x.getShape().size == 1:
            new_max_x = x.data()[-1]
        else:
            new_max_x = x.data()[0][-1]
        curr_max_x = float(self.args['curr_max_x' + x_idx_s][-1])
        displayed_width = float(self.args['displayed_width'][-1])
        default_num_samples = float(self.args['default_num_samples'][-1])
        num_samples = int(
            (new_max_x - curr_max_x) * default_num_samples / displayed_width)
        if new_max_x > curr_max_x and num_samples > 1:
            if issubclass(x.dtype.type, integer):
                min_req_x = floor(curr_max_x + 1)
            else:
                min_req_x = curr_max_x + finfo(new_max_x).eps
            update_function = 'MdsMisc->GetXYWave:DSC'
            infinity = sys.float_info.max
            if x.__class__.__name__ == 'Uint64Array' or x.__class__.__name__ == 'Int64Array':
                update_function = 'MdsMisc->GetXYWaveLongTimes:DSC'
                min_req_x = str(int(min_req_x)) + 'QU'
                infinity = str((1 << 63) - 1) + 'QU'
            sig = Data.execute(
                update_function + '(\'' +
                expr.replace('\\', '\\\\').replace('\'', '\\\'') + '\',' +
                str(min_req_x) + ',' + str(infinity) + ',' + str(num_samples) +
                ')')
            return makeData(sig.dim_of().data()), makeData(sig.data())
        else:
            return Float64Array([]), Float64Array([])

    response_headers = list()
    response_headers.append(
        ('Cache-Control', 'no-store, no-cache, must-revalidate'))
    response_headers.append(('Pragma', 'no-cache'))
    t = None
    if 'tree' in self.args:
        Tree.usePrivateCtx()
        try:
            t = Tree(self.args['tree'][-1],
                     int(self.args['shot'][-1].split(',')[0]))
        except:
            pass

    for name in ('title', 'xlabel', 'ylabel', 'xmin', 'xmax', 'ymin', 'ymax'):
        getStringExp(self, name, response_headers, t)

    continuous_update = 'continuous_update' in self.args

    sig_idx = 0
    output = ''
    if 'tree' in self.args:
        shots = self.args['shot'][-1].split(',')
        for shot in shots:
            y_idx = 1
            y_idx_s = '%d' % (y_idx, )
            while 'y' + y_idx_s in self.args:
                x_idx_s = y_idx_s
                sig_idx = sig_idx + 1
                sig_idx_s = '%d' % (sig_idx, )
                expr = self.args['y' + y_idx_s][-1]
                y_idx = y_idx + 1
                y_idx_s = '%d' % (y_idx, )
                try:
                    t = Tree(self.args['tree'][-1], int(shot))
                    response_headers.append(('SHOT' + sig_idx_s, str(t.shot)))
                except Exception:
                    response_headers.append(
                        ('ERROR' + sig_idx_s,
                         'Error opening tree %s, shot %s, error: %s' %
                         (self.args['tree'][-1], shot, sys.exc_info())))
                    continue
                if 'default_node' in self.args:
                    try:
                        t.setDefault(t.getNode(self.args['default_node'][-1]))
                    except Exception:
                        response_headers.append((
                            'ERROR' + sig_idx_s,
                            'Error setting default to %s in tree %s, shot %s, error: %s'
                            % (self.args['default_node'][-1],
                               self.args['tree'][-1], shot, sys.exc_info())))
                        continue
                try:
                    if t == None:
                        sig = Data.execute(expr)
                    else:
                        sig = t.tdiExecute(expr)
                    if not continuous_update:
                        y = makeData(sig.data())
                except Exception:
                    response_headers.append(
                        ('ERROR' + sig_idx_s,
                         'Error evaluating expression: "%s", error: %s' %
                         (expr, sys.exc_info())))
                    continue
                if 'x' + x_idx_s in self.args:
                    expr = self.args['x' + x_idx_s][-1]
                    try:
                        if t == None:
                            x = Data.execute(expr)
                        else:
                            x = t.tdiEexecute(expr)
                        x = makeData(x.data())
                        if continuous_update:
                            x, y = manageContinuousUpdate(self, x)
                    except Exception:
                        response_headers.append(
                            ('ERROR' + sig_idx_s,
                             'Error evaluating expression: "%s", error: %s' %
                             (expr, sys.exc_info())))
                        continue
                else:
                    try:
                        x = makeData(sig.dim_of().data())
                        if continuous_update:
                            x, y = manageContinuousUpdate(self, x)
                    except Exception:
                        response_headers.append(
                            ('ERROR' + sig_idx_s,
                             'Error getting x axis of %s:, error: %s' %
                             (expr, sys.exc_info())))
                        continue
                if x.__class__.__name__ == 'Uint64Array' or x.__class__.__name__ == 'Int64Array':
                    x = Float64Array(
                        x)  # Javascript doesn't support 64 bit integers
                    response_headers.append(('X_IS_DATETIME', 'true'))
                response_headers.append(
                    ('X' + sig_idx_s + '_DATATYPE', x.__class__.__name__))
                response_headers.append(
                    ('Y' + sig_idx_s + '_DATATYPE', y.__class__.__name__))
                response_headers.append(
                    ('X' + sig_idx_s + '_LENGTH', str(len(x))))
                response_headers.append(
                    ('Y' + sig_idx_s + '_LENGTH', str(len(y))))
                output = output + str(x.data().data) + str(y.data().data)
    else:
        y_idx = 1
        y_idx_s = '%d' % (y_idx, )
        while 'y' + y_idx_s in self.args:
            x_idx_s = y_idx_s
            expr = self.args['y' + y_idx_s][-1]
            y_idx = y_idx + 1
            y_idx_s = '%d' % (y_idx, )
            sig_idx = sig_idx + 1
            sig_idx_s = '%d' % (sig_idx, )
            try:
                if t == None:
                    sig = Data.execute(expr)
                else:
                    sig = t.tdiExecute(expr)
                if not continuous_update:
                    y = makeData(sig.data())
            except Exception:
                response_headers.append(
                    ('ERROR' + sig_idx_s,
                     'Error evaluating expression: "%s", error: %s' %
                     (expr, sys.exc_info())))
                continue
            if 'x' + x_idx_s in self.args:
                expr = self.args['x' + x_idx_s][-1]
                try:
                    if t == None:
                        x = Data.execute(expr)
                    else:
                        x = t.tdiExecute(expr)
                    x = makeData(x.data())
                    if continuous_update:
                        x, y = manageContinuousUpdate(self, x)
                except Exception:
                    response_headers.append(
                        ('ERROR' + sig_idx_s,
                         'Error evaluating expression: "%s", error: %s' %
                         (expr, sys.exc_info())))
                    continue
            else:
                try:
                    x = makeData(sig.dim_of().data())
                    if continuous_update:
                        x, y = manageContinuousUpdate(self, x)
                except Exception:
                    response_headers.append(
                        ('ERROR' + sig_idx_s,
                         'Error getting x axis of %s: "%s", error: %s' %
                         (expr, sys.exc_info())))
                    continue
            if x.__class__.__name__ == 'Uint64Array' or x.__class__.__name__ == 'Int64Array':
                x = Float64Array(
                    x)  # Javascript doesn't support 64 bit integers
                response_headers.append(('X_IS_DATETIME', 'true'))
            response_headers.append(
                ('X' + sig_idx_s + '_DATATYPE', x.__class__.__name__))
            response_headers.append(
                ('Y' + sig_idx_s + '_DATATYPE', y.__class__.__name__))
            response_headers.append(('X' + sig_idx_s + '_LENGTH', str(len(x))))
            response_headers.append(('Y' + sig_idx_s + '_LENGTH', str(len(y))))
            output = output + str(x.data().data) + str(y.data().data)
    return ('200 OK', response_headers, output)
コード例 #36
0
ファイル: doScope.py プロジェクト: MDSplus/Python-TDISHR
 def getStringExp(self,name,response_headers):
     if name in self.args:
         try:
             response_headers.append((name,str(Data.execute(self.args[name][-1]).data())))
         except Exception:
             response_headers.append((name,str(sys.exc_info()[1])))
コード例 #37
0
ファイル: doScope.py プロジェクト: AndreaRigoni/mdsplus
def doScope(self):
    response_headers = list()
    noCache(response_headers)
    overallShot = None
    if 'user' in self.args:
        user = self.args['user'][-1]
        response_headers.append(('Content-type', 'text/html'))
        outStr = '<html><head><title>Scope Selection</title><body>'
        subdir = ''
        if 'dir' in self.args and '..' not in self.args['dir'][-1]:
            file_list = getConfigFiles(user, 'jScope' in self.args,
                                       self.args['dir'][-1])
        else:
            file_list = getConfigFiles(user, True, '')
            file_list.extend(getConfigFiles(user, False, ''))
        if (len(file_list) == 0):
            outStr = outStr + 'No Scope configuration file found for user ' + user + '</body></html>'
            status = '200 OK'
            return (status, response_headers, outStr)
        file_list.sort(file_list_cmp)
        last_is_dir = False
        for f in file_list:
            if not f['notdir']:
                last_is_dir = True
                if f['jScope']:
                    jscope = '&jScope=yes'
                else:
                    jscope = ''
                outStr = outStr + '<a href="?user='******'&dir=' + f[
                    'subdir'] + '/' + f['file'] + jscope + '">' + f[
                        'filespec'] + '</a><br>'
            else:
                if last_is_dir:
                    outStr = outStr + '<br>'
                last_is_dir = False
                outStr = outStr + '<a href="scope?config=' + f[
                    'filespec'] + '" target="_blank">' + f[
                        'filespec'] + '</a><br>'
        outStr = outStr + '</body></html>'
        status = '200 OK'
        return (status, response_headers, outStr)
    elif 'configxml' in self.args:

        #Handle direct configuration
        response_headers.append(('IS_CONFIG', 'YES'))
        response_headers.append(('Content-type', 'text/xml'))
        if 'shot' in self.args:
            overallShot = self.args['shot'][-1]
        f = open(self.args['configxml'][-1], 'r')
        lines = f.readlines()
        f.close()
        outStr = '<scope>'
        title = getValue(lines, 'Scope.title')
        if title:
            outStr = outStr + '<title><expression>' + encodeUrl(
                title) + '</expression>'
            event = getValue(lines, 'Scope.update_event')
            if event:
                outStr = outStr + '<event>' + event + '</event>'
            outStr = outStr + '</title>'
        outStr = outStr + '<palette>'
        idx = 0
        GLOBAL_SHOT_IDX = 8
        GLOBAL_TREE_IDX = 7
        GLOBAL_XMIN_IDX = 12
        GLOBAL_XMAX_IDX = 13
        GLOBAL_YMIN_IDX = 14
        GLOBAL_YMAX_IDX = 15
        while True:
            color = getValue(lines, 'Scope.color_' + str(idx))
            if (color == None):
                break
            color = color.split(',')[0]
            if color == 'Blak':
                color = 'Black'
            outStr = outStr + '<color>' + color + '</color>'
            idx = idx + 1


#Handle missing color palette
        if (idx == 0):
            outStr = outStr + '<color>Black</color>'
        outStr = outStr + '</palette>'
        globalTree = getValue(lines, 'Scope.global_1_1.experiment')
        globalShot = getValue(lines, 'Scope.global_1_1.shot')

        globalXMin = getValue(lines, 'Scope.global_1_1.xmin')
        globalXMax = getValue(lines, 'Scope.global_1_1.xmax')
        globalYMin = getValue(lines, 'Scope.global_1_1.ymin')
        globalYMax = getValue(lines, 'Scope.global_1_1.ymax')
        globalXLabel = getValue(lines, 'Scope.global_1_1.x_label')
        globalYLabel = getValue(lines, 'Scope.global_1_1.y_label')
        globalEvent = getValue(lines, 'Scope.global_1_1.event')
        numCols = int(getValue(lines, 'Scope.columns'))
        outStr = outStr + '<columns>'
        for colIdx in range(1, numCols + 1):
            outStr = outStr + '<column>'
            numRows = int(
                getValue(lines, 'Scope.rows_in_column_' + str(colIdx)))
            for rowIdx in range(1, numRows + 1):
                outStr = outStr + '<panel '
                globalDefs = int(
                    getValue(
                        lines, 'Scope.plot_' + str(rowIdx) + '_' +
                        str(colIdx) + '.global_defaults'))
                if (globalDefs & (1 << GLOBAL_TREE_IDX)):
                    tree = globalTree
                else:
                    tree = getValue(
                        lines, 'Scope.plot_' + str(rowIdx) + '_' +
                        str(colIdx) + '.experiment')

                if (tree != None):
                    outStr = outStr + ' tree = "' + tree + '" '
                    if overallShot != None:
                        outStr = outStr + ' shot = "' + overallShot + '" '
                    else:
                        if (globalDefs & (1 << GLOBAL_SHOT_IDX)):
                            shotNum = globalShot
                        else:
                            shotNum = getValue(
                                lines, 'Scope.plot_' + str(rowIdx) + '_' +
                                str(colIdx) + '.shot')
                        if (shotNum != None):
                            outStr = outStr + ' shot = "' + shotNum + '" '

                if (globalDefs & (1 << GLOBAL_XMIN_IDX)):
                    xmin = globalXMin
                else:
                    xmin = getValue(
                        lines, 'Scope.plot_' + str(rowIdx) + '_' +
                        str(colIdx) + '.xmin')
                if (xmin != None):
                    outStr = outStr + ' xmin = "' + encodeUrl(xmin) + '" '

                if (globalDefs & (1 << GLOBAL_XMAX_IDX)):
                    xmax = globalXMax
                else:
                    xmax = getValue(
                        lines, 'Scope.plot_' + str(rowIdx) + '_' +
                        str(colIdx) + '.xmax')
                if (xmax != None):
                    outStr = outStr + ' xmax = "' + encodeUrl(xmax) + '" '

                if (globalDefs & (1 << GLOBAL_YMIN_IDX)):
                    ymin = globalYMin
                else:
                    ymin = getValue(
                        lines, 'Scope.plot_' + str(rowIdx) + '_' +
                        str(colIdx) + '.ymin')
                if (ymin != None):
                    outStr = outStr + ' ymin = "' + encodeUrl(ymin) + '" '

                if (globalDefs & (1 << GLOBAL_YMAX_IDX)):
                    ymax = globalYMax
                else:
                    ymax = getValue(
                        lines, 'Scope.plot_' + str(rowIdx) + '_' +
                        str(colIdx) + '.ymax')
                if (ymax != None):
                    outStr = outStr + ' ymax = "' + encodeUrl(ymax) + '" '

                title = getValue(
                    lines,
                    'Scope.plot_' + str(rowIdx) + '_' + str(colIdx) + '.title')
                if (title != None):
                    title = encodeUrl(title)
                    title = title.replace('"', "'")
                    outStr = outStr + ' title = "' + title + '"'
                xlabel = getValue(
                    lines, 'Scope.plot_' + str(rowIdx) + '_' + str(colIdx) +
                    '.x_label')
                if (xlabel == None):
                    xlabel = globalXLabel
                if (xlabel != None):
                    xlabel = encodeUrl(xlabel)
                    xlabel = xlabel.replace('"', "'")
                    outStr = outStr + ' xlabel = "' + xlabel + '"'
                ylabel = getValue(
                    lines, 'Scope.plot_' + str(rowIdx) + '_' + str(colIdx) +
                    '.y_label')
                if (ylabel == None):
                    ylabel = globalYLabel
                if (ylabel != None):
                    ylabel = encodeUrl(ylabel)
                    ylabel = ylabel.replace('"', "'")
                    outStr = outStr + ' ylabel = "' + ylabel + '"'
                event = getValue(
                    lines,
                    'Scope.plot_' + str(rowIdx) + '_' + str(colIdx) + '.event')
                if (event == None):
                    event = globalEvent
                if (event != None):
                    outStr = outStr + ' event = "' + event + '"'
                continuous_update = getValue(
                    lines, 'Scope.plot_' + str(rowIdx) + '_' + str(colIdx) +
                    '.continuous_update')
                if (continuous_update != None):
                    outStr = outStr + ' continuous_update = "' + continuous_update + '"'
                is_image = getValue(
                    lines, 'Scope.plot_' + str(rowIdx) + '_' + str(colIdx) +
                    '.is_image')
                if (is_image != None and is_image == 'true'):
                    outStr = outStr + ' is_image = "true"'
                keep_ratio = getValue(
                    lines, 'Scope.plot_' + str(rowIdx) + '_' + str(colIdx) +
                    '.keep_ratio')
                if (keep_ratio != None):
                    outStr = outStr + ' keep_ratio = "' + keep_ratio + '"'
                horizontal_flip = getValue(
                    lines, 'Scope.plot_' + str(rowIdx) + '_' + str(colIdx) +
                    '.horizontal_flip')
                if (horizontal_flip != None):
                    outStr = outStr + ' horizontal_flip = "' + horizontal_flip + '"'
                vertical_flip = getValue(
                    lines, 'Scope.plot_' + str(rowIdx) + '_' + str(colIdx) +
                    '.vertical_flip')
                if (vertical_flip != None):
                    outStr = outStr + ' vertical_flip = "' + vertical_flip + '"'
                palette = getValue(
                    lines, 'Scope.plot_' + str(rowIdx) + '_' + str(colIdx) +
                    '.palette')
                if (palette != None):
                    outStr = outStr + ' palette = "' + palette + '"'
                bitShift = getValue(
                    lines, 'Scope.plot_' + str(rowIdx) + '_' + str(colIdx) +
                    '.bitShift')
                if (bitShift != None):
                    outStr = outStr + ' bitShift = "' + bitShift + '"'
                bitClip = getValue(
                    lines, 'Scope.plot_' + str(rowIdx) + '_' + str(colIdx) +
                    '.bitClip')
                if (bitClip != None):
                    outStr = outStr + ' bitClip = "' + bitClip + '"'

                outStr = outStr + '>'
                numExprStr = getValue(
                    lines, 'Scope.plot_' + str(rowIdx) + '_' + str(colIdx) +
                    '.num_expr')
                if (numExprStr == None):
                    numExpr = 1
                else:
                    numExpr = int(numExprStr)
                for exprIdx in range(1, numExpr + 1):
                    outStr = outStr + '<signal'
                    color = getValue(
                        lines, 'Scope.plot_' + str(rowIdx) + '_' +
                        str(colIdx) + '.color_' + str(exprIdx) + '_1')
                    if (color != None):
                        if color == 'Blak':
                            color = 'Black'  #fix old config file typo
                        outStr = outStr + ' color="' + color + '"'
                    else:
                        outStr = outStr + ' color="Black"'
                    mode = getValue(
                        lines, 'Scope.plot_' + str(rowIdx) + '_' +
                        str(colIdx) + '.mode_1D_' + str(exprIdx) + '_1')
                    marker = getValue(
                        lines, 'Scope.plot_' + str(rowIdx) + '_' +
                        str(colIdx) + '.marker_' + str(exprIdx) + '_1')
                    if (mode == 'Line' and marker == '0'):
                        outStr = outStr + ' mode="1"'
                    elif (mode == 'Line' and marker != '0'):
                        outStr = outStr + ' mode="3"'
                    elif (mode == 'Noline' and marker != '0'):
                        outStr = outStr + ' mode="2"'
                    outStr = outStr + '>'
                    yExpr = getValue(
                        lines, 'Scope.plot_' + str(rowIdx) + '_' +
                        str(colIdx) + '.y_expr_' + str(exprIdx))
                    if (yExpr == None):
                        yExpr = getValue(
                            lines, 'Scope.plot_' + str(rowIdx) + '_' +
                            str(colIdx) + '.y')
                    xExpr = getValue(
                        lines, 'Scope.plot_' + str(rowIdx) + '_' +
                        str(colIdx) + '.x_expr_' + str(exprIdx))
                    if (xExpr == None):
                        xExpr = getValue(
                            lines, 'Scope.plot_' + str(rowIdx) + '_' +
                            str(colIdx) + '.x')
                    if (xExpr == None):
                        outStr = outStr + encodeUrl(yExpr) + '</signal>'
                    else:
                        outStr = outStr + 'BUILD_SIGNAL(' + encodeUrl(
                            yExpr) + ',,' + encodeUrl(xExpr) + ')</signal>'
                outStr = outStr + '</panel>\n'
            outStr = outStr + '</column>\n\n'
        outStr = outStr + '</columns></scope>'
        output = str(outStr)
        status = '200 OK'
        return (status, response_headers, output)
    elif 'panel' in self.args:
        return doScopepanel(self)
    elif 'title' in self.args:
        response_headers.append(('Content-type', 'text/text'))
        try:
            output = str(Data.execute(self.args['title'][0]))
        except Exception:
            output = str(
                sys.exc_info()) + ' expression was ' + self.args['title'][0]
        return ('200 OK', response_headers, output)
    elif 'colortables' in self.args:
        response_headers.append(('Content-type', 'application/octet-stream'))
        try:
            f = open(os.path.dirname(__file__) + '/colors1.tbl', "r")
            output = f.read()
            f.close()
        except:
            response_headers.append(('ERROR', str(sys.exc_info())))
            output = ''
        return ('200 OK', response_headers, output)
    else:
        ans = ('400 NOT FOUND', [
            ('Content-type', 'text/text'),
        ], '')
        try:
            f = open(os.path.dirname(__file__) + '/../html/scope.html', "r")
            contents = f.read()
            f.close()
            ans = ('200 OK', [
                ('Content-type', 'text/html'),
            ], contents)
        except:
            pass
        return ans
コード例 #38
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=str(self.clock_src.record.getOriginalPartName())[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,))
コード例 #39
0
ファイル: NI6259AI.py プロジェクト: santorofer/mdsplus
        def run(self):

            self.device.setTree(
                Tree(self.device.getTree().name, self.device.getTree().shot))
            self.device = self.device.copy()

            bufSize = self.device.buf_size.data()
            segmentSize = self.device.seg_length.data()
            #counters = [0]*len(self.chanMap)
            boardId = self.device.board_id.data()
            acqMode = self.device.acq_mode.data()
            transientRec = False

            sampleToSkip = self.device.start_idx.data()
            #endIdx = self.device.end_idx.data()

            startTime = float(self.device.start_time.data())
            #trigSource = self.device.trig_source.data()
            clockSource = self.device.clock_source.evaluate()

            period = float(clockSource.getDelta())

            if(acqMode == 'TRANSIENT REC.'):
                transientRec = True

            chanFd = []
            chanNid = []
            resNid = []
            coeffsNid = []

            coeff_array = c_float*4
            coeff = coeff_array()

            # NI6259AI.niInterfaceLib.getStopAcqFlag(byref(self.stopAcq));
            gainDividers = []
            for chan in range(len(self.chanMap)):
                try:
                    # self.device.debugPrint 'CHANNEL', self.chanMap[chan]+1
                    # self.device.debugPrint '/dev/pxi6259.'+str(boardId)+'.ai.'+str(self.hwChanMap[self.chanMap[chan]])
                    currFd = os.open('/dev/pxi6259.'+str(boardId)+'.ai.'+str(
                        self.hwChanMap[self.chanMap[chan]]), os.O_RDWR | os.O_NONBLOCK)
                    chanFd.append(currFd)

                    chanNid.append(getattr(self.device, 'channel_%d_data_raw' % (
                        self.chanMap[chan]+1)).getNid())
                    # self.device.debugPrint "chanFd "+'channel_%d_data'%(self.chanMap[chan]+1), chanFd[chan], " chanNid ", chanNid[chan]
                    resNid.append(getattr(self.device, 'channel_%d_res_raw' % (
                        self.chanMap[chan]+1)).getNid())
                    coeffsNid.append(getattr(self.device, 'channel_%d_calib_param' % (
                        self.chanMap[chan]+1)).getNid())

                    gain = getattr(self.device, 'channel_%d_range' %
                                   (self.chanMap[chan]+1)).data()
                    gain_code = self.device.gainDict[gain]
                    gainDividers.append(self.device.gainDividerDict[gain])
                    n_coeff = c_int(0)
                    status = NI6259AI.niInterfaceLib.pxi6259_getCalibrationParams(
                        currFd, gain_code, coeff, byref(n_coeff))

                    if(status < 0):
                        errno = NI6259AI.niInterfaceLib.getErrno()
                        msg = 'Error (%d) %s' % (errno, os.strerror(errno))
                        self.device.debugPrint(msg)
                        Data.execute('DevLogErr($1,$2)', self.device.getNid(
                        ), 'Cannot read calibration values for Channel %d. Default value assumed ( offset= 0.0, gain = range/65536' % ((self.chanMap[chan])))
                        gainValue = self.device.gainValueDict[gain] * 2.
                        coeff[0] = coeff[2] = coeff[3] = 0
                        coeff[1] = c_float(gainValue / 65536.)

                    getattr(self.device, 'channel_%d_calib_param' %
                            (self.chanMap[chan]+1)).putData(Float32Array(coeff))

                except Exception as e:
                    self.device.debugPrint(e)
                    Data.execute('DevLogErr($1,$2)', self.device.getNid(
                    ), 'Cannot open Channel ' + str(self.chanMap[chan]))
                    self.error = self.ACQ_ERROR
                    return
            if(not transientRec):

                if(bufSize > segmentSize):
                    segmentSize = bufSize
                else:
                    c = segmentSize/bufSize
                    if (segmentSize % bufSize > 0):
                        c = c+1
                    segmentSize = c*bufSize

                numSamples = -1
                self.device.debugPrint("PXI 6259 CONTINUOUS ", numSamples)

            else:
                NI6259AI.niInterfaceLib.setStopAcqFlag(self.stopAcq)

                try:
                    numSamples = self.device.end_idx.data() - self.device.start_idx.data()
                except:
                    numSamples = 0
                    self.device.debugPrint("PXI 6259 NUM SAMPLES ", numSamples)

            status = NI6259AI.niLib.pxi6259_start_ai(c_int(self.fd))

            if(status != 0):
                Data.execute('DevLogErr($1,$2)', self.device.getNid(),
                             'Cannot Start Acquisition ')
                self.error = self.ACQ_ERROR
                return

            saveList = c_void_p(0)
            NI6259AI.niInterfaceLib.startSave(byref(saveList))
            #count = 0

            val = 0
            chanNid_c = (c_int * len(chanNid))(*chanNid)
            chanFd_c = (c_int * len(chanFd))(*chanFd)
            resNid_c = (c_int * len(resNid))(*resNid)
            coeffsNid_c = (c_int * len(coeffsNid))(*coeffsNid)
            gainDividers_c = (c_float * len(gainDividers))(*gainDividers)

            #timeAt0 = trigSource + startTime
            #self.device.debugPrint("PXI 6259 TIME AT0 ", numSamples)
            timeAt0 = startTime

            while not self.stopReq:
                try:
                    status = NI6259AI.niInterfaceLib.pxi6259_readAndSaveAllChannels(c_int(len(self.chanMap)), chanFd_c, c_int(int(round(bufSize))), c_int(int(round(segmentSize))), c_int(sampleToSkip), c_int(
                        numSamples), chanNid_c, gainDividers_c, coeffsNid_c, self.device.clock_source.getNid(), c_float(timeAt0), c_float(period), self.treePtr, saveList, self.stopAcq, c_int(self.device.getTree().shot), resNid_c)
                except Exception as ex:
                    self.device.debugPrint(
                        'Acquisition thread start error : %s' % (str(ex)))
                    self.error = self.ACQ_ERROR
                    self.stopReq = True

   # Check termination
                if (numSamples > 0 or (transientRec and status == -1)):
                    self.stopReq = True

                if status < 0:
                    self.device.debugPrint(
                        'Acquisition Loop exit with code %d' % (status))
                    self.error = self.ACQ_ERROR
                    self.stopReq = True

            if(transientRec and status == -1):
                Data.execute('DevLogErr($1,$2)', self.device.getNid(),
                             'PXI 6259 Module is not in stop state')
                self.error = self.ACQ_ERROR

            if(status < 0):
                if(status == -1):
                    Data.execute('DevLogErr($1,$2)', self.device.getNid(
                    ), 'PXI 6259 Module is not triggered')
                if(status == -2):
                    Data.execute('DevLogErr($1,$2)',
                                 self.device.getNid(), 'PXI 6259 DMA overflow')
                if(status == -3):
                    Data.execute('DevLogErr($1,$2)', self.device.getNid(
                    ), 'PXI 6259 Exception on acquisition function')
                self.error = self.ACQ_ERROR

            status = NI6259AI.niLib.pxi6259_stop_ai(c_int(self.fd))

            for chan in range(len(self.chanMap)):
                os.close(chanFd[chan])
            self.device.debugPrint('ASYNCH WORKER TERMINATED')
            NI6259AI.niInterfaceLib.stopSave(saveList)
            NI6259AI.niInterfaceLib.freeStopAcqFlag(self.stopAcq)

            self.device.closeInfo()
コード例 #40
0
 def getValue(self):
     try:
         return Data.compile(self.get_text())
     except Exception:
         MDSplusErrorMsg('Invalid Expression','Invalid expression specified.\n\n%s\n\n%s' % (self.get_text(),sys.exc_info()))
         raise
コード例 #41
0
ファイル: dt132_mod.py プロジェクト: shaunhaskey/AnuDevices
    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
        """
        print "=========== ANUDEVICES SH edited dt132.py 13/06/2012 ==========="
        stall=os.getenv("Shaun_Stall")
        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
            complete2=0
            tries2 = 0
            #SHAUN MODIFICATION SO THAT IT CAN BE RUN IN A LOOP AND WILL STALL HERE UNTIL CARD GOES TO POSTPROCESS
            if stall=="YES":
                print "stall is yes"
                while complete2==0:
                    if UUT.get_state().split()[-1] != "ST_STOP" :
                        tries2 +=1
                        sleep(1)
                        #print 'Still in run state'
                    else:
                        complete2=1
                        print 'Finished'
            #End Shaun Modification
            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]
            print mask
            error="Clock source must be a string"
            #clock_src=self.clock_src.record.getOriginalPartName().getString()[1:]
            clock_src=str(self.clock_src.record)[-3:] #edit!!
            #print "clock_src:", clock_src
            error=None
            if clock_src == 'INT_CLOCK' :
                self.clock.record = Range(delta=1./self.getInternalClock(UUT))
            else:
                self.clock.record = Range(delta=1./self.getInternalClock(UUT)) #TEST FOR 32MHZ clock!!! - getInternalCock is deceptively named - it also works for external clock and is the second value that is given when setting it
                
                #self.clock.record = Range(delta=1./self.clock_src.data()) #SHAUN EDIT!!!!!

                #SHAUN FAST DTACQ EDIT
#                if os.getenv('DTACQFAST')=='YES16' and boardip=='192.168.1.9':
#                    self.clock.record = Range(delta=1./(16000000)) #SHAUN EDIT!!!!!
#                if os.getenv('DTACQFAST')=='YES32' and boardip=='192.168.1.9':
#                    self.clock.record = Range(delta=1./(32000000)) #SHAUN EDIT!!!!!

                #print self.clock_src.data()
                #self.clock.record = self.clock_src
            clock = self.clock.record
            #print 'clock record being used is : '#SHAUN EDIT
            if debug:
                print "about to ask it to mdsconnect"
            #print "mdsConnect %s" % str(self.hostip.record)
            UUT.uut.acq2sh("mdsConnect %s" % str(self.hostip.record))
            if debug:
                print "about to ask it to mdsopen"
            #print 'mdsOpen %s %d'  % (self.boardip.tree.name, self.boardip.tree.shot,)
            UUT.uut.acq2sh('mdsOpen %s %d'  % (self.boardip.tree.name, self.boardip.tree.shot,))

            #SHAUN EDIT START
            mdsputchsent=0 #Remember if command has been sent - initialise to be 0
            listofchannels="" #Initialise list of channels to be used by bulk command
            for spot in range(32):#Build list of channels to be used
                chan_node = self.__getattr__('input_%2.2d' % (spot+1,))
                if chan_node.on:
                    listofchannels=listofchannels + str(spot+1) + ","
            if listofchannels[len(listofchannels)-1]==",": #remove the last comma
                listofchannels=listofchannels[:len(listofchannels)-1]

            #Shaun edit for DTACQ Fast Sampling
            if os.getenv('DTACQFAST')=='YES16' and boardip=='192.168.1.9':
                listofchannels='1,5,17,21'
            if os.getenv('DTACQFAST')=='YES32' and boardip=='192.168.1.9':
                listofchannels='1,17'
                
            mdsputchbulkcommand=1 #switch to use bulk mdsputch or not
            #SHAUN EDIT END
            
            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)
                        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"
                        #!!!!!!!!!!!!!!! SHAUN MODIFIED THE FOLLOWING LINE (ADDED the +1 on the third argument to fix 1 more sample in time/data - ORIGINALLY WASN"T THERE - also replaced %%calsig with %%CAL to reduce complexity of the created tree - Boyd???)
                        command = "mdsPutCh --field %s:raw --expr %%CAL --timebase %d,%d,%d %d" % (chan_node.getFullPath(), int(start-pre), int(end-pre)+1, int(inc), chan+1)
                        command = command.replace('\\','\\\\')
                        if debug:
                            print "about to execute %s" % command

                        #START Shaun EDIT TO USE MDSPUTCH TO DO LOTS OF CHANNELS (mdsputchbulkcommand decides if it is used)
                        if mdsputchbulkcommand==1:
                            if mdsputchsent==0: #Check to see if command has already been sent
                                fieldstring=str(chan_node.getFullPath()) #building the string
                                fieldstring=fieldstring[0:len(fieldstring)-2]+"%02d" #building the string
                                bulkcommand = "mdsPutCh --field %s:raw --expr %%CAL --timebase %d,%d,%d %s" % (fieldstring, int(start-pre), int(end-pre)+1, int(inc), listofchannels)
                                bulkcommand = bulkcommand.replace('\\','\\\\')
                                print bulkcommand
                                UUT.uut.acq2sh(bulkcommand) #send command
                                mdsputchsent=1 #Remember the command has been sent                        
                        else:
                            UUT.uut.acq2sh(command) #ORIGINAL COMMAND
                        #END SHAUN EDIT
                        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,))
コード例 #42
0
    def restoreInfo(self):
        if FAKECAMERA.fakecamera is None:
            FAKECAMERA.fakecamera = CDLL("libfakecamera.so")
        if FAKECAMERA.cammdsutils is None:
            FAKECAMERA.cammdsutils = CDLL("libcammdsutils.so")
        if FAKECAMERA.camstreamutils is None:
            FAKECAMERA.camstreamutils = CDLL("libcamstreamutils.so")
        if self.getNid() in FAKECAMERA.handles.keys():
            self.handle = FAKECAMERA.handles[self.getNid()]
            if Device.debug: print('RESTORE INFO HANDLE TROVATO')
        else:
            print('RESTORE INFO HANDLE NON TROVATO')

            try:
                name = self.name.data()
            except:
                Data.execute('DevLogErr($1,$2)', self.getNid(),
                             'Missing device name')
                raise mdsExceptions.TclFAILED_ESSENTIAL

            try:
                exp_name = self.exp_name.data()
            except:
                Data.execute('DevLogErr($1,$2)', self.getNid(),
                             'Missing source experiment name')
                raise mdsExceptions.TclFAILED_ESSENTIAL

            try:
                exp_shot = self.exp_shot.data()
            except:
                Data.execute('DevLogErr($1,$2)', self.getNid(),
                             'Missing source shot')
                raise mdsExceptions.TclFAILED_ESSENTIAL

            try:
                exp_node = self.exp_node.data()
            except:
                Data.execute('DevLogErr($1,$2)', self.getNid(),
                             'Missing source frame node')
                raise mdsExceptions.TclFAILED_ESSENTIAL

            try:
                frame_rate = self.frame_rate.data()
            except:
                Data.execute('DevLogErr($1,$2)', self.getNid(),
                             'Missing reading frame rate')
                raise mdsExceptions.TclFAILED_ESSENTIAL

            self.handle = c_void_p(0)
            print('restoreInfo before fakeOpen')
            status = FAKECAMERA.lib.fakeOpen(c_char_p(exp_name),
                                             c_char_p(exp_shot),
                                             c_char_p(exp_node),
                                             c_float(frame_rate),
                                             byref(self.handle))
            if status < 0:
                Data.execute('DevLogErr($1,$2)', self.getNid(),
                             'Cannot open device ' + name)
                raise mdsExceptions.TclFAILED_ESSENTIAL
            if Device.debug: print('restoreInfo ended')
        return
コード例 #43
0
ファイル: dt132.py プロジェクト: dgarnier/MDSplus-forked
    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($,*, $)', a, 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)
            post = int(post)
            mask = UUT.uut.acqcmd('getChannelMask').split('=')[-1]
        
            clock_src=self.check('self.clock_src.record.getOriginalPartName().getString()[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 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 = 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
                        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" % (chan_node.getFullPath(), int(start), int(end), 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 = eval('Signal(raw, "", dim)' % chan_node.getPath())
                        else:
			    raw = Data.compile('data($)', chan_raw_node)
                            chan_node.record = Signal(raw, "", Dimension(Window(start, end, self.trig_src), clock))
        
            UUT.uut.acq2sh('mdsClose %s' % (self.boardip.tree.name,))
コード例 #44
0
def doPlot(self):

    viewbox = [0, 0, 10000, 10000]

    def scale(xmin, ymin, xmax, ymax, xmin_s, ymin_s, xmax_s, ymax_s, x, y):
        px = (x - xmin) * (xmax_s - xmin_s) / (xmax - xmin)
        py = (y - ymin) * (ymax_s - ymin_s) / (ymax - ymin)
        return " %d %d" % (int(round(px)), int(round(py)))

    def gridScaling(min_in, max_in, divisions, span):
        from math import log10, pow, fabs, ceil, floor, modf
        resdivlog = log10(fabs(max_in - min_in))
        if resdivlog < 0:
            res = pow(10, ceil(resdivlog) - 4)
        else:
            res = pow(10, floor(resdivlog) - 4)
        divlog = log10(fabs(max_in - min_in) / divisions)
        fractpart, wholepart = modf(divlog)
        intinc = pow(10, fabs(fractpart))
        if intinc < 1.3333333:
            intinc = 1
        elif intinc < 2.857:
            intinc = 2
        else:
            intinc = 10
        if divlog < 0:
            val_inc = pow(10, -log10(intinc) + wholepart)
        else:
            val_inc = pow(10, log10(intinc) + wholepart)
        grid = ceil(min_in / val_inc) * val_inc
        divs_out = floor((max_in - grid + val_inc) / val_inc)
        if max_in > min_in:
            first_pix = span * ((grid - min_in) / (max_in - min_in))
            pix_inc = span * val_inc / (max_in - min_in)
            first_val = (first_pix * ((max_in - min_in) / span)) + min_in
        else:
            divs_out = 2
            first_pix = 0
            pix_inc = span
            val_inc = 0
        return {
            "divisions": divs_out,
            "first_pixel": first_pix,
            "pixel_increment": pix_inc,
            "first_value": first_val,
            "value_increment": val_inc,
            "resolution": res
        }

    if len(self.path_parts) > 2:
        self.openTree(self.path_parts[1], self.path_parts[2])
    expr = self.args['expr'][-1]
    try:
        sig = Data.execute(expr)
        y = makeData(sig.data()).data()
        x = makeData(sig.dim_of().data()).data()
    except Exception:
        raise Exception("Error evaluating expression: '%s', error: %s" %
                        (expr, sys.get_info()))
    response_headers = list()
    response_headers.append(
        ('Cache-Control', 'no-store, no-cache, must-revalidate'))
    response_headers.append(('Pragma', 'no-cache'))
    response_headers.append(('XDTYPE', x.__class__.__name__))
    response_headers.append(('YDTYPE', y.__class__.__name__))
    response_headers.append(('XLENGTH', str(len(x))))
    response_headers.append(('YLENGTH', str(len(y))))
    response_headers.append(('Content-type', 'text/xml'))
    if self.tree is not None:
        response_headers.append(('TREE', self.tree))
        response_headers.append(('SHOT', self.shot))

    output = """<?xml version="1.0" standalone="no"?>
<!DOCTYPE svg PUBLIC "-//W3C//DTD SVG 1.1//EN" 
"http://www.w3.org/Graphics/SVG/1.1/DTD/svg11.dtd">
<svg viewBox="%d %d %d %d"
     xmlns="http://www.w3.org/2000/svg" version="1.1">
""" % (viewbox[0], viewbox[1], viewbox[2], viewbox[3])
    output += "<title>Plot of %s </title>" % (expr, )
    output += """
  <path fill="none" stroke="black" stroke-width="30" d="M """
    xmin = float(min(x))
    xmax = float(max(x))
    ymin = float(min(y))
    ymax = float(max(y))
    xmin_s = float(viewbox[0])
    ymin_s = float(viewbox[1])
    xmax_s = float(viewbox[2])
    ymax_s = float(viewbox[3])
    for i in range(len(x)):
        output += scale(xmin - (xmax - xmin) * .1, ymin - (ymax - ymin) * .1,
                        xmax + (xmax - xmin) * .1, ymax + (ymax - ymin) * .1,
                        xmin_s, ymin_s, xmax_s, ymax_s, x[i], y[i])
    output += """ " />
"""
    scaling = gridScaling(xmin, xmax, 5, viewbox[2] - viewbox[0])
    for i in range(scaling['divisions']):
        output += """<text text-anchor="middle" x="%d" y="%d" font-size="300" >%g</text>
<path fill="none" stroke="black" stroke-width="5" stroke-dasharray="200,100,50,50,50,100" d="M%d %d %d %d" />
""" % (scaling["first_pixel"] + i * scaling["pixel_increment"],
        viewbox[2] - 200,
        round(scaling['first_value'] + i * scaling["value_increment"],
             scaling["resolution"]),
        scaling["first_pixel"] + i * scaling["pixel_increment"], viewbox[2],
        scaling["first_pixel"] + i * scaling["pixel_increment"], viewbox[0])

    scaling = gridScaling(ymin, ymax, 5, viewbox[3] - viewbox[1])
    for i in range(scaling['divisions']):
        output += """<text text-anchor="left" x="%d" y="%d" font-size="300" >%g</text>
<path fill="none" stroke="black" stroke-width="5" stroke-dasharray="200,100,50,50,50,100" d="M%d %d %d %d" />
""" % (100, scaling["first_pixel"] + i * scaling["pixel_increment"],
        round(scaling['first_value'] + i * scaling["value_increment"],
             scaling["resolution"]), 0,
        scaling["first_pixel"] + i * scaling["pixel_increment"], 10000,
        scaling["first_pixel"] + i * scaling["pixel_increment"])
    output += """</svg>
"""
    status = '200 OK'
    return (status, response_headers, output)
コード例 #45
0
ファイル: NI6259EV.py プロジェクト: zack-vii/mdsplus
        def run(self):

            nid = self.device.getNid()
            chanModes = NI6259EV.ni6259chanModes[nid]
            chanEvents = NI6259EV.ni6259chanEvents[nid]
            chanPreTimes = NI6259EV.ni6259chanPreTimes[nid]
            chanPostTimes = NI6259EV.ni6259chanPostTimes[nid]
            chanFd = []
            chanNid = []
            f1Div = self.device.freq1_div.data()
            f2Div = self.device.freq2_div.data()
            baseFreq = self.device.clock_freq.data()
            baseStart = self.device.clock_start.data()
            coeff_array = c_float * 4
            coeff = coeff_array()

            maxDelay = self.device.history_len.data()
            #NI6259AI.niInterfaceLib.getStopAcqFlag(byref(self.stopAcq));
            numChans = len(self.chanMap)
            isBurst_c = (c_int * numChans)()
            f1Divs_c = (c_int * numChans)()
            f2Divs_c = (c_int * numChans)()
            preTimes_c = (c_double * numChans)()
            postTimes_c = (c_double * numChans)()
            eventNames_c = (c_char_p * numChans)()

            for chan in range(numChans):
                #self.device.debugPrint 'CHANNEL', self.chanMap[chan]+1
                #self.device.debugPrint '/dev/pxi6259.'+str(boardId)+'.ai.'+str(self.hwChanMap[self.chanMap[chan]])
                if chanModes[chan] == 'CONTINUOUS(FREQ1)':
                    isBurst_c[chan] = 0
                    f1Divs_c[chan] = f1Div
                    f2Divs_c[chan] = f1Div
                    eventNames_c[chan] = c_char_p('')
                elif chanModes[chan] == 'CONTINUOUS(FREQ2)':
                    isBurst_c[chan] = 0
                    f1Divs_c[chan] = f2Div
                    f2Divs_c[chan] = f2Div
                    eventNames_c[chan] = c_char_p('')
                elif chanModes[chan] == 'BURST(FREQ1)':
                    isBurst_c[chan] = 1
                    f1Divs_c[chan] = f1Div
                    f2Divs_c[chan] = f1Div
                    eventNames_c[chan] = c_char_p(chanEvents[chan])
                elif chanModes[chan] == 'BURST(FREQ2)':
                    isBurst_c[chan] = 1
                    f1Divs_c[chan] = f2Div
                    f2Divs_c[chan] = f2Div
                    eventNames_c[chan] = c_char_p(chanEvents[chan])
                elif chanModes[chan] == 'DUAL SPEED':
                    isBurst_c[chan] = 0
                    f1Divs_c[chan] = f1Div
                    f2Divs_c[chan] = f2Div
                    eventNames_c[chan] = c_char_p(chanEvents[chan])
                else:
                    Data.execute('DevLogErr($1,$2)', self.getNid(),
                                 'Invalid Mode for channel ' + str(chan + 1))
                    raise DevBAD_PARAMETER

                preTimes_c[chan] = chanPreTimes[chan]
                postTimes_c[chan] = chanPostTimes[chan]

                try:
                    boardId = getattr(self.device, 'board_id').data()
                    print(
                        'APRO', '/dev/pxi6259.' + str(boardId) + '.ai.' +
                        str(self.hwChanMap[self.chanMap[chan]]))
                    currFd = os.open(
                        '/dev/pxi6259.' + str(boardId) + '.ai.' +
                        str(self.hwChanMap[self.chanMap[chan]]),
                        os.O_RDWR | os.O_NONBLOCK)
                    chanFd.append(currFd)
                    print('APERTO')
                except Exception as e:
                    self.device.debugPrint(e)
                    Data.execute(
                        'DevLogErr($1,$2)', self.device.getNid(),
                        'Cannot open Channel ' + str(self.chanMap[chan]))
                    self.error = self.ACQ_ERROR
                    return
                chanNid.append(
                    getattr(self.device, 'channel_%d_raw' %
                            (self.chanMap[chan] + 1)).getNid())

                self.device.debugPrint(
                    'chanFd ' + 'channel_%d_raw' % (self.chanMap[chan] + 1),
                    chanFd[chan])

                gain = getattr(self.device, 'channel_%d_range' %
                               (self.chanMap[chan] + 1)).data()
                gain_code = self.device.gainDict[gain]

                #time.sleep(0.600)
                n_coeff = c_int(0)
                status = NI6259EV.niInterfaceLib.pxi6259_getCalibrationParams(
                    currFd, gain_code, coeff, byref(n_coeff))

                if (status < 0):
                    errno = NI6259EV.niInterfaceLib.getErrno()
                    msg = 'Error (%d) %s' % (errno, os.strerror(errno))
                    self.device.debugPrint(msg)
                    Data.execute(
                        'DevLogErr($1,$2)', self.device.getNid(),
                        'Cannot read calibration values for Channel %d. Default value assumed ( offset= 0.0, gain = range/65536'
                        % (self.chanMap[chan]))

                gainValue = self.device.gainValueDict[gain] * 2.
                coeff[0] = coeff[2] = coeff[3] = 0
                coeff[1] = c_float(gainValue / 65536.)
                print('SCRIVO CALIBRAZIONE', coeff)
                getattr(self.device,
                        'channel_%d_calib' % (self.chanMap[chan] + 1)).putData(
                            Float32Array(coeff))
                print('SCRITTO')

            bufSize = self.device.buf_size.data()
            segmentSize = self.device.seg_length.data()

            if (bufSize > segmentSize):
                segmentSize = bufSize
            else:
                c = segmentSize / bufSize
                if (segmentSize % bufSize > 0):
                    c = c + 1
                segmentSize = c * bufSize

            status = NI6259EV.niLib.pxi6259_start_ai(c_int(self.fd))

            if (status != 0):
                Data.execute('DevLogErr($1,$2)', self.device.getNid(),
                             'Cannot Start Acquisition ')
                self.error = self.ACQ_ERROR
                return

            saveList = c_void_p(0)
            NI6259EV.niInterfaceLib.startSaveEV(byref(saveList))
            #count = 0

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

            while not self.stopReq:
                status = NI6259EV.niInterfaceLib.pxi6259EV_readAndSaveAllChannels(
                    c_int(numChans), chanFd_c, isBurst_c, f1Divs_c, f2Divs_c,
                    c_double(maxDelay), c_double(baseFreq), preTimes_c,
                    postTimes_c, c_double(baseStart), c_int(bufSize),
                    c_int(segmentSize), eventNames_c, chanNid_c, self.treePtr,
                    saveList, self.stopAcq)

                if status < 1:
                    return 0

            status = NI6259EV.niLib.pxi6259_stop_ai(c_int(self.fd))

            for chan in range(len(self.chanMap)):
                os.close(chanFd[chan])
            self.device.debugPrint('ASYNCH WORKER TERMINATED')
            #            NI6259EV.niInterfaceLib.stopSaveEV(saveList)
            #            NI6259EV.niInterfaceLib.freeStopAcqFlag(self.stopAcq)
            self.device.closeInfo()

            return