コード例 #1
0
    def stop_store(self):

      self.debugPrint('================= PXI 6259 stop store ================')
      error = False
      """
      if self.restoreInfo() != self.DEV_IS_OPEN :
          Data.execute('DevLogErr($1,$2)', self.getNid(), 'Module not Initialized')
          raise mdsExceptions.TclFAILED_ESSENTIAL
      """

      try:
          self.restoreWorker()
      except:
          Data.execute('DevLogErr($1,$2)', self.getNid(), 'Acquisition thread not created')
          return

      if self.worker.isAlive():
          self.debugPrint("PXI 6259 stop_worker")
          self.worker.stop()
          self.worker.join()
          error = self.worker.hasError()
      else:
          error = self.worker.hasError()
          if not error: 
              Data.execute('DevLogErr($1,$2)', self.getNid(), 'Acquisition thread stopped')


      if error :
          raise mdsExceptions.TclFAILED_ESSENTIAL

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

      return 1
コード例 #2
0
ファイル: BCM2835_DAC.py プロジェクト: santorofer/mdsplus
    def configChannel(self, ch, reset, wavePoint, chMax, chMin, chType, aoX,
                      aoY, nPeriod, gain, offset):

        isOn = getattr(self, 'ao_%d' % (ch + 1)).isOn()

        if not reset and isOn:
            print("configChannel ", ch, reset, wavePoint, chMax, chMin, chType,
                  aoX, aoY, nPeriod)
            scaledWriteArray = self.buildWave(wavePoint, chMax, chMin, chType,
                                              aoX, aoY, nPeriod)
        else:
            zero_arr = np.zeros(wavePoint)
            scaledWriteArray = (c_float * len(zero_arr))(*zero_arr)

        if scaledWriteArray == None:
            Data.execute(
                'DevLogErr($1,$2)', self.getNid(),
                "Invalid waveform type -%s- for channel %d " % (chType, ch))
            zero_arr = np.zeros(wavePoint)
            scaledWriteArray = (c_float * len(zero_arr))(*zero_arr)

        retval = BCM2835_DAC.bcm2835InterfaceLib.bcm2835_write_ao(
            ch, scaledWriteArray, c_float(gain), c_float(offset),
            c_uint(wavePoint))
        if retval != wavePoint:
            errno = BCM2835_DAC.niInterfaceLib.getErrno()
            Data.execute(
                'DevLogErr($1,$2)', self.getNid(),
                "Failed while writing! Written samples %d : %s (%d)" %
                (retval, os.strerror(errno), errno))
            raise mdsExceptions.DevIO_STUCK

        del scaledWriteArray
コード例 #3
0
ファイル: BCM2835_DAC.py プロジェクト: santorofer/mdsplus
    def configChannels(self, reset):

        #wavePoint = self.wave_point.data()

        try:
            gain = self.gain.data()
        except Exception as ex:
            Data.execute('DevLogErr($1,$2)', self.getNid(),
                         'Invalid gain value : %s' % (str(ex)))
            raise mdsExceptions.DevBAD_GAIN

        periodPoint = []
        for ch in range(4):
            # if getattr(self, 'ao_%d'%(ch+1)).isOn():
            fr = getattr(self, 'ao_%d_freq' % (ch + 1)).data()
            periodPoint.append(self.DAC_MAX_FREQ / fr)
        # else :
        #    periodPoint.append( 0 )

        wavePoint = (np.asarray(periodPoint) + 0.5).astype(int)
        print('Wave point ', wavePoint)

        for ch in range(4):
            self.__checkChanneParam__(ch, gain)
            self.configChannel(ch, reset, wavePoint[ch], self.chMax,
                               self.chMin, self.chType, self.chAOX, self.chAOY,
                               1, self.chGain, self.chOffset)
コード例 #4
0
    def startAcquisition(self):
        if self.restoreInfo() == 0:
            raise mdsExceptions.TclFAILED_ESSENTIAL

        print("start store")
        self.worker = self.AsynchStore()
        self.worker.daemon = True
        self.worker.stopReq = False
        print("start store2")
        width = c_int(0)
        height = c_int(0)
        payloadSize = c_int(0)
        status = FLIRSC65X.flirLib.startAcquisition(self.handle, byref(width),
                                                    byref(height),
                                                    byref(payloadSize))
        if status < 0:
            FLIRSC65X.flirLib.getLastError(self.handle, self.error)
            Data.execute('DevLogErr($1,$2)', self.nid,
                         'Cannot Start Camera Acquisition : ' + self.error.raw)
            raise mdsExceptions.TclFAILED_ESSENTIAL
        print("start store3")
        self.worker.configure(self)
        self.saveWorker()
        self.worker.start()
        return
コード例 #5
0
 def restoreInfo(self):
     if NI6368EV.niLib is None:
         NI6368EV.niLib = CDLL('libnixseries.so')
     if NI6368EV.niInterfaceLib is None:
         NI6368EV.niInterfaceLib = CDLL('libNiInterface.so')
     try:
         self.ai_fd = NI6368EV.ni6368EvFds[self.getNid()]
         return self.DEV_IS_OPEN  # if present, already opened
     except:
         try:
             boardId = self.board_id.data()
             #The boardId number refers to device number (/dev/pxie6368.N)
             #if it is less than MAX_NUM_BOARDS otherwise, it refers to the board
             #serial number and the getPxie6368BoarId function translate serial
             #number to device number of the board.
             if boardId > self.MAX_NUM_BOARDS:
                 boardId = Data.execute('getPxie6368BoarId(' +
                                        str(boardId) + ')')
         except Exception as ex:
             Data.execute('DevLogErr($1,$2)', self.getNid(),
                          'Missing board ID ' + str(ex))
             raise mdsExceptions.TclFAILED_ESSENTIAL
         try:
             fileName = '/dev/pxie-6368.' + str(boardId) + '.ai'
             self.ai_fd = os.open(fileName,
                                  os.O_RDWR)  # if not present, try to open
         except:
             Data.execute('DevLogErr($1,$2)', self.getNid(),
                          'Cannot open device' + fileName)
             raise mdsExceptions.TclFAILED_ESSENTIAL
     return self.DEV_OPEN  # return of RestoreInfo
コード例 #6
0
 def getStartPulse(self, termName):
     termNameNid = termName + str(self.nid)
     try:
         print(NI6683.ni6683TermStarts)
         start = NI6683.ni6683TermStarts[termNameNid]
     except:
         emsg = 'Error reading start time in ' + termName
         Data.execute('DevLogErr($1,$2)', self.getNid(), emsg)
         raise DevBAD_PARAMETER
     if np.isscalar(start):
         start = [start]
     try:
         pulseLen = NI6683.ni6683PulseLengths[termNameNid]
     except:
         emsg = 'Error reading pulse len in ' + termName
         Data.execute('DevLogErr($1,$2)', self.getNid(), emsg)
         raise DevBAD_PARAMETER
     if np.isscalar(pulseLen):
         pulseLen = [pulseLen]
     minLen = len(start)
     if minLen > len(pulseLen):
         minLen = len(pulseLen)
     startNs = []
     endNs = []
     for i in range(0, minLen):
         print('DEBUG -> START PULSE in GetStartPulse: ', start[i])
         currStartNs = self.getAbsTime(start[i])
         startNs.append(currStartNs)
         endNs.append(currStartNs + int(pulseLen[i] * 1000000000))
     return startNs, endNs
コード例 #7
0
        def run(self):

            print("Asychronous acquisition thread")

            status = FLIRSC65X.flirLib.startFramesAcquisition(
                self.device.handle)
            if status < 0:
                FLIRSC65X.flirLib.getLastError(self.device.handle,
                                               self.device.error)
                Data.execute(
                    'DevLogErr($1,$2)', self.device.nid,
                    'Cannot start frames acquisition : ' +
                    self.device.error.raw)

            print("Fine acquisition thread")

            status = FLIRSC65X.flirLib.flirClose(
                self.device.handle)  #close device and remove from info
            if status < 0:
                FLIRSC65X.flirLib.getLastError(self.device.handle,
                                               self.device.error)
                Data.execute('DevLogErr($1,$2)', self.device.nid,
                             'Cannot close camera : ' + self.device.error.raw)

            self.device.removeInfo()
コード例 #8
0
    def wait_store(self):

        self.debugPrint(
            '================= BCM2835 wait store ================')

        try:
            self.restoreWorker()
        except:
            Data.execute('DevLogErr($1,$2)', self.getNid(),
                         'Acquisition thread not created')
            return

        if self.worker.isAlive():
            self.worker.stop()
            self.worker.join()
            error = self.worker.hasError()
        else:
            error = self.worker.hasError()
            if not error:
                Data.execute('DevLogErr($1,$2)', self.getNid(),
                             'Acquisition thread already stopped')

        if error:
            raise mdsExceptions.TclFAILED_ESSENTIAL

        self.debugPrint(
            "======================================================")
        return 1
コード例 #9
0
    def getStartEnd(self, termName):

        termNameNid = termName + str(self.nid)
        try:
            start = NI6683.ni6683TermStarts[termNameNid]
            if start < NI6683.ni6683RelTime:
                emsg = 'Start time less than relative time in ' + termName
                Data.execute('DevLogErr($1,$2)', self.getNid(), emsg)
                raise DevBAD_PARAMETER
                # start = 0 # NISYNC_TIME_IMMEDIATE_NANOS in the API
            else:
                start = self.getAbsTime(start)
        except:
            print("Exception in defining Start")
            start = self.getAbsTime(start)
        try:
            end = NI6683.ni6683TermEnds[termNameNid]
            if end <= 0:
                end = sys.maxint
            else:
                end = self.getAbsTime(end)
        except:
            end = sys.maxint
        if start >= end:
            emsg = 'End time less than start time in ' + termName
            Data.execute('DevLogErr($1,$2)', self.getNid(), emsg)
            raise DevBAD_PARAMETER
        return start, end
コード例 #10
0
 def restoreInfo(self):
     if CAENDT5720.caenLib is None:
         CAENDT5720.caenLib = CDLL("libCAENVME.so")
     if self.getNid() in CAENDT5720.workers.keys():
         self.worker, self.handle, self.cvself.readCv = CAENDT5720.workers[
             self.nid]
     else:
         try:
             boardId = self.board_id.data()
         except:
             Data.execute('DevLogErr($1,$2)', self.getNid(),
                          'Invalid Board ID specification')
             raise mdsExceptions.TclFAILED_ESSENTIAL
         self.handle = c_long(0)
         print('HANDLE NON TROVATO ADESSO INIZIA:IZZO DRIVER')
         status = CAENDT5720.caenLib.CAENVME_Init(c_int(self.cvV2718),
                                                  c_int(0), c_int(boardId),
                                                  byref(self.handle))
         if status != 0:
             print('Error initializing CAENVME')
             raise mdsExceptions.TclFAILED_ESSENTIAL
         self.cv = Condition()
         self.readCv = Condition()
         IRQw = self.IRQWait()
         IRQw.daemon = True
         IRQw.configure(self.handle, self.cv, self.readCv)
         IRQw.start()
     return
コード例 #11
0
ファイル: NI_WAVE_GEN.py プロジェクト: santorofer/mdsplus
    def configChannels(self, reset):

        boardId = self.board_id.data()
        boardType = self.board_type.data()
        wavePoint = self.wave_point.data()

        try:
            gain = self.gain.data()
        except Exception as ex:
            Data.execute('DevLogErr($1,$2)', self.getNid(),
                         'Invalid gain value : %s' % (str(ex)))
            raise mdsExceptions.DevBAD_GAIN

        freq = []
        minFreq = 1e6
        for ch in range(4):
            fr = getattr(self, 'ao_%d_freq' % (ch + 1)).data()
            freq.append(fr)
            if getattr(self, 'ao_%d' % (ch + 1)).isOn():
                if fr < minFreq:
                    minFreq = fr

        numPeriod = (np.asarray(freq) / minFreq + 0.5).astype(int)
        print('Num Period ', freq, numPeriod, minFreq)

        for ch in range(4):
            self.__checkChanneParam__(ch, gain)

            self.configChannel(boardType, boardId, ch, reset, wavePoint,
                               self.chMax, self.chMin, self.chType, self.chAOX,
                               self.chAOY, numPeriod[ch])
コード例 #12
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),)
コード例 #13
0
    def reset(self):
        print ('================= RESET EPICS WAVE SETUP ===============')
        from CaChannel import CaChannel

        wavex = CaChannel()
        wavey = CaChannel()

        for chan in range(1, 3):

            if getattr(self, 'wave_%d' % (chan)).isOn():

                try:
                    pv_wave_x = getattr(self, 'wave_%d_pv_x' % (chan)).data()
                    wavex.searchw(pv_wave_x)
                except:
                    msg = 'Error on PV waveform %d x variable' % (chan)
                    Data.execute('DevLogErr($1,$2)', self.getNid(), msg)
                    raise mdsExceptions.TclFAILED_ESSENTIAL

                try:
                    pv_wave_y = getattr(self, 'wave_%d_pv_y' % (chan)).data()
                    wavey.searchw(pv_wave_y)
                except:
                    msg = 'Error reading y waveform %d values' % (chan)
                    Data.execute('DevLogErr($1,$2)', self.getNid(), msg)
                    raise mdsExceptions.TclFAILED_ESSENTIAL

                wavex.putw([0, 0])
                wavey.putw([0, 0])

        del wavex
        del wavey
        print ('========================================================')

        return 1
コード例 #14
0
 def getStartPulse(self, termName):
     try:
         start = getattr(self, termName.lower() + '_start').data()
     except:
         emsg = 'Error reading start time in ' + termName
         Data.execute('DevLogErr($1,$2)', self.getNid(), emsg)
         raise DevBAD_PARAMETER
     if np.isscalar(start):
         start = [start]
     try:
         pulseLen = getattr(self, termName.lower() + '_pulse_len').data()
     except:
         emsg = 'Error reading pulse len in ' + termName
         Data.execute('DevLogErr($1,$2)', self.getNid(), emsg)
         raise DevBAD_PARAMETER
     if np.isscalar(pulseLen):
         pulseLen = [pulseLen]
     minLen = len(start)
     if minLen > len(pulseLen):
         minLen = len(pulseLen)
     startNs = []
     endNs = []
     for i in range(0, minLen):
         currStartNs = self.getAbsTime(start[i])
         startNs.append(currStartNs)
         endNs.append(currStartNs + int(pulseLen[i] * 1000000000))
     return startNs, endNs
コード例 #15
0
    def restoreInfo(self):
        if ZELOS2150GV.kappaLib is None:
            ZELOS2150GV.kappaLib = CDLL("libkappazelos.so")
        if ZELOS2150GV.mdsLib is None:
            ZELOS2150GV.mdsLib = CDLL("libcammdsutils.so")
        if ZELOS2150GV.streamLib is None:
            ZELOS2150GV.streamLib = CDLL("libcamstreamutils.so")
        if self.nid in ZELOS2150GV.handels.keys():
            self.handel = ZELOS2150GV.handels[self.nid]
        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

            self.handle = c_void_p(0)
            status = ZELOS2150GV.kappaLib.kappaOpen(c_char_p(name),
                                                    byref(self.handle))
            if status < 0:
                Data.execute('DevLogErr($1,$2)', self.getNid(),
                             'Cannot open device ' + name)
                raise mdsExceptions.TclFAILED_ESSENTIAL
        return
コード例 #16
0
 def store(self):
     """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 as e:
                 print("Error inputting from DI%d\n\t%s" % (i, str(e),))
     return 1
コード例 #17
0
 def restoreWorker(self):
     if self.nid in BASLERACA.workers.keys():
         self.worker = BASLERACA.workers[self.nid]
     else:
         Data.execute("DevLogErr($1,$2)", self.nid,
                      "Cannot restore worker!!")
         raise mdsExceptions.TclFAILED_ESSENTIAL
コード例 #18
0
    def restoreInfo(self):
        if NI6259EV.niLib is None:
            NI6259EV.niLib = CDLL("libpxi6259.so")
        if NI6259EV.niInterfaceLib is None:
            NI6259EV.niInterfaceLib = CDLL("libNiInterface.so")

        if self.nid in NI6259EV.ni6259Fds.keys():
            self.fd = NI6259EV.ni6259Fds[self.nid]
            return self.DEV_IS_OPEN
        else:
            try:
                boardId = self.board_id.data()
            except:
                Data.execute('DevLogErr($1,$2)', self.getNid(),
                             'Missing Board Id')
                raise mdsExceptions.TclFAILED_ESSENTIAL
            try:
                fileName = '/dev/pxi6259.' + str(boardId) + '.ai'
                self.fd = os.open(fileName, os.O_RDWR)
            except:
                Data.execute('DevLogErr($1,$2)', self.getNid(),
                             'Cannot open device ' + fileName)
                raise mdsExceptions.TclFAILED_ESSENTIAL
        """
        try:
            if( niLib.pxi6259_reset_ai(self.fd) ):
                Data.execute('DevLogErr($1,$2)', self.getNid(), 'Cannot reset device '+ fileName)
                raise mdsExceptions.TclFAILED_ESSENTIAL
        except:
            Data.execute('DevLogErr($1,$2)', self.getNid(), 'Cannot reset device '+ fileName)
            raise mdsExceptions.TclFAILED_ESSENTIAL
        """
        return self.DEV_OPEN
コード例 #19
0
 def init(self):
     """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 as e:
                 print("Error outputing to DO%d\n\t%s" % (i, str(e),))
     return 1
コード例 #20
0
    def startAcquisition(self):
        if self.checkWorker():  # FM 20191114
            self.debugPrint(
                'Acquisition already in progress. Action not performed.')
            return 1

        if self.checkInfo():  # FM 20191114
            self.restoreInfo()
        else:
            Data.execute('DevLogErr($1,$2)', self.nid,
                         'Init action must be performed before acquisition : '+self.error.raw)
            raise mdsExceptions.TclFAILED_ESSENTIAL

        self.debugPrint("Starting acquisition")
        self.worker = self.AsynchStore()
        self.worker.daemon = True
        self.worker.stopReq = False
        width = c_int(0)
        height = c_int(0)
        payloadSize = c_int(0)
        status = PTGREY.ptgreyLib.startAcquisition(
            self.handle, byref(width), byref(height), byref(payloadSize))
        if status < 0:
            PTGREY.ptgreyLib.getLastError(self.handle, self.error)
            Data.execute('DevLogErr($1,$2)', self.nid,
                         'Cannot Start Camera Acquisition : '+self.error.raw)
            raise mdsExceptions.TclFAILED_ESSENTIAL
        self.debugPrint("Acquisition started")
        self.worker.configure(self.copy())
        self.saveWorker()
        self.worker.start()
        return 1
コード例 #21
0
def _devHelpDevtype(devtype, full):
  from pydoc import TextDoc
  global _device_list
  if _device_list is None:
    alldevices=Data.execute('MDSDEVICES()')
    _device_list=[item[0].strip() for item in alldevices]
  devnames=[]
  if ('*' in devtype) or ('?' in devtype):
    for device in _device_list:
      if (Data.execute('MdsShr->StrMatchWild(descr($),descr($))',(device.upper(),devtype.upper())) & 1) == 1:
        devnames.append(DevHelp(device,-1))
    return '\n'.join(devnames)
  else:
    try: 
	dmod = Device.importPyDeviceModule(devtype)
        cls = eval('dmod.%s' % dmod.__name__.upper())
        if full == 1:
          return TextDoc().docclass(cls)
        elif full == -1:
          return "%s: python device" % devtype
        else:
          return cls.__doc__
    except:
      for device in _device_list:
        if device.upper() == devtype.upper():
          return "%s: tdi, java or shared library device" % device
      return "Error obtaining help on device " + devtype
コード例 #22
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),)
コード例 #23
0
    def stop_store(self):

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

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

        self.restoreWorker()
        if self.worker.isAlive():
            print("PXI CAENDT5720 stop_worker")
            self.worker.stop()
        del self.worker

        return 1
コード例 #24
0
    def stop_store(self):

        error = False
        self.debugPrint("=============== PXI 6368 stop_store ===========")

        try:
            self.restoreWorker()
        except:
            Data.execute('DevLogErr($1,$2)', self.getNid(),
                         'Acquisition thread not started')
            return

        if self.worker.isAlive():
            #          self.debugPrint ("PXI 6368 stop_worker")
            #          self.debugPrint("PXI 6368 join to worker thread")
            self.worker.stop()
            error = self.worker.hasError()
        else:
            error = self.worker.hasError()
            if not error:
                Data.execute('DevLogErr($1,$2)', self.getNid(),
                             'Acquisition thread stopped')

        if error:
            self.worker.error = self.worker.ACQ_NOERROR
            raise mdsExceptions.TclFAILED_ESSENTIAL

        self.debugPrint("===============================================")
コード例 #25
0
    def restoreInfo(self):
        if NI6368AI.niLib is None:
            NI6368AI.niLib = CDLL("libnixseries.so")
        if NI6368AI.niInterfaceLib is None:
            NI6368AI.niInterfaceLib = CDLL("libNiInterface.so")

        try:
            self.ai_fd = NI6368AI.ni6368AiFds[self.getNid()]
            return self.DEV_IS_OPEN
            #self.debugPrint('RESTORE INFO HANDLE FOUND')
        except:
            #self.debugPrint('RESTORE INFO HANDLE NOT FOUND')
            try:
                boardId = self.board_id.data()
            except:
                Data.execute('DevLogErr($1,$2)', self.getNid(),
                             'Missing Board Id')
                raise mdsExceptions.TclFAILED_ESSENTIAL
            try:
                fileName = '/dev/pxie-6368.' + str(boardId) + '.ai'
                self.ai_fd = os.open(fileName, os.O_RDWR)
                #self.debugPrint('Open fileName : ', fileName)
            except:
                Data.execute('DevLogErr($1,$2)', self.getNid(),
                             'Cannot open device ' + fileName)
                raise mdsExceptions.TclFAILED_ESSENTIAL
        return self.DEV_OPEN
コード例 #26
0
 def generateSegFault(self):
     try:
         Data.execute('MdsShr->LibFindImageSymbol(val(0))')
     except Exception as exc:
         expected = 'exception: access violation reading 0x0000000000000000'
         self.assertEqual(exc.__class__, WindowsError)
         self.assertEqual(exc.message, expected[0:len(exc.message)])
コード例 #27
0
        def run(self):

            self.device.debugPrint("Asychronous acquisition thread")

            status = BASLERACA.baslerLib.startFramesAcquisition(
                self.device.handle)
            if status < 0:
                BASLERACA.baslerLib.getLastError(self.device.handle,
                                                 self.device.error)
                Data.execute(
                    'DevLogErr($1,$2)', self.device.nid,
                    'Cannot start frames acquisition : ' +
                    self.device.error.raw)

            self.device.debugPrint("End acquisition thread")

            status = BASLERACA.baslerLib.baslerClose(
                self.device.handle)  #close device and remove from info
            if status < 0:
                BASLERACA.baslerLib.getLastError(self.device.handle,
                                                 self.device.error)
                Data.execute('DevLogErr($1,$2)', self.device.nid,
                             'Cannot close camera : ' + self.device.error.raw)

            self.device.removeInfo()
コード例 #28
0
    def swTrigger(self):
        if self.restoreInfo() == 0:
            raise mdsExceptions.TclFAILED_ESSENTIAL

#Module in acquisition check
        try:
            self.restoreWorker()
        except:
            self.stopAcquisition()
            Data.execute(
                'DevLogErr($1,$2)', self.nid,
                'Camera cannot be triggered, it is not in acquisition.')
            raise mdsExceptions.TclFAILED_ESSENTIAL

        self.debugPrint('SOFTWARE TRIGGER')

        status = BASLERACA.baslerLib.softwareTrigger(self.handle)
        if status < 0:
            BASLERACA.baslerLib.getLastError(self.handle, self.error)
            Data.execute('DevLogErr($1,$2)', self.nid,
                         'Cannot Execute Software Trigger : ' + self.error.raw)
            raise mdsExceptions.TclFAILED_ESSENTIAL

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

        
        if self.restoreInfo() == self.DEV_NOT_OPEN :
            Data.execute('DevLogErr($1,$2)', self.getNid(), 'cRIO MPAG device not initialized')
            raise mdsExceptions.TclFAILED_ESSENTIAL
 

        treePtr = c_void_p(0)
        CRIO_MPAG.niInterfaceLib.openTree(c_char_p(self.getTree().name), c_int(self.getTree().shot), byref(treePtr))
 
        self.worker = self.AsynchStore()        
        self.worker.daemon = True 
        self.worker.stopReq = False


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

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

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

 
        return 1
コード例 #30
0
ファイル: CRIO_FAU.py プロジェクト: KambaVVV/mdsplus
    def trigger(self):
        try:
            self.restoreInfo()
        except:
            Data.execute('DevLogErr($1,$2)', self.getNid(),
                         'FAU device not initialized')
            raise mdsExceptions.TclFAILED_ESSENTIAL

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

        sleep(1)

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

        return 1
コード例 #31
0
    def restoreInfo(self):
      global caenHandles
      global caenCvs
      global caenWorkers
      global nids
      global caenLib
      global caenInterfaceLib
      from ctypes import CDLL, c_int, c_short, c_long, byref, Structure
      try:
        caenLib
      except:
        caenLib = CDLL("libCAENVME.so")

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

      try:
        caenInterfaceLib
      except:
          print 'Error loading library libCaenInterface.so' 
          return 0
        
      try:
        idx = caenNids.index(self.getNid())
        self.handle = caenHandles[idx]
        self.cv = caenCvs[idx]
        self.readCv = caenReadCvs[idx]
        self.worker = caenWorkers[idx]
        return self.HANDLE_RESTORE
      except:
        try:
          boardId = self.board_id.data()
        except:
          Data.execute('DevLogErr($1,$2)', self.getNid(), 'Invalid Board ID specification')
          return 0
        self.handle = c_long(0)
        print 'HANDLE NON TROVATO ADESSO INIZIALIZZO DRIVER'
        status = caenLib.CAENVME_Init(c_int(self.cvV2718), c_int(0), c_int(boardId), byref(self.handle))
        if status != 0:
          print 'Error initializing CAENVME' 
          return 0
        
        self.cv     = Condition()
        self.readCv = Condition()
        print "recsv", self.readCv 
        IRQw = self.IRQWait()
        IRQw.daemon = True
        IRQw.configure(self.handle, self.cv, self.readCv)
        IRQw.start()
        
      return self.HANDLE_OPEN
コード例 #32
0
ファイル: FLIRSC65X.py プロジェクト: seanalsop/mdsplus
 def restoreWorker(self):
     if self.nid in FLIRSC65X.workers.keys():
         self.worker = FLIRSC65X.workers[self.nid]
         return 1
     else:
         Data.execute('DevLogErr($1,$2)', self.nid,
                      'Cannot restore worker!!')
         raise mdsExceptions.TclFAILED_ESSENTIAL
コード例 #33
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))
コード例 #34
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))
コード例 #35
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))
コード例 #36
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)
コード例 #37
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))
コード例 #38
0
ファイル: doPlot.py プロジェクト: MDSplus/Python-TDISHR
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.exc_info()[1]))
    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)
コード例 #39
0
 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,e:
     response_headers.append(('ERROR'+sig_idx_s,'Error opening tree %s, shot %s, error: %s' % (self.args['tree'][-1],shot,e)))
     continue
 if 'default_node' in self.args:
     try:
         t.setDefault(t.getNode(self.args['default_node'][-1]))
     except Exception,e:
         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,e)))
         continue
 try:
     sig=Data.execute(expr)
     y=makeData(sig.data())
 except Exception,e:
     response_headers.append(('ERROR' + sig_idx_s,'Error evaluating expression: "%s", error: %s' % (expr,e)))
     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,e:
         response_headers.append(('ERROR'+sig_idx_s,'Error evaluating expression: "%s", error: %s' % (expr,e)))
         continue
 else:
     try:
         x=makeData(sig.dim_of().data())
コード例 #40
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)
コード例 #41
0
	def store(self, arg):
		from MDSplus import Tree, TreeNode, Int16Array, Float64Array, Int32, Int64, Float32, Float64, Signal, Data, Dimension, Window, Range
		from ctypes import CDLL, c_int, c_short, c_long, byref, Structure, c_char_p
		print '************ START STORE ************'
	# Get IP Address
		try:
			ipAddr = self.ip_addr.data()
		except:
			Data.execute('DevLogErr($1,$2)', self.nid, 'Invalid Remote IP Address')
			return 0
	# Get Base Address   
		try:
			baseAddr = self.base_addr.data()
		except: 
			Data.execute('DevLogErr($1,$2)', self.nid, 'Invalid Base Address specification')
			return 0
	# Get Scan Count
		try:
			scanCount = self.scan_count.data()
		except:
			Data.execute('DevLogErr($1,$2)', self.nid, 'Invalid Scan Count')
			return 0	  
		print 'Scan Count=',scanCount
	# Get LNE Mode
		lneModeDict = {'VME':0, 'CONTROL SIGNAL':1, 'INTERNAL 10MHZ':2, 'CHANNEL N':3, 'PRESET':4}
		try:
			lneMode = lneModeDict[self.lne_mode.data()]
		except:
			Data.execute('DevLogErr($1,$2)', self.nid, 'Invalid LNE Mode')
			return 0
		print 'LNE Mode=',lneMode
	# Get LNE Source
		try:
			lneSource = self.lne_source.data()
		except:
			Data.execute('DevLogErr($1,$2)', self.nid, 'Invalid LNE Source')
			return 0	  
		print 'LNE Source=',lneSource
	# Get Channels Setup
		channelMask = 0
		for a in range(0, 32):
			if a < 10:
				if getattr(self, 'channel_0%d'%(a)).isOn():
					print 'Channel_0' + str(a) + ' IS ON'
					channelMask = channelMask | (1 << a)
			else:
				if getattr(self, 'channel_%d'%(a)).isOn():
					print 'Channel_' + str(a) + ' IS ON'
					channelMask = channelMask | (1 << a)
		del a
		print 'Channel Mask= ', channelMask
	# Connect to SIS3820 via MDS IP
		status = Data.execute('MdsConnect("'+ ipAddr +'")')
		if status == 0:
			Data.execute('MdsDisconnect()')
			Data.execute('DevLogErr($1,$2)', self.nid, 'Cannot Connect to VME. See VME console for details')
			return 0
	# Wait End Acquisition
		status = Data.execute('MdsValue("SIS3820->sis3820_waitEndAcquisition(val($1), val($2))", $1, $2)', baseAddr, scanCount)
		if status <> 0:
			Data.execute('MdsDisconnect()')
			Data.execute('DevLogErr($1,$2)', self.nid, 'Cannot execute HW Acquisition. See VME console for details')
			return 0
	# Pre Store Fase
		status = Data.execute('MdsValue("SIS3820->sis3820_preStore(val($1), val($2))", $1, $2)', baseAddr, channelMask)
		if status <> 0:
			Data.execute('MdsDisconnect()')
			Data.execute('DevLogErr($1,$2)', self.nid, 'Cannot execute HW Acquisition. See VME console for details')
			return 0
		
		DataArray = c_int * scanCount		
		rawChan = []
		rawChan = DataArray()		

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

		Data.execute('MdsDisconnect()')	
		del chan
		print '************ END STORE ************'
		return 1
########################################### END STORE #######################################	  
コード例 #42
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
コード例 #43
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)
コード例 #44
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])))
コード例 #45
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