Esempio n. 1
0
    def query(self, command, *, send_args=(None, None),
              recv_args=(None, None)):
        """Send query to the stage and return the answer, after handling
        possible errors.

        :param command: command to be sent to the instrument
        :type command: string

        :param send_args: (termination, encoding) to override class defaults
        :param recv_args: (termination, encoding) to override class defaults
        """
        ans = super().query(command, send_args=send_args, recv_args=recv_args)
        if ans[0] == 'E':
            code = ans[2]
            if code == '8':
                raise InstrumentError('Value out of range')
            elif code == '4':
                raise InstrumentError(
                    'Command parse error, ie wrong number  of parameters')
            elif code == '5':
                raise InstrumentError('Unknown command')
            elif code == '2':
                raise InstrumentError('Invalid checksum')

        return ans
Esempio n. 2
0
    def __init__(self,
                 vendor=None,
                 product=None,
                 serial_number=None,
                 device_filters=None,
                 timeout=None,
                 **kwargs):
        super().__init__(**kwargs)

        device_filters = device_filters or {}
        devices = self.find_devices(vendor, product, serial_number, None,
                                    **device_filters)

        if not devices:
            raise InstrumentError('No device found.')
        elif len(devices) > 1:
            desc = '\n'.join(
                str(DeviceInfo.from_device(dev)) for dev in devices)
            raise InstrumentError('{} devices found:\n{}\n'
                                  'Please narrow the search criteria'.format(
                                      len(devices), desc))

        self.usb_dev, other = devices[0], devices[1:]
        nfo = DeviceInfo.from_device(self.usb_dev)
        self.log_debug('- Manufacturer: {} ({})'.format(
            nfo.manufacturer, self.usb_dev.idVendor))
        self.log_debug('- Product: {} ({})'.format(nfo.product,
                                                   self.usb_dev.idProduct))
        self.log_debug('- Serial Number: {}'.format(nfo.serial_number))
        try:
            if self.usb_dev.is_kernel_driver_active(0):
                self.usb_dev.detach_kernel_driver(0)
        except (usb.core.USBError, NotImplementedError) as e:
            self.log_warning(repr(e))

        try:
            self.usb_dev.set_configuration()  #self.CONFIGURATION
            self.usb_dev.set_interface_altsetting()
        except usb.core.USBError as e:
            self.log_error("Could not set configuration")
            raise InstrumentError('failed to set configuration')

        self.usb_intf = self._find_interface(self.usb_dev, self.INTERFACE)
        self.log_debug('Interface: {}'.format(self.usb_intf.index))

        self.usb_recv_ep, self.usb_send_ep = self._find_endpoints(
            self.usb_intf, self.ENDPOINTS)

        self.log_debug('EP Address: recv={}, send={}'.format(
            self.usb_recv_ep.bEndpointAddress,
            self.usb_send_ep.bEndpointAddress))
Esempio n. 3
0
    def query(self, command, *, send_args=(None, None),
              recv_args=(None, None)):
        """Send query to the laser and return the answer, after handling
        possible errors.

        :param command: command to be sent to the instrument
        :type command: string

        :param send_args: (termination, encoding) to override class defaults
        :param recv_args: (termination, encoding) to override class defaults
        """
        ans = super().query(command, send_args=send_args, recv_args=recv_args)
        # TODO: Echo handling
        code = ans[0]
        if code != 0:
            if code == '1':
                raise InstrumentError('Command invalid')
            elif code == '2':
                raise InstrumentError('Wrong number of parameters')
            elif code == '3':
                raise InstrumentError('Parameter value is out of range')
            elif code == '4':
                raise InstrumentError('Unlocking code is wrong')
            elif code == '5':
                raise InstrumentError('Device is locked for this command')
            elif code == '6':
                raise InstrumentError('This function is not supported')
            elif code == '7':
                raise InstrumentError('Timeout while reading command (60 s)')
            elif code == '8':
                raise InstrumentError('This value is currently not available')

        ans = ans[2:]
        # TODO: Code reporting?
        return ans
Esempio n. 4
0
    def trigger_ecl_mode(self, value):
        """Trigger mode for ECL logic.
        """
        if self.recall('trigger_type') == 'ttl':
            raise InstrumentError('Level triggering only with ECL')

        self.query_expect(value)
Esempio n. 5
0
    def _return_handler(self, func_name, ret_value):
        if ret_value < 0:
            raise InstrumentError(_ERRORS[ret_value])
        elif (ret_value > 0 and
              func_name not in ('GET_COCTIME', 'GET_DELTIME', 'GET_BELTIME', 'GET_EXPTIME')):
            self.log_warning('While calling {}: {}', func_name, _ERRORS[ret_value])

        return ret_value
Esempio n. 6
0
    def _find_interface(self, dev, setting):
        interfaces = find_interfaces(dev,
                                     bInterfaceClass=0xFE,
                                     bInterfaceSubClass=3)
        if not interfaces:
            raise InstrumentError('USB TMC interface not found.')
        elif len(interfaces) > 1:
            self.log_warning('More than one interface found, selecting first.')

        return interfaces[0]
Esempio n. 7
0
    def query(self, command, *, send_args=(None, None),
              recv_args=(None, None)):
        """Query the instrument and parse the response.

        :raises: InstrumentError
        """
        response = super().query(command,
                                 send_args=recv_args,
                                 recv_args=recv_args)
        command = command.strip()[0]
        if response in ('1x', '2x'):
            raise InstrumentError("Unknown command: '{}'".format(command))
        if not response.startswith(command):
            raise InstrumentError("Unknown response: '{}'".format(response))
        if response == 'X' or 'x':
            raise InstrumentError('Unable to set')
        elif not response == '+':
            raise InstrumentError("Unknown response: '{}'".format(response))
        return response
Esempio n. 8
0
 def _return_handler(self, func_name, ret_value):
     if ret_value < 0:
         msg = 'Cannot obtain error message'
         if not func_name == 'DAQmxGetExtendedErrorInfo':
             err, msg = self.lib.DAQmxGetExtendedErrorInfo(
                 *RetStr(default_buf_size * 100))
             if err < 0:
                 msg = 'Cannot obtain error message'
         raise InstrumentError('In {}: {} ({})'.format(
             func_name, msg, ret_value))
     return ret_value
Esempio n. 9
0
    def raw_send(self, data):
        """Send raw bytes to the instrument.

        :param data: bytes to be sent to the instrument
        :type data: bytes
        """

        try:
            return self.usb_send_ep.write(data)
        except usb.core.USBError as e:
            raise InstrumentError(str(e))
Esempio n. 10
0
 def clamp_voltage(self):
     """Most negative value of the gate pulse.
     """
     if self.revision >= 2.0:
         ans = self.query_expect('CLAMP ?')
         ans = between(ans, 'CLAMP ?', 'ok').strip()
         return float(ans)
     else:
         ans = self.query_expect('CLAMP @ .')
         try:
             pos = ans.index('.')
         except ValueError:
             raise InstrumentError('Unsupported operation.')
         return float(ans[pos + 2:pos + 7]) / 10.0
Esempio n. 11
0
 def average_voltage(self):
     """Cathode potential bias with respect of MCP.
     """
     if self.revision >= 2.0:
         ans = self.query_expect('AVE ?')
         ans = between(ans, 'AVE ?', 'ok')
         return float(ans.strip()) / 10.
     else:
         ans = self.query_expect('THRESHV @ .')[8:]
         try:
             pos = ans.index('.')
         except ValueError:
             raise InstrumentError('Unsupported operation.')
         return float(ans[pos + 2:pos + 7]) / 10.
Esempio n. 12
0
 def trigger_ecl_level(self):
     """Trigger level for ECL logic, mode level.
     """
     if self.revision >= 2.0:
         ans = self.query_expect('THRESHV ?')
         ans = between(ans, 'THRESHV ?', 'ok')
         return float(ans.strip())
     else:
         ans = self.query_expect('THRESHV @ .')[8:]
         try:
             pos = ans.index('.')
         except ValueError:
             raise InstrumentError('Unsupported operation.')
         return float(ans[pos + 2:pos + 7])
Esempio n. 13
0
    def query_expect(self, command, read_termination=None, expected='ok'):
        """Send a query and check that the answer contains the string.

        :type command: str
        :type read_termination: str | None
        :type expected: str | None
        """
        if command and not self.recall('remote'):
            self.log_info('Setting Remote.')
            self.remote = True
        self.resource.write(command)
        ans = self.read(read_termination)
        if expected and not expected in ans:
            raise InstrumentError("'{}' not in '{}'".format(expected, ans))
        return ans
Esempio n. 14
0
 def analog_dif_in(self, key, gain = 1):
     '''
     Differential channels can make use of the low noise precision PGA to provide gains up to 20. In differential mode, the voltage of each AI with respect to ground must be between +20 and -10 volts, but the range of voltage difference between the 2 AI is a function of gain (G) as follows:
     G=1     ±20 volts
     G=2     ±10 volts
     G=4     ±5 volts
     G=5     ±4 volts
     G=8     ±2.5 volts
     G=10    ±2 volts
     G=16    ±1.25 volts
     G=20    ±1 volt
     The reason the range is ±20 volts at G=1 is that, for example, AI0 could be +10 volts and AI1 could be -10 volts giving a difference of +20 volts, or AI0 could be -10 volts and AI1 could be +10 volts giving a difference of -20 volts. The PGA (programmable gain amplifier, available on differential channels only) amplifies the AI voltage before it is digitized by the A/D converter. The high level drivers then divide the reading by the gain and return the actual measured voltage.
     '''
     gain_list = [1,2,4,5,8,10,16,20]
     gain_value = gain
     if gain_value not in gain_list:
         raise InstrumentError('Gain value not permitted, check driver code or Labjack user guide')
     else:
         return self._internal.eAnalogIn(channel = key + 8, gain = gain_value)['voltage']
Esempio n. 15
0
    def __init__(self,
                 vendor=None,
                 product=None,
                 serial_number=None,
                 **kwargs):
        super().__init__(vendor, product, serial_number, **kwargs)
        self.usb_intr_in = find_endpoint(self.usb_intf, usb.ENDPOINT_IN,
                                         usb.ENDPOINT_TYPE_INTERRUPT)
        self.log_debug('EP Address: intr={}'.format(
            self.usb_intr_in.bEndpointAddress))

        self.usb_dev.reset()

        time.sleep(0.01)

        self._get_capabilities()

        self._btag = 0

        if not (self.usb_recv_ep and self.usb_send_ep):
            raise InstrumentError(
                "TMC device must have both Bulk-In and Bulk-out endpoints.")
Esempio n. 16
0
 def check_error(self, err):
     if err != -50:
         raise InstrumentError(self.errors[err])
     else:
         return
Esempio n. 17
0
 def _return_handler(self, func_name, ret_value):
     if ret_value != 0:
         raise InstrumentError('{} ({})'.format(ret_value,
                                                _ERRORS[ret_value]))
     return ret_value
Esempio n. 18
0
 def query_expect(self, command, recv_termination=None, expected='ok'):
     ans = self.query(command, recv_args=(recv_termination, HRI.ENCODING))
     if expected and not expected in ans:
         raise InstrumentError("'{}' not in '{}'".format(expected, ans))
     return ans
Esempio n. 19
0
 def trigger_ttl_termination(self, value):
     """Trigger termination for TTL logic (for ECL is fixed to 50 ohm).
     """
     if self.recall('trigger_type') == 'ecl':
         raise InstrumentError('Level triggering only with ECL')
     self.query_expect(value)