Esempio n. 1
0
 def importDevices(name):
     bname = version.tobytes(name)
     try:
         module = __import__(name)
         ans = [[version.tobytes(k),bname] for k,v in module.__dict__.items() if isinstance(v,int.__class__) and issubclass(v,Device)]
     except (ImportError, ImportWarning): ans = []
     tdidev = tdi("if_error(%s(),*)"%name)
     if tdidev is None: return ans
     tdidev = [[k.rstrip(), v.rstrip()] for k,v in tdidev.value.reshape((int(tdidev.value.size/2),2)).tolist()]
     return tdidev+ans
Esempio n. 2
0
def RFXDEVICES():
    from MDSplus import version
    return numpy.array([
        [version.tobytes(file[0:len(file)-9]), b'RfxDevices']
        for file in os.listdir(rfxdir)
        if file.lower().endswith('__add.fun')
    ])
Esempio n. 3
0
def MDSDEVICES():
  with lock:
   if cache[0] is None:
    from MDSplus import Device,tdi,version,getenv
    from numpy import array
    def importDevices(name):
        bname = version.tobytes(name)
        try:
            module = __import__(name)
            ans = [[version.tobytes(k),bname] for k,v in module.__dict__.items() if isinstance(v,int.__class__) and issubclass(v,Device)]
        except (ImportError, ImportWarning): ans = []
        tdidev = tdi("if_error(%s(),*)"%name)
        if tdidev is None: return ans
        tdidev = [[k.rstrip(), v.rstrip()] for k,v in tdidev.value.reshape((int(tdidev.value.size/2),2)).tolist()]
        return tdidev+ans
    ans = [[version.tobytes(d),b'pydevice'] for d in Device.findPyDevices()]
    mdsdevs=getenv('MDS_DEVICES')
    if mdsdevs is not None:
      modules=mdsdevs.split(':')
    else:
      modules=["KbsiDevices","MitDevices","RfxDevices","W7xDevices"]
    for module in modules:
        ans += importDevices(module)
    ans = array(list(dict(ans).items()))
    ans.view('%s,%s'%(ans.dtype,ans.dtype)).sort(order=['f0'], axis=0)
    cache[0] = ans
   return cache[0]
Esempio n. 4
0
class FLIRSC65X(Device):
    """FLIR655 NEW Camera"""
    parts = [  #offset nid
        {
            'path': ':IP_NAME',
            'type': 'text'
        },  #1
        {
            'path': ':COMMENT',
            'type': 'text'
        },
        {
            'path': '.OBJECT',
            'type': 'structure'
        },  #3
        {
            'path': '.OBJECT:EMISSIVITY',
            'type': 'numeric',
            'value': 920E-3
        },
        {
            'path': '.OBJECT:DISTANCE',
            'type': 'numeric',
            'value': 2
        },
        {
            'path': '.OBJECT:REFL_TEMP',
            'type': 'numeric',
            'value': 20
        },
        {
            'path': '.OBJECT:OPTIC_TEMP',
            'type': 'numeric',
            'value': 20
        },
        {
            'path': '.OBJECT:OPTIC_TRANS',
            'type': 'numeric',
            'value': 1
        },
        {
            'path': '.OBJECT:ATM_TEMP',
            'type': 'numeric',
            'value': 20
        },
        {
            'path': '.OBJECT:ATM_HUM',
            'type': 'numeric',
            'value': 0.50
        },
        {
            'path': '.OBJECT:ATM_TRANS',
            'type': 'numeric',
            'value': 99E-2
        },
        {
            'path': '.FRAME',
            'type': 'structure'
        },  #12
        {
            'path': '.FRAME:X',
            'type': 'numeric',
            'value': 0
        },
        {
            'path': '.FRAME:Y',
            'type': 'numeric',
            'value': 0
        },
        {
            'path': '.FRAME:WIDTH',
            'type': 'numeric',
            'value': 640
        },
        {
            'path': '.FRAME:HEIGHT',
            'type': 'numeric',
            'value': 480
        },
        {
            'path': '.FRAME:TEMP_UNIT',
            'type': 'text',
            'value': 'Radiometric'
        },
        {
            'path': '.CAM_SETUP',
            'type': 'structure'
        },  #18
        {
            'path': '.CAM_SETUP:FOCAL_LENGTH',
            'type': 'text',
            'value': '25'
        },
        {
            'path': '.CAM_SETUP:MEAS_RANGE',
            'type': 'text',
            'value': '100...650'
        },
        {
            'path': '.CAM_SETUP:FOCUS_POS',
            'type': 'numeric',
            'value': 0
        },
        {
            'path': '.CAM_SETUP:CALIB_AUTO',
            'type': 'text',
            'value': 'NO'
        },
        {
            'path': '.CAM_SETUP:CALIB_TIME',
            'type': 'numeric',
            'value': 4
        },
        {
            'path': '.TIMING',
            'type': 'structure'
        },  #24
        {
            'path': '.TIMING:TRIG_MODE',
            'type': 'text',
            'value': 'INTERNAL'
        },
        {
            'path': '.TIMING:TRIG_SOURCE',
            'type': 'numeric'
        },
        {
            'path': '.TIMING:TIME_BASE',
            'type': 'numeric'
        },
        {
            'path': '.TIMING:FRAME_RATE',
            'type': 'numeric',
            'value': 25
        },
        {
            'path': '.TIMING:BURST_DUR',
            'type': 'numeric',
            'value': 5
        },
        {
            'path': '.TIMING:SKIP_FRAME',
            'type': 'numeric',
            'value': 0
        },
        {
            'path': '.STREAMING',
            'type': 'structure'
        },  #31
        {
            'path': '.STREAMING:MODE',
            'type': 'text',
            'value': 'Stream and Store'
        },
        {
            'path': '.STREAMING:SERVER',
            'type': 'text',
            'value': 'localhost'
        },
        {
            'path': '.STREAMING:PORT',
            'type': 'numeric',
            'value': 8888
        },
        {
            'path': '.STREAMING:AUTOSCALE',
            'type': 'text',
            'value': 'NO'
        },
        {
            'path': '.STREAMING:LOLIM',
            'type': 'numeric',
            'value': 15
        },
        {
            'path': '.STREAMING:HILIM',
            'type': 'numeric',
            'value': 50
        },
        {
            'path': '.STREAMING:ADJROIX',
            'type': 'numeric',
            'value': 0
        },
        {
            'path': '.STREAMING:ADJROIY',
            'type': 'numeric',
            'value': 0
        },
        {
            'path': '.STREAMING:ADJROIW',
            'type': 'numeric',
            'value': 640
        },
        {
            'path': '.STREAMING:ADJROIH',
            'type': 'numeric',
            'value': 480
        },
        {
            'path': ':FRAMES',
            'type': 'signal',
            'options': ('no_write_model', 'no_compress_on_put')
        },
        {
            'path': ':FRAMES_METAD',
            'type': 'signal',
            'options': ('no_write_model', 'no_compress_on_put')
        },
        {
            'path': ':FRAME0_TIME',
            'type': 'numeric',
            'value': 0
        }
    ]

    parts.append({
        'path': ':INIT_ACT',
        'type': 'action',
        'valueExpr':
        "Action(Dispatch('CAMERA_SERVER','PULSE_PREPARATION',50,None),Method(None,'init',head))",
        'options': ('no_write_shot', )
    })
    parts.append({
        'path': ':START_ACT',
        'type': 'action',
        'valueExpr':
        "Action(Dispatch('CAMERA_SERVER','INIT',50,None),Method(None,'startAcquisition',head))",
        'options': ('no_write_shot', )
    })
    parts.append({
        'path': ':STOP_ACT',
        'type': 'action',
        'valueExpr':
        "Action(Dispatch('CAMERA_SERVER','STORE',50,None),Method(None,'stopAcquisition',head))",
        'options': ('no_write_shot', )
    })

    handle = c_int(-1)
    handles = {}
    workers = {}
    flirLib = None
    mdsLib = None
    streamLib = None
    flirUtilsLib = None

    error = create_string_buffer(version.tobytes(''), 512)
    """Asynchronous readout internal class"""
    class AsynchStore(Thread):
        def configure(self, device):
            self.device = device
            self.frameIdx = 0
            self.stopReq = False

        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("Acquisition thread terminated")
            self.device.removeInfo()

        def stop(self):
            print("STOP frames acquisition loop")
            status = FLIRSC65X.flirLib.stopFramesAcquisition(
                self.device.handle)
            if status < 0:
                FLIRSC65X.flirLib.getLastError(self.device.handle,
                                               self.device.error)
                Data.execute(
                    'DevLogErr($1,$2)', self.device.nid,
                    'Cannot stop frames acquisition : ' +
                    self.device.error.raw)

    def saveWorker(self):
        FLIRSC65X.workers[self.nid] = self.worker

###save Info###
#saveInfo and restoreInfo allow to manage multiple occurrences of camera devices
#and to avoid opening and closing devices handles

    def saveInfo(self):
        FLIRSC65X.handles[self.nid] = self.handle

###restore worker###

    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

###restore info###   (returned value 0:error 1:camera opened 2:camera was already opened)

    def restoreInfo(self):
        print("restore Info")
        try:
            if FLIRSC65X.flirLib is None:
                libName = "libflirsc65x.so"
                FLIRSC65X.flirLib = CDLL(libName)
                print(FLIRSC65X.flirLib)
            if FLIRSC65X.mdsLib is None:
                libName = "libcammdsutils.so"
                FLIRSC65X.mdsLib = CDLL(libName)
                print(FLIRSC65X.mdsLib)
            if FLIRSC65X.streamLib is None:
                libName = "libcamstreamutils.so"
                FLIRSC65X.streamLib = CDLL(libName)
                print(FLIRSC65X.streamLib)
            """
        if FLIRSC65X.flirUtilsLib is None:
           libName = "libflirutils.so"
           FLIRSC65X.flirUtilsLib = CDLL(libName)
           print(FLIRSC65X.flirUtilsLib)
        """
        except:
            Data.execute('DevLogErr($1,$2)', self.nid,
                         'Cannot load library : ' + libName)
            raise mdsExceptions.TclFAILED_ESSENTIAL
        if self.nid in FLIRSC65X.handles.keys():
            self.handle = FLIRSC65X.handles[self.nid]
            print('RESTORE INFO HANDLE FOUND')
            return 2
        else:
            print('RESTORE INFO HANDLE NOT FOUND')
            try:
                name = self.ip_name.data()
            except:
                Data.execute('DevLogErr($1,$2)', self.nid,
                             'Missing device name')
                raise mdsExceptions.TclFAILED_ESSENTIAL

            print("Opening")

            self.handle = c_int(-1)
            status = FLIRSC65X.flirLib.flirOpen(c_char_p(name),
                                                byref(self.handle))

            print("Opened ", status)

            if status < 0:
                FLIRSC65X.flirLib.getLastError(self.handle, self.error)
                Data.execute(
                    'DevLogErr($1,$2)', self.nid,
                    'Cannot open device ' + name + ' (' + self.error.raw + ')')
                raise mdsExceptions.TclFAILED_ESSENTIAL

            self.saveInfo()

        return 1

###remove info###

    def removeInfo(self):
        try:
            status = FLIRSC65X.flirLib.flirClose(self.handle)  #close camera
            if status < 0:
                FLIRSC65X.flirLib.getLastError(self.handle, self.error)
                Data.execute('DevLogErr($1,$2)', self.nid,
                             'Cannot close camera : ' + self.error.raw)
        except:
            print('ERROR in flirLib.flirClose()')

        try:
            del (FLIRSC65X.handles[self.nid])
            print('Camera Info removed.')
        except:
            print('ERROR TRYING TO REMOVE INFO')

##########init############################################################################

    def init(self):
        if self.restoreInfo() == 0:
            raise mdsExceptions.TclFAILED_ESSENTIAL

        try:
            self.frames.setCompressOnPut(False)
        except:
            Data.execute(
                'DevLogErr($1,$2)', self.nid,
                'Cannot disable automatic compress on put for frames node')
            raise mdsExceptions.TclFAILED_ESSENTIAL

        try:
            self.frames_metad.setCompressOnPut(False)
        except:
            Data.execute(
                'DevLogErr($1,$2)', self.nid,
                'Cannot disable automatic compress on put for frames_metad node'
            )
            raise mdsExceptions.TclFAILED_ESSENTIAL

###Object Parameters

        try:
            o_refl_temp = c_double(self.object_refl_temp.data())
        except:
            Data.execute('DevLogErr($1,$2)', self.nid,
                         'Invalid value for object refletive temperature')
            raise mdsExceptions.TclFAILED_ESSENTIAL
        try:
            o_atm_temp = c_double(self.object_atm_temp.data())
        except:
            Data.execute('DevLogErr($1,$2)', self.nid,
                         'Invalid value for object atmosfere temperature')
            raise mdsExceptions.TclFAILED_ESSENTIAL
        try:
            o_distance = c_double(self.object_distance.data())
        except:
            Data.execute('DevLogErr($1,$2)', self.nid,
                         'Invalid value for object distance')
            raise mdsExceptions.TclFAILED_ESSENTIAL
        try:
            o_emissivity = c_double(self.object_emissivity.data())
        except:
            Data.execute('DevLogErr($1,$2)', self.nid,
                         'Invalid value for object emissivity')
            raise mdsExceptions.TclFAILED_ESSENTIAL
        try:
            o_atm_hum = c_double(self.object_atm_hum.data())
        except:
            Data.execute('DevLogErr($1,$2)', self.nid,
                         'Invalid value for object atmosfere humidity')
            raise mdsExceptions.TclFAILED_ESSENTIAL
        try:
            o_optic_temp = c_double(self.object_optic_temp.data())
        except:
            Data.execute('DevLogErr($1,$2)', self.nid,
                         'Invalid value for object optic temperature')
            raise mdsExceptions.TclFAILED_ESSENTIAL
        try:
            o_optic_trans = c_double(self.object_optic_trans.data())
        except:
            Data.execute('DevLogErr($1,$2)', self.nid,
                         'Invalid value for object optic transmission')
            raise mdsExceptions.TclFAILED_ESSENTIAL
        try:
            o_atm_trans = c_double(self.object_atm_trans.data())
        except:
            Data.execute('DevLogErr($1,$2)', self.nid,
                         'Invalid value for object atmosfere trasmission')
            raise mdsExceptions.TclFAILED_ESSENTIAL

        status = FLIRSC65X.flirLib.setObjectParameters(
            self.handle, o_refl_temp, o_atm_temp, o_distance, o_emissivity,
            o_atm_hum, o_optic_temp, o_optic_trans, o_atm_trans)
        if status < 0:
            FLIRSC65X.flirLib.getLastError(self.handle, self.error)
            Data.execute('DevLogErr($1,$2)', self.nid,
                         'Cannot Set Object Parameters : ' + self.error.raw)
            raise mdsExceptions.TclFAILED_ESSENTIAL

###Frame Rate
        try:
            frameRate = self.timing_frame_rate.data()
        except:
            Data.execute('DevLogErr($1,$2)', self.nid,
                         'Invalid frame rate value')
            raise mdsExceptions.TclFAILED_ESSENTIAL
        status = FLIRSC65X.flirLib.setFrameRateNew(self.handle,
                                                   c_double(frameRate))
        if status < 0:
            FLIRSC65X.flirLib.getLastError(self.handle, self.error)
            Data.execute('DevLogErr($1,$2)', self.nid,
                         'Cannot Set Frame Rate : ' + self.error.raw)
            raise mdsExceptions.TclFAILED_ESSENTIAL

###Frame Area
        x = c_int(0)
        y = c_int(0)
        width = c_int(0)
        height = c_int(0)
        status = FLIRSC65X.flirLib.getReadoutArea(self.handle, byref(x),
                                                  byref(y), byref(width),
                                                  byref(height))
        if status < 0:
            FLIRSC65X.flirLib.getLastError(self.handle, self.error)
            Data.execute('DevLogErr($1,$2)', self.nid,
                         'Cannot Get Readout Area : ' + self.error.raw)
            raise mdsExceptions.TclFAILED_ESSENTIAL

        #write data in mdsplus
        self.frame_x.putData(x.value)
        self.frame_y.putData(y.value)
        self.frame_width.putData(width.value)
        self.frame_height.putData(height.value)

        ###Focal Length
        try:
            focalLength = self.cam_setup_focal_length.data()
        except:
            Data.execute('DevLogErr($1,$2)', self.nid,
                         'Invalid Focal Length value')
            raise mdsExceptions.TclFAILED_ESSENTIAL

        if focalLength == '25':
            focalLengthInt = 0
        elif focalLength == '41':
            focalLengthInt = 3  #offset to select the correct calibration curve using the Measurement Range

###Measurement Range
        try:
            measureRange = self.cam_setup_meas_range.data()
        except:
            Data.execute('DevLogErr($1,$2)', self.nid,
                         'Invalid measurement range value')
            raise mdsExceptions.TclFAILED_ESSENTIAL

        if measureRange == '-40...150':
            measRangeInt = 0
        elif measureRange == '100...650':
            measRangeInt = 1
        elif measureRange == '300...2000':
            measRangeInt = 2

        status = FLIRSC65X.flirLib.setMeasurementRange(
            self.handle, c_int(measRangeInt + focalLengthInt))
        if status < 0:
            try:
                FLIRSC65X.flirLib.getLastError(self.handle, self.error)
                Data.execute(
                    'DevLogErr($1,$2)', self.nid,
                    'Cannot Set Measurement Range : ' + self.error.raw)
                raise mdsExceptions.TclFAILED_ESSENTIAL
            except:
                traceback.print_exc()

###Image Temperature
        try:
            frameTempUnit = self.frame_temp_unit.data()
        except:
            Data.execute(
                'DevLogErr($1,$2)', self.nid,
                'Invalid image temperature unit (Radiometric, 10mk, 100mk) value'
            )
            raise mdsExceptions.TclFAILED_ESSENTIAL

        if frameTempUnit == 'Radiometric':
            frameTempUnitCode = c_int(0)
        elif frameTempUnit == 'LinearTemperature10mK':
            frameTempUnitCode = c_int(1)
        elif frameTempUnit == 'LinearTemperature100mK':
            frameTempUnitCode = c_int(2)

        status = FLIRSC65X.flirLib.setIrFormat(self.handle, frameTempUnitCode)
        if status < 0:
            FLIRSC65X.flirLib.getLastError(self.handle, self.error)
            Data.execute(
                'DevLogErr($1,$2)', self.nid,
                'Cannot Set Image Temperature unit : ' + self.error.raw)
            raise mdsExceptions.TclFAILED_ESSENTIAL

###Frame Trigger mode
        try:
            burstDuration = self.timing_burst_dur.data()
        except:
            Data.execute('DevLogErr($1,$2)', self.nid,
                         'Invalid acquisition duration value')
            raise mdsExceptions.TclFAILED_ESSENTIAL

        try:
            triggerMode = self.timing_trig_mode.data()
        except:
            Data.execute('DevLogErr($1,$2)', self.nid,
                         'Invalid trigger mode value')
            raise mdsExceptions.TclFAILED_ESSENTIAL

        try:
            trigSource = self.timing_trig_source.data()
        except:
            if triggerMode == 'EXTERNAL':
                Data.execute('DevLogErr($1,$2)', self.nid,
                             'Invalid trigger source value')
                raise mdsExceptions.TclFAILED_ESSENTIAL
            else:
                trigSource = array([0.])

        print("OK " + triggerMode)
        if triggerMode == 'EXTERNAL':  #0=internal  1=external trigger
            trigModeCode = c_int(1)
        else:
            trigSource = array([0.])
            trigModeCode = c_int(0)

        numTrigger = trigSource.size
        print("OK - NUM TRIGGER ", numTrigger)
        print("OK - Trigger Source ", trigSource)

        timeBase = Data.compile(
            " $ : $ + $ :(zero( size( $ ), 0.) + 1.) * 1./$", trigSource,
            trigSource, burstDuration, trigSource, frameRate)

        print("Data = " + Data.decompile(timeBase))

        self.timing_time_base.putData(timeBase)
        status = FLIRSC65X.flirLib.setTriggerMode(self.handle, trigModeCode,
                                                  c_double(burstDuration),
                                                  numTrigger)

        if status < 0:
            FLIRSC65X.flirLib.getLastError(self.handle, self.error)
            Data.execute(
                'DevLogErr($1,$2)', self.nid,
                'Cannot Set Internal/External Trigger : ' + self.error.raw)
            raise mdsExceptions.TclFAILED_ESSENTIAL

###Calibration
        try:
            calibAuto = self.cam_setup_calib_auto.data()
        except:
            Data.execute('DevLogErr($1,$2)', self.nid,
                         'Invalid auto calibration setup')
            raise mdsExceptions.TclFAILED_ESSENTIAL

        calibModeCode = c_int(1)
        if calibAuto == 'NO':
            try:
                calibTime = self.cam_setup_calib_time.data()
                calibModeCode = c_int(0)
            except:
                Data.execute('DevLogErr($1,$2)', self.nid,
                             'Invalid calibration duration value')
                raise mdsExceptions.TclFAILED_ESSENTIAL
            if numTrigger > 1 and (burstDuration + calibTime) > (
                    trigSource[1] - trigSource[0]):
                Data.execute('DevLogErr($1,$2)', self.nid,
                             'Calibration executed during acquisition')
                raise mdsExceptions.TclFAILED_ESSENTIAL

        status = FLIRSC65X.flirLib.setCalibMode(self.handle, calibModeCode)
        if status < 0:
            FLIRSC65X.flirLib.getLastError(self.handle, self.error)
            Data.execute(
                'DevLogErr($1,$2)', self.nid,
                'Cannot Set Internal/External Trigger : ' + self.error.raw)
            raise mdsExceptions.TclFAILED_ESSENTIAL

###Read and save current Focus Position
        try:
            focusPosRes = self.readFocusPos()
        except:
            Data.execute('DevLogErr($1,$2)', self.nid,
                         'Error reading focus position')
            raise mdsExceptions.TclFAILED_ESSENTIAL

###Streaming
        try:
            streamingMode = self.streaming_mode.data()
        except:
            Data.execute('DevLogErr($1,$2)', self.nid,
                         'Invalid streaming mode setup')
            raise mdsExceptions.TclFAILED_ESSENTIAL

        if streamingMode == 'Stream and Store':
            streamingEnabled = c_int(1)
            storeEnabled = c_int(1)
        elif streamingMode == 'Only Stream':
            streamingEnabled = c_int(1)
            storeEnabled = c_int(0)
        else:  #streamingMode == 'Only Store':
            streamingEnabled = c_int(0)
            storeEnabled = c_int(1)

        if 1:  #streamingEnabled   (FM: setStreamingMode use this flag)
            try:
                if self.streaming_autoscale.data() == 'YES':
                    autoAdjustLimit = c_int(1)
                else:
                    autoAdjustLimit = c_int(0)
            except:
                Data.execute('DevLogErr($1,$2)', self.nid,
                             'Invalid streaming autoscale parameter value')
                raise mdsExceptions.TclFAILED_ESSENTIAL

            try:
                lowLim = c_int(self.streaming_lolim.data())
            except:
                Data.execute(
                    'DevLogErr($1,$2)', self.nid,
                    'Invalid streaming low temperature limit parameter value')
                raise mdsExceptions.TclFAILED_ESSENTIAL

            try:
                highLim = c_int(self.streaming_hilim.data())
            except:
                Data.execute(
                    'DevLogErr($1,$2)', self.nid,
                    'Invalid streaming high temperature limit parameter value')
                raise mdsExceptions.TclFAILED_ESSENTIAL

            try:
                streamingPort = c_int(self.streaming_port.data())
            except:
                Data.execute('DevLogErr($1,$2)', self.nid,
                             'Invalid streaming port parameter value')
                raise mdsExceptions.TclFAILED_ESSENTIAL

            try:
                streamingServer = self.streaming_server.data()
            except:
                Data.execute('DevLogErr($1,$2)', self.nid,
                             'Invalid streaming server parameter value')
                raise mdsExceptions.TclFAILED_ESSENTIAL

            try:
                adjRoiX = c_int(self.streaming_adjroix.data())
            except:
                Data.execute('DevLogErr($1,$2)', self.nid,
                             'Invalid streaming ROI x value')
                raise mdsExceptions.TclFAILED_ESSENTIAL

            try:
                adjRoiY = c_int(self.streaming_adjroiy.data())
            except:
                Data.execute('DevLogErr($1,$2)', self.nid,
                             'Invalid streaming ROI y value')
                raise mdsExceptions.TclFAILED_ESSENTIAL

            try:
                adjRoiW = c_int(self.streaming_adjroiw.data())
            except:
                Data.execute('DevLogErr($1,$2)', self.nid,
                             'Invalid streaming ROI width value')
                raise mdsExceptions.TclFAILED_ESSENTIAL

            try:
                adjRoiH = c_int(self.streaming_adjroih.data())
            except:
                Data.execute('DevLogErr($1,$2)', self.nid,
                             'Invalid streaming ROI height value')
                raise mdsExceptions.TclFAILED_ESSENTIAL

            print("lowLim ", lowLim)
            print("highLim ", highLim)
            print("frameTempUnitCode ", frameTempUnitCode)
            print("streamingPort ", streamingPort)
            print("streamingServer ", streamingServer)
            print("streaming adj ROI x ", adjRoiX)
            print("streaming adj ROI y  ", adjRoiY)
            print("streaming adj ROI w  ", adjRoiW)
            print("streaming adj ROI h  ", adjRoiH)
            #FM: recover device name and pass it to setStreaming to overlay text on frame!!!
            deviceName = str(self).rsplit(":", 1)
            deviceName = deviceName[1]
            print("Device Name ", deviceName)

        status = FLIRSC65X.flirLib.setStreamingMode(
            self.handle, frameTempUnitCode, streamingEnabled, autoAdjustLimit,
            c_char_p(streamingServer), streamingPort, lowLim, highLim, adjRoiX,
            adjRoiY, adjRoiW, adjRoiH, c_char_p(deviceName))
        if status < 0:
            FLIRSC65X.flirLib.getLastError(self.handle, self.error)
            Data.execute(
                'DevLogErr($1,$2)', self.nid,
                'Cannot execute streaming setup mode : ' + self.error.raw)
            raise mdsExceptions.TclFAILED_ESSENTIAL

###Acquisition

        try:
            acqSkipFrameNumber = c_int(self.timing_skip_frame.data())
        except:
            Data.execute('DevLogErr($1,$2)', self.nid,
                         'Invalid acquisition decimation value')
            raise mdsExceptions.TclFAILED_ESSENTIAL

        status = FLIRSC65X.flirLib.setAcquisitionMode(self.handle,
                                                      storeEnabled,
                                                      acqSkipFrameNumber)
        if status < 0:
            FLIRSC65X.flirLib.getLastError(self.handle, self.error)
            Data.execute(
                'DevLogErr($1,$2)', self.nid,
                'Cannot execute acquisition setup mode : ' + self.error.raw)
            raise mdsExceptions.TclFAILED_ESSENTIAL

        try:
            treePtr = c_void_p(0)
            status = FLIRSC65X.mdsLib.camOpenTree(
                c_char_p(self.getTree().name), c_int(self.getTree().shot),
                byref(treePtr))
            if status == -1:
                Data.execute('DevLogErr($1,$2)', self.nid, 'Cannot open tree')
                raise mdsExceptions.TclFAILED_ESSENTIAL
        except:
            traceback.print_exc()

        framesNid = self.frames.nid
        timebaseNid = self.timing_time_base.nid
        framesMetadNid = self.frames_metad.nid
        frame0TimeNid = self.frame0_time.nid

        status = FLIRSC65X.flirLib.setTreeInfo(self.handle, treePtr, framesNid,
                                               timebaseNid, framesMetadNid,
                                               frame0TimeNid)
        if status < 0:
            FLIRSC65X.flirLib.getLastError(self.handle, self.error)
            Data.execute('DevLogErr($1,$2)', self.nid,
                         'Cannot execute set tree info : ' + self.error.raw)
            raise mdsExceptions.TclFAILED_ESSENTIAL

###Auto Calibration
        status = FLIRSC65X.flirLib.executeAutoCalib(self.handle)
        if status < 0:
            FLIRSC65X.flirLib.getLastError(self.handle, self.error)
            Data.execute('DevLogErr($1,$2)', self.nid,
                         'Cannot Execute Auto Calibration : ' + self.error.raw)
            raise mdsExceptions.TclFAILED_ESSENTIAL

        print('Init action completed.')
        return 1

####################MANUAL CALIBRATION ACTION

    def calib(self):
        restoreRes = self.restoreInfo()
        if restoreRes == 0:
            raise mdsExceptions.TclFAILED_ESSENTIAL

        status = FLIRSC65X.flirLib.executeAutoCalib(self.handle)
        if status < 0:
            FLIRSC65X.flirLib.getLastError(self.handle, self.error)
            Data.execute('DevLogErr($1,$2)', self.nid,
                         'Cannot Execute Auto Calibration ' + self.error.raw)
            raise mdsExceptions.TclFAILED_ESSENTIAL

        if restoreRes == 1:  #camera must be closed because has been opened only for this action
            self.removeInfo()

        return 1

####################MANUAL AUTOFOCUS ACTION

    def autofocus(self):
        restoreRes = self.restoreInfo()
        if restoreRes == 0:
            raise mdsExceptions.TclFAILED_ESSENTIAL

        status = FLIRSC65X.flirLib.executeAutoFocus(self.handle)
        if status < 0:
            FLIRSC65X.flirLib.getLastError(self.handle, self.error)
            Data.execute('DevLogErr($1,$2)', self.nid,
                         'Cannot Execute Auto Focus : ' + self.error.raw)
            raise mdsExceptions.TclFAILED_ESSENTIAL

        if restoreRes == 1:  #camera must be closed because has been opened only for this action
            self.removeInfo()

        return 1

####################READ FOCUS POSITION

    def readFocusPos(self):
        restoreRes = self.restoreInfo()
        if restoreRes == 0:
            raise mdsExceptions.TclFAILED_ESSENTIAL

        focPos = c_int(0)
        status = FLIRSC65X.flirLib.getFocusAbsPosition(self.handle,
                                                       byref(focPos))
        print('Focus Position Read: ', focPos)
        if status < 0:
            FLIRSC65X.flirLib.getLastError(self.handle, self.error)
            Data.execute('DevLogErr($1,$2)', self.nid,
                         'Cannot Read Focus Position : ' + self.error.raw)
            raise mdsExceptions.TclFAILED_ESSENTIAL

        self.cam_setup_focus_pos.putData(
            focPos.value)  #save focus position in MDS

        if restoreRes == 1:  #camera must be closed because has been opened only for this action
            self.removeInfo()

        return 1

####################WRITE FOCUS POSITION

    def writeFocusPos(self):
        restoreRes = self.restoreInfo()
        if restoreRes == 0:
            raise mdsExceptions.TclFAILED_ESSENTIAL

        status = FLIRSC65X.flirLib.setFocusAbsPosition(
            self.handle, c_int(self.cam_setup_focus_pos.data()))
        if status < 0:
            FLIRSC65X.flirLib.getLastError(self.handle, self.error)
            Data.execute('DevLogErr($1,$2)', self.nid,
                         'Cannot Write Focus Position : ' + self.error.raw)
            raise mdsExceptions.TclFAILED_ESSENTIAL

        if restoreRes == 1:  #camera must be closed because has been opened only for this action
            self.removeInfo()

        return 1

##########start acquisition############################################################################

    def startAcquisition(self):
        if self.restoreInfo() == 0:
            raise mdsExceptions.TclFAILED_ESSENTIAL

        print("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 = 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("flirLib acquisition started")
        self.worker.configure(self)
        self.saveWorker()
        self.worker.start()
        return 1

##########stop acquisition############################################################################

    def stopAcquisition(self):
        if self.restoreWorker():
            self.worker.stop()
        return 1

##########software trigger (start saving in mdsplus)############################################

    def swTrigger(self):
        if self.restoreInfo() == 0:
            raise mdsExceptions.TclFAILED_ESSENTIAL

        print('SOFTWARE TRIGGER')

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

        return 1
Esempio n. 5
0
class BASLERACA(Device):
    """BASLER NEW Camera"""
    parts = [  #offset nid
        {
            'path': ':IP_NAME',
            'type': 'text',
            'value': '192.168.54.96'
        },  #1
        {
            'path': ':COMMENT',
            'type': 'text'
        },
        {
            'path': '.FRAME',
            'type': 'structure'
        },  #3
        {
            'path': '.FRAME:X',
            'type': 'numeric',
            'value': 8
        },
        {
            'path': '.FRAME:Y',
            'type': 'numeric',
            'value': 8
        },
        {
            'path': '.FRAME:WIDTH',
            'type': 'numeric',
            'value': 1920
        },
        {
            'path': '.FRAME:HEIGHT',
            'type': 'numeric',
            'value': 1200
        },
        {
            'path': '.FRAME:PIXEL_FORMAT',
            'type': 'text',
            'value': 'Mono12'
        },
        {
            'path': '.CAM_SETUP',
            'type': 'structure'
        },  #9
        {
            'path': '.CAM_SETUP:GAIN_AUTO',
            'type': 'text',
            'value': 'Off'
        },
        {
            'path': '.CAM_SETUP:GAIN',
            'type': 'numeric',
            'value': 0
        },
        {
            'path': '.CAM_SETUP:GAMMA_EN',
            'type': 'text',
            'value': 'Off'
        },
        {
            'path': '.CAM_SETUP:EXP_AUTO',
            'type': 'text',
            'value': 'Off'
        },
        {
            'path': '.CAM_SETUP:EXPOSURE',
            'type': 'numeric',
            'value': 800E3
        },
        {
            'path': '.TIMING',
            'type': 'structure'
        },  #15
        {
            'path': '.TIMING:TRIG_MODE',
            'type': 'text',
            'value': 'INTERNAL'
        },
        {
            'path': '.TIMING:TRIG_SOURCE',
            'type': 'numeric'
        },
        {
            'path': '.TIMING:TIME_BASE',
            'type': 'numeric'
        },
        {
            'path': '.TIMING:FRAME_RATE',
            'type': 'numeric',
            'value': 1
        },
        {
            'path': '.TIMING:BURST_DUR',
            'type': 'numeric',
            'value': 5
        },
        {
            'path': '.TIMING:SKIP_FRAME',
            'type': 'numeric',
            'value': 0
        },
        {
            'path': '.STREAMING',
            'type': 'structure'
        },  #22
        {
            'path': '.STREAMING:MODE',
            'type': 'text',
            'value': 'Stream and Store'
        },
        {
            'path': '.STREAMING:SERVER',
            'type': 'text',
            'value': 'localhost'
        },
        {
            'path': '.STREAMING:PORT',
            'type': 'numeric',
            'value': 8888
        },
        {
            'path': '.STREAMING:AUTOSCALE',
            'type': 'text',
            'value': 'NO'
        },
        {
            'path': '.STREAMING:LOLIM',
            'type': 'numeric',
            'value': 0
        },
        {
            'path': '.STREAMING:HILIM',
            'type': 'numeric',
            'value': 4095
        },
        {
            'path': '.STREAMING:ADJROIX',
            'type': 'numeric',
            'value': 0
        },
        {
            'path': '.STREAMING:ADJROIY',
            'type': 'numeric',
            'value': 0
        },
        {
            'path': '.STREAMING:ADJROIW',
            'type': 'numeric',
            'value': 1920
        },
        {
            'path': '.STREAMING:ADJROIH',
            'type': 'numeric',
            'value': 1200
        },
        {
            'path': ':FRAMES',
            'type': 'signal',
            'options': ('no_write_model', 'no_compress_on_put')
        },
        {
            'path': ':FRAMES_METAD',
            'type': 'signal',
            'options': ('no_write_model', 'no_compress_on_put')
        },
        {
            'path': ':FRAME0_TIME',
            'type': 'numeric',
            'value': 0
        }
    ]

    parts.append({
        'path': ':INIT_ACT',
        'type': 'action',
        'valueExpr':
        "Action(Dispatch('CAMERA_SERVER','PULSE_PREPARATION',50,None),Method(None,'init',head))",
        'options': ('no_write_shot', )
    })
    parts.append({
        'path': ':START_ACT',
        'type': 'action',
        'valueExpr':
        "Action(Dispatch('CAMERA_SERVER','INIT',50,None),Method(None,'startAcquisition',head))",
        'options': ('no_write_shot', )
    })
    parts.append({
        'path': ':STOP_ACT',
        'type': 'action',
        'valueExpr':
        "Action(Dispatch('CAMERA_SERVER','STORE',50,None),Method(None,'stopAcquisition',head))",
        'options': ('no_write_shot', )
    })

    handle = c_int(-1)
    handles = {}
    workers = {}
    baslerLib = None
    mdsLib = None
    streamLib = None

    error = create_string_buffer(version.tobytes(''), 512)

    def debugPrint(self, msg="", obj=""):
        print("------ DEBUG  " + self.name + ":" + msg, obj)

    """Asynchronous readout internal class"""

    class AsynchStore(Thread):
        def configure(self, device):
            self.device = device
            self.frameIdx = 0
            self.stopReq = False

        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()
            #raise mdsExceptions.TclFAILED_ESSENTIAL

        def stop(self):
            self.device.debugPrint("STOP frames acquisition loop")
            status = BASLERACA.baslerLib.stopFramesAcquisition(
                self.device.handle)
            if status < 0:
                BASLERACA.baslerLib.getLastError(self.device.handle,
                                                 self.device.error)
                Data.execute(
                    'DevLogErr($1,$2)', self.device.nid,
                    'Cannot stop frames acquisition : ' +
                    self.device.error.raw)

    def saveWorker(self):
        BASLERACA.workers[self.nid] = self.worker

###save Info###
#saveInfo and restoreInfo allow to manage multiple occurrences of camera devices
#and to avoid opening and closing devices handles

    def saveInfo(self):
        BASLERACA.handles[self.nid] = self.handle

###restore worker###

    def restoreWorker(self):
        if self.nid in BASLERACA.workers.keys():
            self.worker = BASLERACA.workers[self.nid]
            return 1
        else:
            Data.execute('DevLogErr($1,$2)', self.nid,
                         'Cannot restore worker!!')
            raise mdsExceptions.TclFAILED_ESSENTIAL
        return 1

###restore info###

    def restoreInfo(self):
        self.debugPrint("restore Info")
        try:
            if BASLERACA.baslerLib is None:
                libName = "libbasleraca.so"
                BASLERACA.baslerLib = CDLL(libName)
                self.debugPrint(obj=BASLERACA.baslerLib)
            if BASLERACA.mdsLib is None:
                libName = "libcammdsutils.so"
                BASLERACA.mdsLib = CDLL(libName)
                self.debugPrint(obj=BASLERACA.mdsLib)
            if BASLERACA.streamLib is None:
                libName = "libcamstreamutils.so"
                BASLERACA.streamLib = CDLL(libName)
                self.debugPrint(obj=BASLERACA.streamLib)

        except:
            Data.execute('DevLogErr($1,$2)', self.nid,
                         'Cannot load library : ' + libName)
            raise mdsExceptions.TclFAILED_ESSENTIAL
        if self.nid in BASLERACA.handles.keys():
            self.handle = BASLERACA.handles[self.nid]
            self.debugPrint('RESTORE INFO HANDLE TROVATO', self.handle)
        else:
            self.debugPrint('RESTORE INFO HANDLE NON TROVATO')
            try:
                name = self.ip_name.data()
            except:
                Data.execute('DevLogErr($1,$2)', self.nid,
                             'Missing device name')
                raise mdsExceptions.TclFAILED_ESSENTIAL

            self.debugPrint("Opening")

            self.handle = c_int(-1)
            status = BASLERACA.baslerLib.baslerOpen(c_char_p(name),
                                                    byref(self.handle))

            self.debugPrint("Opened ", self.handle)

            if status < 0:
                BASLERACA.baslerLib.getLastError(self.handle, self.error)
                Data.execute(
                    'DevLogErr($1,$2)', self.nid,
                    'Cannot open device ' + name + '(' + self.error.raw + ')')
                raise mdsExceptions.TclFAILED_ESSENTIAL

        return 1

###remove info###

    def removeInfo(self):
        try:
            del (BASLERACA.handles[self.nid])
        except:
            self.debugPrint('ERROR TRYING TO REMOVE INFO')

##########init############################################################################

    def init(self):
        if self.restoreInfo() == 0:
            raise mdsExceptions.TclFAILED_ESSENTIAL

        self.saveInfo()

        try:
            self.frames.setCompressOnPut(False)
        except:
            Data.execute(
                'DevLogErr($1,$2)', self.nid,
                'Cannot disable automatic compresson on put for frames node')
            raise mdsExceptions.TclFAILED_ESSENTIAL

        try:
            self.frames_metad.setCompressOnPut(False)
        except:
            Data.execute(
                'DevLogErr($1,$2)', self.nid,
                'Cannot disable automatic compresson on put for frames_metad node'
            )
            raise mdsExceptions.TclFAILED_ESSENTIAL

###Gain
        try:
            gain = self.cam_setup_gain.data()
        except:
            Data.execute('DevLogErr($1,$2)', self.nid, 'Invalid gain value')
            raise mdsExceptions.TclFAILED_ESSENTIAL
        status = BASLERACA.baslerLib.setGain(self.handle, c_int(gain))
        if status < 0:
            BASLERACA.baslerLib.getLastError(self.handle, self.error)
            Data.execute('DevLogErr($1,$2)', self.nid,
                         'Cannot Set Gain : ' + self.error.raw)
            raise mdsExceptions.TclFAILED_ESSENTIAL

###Gain Auto
        try:
            gainAuto = self.cam_setup_gain_auto.data()
        except:
            Data.execute('DevLogErr($1,$2)', self.nid,
                         'Invalid gain auto value')
            raise mdsExceptions.TclFAILED_ESSENTIAL
        status = BASLERACA.baslerLib.setGainAuto(self.handle,
                                                 c_char_p(gainAuto))
        if status < 0:
            BASLERACA.baslerLib.getLastError(self.handle, self.error)
            Data.execute('DevLogErr($1,$2)', self.nid,
                         'Cannot Set Gain Auto : ' + self.error.raw)
            raise mdsExceptions.TclFAILED_ESSENTIAL

###Gamma Enable
        try:
            gammaEnable = self.cam_setup_gamma_en.data()
        except:
            Data.execute('DevLogErr($1,$2)', self.nid,
                         'Invalid gamma enable value')
            raise mdsExceptions.TclFAILED_ESSENTIAL
        status = BASLERACA.baslerLib.setGammaEnable(self.handle,
                                                    c_char_p(gammaEnable))
        if status < 0:
            BASLERACA.baslerLib.getLastError(self.handle, self.error)
            Data.execute('DevLogErr($1,$2)', self.nid,
                         'Cannot Set Gamma Enable : ' + self.error.raw)
            raise mdsExceptions.TclFAILED_ESSENTIAL

###Exposure Auto
        try:
            exposureAuto = self.cam_setup_exp_auto.data()
        except:
            Data.execute('DevLogErr($1,$2)', self.nid,
                         'Invalid exposure auto value')
            raise mdsExceptions.TclFAILED_ESSENTIAL
        status = BASLERACA.baslerLib.setExposureAuto(self.handle,
                                                     c_char_p(exposureAuto))
        if status < 0:
            BASLERACA.baslerLib.getLastError(self.handle, self.error)
            Data.execute('DevLogErr($1,$2)', self.nid,
                         'Cannot Set Exposure Auto : ' + self.error.raw)
            raise mdsExceptions.TclFAILED_ESSENTIAL

###Exposure
        try:
            exposure = self.cam_setup_exposure.data()
        except:
            Data.execute('DevLogErr($1,$2)', self.nid,
                         'Invalid exposure value')
            raise mdsExceptions.TclFAILED_ESSENTIAL
        status = BASLERACA.baslerLib.setExposure(self.handle,
                                                 c_double(exposure))
        if status < 0:
            BASLERACA.baslerLib.getLastError(self.handle, self.error)
            Data.execute('DevLogErr($1,$2)', self.nid,
                         'Cannot Set Exposure : ' + self.error.raw)
            raise mdsExceptions.TclFAILED_ESSENTIAL

###READ CAMERA TEMPERATURE
        status = BASLERACA.baslerLib.readInternalTemperature(self.handle)
        if status < 0:
            BASLERACA.baslerLib.getLastError(self.handle, self.error)
            Data.execute(
                'DevLogErr($1,$2)', self.nid,
                'Cannot Read Internal Temperature : ' + self.error.raw)
            raise mdsExceptions.TclFAILED_ESSENTIAL

###Pixel Format
        try:
            pixelFormat = self.frame_pixel_format.data()
        except:
            Data.execute('DevLogErr($1,$2)', self.nid,
                         'Invalid pixel format value')
            raise mdsExceptions.TclFAILED_ESSENTIAL
        status = BASLERACA.baslerLib.setPixelFormat(self.handle,
                                                    c_char_p(pixelFormat))
        if status < 0:
            BASLERACA.baslerLib.getLastError(self.handle, self.error)
            Data.execute('DevLogErr($1,$2)', self.nid,
                         'Cannot Set Pixel Format : ' + self.error.raw)
            raise mdsExceptions.TclFAILED_ESSENTIAL

###Frame Rate

        try:
            frameRate = self.timing_frame_rate.data()
        except:
            Data.execute('DevLogErr($1,$2)', self.nid,
                         'Invalid frame rate value')
            raise mdsExceptions.TclFAILED_ESSENTIAL
        status = BASLERACA.baslerLib.setFrameRate(self.handle,
                                                  c_double(frameRate))
        if status < 0:
            BASLERACA.baslerLib.getLastError(self.handle, self.error)
            Data.execute('DevLogErr($1,$2)', self.nid,
                         'Cannot Set Frame Rate : ' + self.error.raw)
            raise mdsExceptions.TclFAILED_ESSENTIAL

###Frame Area

        try:
            x = self.frame_x.data()
            y = self.frame_y.data()
            width = self.frame_width.data()
            height = self.frame_height.data()
        except:
            Data.execute('DevLogErr($1,$2)', self.nid,
                         'Invalid Frame Area value')
            raise mdsExceptions.TclFAILED_ESSENTIAL
        status = BASLERACA.baslerLib.setReadoutArea(self.handle, c_int(x),
                                                    c_int(y), c_int(width),
                                                    c_int(height))
        if status < 0:
            BASLERACA.baslerLib.getLastError(self.handle, self.error)
            Data.execute('DevLogErr($1,$2)', self.nid,
                         'Cannot Set Frame Area : ' + self.error.raw)
            raise mdsExceptions.TclFAILED_ESSENTIAL

###Frame Trigger mode

        try:
            burstDuration = self.timing_burst_dur.data()
        except:
            Data.execute('DevLogErr($1,$2)', self.nid,
                         'Invalid acquisition duration value')
            raise mdsExceptions.TclFAILED_ESSENTIAL

        try:
            triggerMode = self.timing_trig_mode.data()
        except:
            Data.execute('DevLogErr($1,$2)', self.nid,
                         'Invalid trigger mode value')
            raise mdsExceptions.TclFAILED_ESSENTIAL

        try:
            trigSource = self.timing_trig_source.data()
        except:
            if triggerMode == 'EXTERNAL':
                Data.execute('DevLogErr($1,$2)', self.nid,
                             'Invalid trigger source value')
                raise mdsExceptions.TclFAILED_ESSENTIAL
            else:
                trigSource = array([0.])

        self.debugPrint("---OK ", triggerMode)
        if triggerMode == 'EXTERNAL':  #0=internal  1=external trigger
            trigModeCode = c_int(1)
        else:
            #trigSource = array([0.]) CT 2018-06-06 Use trigger source, if ii is defined, in internal mode
            trigModeCode = c_int(0)

        numTrigger = trigSource.size
        self.debugPrint("OK - NUM TRIGGER ", numTrigger)
        self.debugPrint("OK - Trigger Source ", trigSource)

        timeBase = Data.compile(
            " $ : $ + $ :(zero( size( $ ), 0.) + 1.) * 1./$", trigSource,
            trigSource, burstDuration, trigSource, frameRate)

        self.debugPrint("Data = " + Data.decompile(timeBase))

        self.timing_time_base.putData(timeBase)
        status = BASLERACA.baslerLib.setTriggerMode(self.handle, trigModeCode,
                                                    c_double(burstDuration),
                                                    numTrigger)

        if status < 0:
            BASLERACA.baslerLib.getLastError(self.handle, self.error)
            Data.execute(
                'DevLogErr($1,$2)', self.nid,
                'Cannot Set Internal/External Trigger : ' + self.error.raw)
            raise mdsExceptions.TclFAILED_ESSENTIAL

###Streaming
        try:
            streamingMode = self.streaming_mode.data()
        except:
            Data.execute('DevLogErr($1,$2)', self.nid,
                         'Invalid streaming mode setup')
            raise mdsExceptions.TclFAILED_ESSENTIAL

        if streamingMode == 'Stream and Store':
            streamingEnabled = c_int(1)
            storeEnabled = c_int(1)
        elif streamingMode == 'Only Stream':
            streamingEnabled = c_int(1)
            storeEnabled = c_int(0)
        else:  #streamingMode == 'Only Store':
            streamingEnabled = c_int(0)
            storeEnabled = c_int(1)

        if streamingEnabled:
            try:
                if self.streaming_autoscale.data() == 'YES':
                    autoAdjustLimit = c_int(1)
                else:
                    autoAdjustLimit = c_int(0)
            except:
                Data.execute('DevLogErr($1,$2)', self.nid,
                             'Invalid streaming autoscale parameter value')
                raise mdsExceptions.TclFAILED_ESSENTIAL

            try:
                lowLim = c_int(self.streaming_lolim.data())
            except:
                Data.execute(
                    'DevLogErr($1,$2)', self.nid,
                    'Invalid streaming low temperature limit parameter value')
                raise mdsExceptions.TclFAILED_ESSENTIAL

            try:
                highLim = c_int(self.streaming_hilim.data())
            except:
                Data.execute(
                    'DevLogErr($1,$2)', self.nid,
                    'Invalid streaming high temperature limit parameter value')
                raise mdsExceptions.TclFAILED_ESSENTIAL

            try:
                streamingPort = c_int(self.streaming_port.data())
            except:
                Data.execute('DevLogErr($1,$2)', self.nid,
                             'Invalid streaming port parameter value')
                raise mdsExceptions.TclFAILED_ESSENTIAL

            try:
                streamingServer = self.streaming_server.data()
            except:
                Data.execute('DevLogErr($1,$2)', self.nid,
                             'Invalid streaming server parameter value')
                raise mdsExceptions.TclFAILED_ESSENTIAL

            try:
                adjRoiX = c_int(self.streaming_adjroix.data())
            except:
                Data.execute('DevLogErr($1,$2)', self.nid,
                             'Invalid streaming ROI x value')
                raise mdsExceptions.TclFAILED_ESSENTIAL

            try:
                adjRoiY = c_int(self.streaming_adjroiy.data())
            except:
                Data.execute('DevLogErr($1,$2)', self.nid,
                             'Invalid streaming ROI y value')
                raise mdsExceptions.TclFAILED_ESSENTIAL

            try:
                adjRoiW = c_int(self.streaming_adjroiw.data())
            except:
                Data.execute('DevLogErr($1,$2)', self.nid,
                             'Invalid streaming ROI width value')
                raise mdsExceptions.TclFAILED_ESSENTIAL

            try:
                adjRoiH = c_int(self.streaming_adjroih.data())
            except:
                Data.execute('DevLogErr($1,$2)', self.nid,
                             'Invalid streaming ROI height value')
                raise mdsExceptions.TclFAILED_ESSENTIAL

            self.debugPrint("lowLim ", lowLim)
            self.debugPrint("highLim ", highLim)
            self.debugPrint("streamingPort ", streamingPort)
            self.debugPrint("streamingServer ", streamingServer)
            self.debugPrint("streaming adj ROI x ", adjRoiX)
            self.debugPrint("streaming adj ROI y  ", adjRoiY)
            self.debugPrint("streaming adj ROI w  ", adjRoiW)
            self.debugPrint("streaming adj ROI h  ", adjRoiH)
            deviceName = str(self).rsplit(
                ":", 1)  #Recover device name to overlay it as text on frame
            deviceName = deviceName[1]
            self.debugPrint("Device Name ", deviceName)

            status = BASLERACA.baslerLib.setStreamingMode(
                self.handle, streamingEnabled, autoAdjustLimit,
                c_char_p(streamingServer), streamingPort, lowLim, highLim,
                adjRoiX, adjRoiY, adjRoiW, adjRoiH, c_char_p(deviceName))
            if status < 0:
                BASLERACA.baslerLib.getLastError(self.handle, self.error)
                Data.execute(
                    'DevLogErr($1,$2)', self.nid,
                    'Cannot execute streaming setup mode : ' + self.error.raw)
                raise mdsExceptions.TclFAILED_ESSENTIAL

###Acquisition

        try:
            acqSkipFrameNumber = c_int(self.timing_skip_frame.data())
        except:
            Data.execute('DevLogErr($1,$2)', self.nid,
                         'Invalid acquisition decimation value')
            raise mdsExceptions.TclFAILED_ESSENTIAL

        status = BASLERACA.baslerLib.setAcquisitionMode(
            self.handle, storeEnabled, acqSkipFrameNumber)
        if status < 0:
            BASLERACA.baslerLib.getLastError(self.handle, self.error)
            Data.execute(
                'DevLogErr($1,$2)', self.nid,
                'Cannot execute acquisition setup mode : ' + self.error.raw)
            raise mdsExceptions.TclFAILED_ESSENTIAL

        try:
            treePtr = c_void_p(0)
            status = BASLERACA.mdsLib.camOpenTree(
                c_char_p(self.getTree().name), c_int(self.getTree().shot),
                byref(treePtr))
            if status == -1:
                Data.execute('DevLogErr($1,$2)', self.nid, 'Cannot open tree')
                raise mdsExceptions.TclFAILED_ESSENTIAL
        except:
            traceback.print_exc()

        framesNid = self.frames.nid
        timebaseNid = self.timing_time_base.nid
        framesMetadNid = self.frames_metad.nid
        frame0TimeNid = self.frame0_time.nid

        status = BASLERACA.baslerLib.setTreeInfo(self.handle, treePtr,
                                                 framesNid, timebaseNid,
                                                 framesMetadNid, frame0TimeNid)
        if status < 0:
            BASLERACA.baslerLib.getLastError(self.handle, self.error)
            Data.execute('DevLogErr($1,$2)', self.nid,
                         'Cannot execute set tree info : ' + self.error.raw)
            raise mdsExceptions.TclFAILED_ESSENTIAL

        self.debugPrint('Init action completed.')
        return 1

####################CHANGE GAIN

    def changeGain(self):
        if self.restoreInfo() == 0:
            raise mdsExceptions.TclFAILED_ESSENTIAL

        status = BASLERACA.baslerLib.setGain(self.handle,
                                             c_int(self.cam_setup_gain.data()))
        if status < 0:
            BASLERACA.baslerLib.getLastError(self.handle, self.error)
            Data.execute('DevLogErr($1,$2)', self.nid,
                         'Cannot change Gain value : ' + self.error.raw)
            raise mdsExceptions.TclFAILED_ESSENTIAL

        self.saveInfo()
        return 1

####################CHANGE EXPOSURE

    def changeExposure(self):
        if self.restoreInfo() == 0:
            raise mdsExceptions.TclFAILED_ESSENTIAL

        status = BASLERACA.baslerLib.setExposure(
            self.handle, c_double(self.cam_setup_exposure.data()))
        if status < 0:
            BASLERACA.baslerLib.getLastError(self.handle, self.error)
            Data.execute('DevLogErr($1,$2)', self.nid,
                         'Cannot change Exposure Value : ' + self.error.raw)
            raise mdsExceptions.TclFAILED_ESSENTIAL

        self.saveInfo()
        return 1

####################READ INTERNAL TEMPERATURE

    def readTemperature(self):
        if self.restoreInfo() == 0:
            raise mdsExceptions.TclFAILED_ESSENTIAL

        status = BASLERACA.baslerLib.readInternalTemperature(self.handle)
        if status < 0:
            BASLERACA.baslerLib.getLastError(self.handle, self.error)
            Data.execute(
                'DevLogErr($1,$2)', self.nid,
                'Cannot Read Internal Temperature : ' + self.error.raw)
            raise mdsExceptions.TclFAILED_ESSENTIAL

        self.saveInfo()
        return 1

##########start acquisition############################################################################

    def startAcquisition(self):
        if self.restoreInfo() == 0:
            raise mdsExceptions.TclFAILED_ESSENTIAL

#Module in acquisition check
        try:
            self.restoreWorker()
            if (self.worker != None and self.worker.isAlive()):
                self.debugPrint("Stop acquisition Thread...")
                self.stopAcquisition()
                self.debugPrint("Initialize...")
                self.init()
                self.restoreInfo()
        except:
            pass

        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 = BASLERACA.baslerLib.startAcquisition(self.handle,
                                                      byref(width),
                                                      byref(height),
                                                      byref(payloadSize))
        if status < 0:
            BASLERACA.baslerLib.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("OK!")
        self.worker.configure(self)
        self.saveWorker()
        self.worker.start()
        return 1

##########stop acquisition############################################################################

    def stopAcquisition(self):
        if self.restoreWorker():
            self.worker.stop()
        return 1

##########software trigger (start saving in mdsplus)############################################

    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
Esempio n. 6
0
class PTGREY(Device):
    """PTGREY NEW Camera"""
    parts = [  # offset nid
        {'path': ':IP_NAME', 'type': 'text', 'value': '192.168.100.18'},  # 1
        {'path': ':COMMENT', 'type': 'text'},

        {'path': '.FRAME', 'type': 'structure'},  # 3
        {'path': '.FRAME:X', 'type': 'numeric', 'value': 0},
        {'path': '.FRAME:Y', 'type': 'numeric', 'value': 0},
        {'path': '.FRAME:WIDTH', 'type': 'numeric', 'value': 1936},
        {'path': '.FRAME:HEIGHT', 'type': 'numeric', 'value': 1464},
        {'path': '.FRAME:PIXEL_FORMAT', 'type': 'text', 'value': 'Mono16'},

        {'path': '.CAM_SETUP', 'type': 'structure'},  # 9
        {'path': '.CAM_SETUP:GAIN_AUTO', 'type': 'text', 'value': 'Off'},
        {'path': '.CAM_SETUP:GAIN', 'type': 'numeric', 'value': 0},
        {'path': '.CAM_SETUP:GAMMA_EN', 'type': 'text', 'value': 'Off'},
        {'path': '.CAM_SETUP:EXP_AUTO', 'type': 'text', 'value': 'Off'},
        {'path': '.CAM_SETUP:EXPOSURE', 'type': 'numeric', 'value': 800E3},

        {'path': '.TIMING', 'type': 'structure'},  # 15
        {'path': '.TIMING:TRIG_MODE', 'type': 'text', 'value': 'INTERNAL'},
        {'path': '.TIMING:TRIG_SOURCE', 'type': 'numeric'},
        {'path': '.TIMING:TIME_BASE', 'type': 'numeric'},
        {'path': '.TIMING:FRAME_RATE', 'type': 'numeric', 'value': 1},
        {'path': '.TIMING:BURST_DUR', 'type': 'numeric', 'value': 5},
        {'path': '.TIMING:SKIP_FRAME', 'type': 'numeric', 'value': 0},

        {'path': '.STREAMING', 'type': 'structure'},  # 22
        {'path': '.STREAMING:MODE', 'type': 'text', 'value': 'Stream and Store'},
        {'path': '.STREAMING:SERVER', 'type': 'text', 'value': 'localhost'},
        {'path': '.STREAMING:PORT', 'type': 'numeric', 'value': 8888},
        {'path': '.STREAMING:AUTOSCALE', 'type': 'text', 'value': 'NO'},
        {'path': '.STREAMING:LOLIM', 'type': 'numeric', 'value': 0},
        {'path': '.STREAMING:HILIM', 'type': 'numeric', 'value': 4095},
        {'path': '.STREAMING:ADJROIX', 'type': 'numeric', 'value': 0},
        {'path': '.STREAMING:ADJROIY', 'type': 'numeric', 'value': 0},
        {'path': '.STREAMING:ADJROIW', 'type': 'numeric', 'value': 1936},
        {'path': '.STREAMING:ADJROIH', 'type': 'numeric', 'value': 1464},

        {'path': ':FRAMES', 'type': 'signal', 'options': (
            'no_write_model', 'no_compress_on_put')},
        {'path': ':FRAMES_METAD', 'type': 'signal', 'options': (
            'no_write_model', 'no_compress_on_put')},
        {'path': ':FRAME0_TIME', 'type': 'numeric', 'value': 0}]

    parts.append({'path': ':INIT_ACT', 'type': 'action',
                  'valueExpr': "Action(Dispatch('CAMERA_SERVER','PULSE_PREPARATION',50,None),Method(None,'init',head))",
                  'options': ('no_write_shot',)})
    parts.append({'path': ':START_ACT', 'type': 'action',
                  'valueExpr': "Action(Dispatch('CAMERA_SERVER','INIT',50,None),Method(None,'startAcquisition',head))",
                  'options': ('no_write_shot',)})
    parts.append({'path': ':STOP_ACT', 'type': 'action',
                  'valueExpr': "Action(Dispatch('CAMERA_SERVER','STORE',50,None),Method(None,'stopAcquisition',head))",
                  'options': ('no_write_shot',)})

    handle = c_int(-1)
    handles = {}
    workers = {}
    ptgreyLib = None
    mdsLib = None
    streamLib = None

    error = create_string_buffer(version.tobytes(''), 512)

    def debugPrint(self, msg="", obj=""):
        print("------ DEBUG  " + self.name + ":" + msg, obj)

    """Asynchronous readout internal class"""
    class AsynchStore(Thread):

        def configure(self, device):
            self.device = device
            self.frameIdx = 0
            self.stopReq = False

        def run(self):

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

            status = PTGREY.ptgreyLib.startFramesAcquisition(
                self.device.handle)
            if status < 0:
                PTGREY.ptgreyLib.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("Acquisition thread ended")
            self.device.removeInfo()

        def stop(self):
            self.device.debugPrint("STOP frames acquisition loop")
            status = PTGREY.ptgreyLib.stopFramesAcquisition(self.device.handle)
            if status < 0:
                PTGREY.ptgreyLib.getLastError(
                    self.device.handle, self.device.error)
                Data.execute('DevLogErr($1,$2)', self.device.nid,
                             'Cannot stop frames acquisition : ' + self.device.error.raw)

    def saveWorker(self):
        PTGREY.workers[self.nid] = self.worker

###save Info###
# saveInfo and restoreInfo allow to manage multiple occurrences of camera devices
# and to avoid opening and closing devices handles
    def saveInfo(self):
        PTGREY.handles[self.nid] = self.handle

###restore worker###
    def restoreWorker(self):
        if self.nid in PTGREY.workers.keys():
            self.worker = PTGREY.workers[self.nid]
            return 1
        else:
            Data.execute('DevLogErr($1,$2)', self.nid,
                         'Cannot restore worker!!')
            raise mdsExceptions.TclFAILED_ESSENTIAL

###check worker###
    def checkWorker(self):  # FM 20191114
        if self.nid in PTGREY.workers.keys():
            self.debugPrint('CHECK WORKER: found')
            return 1
        else:
            self.debugPrint('CHECK WORKER: NOT found')
            return 0

###check info###
    def checkInfo(self):  # FM 20191114
        if self.nid in PTGREY.handles.keys():
            self.debugPrint('CHECK INFO: found')
            return 1
        else:
            self.debugPrint('CHECK INFO: NOT found')
            return 0


# restore info###   (returned value 0:error 1:camera opened 2:camera was already opened)
    def restoreInfo(self):
        self.debugPrint("restore Info")
        try:
            if PTGREY.ptgreyLib is None:
                libName = "libptgrey.so"
                PTGREY.ptgreyLib = CDLL(libName)
                self.debugPrint(obj=PTGREY.ptgreyLib)
            if PTGREY.mdsLib is None:
                libName = "libcammdsutils.so"
                PTGREY.mdsLib = CDLL(libName)
                self.debugPrint(obj=PTGREY.mdsLib)
            if PTGREY.streamLib is None:
                libName = "libcamstreamutils.so"
                PTGREY.streamLib = CDLL(libName)
                self.debugPrint(obj=PTGREY.streamLib)
        except:
            Data.execute('DevLogErr($1,$2)', self.nid,
                         'Cannot load library : ' + libName)
            raise mdsExceptions.TclFAILED_ESSENTIAL

        if self.checkInfo():
            self.handle = PTGREY.handles[self.nid]
            return 2
        else:
            try:
                name = self.ip_name.data()
            except:
                Data.execute('DevLogErr($1,$2)', self.nid,
                             'Missing device name')
                raise mdsExceptions.TclFAILED_ESSENTIAL

            self.debugPrint("Opening Camera")
            self.handle = c_int(-1)
            status = PTGREY.ptgreyLib.PGopen(
                c_char_p(name), byref(self.handle))
            if status < 0:
                PTGREY.ptgreyLib.getLastError(self.handle, self.error)
                Data.execute('DevLogErr($1,$2)', self.nid,
                             'Cannot open device ' + name + ' ('+self.error.raw+')')
                raise mdsExceptions.TclFAILED_ESSENTIAL
            self.debugPrint("Connected ", status)

            self.saveInfo()

        return 1

###remove info###
    def removeInfo(self):
        try:
            status = PTGREY.ptgreyLib.PGclose(self.handle)  # close camera
            if status < 0:
                PTGREY.ptgreyLib.getLastError(self.handle, self.error)
                Data.execute('DevLogErr($1,$2)', self.nid,
                             'Cannot close camera : ' + self.error.raw)
        except:
            self.debugPrint('ERROR in ptgreyLib.PGclose()')

        try:
            del(PTGREY.handles[self.nid])
            self.debugPrint('Camera Info removed.')
        except:
            self.debugPrint('ERROR trying to remove info')


###remove worker###
    def removeWorker(self):
        try:
            del(PTGREY.workers[self.nid])
            self.debugPrint('Camera Worker removed.')
        except:
            self.debugPrint('ERROR trying to remove Worker')


##########init############################################################################
    def init(self):
        if self.checkWorker():  # FM 20191114
            self.debugPrint('Cannot dispatch init during acquisition/storing.')
            return 1
        if self.restoreInfo() == 0:
            raise mdsExceptions.TclFAILED_ESSENTIAL

        try:
            self.frames.setCompressOnPut(False)
        except:
            Data.execute('DevLogErr($1,$2)', self.nid,
                         'Cannot disable automatic compress on put for frames node')
            raise mdsExceptions.TclFAILED_ESSENTIAL
        try:
            self.frames_metad.setCompressOnPut(False)
        except:
            Data.execute('DevLogErr($1,$2)', self.nid,
                         'Cannot disable automatic compress on put for frames_metad node')
            raise mdsExceptions.TclFAILED_ESSENTIAL


# Gain
        try:
            gain = self.cam_setup_gain.data()
        except:
            Data.execute('DevLogErr($1,$2)', self.nid, 'Invalid gain value')
            raise mdsExceptions.TclFAILED_ESSENTIAL
        status = PTGREY.ptgreyLib.setGain(self.handle, c_float(gain))
        if status < 0:
            PTGREY.ptgreyLib.getLastError(self.handle, self.error)
            Data.execute('DevLogErr($1,$2)', self.nid,
                         'Cannot Set Gain : ' + self.error.raw)
            raise mdsExceptions.TclFAILED_ESSENTIAL


# Gain Auto
        try:
            gainAuto = self.cam_setup_gain_auto.data()
        except:
            Data.execute('DevLogErr($1,$2)', self.nid,
                         'Invalid gain auto value')
            raise mdsExceptions.TclFAILED_ESSENTIAL
        status = PTGREY.ptgreyLib.setGainAuto(self.handle, c_char_p(gainAuto))
        if status < 0:
            PTGREY.ptgreyLib.getLastError(self.handle, self.error)
            Data.execute('DevLogErr($1,$2)', self.nid,
                         'Cannot Set Gain Auto : ' + self.error.raw)
            raise mdsExceptions.TclFAILED_ESSENTIAL

# Gamma Enable
        try:
            gammaEnable = self.cam_setup_gamma_en.data()
        except:
            Data.execute('DevLogErr($1,$2)', self.nid,
                         'Invalid gamma enable value')
            raise mdsExceptions.TclFAILED_ESSENTIAL
        status = PTGREY.ptgreyLib.setGammaEnable(
            self.handle, c_char_p(gammaEnable))
        if status < 0:
            PTGREY.ptgreyLib.getLastError(self.handle, self.error)
            Data.execute('DevLogErr($1,$2)', self.nid,
                         'Cannot Set Gamma Enable : ' + self.error.raw)
            raise mdsExceptions.TclFAILED_ESSENTIAL


# Exposure Auto
        try:
            exposureAuto = self.cam_setup_exp_auto.data()
        except:
            Data.execute('DevLogErr($1,$2)', self.nid,
                         'Invalid exposure auto value')
            raise mdsExceptions.TclFAILED_ESSENTIAL
        status = PTGREY.ptgreyLib.setExposureAuto(
            self.handle, c_char_p(exposureAuto))
        if status < 0:
            PTGREY.ptgreyLib.getLastError(self.handle, self.error)
            Data.execute('DevLogErr($1,$2)', self.nid,
                         'Cannot Set Exposure Auto : ' + self.error.raw)
            raise mdsExceptions.TclFAILED_ESSENTIAL

# Exposure
        try:
            exposure = self.cam_setup_exposure.data()
        except:
            Data.execute('DevLogErr($1,$2)', self.nid,
                         'Invalid exposure value')
            raise mdsExceptions.TclFAILED_ESSENTIAL
        status = PTGREY.ptgreyLib.setExposure(self.handle, c_float(exposure))
        if status < 0:
            PTGREY.ptgreyLib.getLastError(self.handle, self.error)
            Data.execute('DevLogErr($1,$2)', self.nid,
                         'Cannot Set Exposure : ' + self.error.raw)
            raise mdsExceptions.TclFAILED_ESSENTIAL


# READ CAMERA TEMPERATURE
        status = PTGREY.ptgreyLib.readInternalTemperature(self.handle)
        if status < 0:
            PTGREY.ptgreyLib.getLastError(self.handle, self.error)
            Data.execute('DevLogErr($1,$2)', self.nid,
                         'Cannot Read Internal Temperature : ' + self.error.raw)
            raise mdsExceptions.TclFAILED_ESSENTIAL


# Pixel Format
        try:
            pixelFormat = self.frame_pixel_format.data()
        except:
            Data.execute('DevLogErr($1,$2)', self.nid,
                         'Invalid pixel format value')
            raise mdsExceptions.TclFAILED_ESSENTIAL
        status = PTGREY.ptgreyLib.setPixelFormat(
            self.handle, c_char_p(pixelFormat))
        if status < 0:
            PTGREY.ptgreyLib.getLastError(self.handle, self.error)
            Data.execute('DevLogErr($1,$2)', self.nid,
                         'Cannot Set Pixel Format : ' + self.error.raw)
            raise mdsExceptions.TclFAILED_ESSENTIAL


# Frame Rate
        try:
            frameRate = self.timing_frame_rate.data()
        except:
            Data.execute('DevLogErr($1,$2)', self.nid,
                         'Invalid frame rate value')
            raise mdsExceptions.TclFAILED_ESSENTIAL
        status = PTGREY.ptgreyLib.setFrameRate(
            self.handle, c_double(frameRate))
        if status < 0:
            PTGREY.ptgreyLib.getLastError(self.handle, self.error)
            Data.execute('DevLogErr($1,$2)', self.nid,
                         'Cannot Set Frame Rate : ' + self.error.raw)
            raise mdsExceptions.TclFAILED_ESSENTIAL
        self.debugPrint('fede4')


# Frame Area
        try:
            x = self.frame_x.data()
            y = self.frame_y.data()
            width = self.frame_width.data()
            height = self.frame_height.data()
        except:
            Data.execute('DevLogErr($1,$2)', self.nid,
                         'Invalid Frame Area value')
            raise mdsExceptions.TclFAILED_ESSENTIAL

#      status = PTGREY.ptgreyLib.getReadoutArea(self.handle, byref(x), byref(y), byref(width), byref(height))
#      if status < 0:
#        PTGREY.ptgreyLib.getLastError(self.handle, self.error)
#        Data.execute('DevLogErr($1,$2)', self.nid, 'Cannot Set Readout Area : ' + self.error.raw)
#        raise mdsExceptions.TclFAILED_ESSENTIAL

        status = PTGREY.ptgreyLib.setReadoutArea(
            self.handle, c_int(x), c_int(y), c_int(width), c_int(height))
        if status < 0:
            PTGREY.ptgreyLib.getLastError(self.handle, self.error)
            Data.execute('DevLogErr($1,$2)', self.nid,
                         'Cannot Set Frame Area : ' + self.error.raw)
            raise mdsExceptions.TclFAILED_ESSENTIAL


# Focal Length
#      try:
#         focalLength = self.cam_setup_focal_length.data()
#      except:
#        Data.execute('DevLogErr($1,$2)', self.nid, 'Invalid Focal Length value')
#        raise mdsExceptions.TclFAILED_ESSENTIAL


# Frame Trigger mode
        try:
            burstDuration = self.timing_burst_dur.data()
        except:
            Data.execute('DevLogErr($1,$2)', self.nid,
                         'Invalid acquisition duration value')
            raise mdsExceptions.TclFAILED_ESSENTIAL

        try:
            triggerMode = self.timing_trig_mode.data()
        except:
            Data.execute('DevLogErr($1,$2)', self.nid,
                         'Invalid trigger mode value')
            raise mdsExceptions.TclFAILED_ESSENTIAL

        try:
            trigSource = self.timing_trig_source.data()
        except:
            if triggerMode == 'EXTERNAL':
                Data.execute('DevLogErr($1,$2)', self.nid,
                             'Invalid trigger source value')
                raise mdsExceptions.TclFAILED_ESSENTIAL
            else:
                trigSource = array([0.])

        self.debugPrint("OK " + triggerMode)
        if triggerMode == 'EXTERNAL':  # 0=internal  1=external trigger
            trigModeCode = c_int(1)
        else:
            trigSource = array([0.])
            trigModeCode = c_int(0)

        numTrigger = trigSource.size
        self.debugPrint("Trigger Num.: ", numTrigger)
        self.debugPrint("Trigger Source: ", trigSource)

        timeBase = Data.compile(" $ : $ + $ :(zero( size( $ ), 0.) + 1.) * 1./$",
                                trigSource, trigSource, burstDuration, trigSource, frameRate)

        self.debugPrint("Timebase Data = " + Data.decompile(timeBase))

        self.timing_time_base.putData(timeBase)
        status = PTGREY.ptgreyLib.setTriggerMode(
            self.handle, trigModeCode, c_double(burstDuration), numTrigger)
        if status < 0:
            PTGREY.ptgreyLib.getLastError(self.handle, self.error)
            Data.execute('DevLogErr($1,$2)', self.nid,
                         'Cannot Set Internal/External Trigger : ' + self.error.raw)
            raise mdsExceptions.TclFAILED_ESSENTIAL


# Streaming
        try:
            streamingMode = self.streaming_mode.data()
        except:
            Data.execute('DevLogErr($1,$2)', self.nid,
                         'Invalid streaming mode setup')
            raise mdsExceptions.TclFAILED_ESSENTIAL

        if streamingMode == 'Stream and Store':
            streamingEnabled = c_int(1)
            storeEnabled = c_int(1)
        elif streamingMode == 'Only Stream':
            streamingEnabled = c_int(1)
            storeEnabled = c_int(0)
        else:  # streamingMode == 'Only Store':
            streamingEnabled = c_int(0)
            storeEnabled = c_int(1)

        if 1:  # streamingEnabled   (FM: setStreamingMode use this flag)
            try:
                if self.streaming_autoscale.data() == 'YES':
                    autoAdjustLimit = c_int(1)
                else:
                    autoAdjustLimit = c_int(0)
            except:
                Data.execute('DevLogErr($1,$2)', self.nid,
                             'Invalid streaming autoscale parameter value')
                raise mdsExceptions.TclFAILED_ESSENTIAL

            try:
                lowLim = c_int(self.streaming_lolim.data())
            except:
                Data.execute('DevLogErr($1,$2)', self.nid,
                             'Invalid streaming low temperature limit parameter value')
                raise mdsExceptions.TclFAILED_ESSENTIAL

            try:
                highLim = c_int(self.streaming_hilim.data())
            except:
                Data.execute('DevLogErr($1,$2)', self.nid,
                             'Invalid streaming high temperature limit parameter value')
                raise mdsExceptions.TclFAILED_ESSENTIAL

            try:
                streamingPort = c_int(self.streaming_port.data())
            except:
                Data.execute('DevLogErr($1,$2)', self.nid,
                             'Invalid streaming port parameter value')
                raise mdsExceptions.TclFAILED_ESSENTIAL

            try:
                streamingServer = self.streaming_server.data()
            except:
                Data.execute('DevLogErr($1,$2)', self.nid,
                             'Invalid streaming server parameter value')
                raise mdsExceptions.TclFAILED_ESSENTIAL

            try:
                adjRoiX = c_int(self.streaming_adjroix.data())
            except:
                Data.execute('DevLogErr($1,$2)', self.nid,
                             'Invalid streaming ROI x value')
                raise mdsExceptions.TclFAILED_ESSENTIAL

            try:
                adjRoiY = c_int(self.streaming_adjroiy.data())
            except:
                Data.execute('DevLogErr($1,$2)', self.nid,
                             'Invalid streaming ROI y value')
                raise mdsExceptions.TclFAILED_ESSENTIAL

            try:
                adjRoiW = c_int(self.streaming_adjroiw.data())
            except:
                Data.execute('DevLogErr($1,$2)', self.nid,
                             'Invalid streaming ROI width value')
                raise mdsExceptions.TclFAILED_ESSENTIAL

            try:
                adjRoiH = c_int(self.streaming_adjroih.data())
            except:
                Data.execute('DevLogErr($1,$2)', self.nid,
                             'Invalid streaming ROI height value')
                raise mdsExceptions.TclFAILED_ESSENTIAL

            self.debugPrint("lowLim ", lowLim)
            self.debugPrint("highLim ", highLim)
#          self.debugPrint("frameTempUnitCode ", frameTempUnitCode)
            self.debugPrint("streamingPort ", streamingPort)
            self.debugPrint("streamingServer ", streamingServer)
            self.debugPrint("streaming adj ROI x ", adjRoiX)
            self.debugPrint("streaming adj ROI y  ", adjRoiY)
            self.debugPrint("streaming adj ROI w  ", adjRoiW)
            self.debugPrint("streaming adj ROI h  ", adjRoiH)
            # FM: recover device name and pass it to setStreaming to overlay text on frame!!!
            deviceName = str(self).rsplit(":", 1)
            deviceName = deviceName[1]
            self.debugPrint("Device Name ", deviceName)

        status = PTGREY.ptgreyLib.setStreamingMode(self.handle, streamingEnabled,  autoAdjustLimit, c_char_p(
            streamingServer), streamingPort,  lowLim,  highLim, adjRoiX, adjRoiY, adjRoiW, adjRoiH, c_char_p(deviceName))
        if status < 0:
            PTGREY.ptgreyLib.getLastError(self.handle, self.error)
            Data.execute('DevLogErr($1,$2)', self.nid,
                         'Cannot execute streaming setup mode : ' + self.error.raw)
            raise mdsExceptions.TclFAILED_ESSENTIAL


# Acquisition

        try:
            acqSkipFrameNumber = c_int(self.timing_skip_frame.data())
        except:
            Data.execute('DevLogErr($1,$2)', self.nid,
                         'Invalid acquisition decimation value')
            raise mdsExceptions.TclFAILED_ESSENTIAL

        status = PTGREY.ptgreyLib.setAcquisitionMode(
            self.handle, storeEnabled, acqSkipFrameNumber)
        if status < 0:
            PTGREY.ptgreyLib.getLastError(self.handle, self.error)
            Data.execute('DevLogErr($1,$2)', self.nid,
                         'Cannot execute acquisition setup mode : ' + self.error.raw)
            raise mdsExceptions.TclFAILED_ESSENTIAL

        try:
            treePtr = c_void_p(0)
            status = PTGREY.mdsLib.camOpenTree(
                c_char_p(self.getTree().name), c_int(self.getTree().shot), byref(treePtr))
            if status == -1:
                Data.execute('DevLogErr($1,$2)', self.nid, 'Cannot open tree')
                raise mdsExceptions.TclFAILED_ESSENTIAL
        except:
            traceback.print_exc()

        framesNid = self.frames.nid
        timebaseNid = self.timing_time_base.nid
        framesMetadNid = self.frames_metad.nid
        frame0TimeNid = self.frame0_time.nid

        status = PTGREY.ptgreyLib.setTreeInfo(
            self.handle,  treePtr,  framesNid,  timebaseNid,  framesMetadNid, frame0TimeNid)
        if status < 0:
            PTGREY.ptgreyLib.getLastError(self.handle, self.error)
            Data.execute('DevLogErr($1,$2)', self.nid,
                         'Cannot execute set tree info : '+self.error.raw)
            raise mdsExceptions.TclFAILED_ESSENTIAL

        self.debugPrint('Init action completed.')
        return 1


# CHANGE GAIN
    def changeGain(self):
        # 0:error 1:camera opened 2:camera was already opened
        restoreRes = self.restoreInfo()
        if restoreRes == 0:
            raise mdsExceptions.TclFAILED_ESSENTIAL

        status = PTGREY.ptgreyLib.setGain(
            self.handle, c_float(self.cam_setup_gain.data()))
        if status < 0:
            PTGREY.ptgreyLib.getLastError(self.handle, self.error)
            Data.execute('DevLogErr($1,$2)', self.nid,
                         'Cannot change Gain value : ' + self.error.raw)
            raise mdsExceptions.TclFAILED_ESSENTIAL

        if restoreRes == 1:  # camera must be closed because has been opened only for this action
            self.removeInfo()

        return 1


# CHANGE EXPOSURE
    def changeExposure(self):
        # 0:error 1:camera opened 2:camera was already opened
        restoreRes = self.restoreInfo()
        if restoreRes == 0:
            raise mdsExceptions.TclFAILED_ESSENTIAL

        status = PTGREY.ptgreyLib.setExposure(
            self.handle, c_float(self.cam_setup_exposure.data()))
        if status < 0:
            PTGREY.ptgreyLib.getLastError(self.handle, self.error)
            Data.execute('DevLogErr($1,$2)', self.nid,
                         'Cannot change Exposure value : ' + self.error.raw)
            raise mdsExceptions.TclFAILED_ESSENTIAL

        if restoreRes == 1:  # camera must be closed because has been opened only for this action
            self.removeInfo()

        return 1


# READ INTERNAL TEMPERATURE
    def readTemperature(self):
        # 0:error 1:camera opened 2:camera was already opened
        restoreRes = self.restoreInfo()
        if restoreRes == 0:
            raise mdsExceptions.TclFAILED_ESSENTIAL

        status = PTGREY.ptgreyLib.readInternalTemperature(self.handle)
        if status < 0:
            PTGREY.ptgreyLib.getLastError(self.handle, self.error)
            Data.execute('DevLogErr($1,$2)', self.nid,
                         'Cannot Read Internal Temperature : ' + self.error.raw)
            raise mdsExceptions.TclFAILED_ESSENTIAL

        if restoreRes == 1:  # camera must be closed because has been opened only for this action
            self.removeInfo()

        return 1


##########start acquisition############################################################################
    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


##########stop acquisition############################################################################
    def stopAcquisition(self):
        if self.checkWorker():  # FM 20191114
            self.restoreWorker()
            self.worker.stop()
            self.removeWorker()
        else:
            self.debugPrint(
                "Camera is not in acquisition. Action not performed.")
        return 1


##########software trigger (start saving in mdsplus)############################################
    def swTrigger(self):
        if not self.checkWorker():  # FM 20191114
            self.debugPrint('Camera not in acquisition. Action not performed.')
            return 1
        if not self.checkInfo():  # FM 20191114
            self.debugPrint('Camera not opened. Action not performed.')
            return 1
        if self.restoreInfo() == 0:
            raise mdsExceptions.TclFAILED_ESSENTIAL

        self.debugPrint('SOFTWARE TRIGGER')

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

        return 1