Пример #1
0
    def test_info(self):
        p0 = Parameter('test', 0, int, 'some info')
        self.assertEqual(p0.info['test'], 'some info')

        parameters = Parameter([
            Parameter('test1', 0, int, 'test parameter (int)'),
            Parameter('test2' ,
                      [Parameter('test2_1', 'string', str, 'test parameter (str)'),
                       Parameter('test2_2', 0.0, float, 'test parameter (float)')
                       ])
        ])

        print(parameters.info)
        print(parameters['test1'].info)

        self.assertEqual(parameters.info['test2'], {'test2_1': 'test parameter (str)', 'test2_2': 'test parameter (float)'})
        self.assertEqual(parameters.info['test1'], 'test parameter (int)')
        self.assertEqual(parameters.info['test2']['test2_1'], 'test parameter (str)')
Пример #2
0
    def test_parameter_single(self):
        # init

        p0 = Parameter('param', 0, int, 'integer')
        self.assertEqual(p0.info, 'integer')

        p0 = Parameter('param', 0.0, float, 'float')
        p0 = Parameter('param', '0', str, 'string')
        p0 = Parameter('param', 0, [0, 1, 2, 3], 'list')

        p0 = Parameter('param', 0)
        self.assertEqual(p0.valid_values['param'], int)
        p0 = Parameter('param', 0.0)
        self.assertEqual(p0.valid_values['param'], float)
        p0 = Parameter('param', '0')
        self.assertEqual(p0.valid_values['param'], str)
        p0 = Parameter('param', [0, 1, 2, 3])
        self.assertEqual(p0.valid_values['param'], list)

        p0 = Parameter('param', 0, int, 'integer')
        self.assertEquals(p0, {'param': 0})
        self.assertEquals(p0['param'], 0)

        p0 = Parameter({'param': 1})
        self.assertEquals(p0, {'param': 1})

        #update

        p0.update({'param': 2})
        self.assertEquals(p0, {'param': 2})

        with self.assertRaises(KeyError):
            p0.update({'paramX': 2})

        with self.assertRaises(AssertionError):
            Parameter('param1', 0, [1, 2, 3])

        with self.assertRaises(AssertionError):
            Parameter('pa', 2.2, int, 'type is int but value is float!')

        p0 = Parameter('param', [0, 1, 2, 3])
        p0.update({'param': [0, 5]})

        with self.assertRaises(AssertionError):
            p0.update({'param': 0})
Пример #3
0
    def test_parameter_multi(self):

        # init
        p1 = Parameter('param1', 1)
        p2 = Parameter('param2', 2)
        p0 = Parameter('param0', [p1, p2])

        self.assertEquals(p0, {'param0': {'param1': 1, 'param2': 2}})

        #update
        p0['param0'] = {'param1': 3}
        self.assertEquals(p0, {'param0': {'param1': 3, 'param2': 2}})
        self.assertEquals(p0['param0'], {'param1': 3, 'param2': 2})
        self.assertEquals(p0['param0']['param1'], 3)

        with self.assertRaises(KeyError):
            p0.update({'param1': 4})

        p0['param0'].update(Parameter('param2', 7))
        self.assertEquals(p0['param0'], {'param1': 3, 'param2': 7})

        p0['param0'].update({'param2': 8})
        self.assertEquals(p0['param0'], {'param1': 3, 'param2': 8})

        p0['param0'] = {'param1': 5, 'param2': 6}
        self.assertEquals(p0['param0'], {'param1': 5, 'param2': 6})

        self.assertEquals(p0['param0']['param1'], 5)
        self.assertEquals(p0['param0']['param2'], 6)

        # p0['param0'].update(Parameter('param2', 's'))
        #
        # p0['param0'].update(Parameter('param3', 's'))
        #

        # p0['param0'].update({'param2', 's'})

        with self.assertRaises(KeyError):
            print(p0['param3'])

        p1 = Parameter('param1', 1)
        p2 = Parameter('param2', 2)
        p0 = Parameter('param0', [p1, p2])

        with self.assertRaises(AssertionError):
            p0['param0'] = [0, 1]  # asign list of different type

            p1 = Parameter('param1', 1)
            p2 = Parameter('param2', 2)
            p3 = Parameter('param2', 3)
            p0 = Parameter('param0', [p1, p2])

            p0['param0'] = [p1, p3]

        with self.assertRaises(AssertionError):
            p1 = Parameter('param1', 1)
            p2 = Parameter('param2', 2)
            p3 = Parameter('param3', 3)
            p0 = Parameter('param0', [p1, p2])

            p0['param0'] = [p1, p3]

        with self.assertRaises(AssertionError):
            p1 = Parameter('param1', 1)
            p2 = Parameter('param2', 2)
            p3 = Parameter('param2', 's')
            p0 = Parameter('param0', [p1, p2])

            p0['param0'] = [p1, p3]
Пример #4
0
    def test_parameter_multi_v2(self):
        '''
        test for next generation parameter object
        Args:
            self:

        Returns:

        '''

        p0 = Parameter({'p1': 1, 'p2': 2})

        self.assertEqual(p0, {'p2': 2, 'p1': 1})

        with self.assertRaises(KeyError):
            p0['p3']

        with self.assertRaises(KeyError):
            p0.update({'p3': 2})

        with self.assertRaises(AssertionError):
            p0.update({'p1': 2.0})

        p0 = Parameter('p0', 0)
        p1 = Parameter('p1', 1)
        p2 = Parameter([p0, p1])

        self.assertEqual(p2, {'p0': 0, 'p1': 1})

        p2['p0'] = 44
        self.assertEqual(p2, {'p0': 44, 'p1': 1})

        p2.update({'p0': 45})
        self.assertEqual(p2, {'p0': 45, 'p1': 1})

        p0['p0'] = 555
        p2.update(p0)
        self.assertEqual(p2, {'p0': 555, 'p1': 1})

        # check for nested parameters
        p0 = Parameter('p0', 0, int, 'test parameter (int)')
        p1 = Parameter('p1', 'string', str, 'test parameter (str)')
        p2 = Parameter('p2', 0.0, float, 'test parameter (float)')
        p12 = Parameter('p12', [p1, p2])

        pall = Parameter([p0, p12])

        self.assertEqual(pall, {'p0': 0, 'p12': {'p2': 0.0, 'p1': 'string'}})

        parameters = Parameter([
            Parameter('test1', 0, int, 'test parameter (int)'),
            Parameter('test2', [
                Parameter('test2_1', 'string', str, 'test parameter (str)'),
                Parameter('test2_2', 0.0, float, 'test parameter (float)')
            ])
        ])

        self.assertIsInstance(parameters['test2'], Parameter)

        with self.assertRaises(AssertionError):
            parameters['test1'] = 0.2

        with self.assertRaises(AssertionError):
            parameters['test2'] = 0.2

        with self.assertRaises(AssertionError):
            parameters['test2']['test2_1'] = 0.2

        with self.assertRaises(AssertionError):
            parameters['test2']['test2_2'] = 's'
Пример #5
0
class PiezoController(Instrument):

    _DEFAULT_SETTINGS = Parameter([
        Parameter('axis', 'x', ['x', 'y', 'z'], '"x", "y", or "z" axis'),
        Parameter('port', 'COM17', str, 'serial port on which to connect'),
        Parameter('baudrate', 115200, int, 'baudrate of connection'),
        Parameter('timeout', .1, float, 'connection timeout'),
        Parameter('voltage', 0.0, float, 'current voltage')
    ])

    def __init__(self, name = None, settings = None):
        super(PiezoController, self).__init__(name, settings)
        self._is_connected = False
        try:
            self.connect(port = self.settings['port'], baudrate = self.settings['baudrate'], timeout = self.settings['timeout'])
        except Exception:
            print('No Piezo Controller Detected')
            raise

    def connect(self, port, baudrate, timeout):
            self.ser = serial.Serial(port = port, baudrate = baudrate, timeout = timeout)
            self.ser.write('echo=0\r') #disables repetition of input commands in output
            self.ser.readlines()
            self._is_connected = True

    def update(self, settings):
        super(PiezoController, self).update(settings)
        for key, value in settings.iteritems():
            if key == 'voltage':
                self.set_voltage(value)
            elif key == 'voltage_limit':
                raise EnvironmentError('Voltage limit cannot be set in software. Change physical switch on back of device')

    @property
    def _PROBES(self):
        '''

        Returns: a dictionary that contains the values that can be read from the instrument
        the key is the name of the value and the value of the dictionary is an info

        '''
        return {
            'voltage': 'the voltage on the current channel',
            'voltage_limit': 'the maximum voltage that can be applied to the channel. must be physically switched on the back of the controller.',
        }

    def read_probes(self, key):
        '''
        requestes value from the instrument and returns it
        Args:
            key: name of requested value

        Returns: reads values from instrument

        '''
        assert key in self._PROBES.keys()
        assert isinstance(key, str)

        if key in ['voltage']:
            self.ser.write(self.settings['axis'] + 'voltage?\r')
            xVoltage = self.ser.readline()
            return(float(xVoltage[2:-2].strip()))
        elif key in ['voltage_limit']:
            self.ser.write('vlimit?\r')
            vlimit = self.ser.readline()
            return vlimit[2:-3].strip()

    @property
    def is_connected(self):
        try:
            self.voltage
            return True
        except serial.serialutil.SerialTimeoutException:
            return False

    def __del__(self):
        if self._is_connected:
            self.ser.close()

    def set_voltage(self, voltage):
        self.ser.write(self.settings['axis'] + 'voltage=' + str(voltage) + '\r')
        successCheck = self.ser.readlines()
        # print(successCheck)
        # * and ! are values returned by controller on success or failure respectively
        if(successCheck[0] == '*'):
            print('Voltage set')
        elif(successCheck[0] == '!'):
            message = 'Setting voltage failed. Confirm that device is properly connected and a valid voltage was entered'
            raise ValueError(message)
Пример #6
0
    def  test_parameter_single(self):
        # init

        p0 = Parameter('param', 0, int, 'integer')
        self.assertEqual(p0.info, 'integer')

        p0 = Parameter('param', 0.0, float, 'float')
        p0 = Parameter('param', '0', str, 'string')
        p0 = Parameter('param', 0, [0,1,2,3], 'list')



        p0 = Parameter('param', 0)
        self.assertEqual(p0.valid_values['param'], int)
        p0 = Parameter('param', 0.0)
        self.assertEqual(p0.valid_values['param'], float)
        p0 = Parameter('param', '0')
        self.assertEqual(p0.valid_values['param'], str)
        p0 = Parameter('param', [0,1,2,3])
        self.assertEqual(p0.valid_values['param'], list)


        p0 = Parameter('param', 0, int, 'integer')
        self.assertEquals(p0,{'param':0})
        self.assertEquals(p0['param'],0)

        p0 = Parameter({'param':  1})
        self.assertEquals(p0,{'param':1})

        #update

        p0.update({'param':2})
        self.assertEquals(p0,{'param':2})

        with self.assertRaises(KeyError):
            p0.update({'paramX':2})


        with self.assertRaises(AssertionError):
            Parameter('param1', 0, [ 1, 2, 3])

        with self.assertRaises(AssertionError):
            Parameter('pa',2.2, int, 'type is int but value is float!')


        p0 = Parameter('param', [0,1,2,3])
        p0.update({'param':[0,5]})

        with self.assertRaises(AssertionError):
            p0.update({'param':0})
Пример #7
0
    def  test_parameter_multi(self):


        # init
        p1 = Parameter('param1', 1)
        p2 = Parameter('param2', 2)
        p0 = Parameter('param0', [p1, p2])

        self.assertEquals(p0 , {'param0': {'param1':1, 'param2':2}})


        #update
        p0['param0'] = {'param1':3}
        self.assertEquals(p0 , {'param0': {'param1':3, 'param2':2}})
        self.assertEquals(p0['param0'] , {'param1':3, 'param2':2})
        self.assertEquals(p0['param0']['param1'] , 3)

        with self.assertRaises(KeyError):
            p0.update({'param1':4})


        p0['param0'].update(Parameter('param2', 7))
        self.assertEquals(p0['param0'], {'param1':3, 'param2':7})

        p0['param0'].update({'param2': 8})
        self.assertEquals(p0['param0'] , {'param1':3, 'param2':8})

        p0['param0'] = {'param1':5, 'param2':6}
        self.assertEquals(p0['param0'] , {'param1':5, 'param2':6})

        self.assertEquals(p0['param0']['param1'] ,5)
        self.assertEquals(p0['param0']['param2'] ,6)

        # p0['param0'].update(Parameter('param2', 's'))
        #
        # p0['param0'].update(Parameter('param3', 's'))
        #

        # p0['param0'].update({'param2', 's'})


        with self.assertRaises(KeyError):
            print(p0['param3'])


        p1 = Parameter('param1', 1)
        p2 = Parameter('param2', 2)
        p0 = Parameter('param0', [p1, p2])


        with self.assertRaises(AssertionError):
            p0['param0'] = [0,1] # asign list of different type



            p1 = Parameter('param1', 1)
            p2 = Parameter('param2', 2)
            p3 = Parameter('param2', 3)
            p0 = Parameter('param0', [p1, p2])


            p0['param0'] = [p1,p3]




        with self.assertRaises(AssertionError):
            p1 = Parameter('param1', 1)
            p2 = Parameter('param2', 2)
            p3 = Parameter('param3', 3)
            p0 = Parameter('param0', [p1, p2])

            p0['param0'] = [p1,p3]



        with self.assertRaises(AssertionError):
            p1 = Parameter('param1', 1)
            p2 = Parameter('param2', 2)
            p3 = Parameter('param2', 's')
            p0 = Parameter('param0', [p1, p2])

            p0['param0'] = [p1,p3]
Пример #8
0
    def  test_parameter_multi_v2(self):
        '''
        test for next generation parameter object
        Args:
            self:

        Returns:

        '''


        p0 = Parameter({'p1' : 1, 'p2' : 2})

        self.assertEqual(p0, {'p2': 2, 'p1': 1})

        with self.assertRaises(KeyError):
            p0['p3']


        with self.assertRaises(KeyError):
            p0.update({'p3': 2})

        with self.assertRaises(AssertionError):
            p0.update({'p1': 2.0})

        p0 = Parameter('p0', 0)
        p1 = Parameter('p1', 1)
        p2 = Parameter([p0,p1])

        self.assertEqual(p2, {'p0': 0, 'p1': 1})


        p2['p0'] = 44
        self.assertEqual(p2, {'p0': 44, 'p1': 1})

        p2.update({'p0': 45 })
        self.assertEqual(p2, {'p0': 45, 'p1': 1})

        p0['p0'] = 555
        p2.update(p0)
        self.assertEqual(p2, {'p0': 555, 'p1': 1})

        # check for nested parameters
        p0 = Parameter('p0', 0, int, 'test parameter (int)')
        p1 = Parameter('p1', 'string', str, 'test parameter (str)')
        p2 = Parameter('p2', 0.0, float, 'test parameter (float)')
        p12 = Parameter('p12', [p1,p2])

        pall = Parameter([p0, p12])

        self.assertEqual(pall, {'p0': 0, 'p12': {'p2': 0.0, 'p1': 'string'}})




        parameters = Parameter([
            Parameter('test1', 0, int, 'test parameter (int)'),
            Parameter('test2' ,
                      [Parameter('test2_1', 'string', str, 'test parameter (str)'),
                       Parameter('test2_2', 0.0, float, 'test parameter (float)')
                       ])
        ])

        self.assertIsInstance(parameters['test2'], Parameter)

        with self.assertRaises(AssertionError):
            parameters['test1'] = 0.2

        with self.assertRaises(AssertionError):
            parameters['test2'] = 0.2

        with self.assertRaises(AssertionError):
            parameters['test2']['test2_1'] = 0.2

        with self.assertRaises(AssertionError):
            parameters['test2']['test2_2'] = 's'
Пример #9
0
class Attocube(Instrument):

    _DEFAULT_SETTINGS = Parameter([
        Parameter('x', [
            Parameter('on', False, [True, False], 'x axis on'),
            Parameter('pos', 0.0, float, 'x axis position in um'),
            Parameter('voltage', 30, float, 'voltage on x axis'),
            Parameter('freq', 1000, float, 'x frequency in Hz')
        ]),
        Parameter('y', [
            Parameter('on', False, [True, False], 'y axis on'),
            Parameter('pos', 0, float, 'y axis position in um'),
            Parameter('voltage', 30, float, 'voltage on y axis'),
            Parameter('freq', 1000, float, 'y frequency in Hz')
        ]),
        Parameter('z', [
            Parameter('on', False, [True, False], 'z axis on'),
            Parameter('pos', 0, float, 'x axis position in um'),
            Parameter('voltage', 30, float, 'voltage on x axis'),
            Parameter('freq', 1000, float, 'x frequency in Hz')
        ])
    ])

    def __init__(self, name=None, settings=None):
        super(Attocube, self).__init__(name, settings)
        try:
            self.attocube = ctypes.WinDLL(
                'C:/Users/Experiment/Downloads/attocube/Software/ANC350_Software_v1.5.15/ANC350_DLL/Win_64Bit/src/anc350v2.dll'
            )
            dll_detected = True
        except WindowsError:
            # make a fake Attocube instrument
            dll_detected = False
        if dll_detected == True:
            try:
                self.pi = PositionerInfo()
                dev_count = self.attocube.PositionerCheck(ctypes.byref(
                    self.pi))
                device_handle = int32()
                self._check_error(
                    self.attocube.PositionerConnect(
                        0, ctypes.byref(device_handle)))
                self._check_error(self.attocube.PositionerClose(device_handle))
            except Exception:
                print('Attocube not detected. Check connection.')

    def update(self, settings):
        super(Attocube, self).update(settings)
        for key, value in settings.iteritems():
            if isinstance(value, dict) and key in ['x', 'y', 'z']:
                for sub_key, sub_value in sorted(value.iteritems()):
                    if sub_key == 'on':
                        self._toggle_axis(self._convert_axis(key), sub_value)
                    elif sub_key == 'pos':
                        self._move_absolute(self._convert_axis(key), sub_value)
                    elif sub_key == 'voltage':
                        self._set_amplitude(self._convert_axis(key), sub_value)
                    elif sub_key == 'freq':
                        self._set_frequency(self._convert_axis(key), sub_value)
                    else:
                        raise ValueError('No such key')
            else:
                raise ValueError('No such key')

    @property
    def _PROBES(self):
        return {
            'x_pos':
            'the position the x direction (with respect to the camera) in um',
            'x_voltage':
            'the voltage of the x direction (with respect to the camera)',
            'x_freq':
            'the frequency of the x direction (with respect to the camera)',
            'x_cap':
            'the capacitance of the piezo in the x direction (with respect to the camera)',
            'y_pos':
            'the position the y direction (with respect to the camera) in um',
            'y_voltage':
            'the voltage of the y direction (with respect to the camera)',
            'y_freq':
            'the frequency of the y direction (with respect to the camera)',
            'y_cap':
            'the capacitance of the piezo in the y direction (with respect to the camera)',
            'z_pos':
            'the position the z direction (with respect to the camera) in um',
            'z_voltage':
            'the voltage of the z direction (with respect to the camera)',
            'z_freq':
            'the frequency of the z direction (with respect to the camera)',
            'z_cap':
            'the capacitance of the piezo in the z direction (with respect to the camera)'
        }

    def read_probes(self, key):
        assert key in self._PROBES.keys()
        assert isinstance(key, str)

        if key in ['x_pos', 'y_pos', 'z_pos']:
            return self._get_position(self._convert_axis(key[0]))
        elif key in ['x_voltage', 'y_voltage', 'z_voltage']:
            return self._get_amplitude(self._convert_axis(key[0]))
        elif key in ['x_freq', 'y_freq', 'z_freq']:
            return self._get_frequency(self._convert_axis(key[0]))
        elif key in ['x_cap', 'y_cap', 'z_cap']:
            return self._cap_measure(self._convert_axis(key[0]))

    @property
    def is_connected(self):
        try:
            device_handle = int32()
            self._check_error(
                self.attocube.PositionerConnect(0,
                                                ctypes.byref(device_handle)))
            self._check_error(self.attocube.PositionerClose(device_handle))
            return True
        except Exception:
            return False

    def _toggle_axis(self, axis, on):
        '''
        Turn axis on or off
        :param axis: axis_x, axis_y, or axis_z
        :param on: True or False
        '''
        device_handle = int32()
        self._check_error(
            self.attocube.PositionerConnect(0, ctypes.byref(device_handle)))
        self._check_error(
            self.attocube.PositionerSetOutput(device_handle, axis,
                                              ctypes.c_bool(on)))
        self._check_error(self.attocube.PositionerClose(device_handle))

    def _set_frequency(self, axis, freq):
        '''
        :param axis: axis_x, axis_y, or axis_z
        :param freq: frequency to set in Hz
        '''
        assert (freq <= 2000)
        device_handle = int32()
        self._check_error(
            self.attocube.PositionerConnect(0, ctypes.byref(device_handle)))
        self._check_error(
            self.attocube.PositionerFrequency(device_handle, axis,
                                              int32(int(freq))))
        self._check_error(self.attocube.PositionerClose(device_handle))

    def _get_frequency(self, axis):
        '''
        :param axis: axis_x, axis_y, or axis_z
        :return: current frequency of axis in Hz
        '''
        device_handle = int32()
        freq = int32()
        self._check_error(
            self.attocube.PositionerConnect(0, ctypes.byref(device_handle)))
        self._check_error(
            self.attocube.PositionerGetFrequency(device_handle, axis,
                                                 ctypes.byref(freq)))
        self._check_error(self.attocube.PositionerClose(device_handle))
        return freq.value

    def _set_amplitude(self, axis, amplitude):
        '''
        :param axis: axis: axis_x, axis_y, or axis_z
        :param amplitude: amplitude in V
        '''
        assert (amplitude <= 60)
        device_handle = int32()
        amplitude *= 1000
        self._check_error(
            self.attocube.PositionerConnect(0, ctypes.byref(device_handle)))
        self._check_error(
            self.attocube.PositionerAmplitude(device_handle, axis,
                                              int32(int(amplitude))))
        self._check_error(self.attocube.PositionerClose(device_handle))

    def _get_amplitude(self, axis):
        '''
        :param axis: axis_x, axis_y, or axis_z
        :return: amplitude in V
        '''
        device_handle = int32()
        amplitude = int32()
        self._check_error(
            self.attocube.PositionerConnect(0, ctypes.byref(device_handle)))
        self._check_error(
            self.attocube.PositionerGetAmplitude(device_handle, axis,
                                                 ctypes.byref(amplitude)))
        self._check_error(self.attocube.PositionerClose(device_handle))
        return (amplitude.value / 1000.0)

    def _get_position(self, axis):
        '''
        :param axis: axis_x, axis_y, or axis_z
        :return: position of axis in um
        '''
        device_handle = int32()
        position = int32()
        self._check_error(
            self.attocube.PositionerConnect(0, ctypes.byref(device_handle)))
        # wait command needed since polling rate of attocube is 20 Hz. Empirically determined that .2 is lowest value
        # that always works. No idea why no other function also needs this wait command
        time.sleep(.2)
        self._check_error(
            self.attocube.PositionerGetPosition(device_handle, axis,
                                                ctypes.byref(position)))
        self._check_error(self.attocube.PositionerClose(device_handle))
        return position.value / 1000.0

    def _cap_measure(self, axis):
        '''
        :param axis: axis_x, axis_y, or axis_z
        :return: Capacitance in uF
        '''
        device_handle = int32()
        capacitance = int32()
        self._check_error(
            self.attocube.PositionerConnect(0, ctypes.byref(device_handle)))
        self._check_error(
            self.attocube.PositionerCapMeasure(device_handle, axis,
                                               ctypes.byref(capacitance)))
        self._check_error(self.attocube.PositionerClose(device_handle))
        return capacitance.value

    def _move_absolute(self, axis, position):
        '''
        Precondition: Must set voltage and frequency sufficiently low that ANC's internal feedback will be able to
        settle on the appropriate position (ex. 7V, 100Hz). Otherwise, fluctuates around target position and never stops
        :param axis: axis_x, axis_y, or axis_z
        :param position: position of axis to move to in um
        '''
        device_handle = int32()
        self._check_error(
            self.attocube.PositionerConnect(0, ctypes.byref(device_handle)))
        self._check_error(
            self.attocube.PositionerMoveAbsolute(device_handle, axis,
                                                 int32(int(position *
                                                           1000.0))))
        self._check_error(self.attocube.PositionerClose(device_handle))

    def _convert_axis(self, axis):
        if axis == 'x':
            return axis_x
        elif axis == 'y':
            return axis_y
        elif axis == 'z':
            return axis_z
        else:
            raise ValueError('No such axis')

    @staticmethod
    def _check_error(code):
        '''
        Translates error codes to human readable message
        :param code: input error code (integer 0-8)
        :poststate: message printed to stdout
        '''
        if (code == NCB_Ok):
            return
        elif (code == NCB_BootIgnored):
            print("Warning: boot ignored\n")
            raise Exception
        elif (code == NCB_Error):
            print("Error: unspecific\n")
            raise Exception
        elif (code == NCB_Timeout):
            print("Error: comm. timeout\n")
            raise Exception
        elif (code == NCB_NotConnected):
            print("Error: not connected\n")
            raise Exception
        elif (code == NCB_DriverError):
            print("Error: driver error\n")
            raise Exception
        elif (code == NCB_FileNotFound):
            print("Error: file not found\n")
            raise Exception
        elif (code == NCB_InvalidParam):
            print("Error: invalid parameter\n")
            raise Exception
        elif (code == NCB_DeviceLocked):
            print("Error: device locked\n")
            raise Exception
        elif (code == NCB_NotSpecifiedParam):
            print("Error: unspec. parameter\n")
            raise Exception
        else:
            print("Error: unknown\n")
            raise Exception
Пример #10
0
class DAQ(Instrument):

    try:
        if os.name == 'nt':
            nidaq = ctypes.WinDLL(
                "C:\\Windows\\System32\\nicaiu.dll")  # load the DLL
            dll_detected = True
        else:
            dll_detected = False
    except WindowsError:
        # make a fake DAQOut instrument
        dll_detected = False
    except:
        raise

    _DEFAULT_SETTINGS = Parameter([
        Parameter('device', 'Dev1', (str), 'Name of DAQ device'),
        Parameter('override_buffer_size', -1, int,
                  'Buffer size for manual override (unused if -1)'),
        Parameter('output', [
            Parameter('channel', [0, 1], [0, 1, 2, 3], 'output channel(s)'),
            Parameter('sample_rate', 1000, float, 'output sample rate'),
            Parameter('min_voltage', -10, float, 'minimum output voltage'),
            Parameter('max_voltage', 10, float, 'maximum output voltage')
        ]),
        Parameter('analog_input', [
            Parameter('channel', 0, range(0, 32), 'input channel(s)'),
            Parameter('sample_rate', 1000, float, 'input sample rate'),
            Parameter('min_voltage', -10, float, 'minimum input voltage'),
            Parameter('max_voltage', 10, float, 'maximum input voltage')
        ]),
        Parameter('digital_input', [
            Parameter('input_channel', 0, range(0, 32), 'input channel(s)'),
            Parameter('clock_PFI_channel', 13, range(0, 32),
                      'PFI output clock channel'),
            Parameter('clock_counter_channel', 1, [0, 1],
                      'counter output clock channel'),
            Parameter('sample_rate', 1000, float, 'input sample rate')
        ])
    ])

    def __init__(self, name=None, settings=None):
        if self.dll_detected:
            # buf_size = 10
            # data = ctypes.create_string_buffer('\000' * buf_size)
            # try:
            #     #Calls arbitrary function to check connection
            #     self.CHK(self.nidaq.DAQmxGetDevProductType(device, ctypes.byref(data), buf_size))
            #     self.hardware_detected = True
            # except RuntimeError:
            #     self.hardware_detected = False
            super(DAQ, self).__init__(name, settings)

    def update(self, settings):
        super(DAQ, self).update(settings)
        for key, value in settings.iteritems():
            if key == 'device':
                if not (self.is_connected):
                    raise EnvironmentError(
                        'Device invalid, cannot connect to DAQ')

    @property
    def _PROBES(self):
        return None

    def read_probes(self, key):
        pass

    @property
    def is_connected(self):
        buf_size = 10
        data = ctypes.create_string_buffer('\000' * buf_size)
        try:
            #Calls arbitrary function to check connection
            self.CHK(
                self.nidaq.DAQmxGetDevProductType(self._parameters['device'],
                                                  ctypes.byref(data),
                                                  buf_size))
            return True
        except RuntimeError:
            return False

    # error checking routine for nidaq commands. Input should be return value
    # from nidaq function
    # err: nidaq error code
    def CHK(self, err):
        if err < 0:
            buf_size = 100
            buf = ctypes.create_string_buffer('\000' * buf_size)
            self.nidaq.DAQmxGetErrorString(err, ctypes.byref(buf), buf_size)
            raise RuntimeError('nidaq call failed with error %d: %s' %
                               (err, repr(buf.value)))
        if err > 0:
            buf_size = 100
            buf = ctypes.create_string_buffer('\000' * buf_size)
            self.nidaq.DAQmxGetErrorString(err, ctypes.byref(buf), buf_size)
            raise RuntimeError('nidaq generated warning %d: %s' %
                               (err, repr(buf.value)))