Пример #1
0
    def read(self, gpibaddr, count=None, timeout=None):
        if count is None:
            count = self.max_recv_size

        # Change address
        self.addr = gpibaddr

        # Send reqd request if a GPIB address provided
        if not self._auto and gpibaddr is not None:
            self.write_raw('++read eoi')

        # Get reference to the appropriate buffer
        buffer = self._bufferPending[gpibaddr]

        # Try to read data, if fail, send read request and try again
        status = self.read_raw(count,
                               buffer,
                               term_char_en=True,
                               timeout=timeout)

        if status == StatusCode.success_termination_character_read:
            term_byte = bytes([self.term_char]) if self.term_char else b''
            term_byte_index = buffer.index(term_byte) + 1
        elif status == StatusCode.success_max_count_read:
            term_byte_index = len(buffer)
        elif status == StatusCode.error_timeout:
            raise errors.VisaIOError(errors.VI_ERROR_TMO)
        else:
            raise errors.VisaIOError('Unknown Error')

        out = buffer[:term_byte_index].decode().rstrip()  # Extract out output
        buffer[:term_byte_index] = []  # Remove otuput from buffer
        self.logger.debug('PrologiXEthernet.read():  %s', out)
        return out
Пример #2
0
    def find_resources(self, session, query):
        """Queries a VISA system to locate the resources associated with a specified interface.

        Corresponds to viFindRsrc function of the VISA library.

        :param session: Unique logical identifier to a session (unused, just to uniform signatures).
        :param query: A regular expression followed by an optional logical expression. Use '?*' for all.
        :return: find_list, return_counter, instrument_description, return value of the library call.
        :rtype: ViFindList, int, unicode (Py2) or str (Py3), VISAStatus
        """

        # For each session type, ask for the list of connected resources and
        # merge them into a single list.

        resources = sum([
            st.list_resources()
            for key, st in sessions.Session.iter_valid_session_classes()
        ], [])

        query = query.replace('?*', '.*')
        matcher = re.compile(query, re.IGNORECASE)

        resources = [res for res in resources if matcher.match(res)]

        count = len(resources)
        resources = iter(resources)
        if count:
            return resources, count, next(
                resources), constants.StatusCode.success

        raise errors.VisaIOError(
            errors.StatusCode.error_resource_not_found.value)
Пример #3
0
 def get_visa_attribute(cls, id):
     if id == constants.VI_ATTR_TMO_VALUE:
         raise errors.VisaIOError(constants.VI_ERROR_NSUP_ATTR)
     elif id == constants.VI_ATTR_INTF_NUM:
         raise Exception("Long text: aaaaaaaaaaaaaaaaaaaa")
     else:
         raise Exception("Test")
Пример #4
0
    def after_parsing(self) -> None:
        # TODO: board_number not handled
        # vx11 expect all timeouts to be expressed in ms and should be integers
        try:
            self.interface = vxi11.CoreClient(self.parsed.host_address,
                                              self.open_timeout)
        except rpc.RPCError:
            raise errors.VisaIOError(constants.VI_ERROR_RSRC_NFOUND)

        self.lock_timeout = 10000
        self.client_id = random.getrandbits(31)

        error, link, abort_port, max_recv_size = self.interface.create_link(
            self.client_id, 0, self.lock_timeout, self.parsed.lan_device_name)

        if error:
            raise Exception("error creating link: %d" % error)

        self.link = link
        self.max_recv_size = min(max_recv_size, 2**30)  # 1GB

        for name in ("SEND_END_EN", "TERMCHAR", "TERMCHAR_EN"):
            attribute = getattr(constants, "VI_ATTR_" + name)
            self.attrs[attribute] = attributes.AttributesByID[
                attribute].default
Пример #5
0
    def _return_handler(self, ret_value: int, func: Callable,
                        arguments: tuple) -> Any:
        """Check return values for errors and warnings."""
        logger.debug(
            "%s%s -> %r",
            func.__name__,
            _args_to_str(arguments),
            ret_value,
            extra=self._logging_extra,
        )

        rv: constants.StatusCode
        try:
            rv = constants.StatusCode(ret_value)
        except ValueError:
            rv = cast(constants.StatusCode, ret_value)

        self._last_status = rv

        # The first argument of almost all registered visa functions is a session.
        # We store the error code per session
        session = None
        if func.__name__ not in ("viFindNext", ):
            try:
                session = arguments[0]
            except KeyError:
                raise Exception("Function %r does not seem to be a valid "
                                "visa function (len args %d)" %
                                (func, len(arguments)))

            # Functions that use the first parameter to get a session value.
            if func.__name__ in ("viOpenDefaultRM", ):
                # noinspection PyProtectedMember
                session = session._obj.value

            if isinstance(session, int):
                self._last_status_in_session[session] = rv
            else:
                # Functions that might or might have a session in the first argument.
                if func.__name__ not in (
                        "viClose",
                        "viGetAttribute",
                        "viSetAttribute",
                        "viStatusDesc",
                ):
                    raise Exception("Function %r does not seem to be a valid "
                                    "visa function (type args[0] %r)" %
                                    (func, type(session)))

        if ret_value < 0:
            raise errors.VisaIOError(rv)

        if rv in self.issue_warning_on:
            if session and ret_value not in self._ignore_warning_in_session[
                    session]:
                warnings.warn(errors.VisaIOWarning(ret_value), stacklevel=2)

        return ret_value
Пример #6
0
    def list_resources(self, session: int, query='?*::INSTR') -> List[str]:

        resources_list = rname.filter(list(resources), query)

        if resources_list:
            return resources_list

        raise errors.VisaIOError(
            errors.StatusCode.error_resource_not_found.value)
Пример #7
0
 def lock(
     self,
     session: int,
     lock_type: constants.Lock,
     timeout: int,
     requested_key: Optional[str] = None,
 ) -> Tuple[str, StatusCode]:
     """Establishes an access mode to the specified resources.
     Corresponds to viLock function of the VISA library.
     Parameters
     ----------
     session : VISASession
         Unique logical identifier to a session.
     lock_type : constants.Lock
         Specifies the type of lock requested.
     timeout : int
         Absolute time period (in milliseconds) that a resource waits to get
         unlocked by the locking session before returning an error.
     requested_key : Optional[str], optional
         Requested locking key in the case of a shared lock. For an exclusive
         lock it should be None.
     Returns
     -------
     Optional[str]
         Key that can then be passed to other sessions to share the lock, or
         None for an exclusive lock.
     StatusCode
         Return value of the library call.
     """
     if lock_type != constants.Lock.exclusive:
         raise NotImplementedError(
             f'Only constant.Lock.exclusive supported.  ({lock_type})')
     if requested_key is not None:
         raise NotImplementedError(
             f'Requested key is not supported. ({requested_key})')
     try:
         cur_session = self._sessions[session]
     except KeyError as e:
         raise errors.VisaIOError(StatusCode.error_connection_lost) from e
     acquired = cur_session.resource_lock.acquire(timeout=timeout / 1000)
     if not acquired:
         raise errors.VisaIOError(StatusCode.error_timeout)
     return ('', StatusCode.success)
Пример #8
0
    def _return_handler(self, ret_value, func, arguments):
        """Check return values for errors and warnings.

        TODO: THIS IS JUST COPIED PASTED FROM NIVisaLibrary.
        Needs to be adapted.
        """

        logger.debug('%s%s -> %r',
                     func.__name__,
                     _args_to_str(arguments),
                     ret_value,
                     extra=self._logging_extra)

        try:
            ret_value = constants.StatusCode(ret_value)
        except ValueError:
            pass

        self._last_status = ret_value

        # The first argument of almost all registered visa functions is a session.
        # We store the error code per session
        session = None
        if func.__name__ not in ('viFindNext', ):
            try:
                session = arguments[0]
            except KeyError:
                raise Exception('Function %r does not seem to be a valid '
                                'visa function (len args %d)' %
                                (func, len(arguments)))

            # Functions that use the first parameter to get a session value.
            if func.__name__ in ('viOpenDefaultRM', ):
                # noinspection PyProtectedMember
                session = session._obj.value

            if isinstance(session, integer_types):
                self._last_status_in_session[session] = ret_value
            else:
                # Functions that might or might have a session in the first argument.
                if func.__name__ not in ('viClose', 'viGetAttribute',
                                         'viSetAttribute', 'viStatusDesc'):
                    raise Exception('Function %r does not seem to be a valid '
                                    'visa function (type args[0] %r)' %
                                    (func, type(session)))

        if ret_value < 0:
            raise errors.VisaIOError(ret_value)

        if ret_value in self.issue_warning_on:
            if session and ret_value not in self._ignore_warning_in_session[
                    session]:
                warnings.warn(errors.VisaIOWarning(ret_value), stacklevel=2)

        return ret_value
Пример #9
0
    def enable_event(
        self,
        session: int,
        event_type: EventType,
        mechanism: EventMechanism,
        context: None = None,
    ) -> StatusCode:
        """Enable event occurrences for specified event types and mechanisms in a session.

        Corresponds to viEnableEvent function of the VISA library.

        Parameters
        ----------
        session : VISASession
            Unique logical identifier to a session.
        event_type : EventType
            Logical event identifier.
        mechanism : EventMechanism
            Specifies event handling mechanisms to be enabled.
        context : None, optional
            Unused parameter...

        Returns
        -------
        StatusCode
            Return value of the library call.

        """
        try:
            cur_session = self._sessions[session]
        except KeyError as e:
            raise errors.VisaIOError(StatusCode.error_connection_lost) from e
        if mechanism != EventMechanism.queue:
            raise errors.VisaIOError(StatusCode.error_invalid_mechanism)
        try:
            cur_session.enable_event(event_type)
        except EventNotSupportedError as e:
            raise errors.VisaIOError(StatusCode.error_invalid_event) from e
        except EventNotDisabledError:
            # Okay to re-enable event
            pass
        return StatusCode.success
Пример #10
0
    def wait_on_event(self, session: int, in_event_type: EventType,
                      timeout: int) -> Tuple[EventType, int, StatusCode]:
        """Wait for an occurrence of the specified event for a given session.

        Corresponds to viWaitOnEvent function of the VISA library.

        Parameters
        ----------
        session : VISASession
            Unique logical identifier to a session.
        in_event_type : EventType
            Logical identifier of the event(s) to wait for.
        timeout : int
            Absolute time period in time units that the resource shall wait for
            a specified event to occur before returning the time elapsed error.
            The time unit is in milliseconds.

        Returns
        -------
        EventType
            Logical identifier of the event actually received
        int
            A handle specifying the unique occurrence of an event
        StatusCode
            Return value of the library call.

        """
        try:
            cur_session = self._sessions[session]
        except KeyError as e:
            raise errors.VisaIOError(StatusCode.error_connection_lost) from e
        timeout_td = timedelta(milliseconds=timeout)
        try:
            cur_session.wait_for_event(event_type=in_event_type,
                                       timeout=timeout_td)
        except (EventNotEnabledError, EventNotSupportedError) as e:
            raise errors.VisaIOError(StatusCode.error_invalid_event) from e
        except EventTimeoutError as e:
            raise errors.VisaIOError(StatusCode.error_timeout) from e
        return (in_event_type, 0, StatusCode.success)
Пример #11
0
    def discard_events(
        self,
        session: int,
        event_type: EventType,
        mechanism: EventMechanism,
    ) -> StatusCode:
        """Discard event occurrences for a given type and mechanisms in a session.

        Corresponds to viDiscardEvents function of the VISA library.

        Parameters
        ----------
        session : int
            Unique logical identifier to a session.
        event_type : constans.EventType
            Logical event identifier.
        mechanism : EventMechanism
            Specifies event handling mechanisms to be discarded.

        Returns
        -------
        StatusCode
            Return value of the library call.

        """
        try:
            cur_session = self._sessions[session]
        except KeyError as e:
            raise errors.VisaIOError(StatusCode.error_connection_lost) from e
        if mechanism != EventMechanism.queue:
            return StatusCode.success
        try:
            cur_session.discard_events(event_type=event_type)
        except (EventNotEnabledError, EventNotSupportedError) as e:
            raise errors.VisaIOError(StatusCode.error_invalid_event) from e
        return StatusCode.success
Пример #12
0
    def list_resources(self, session, query='?*::INSTR'):
        """Returns a tuple of all connected devices matching query.

        :param query: regular expression used to match devices.
        """

        # For each session type, ask for the list of connected resources and merge them into a single list.

        resources = self.devices.list_resources()

        resources = rname.filter(resources, query)

        if resources:
            return resources

        raise errors.VisaIOError(
            errors.StatusCode.error_resource_not_found.value)
Пример #13
0
 def unlock(self, session: int) -> StatusCode:
     """Relinquish a lock for the specified resource.
     Corresponds to viUnlock function of the VISA library.
     Parameters
     ----------
     session : VISASession
         Unique logical identifier to a session.
     Returns
     -------
     StatusCode
         Return value of the library call.
     """
     try:
         cur_session = self._sessions[session]
     except KeyError as e:
         raise errors.VisaIOError(StatusCode.error_connection_lost) from e
     cur_session.resource_lock.release()
     return StatusCode.success
Пример #14
0
    def read(self, session, count):
        """Reads data from device or interface synchronously.

        Corresponds to viRead function of the VISA library.

        :param session: Unique logical identifier to a session.
        :param count: Number of bytes to be read.
        :return: data read, return value of the library call.
        :rtype: bytes, VISAStatus
        """
        # from the session handle, dispatch to the read method of the session object.
        try:
            ret = self.sessions[session].read(count)
        except KeyError:
            return 0, StatusCode.error_invalid_object

        if ret[1] < 0:
            raise errors.VisaIOError(ret[1])

        return ret
Пример #15
0
    def write(self, session, data):
        """Writes data to device or interface synchronously.

        Corresponds to viWrite function of the VISA library.

        :param session: Unique logical identifier to a session.
        :param data: data to be written.
        :type data: str
        :return: Number of bytes actually transferred, return value of the library call.
        :rtype: int, VISAStatus
        """
        # from the session handle, dispatch to the write method of the session object.
        try:
            ret = self.sessions[session].write(data)
        except KeyError:
            return 0, StatusCode.error_invalid_object

        if ret[1] < 0:
            raise errors.VisaIOError(ret[1])

        return ret
Пример #16
0
    def read(self, session, count):
        """Reads data from device or interface synchronously.

        Corresponds to viRead function of the VISA library.

        :param session: Unique logical identifier to a session.
        :param count: Number of bytes to be read.
        :return: data read, return value of the library call.
        :rtype: bytes, :class:`pyvisa.constants.StatusCode`
        """

        try:
            sess = self.sessions[session]
        except KeyError:
            return b'', constants.StatusCode.error_invalid_object

        try:
            chunk, status = sess.read(count)
            if status == constants.StatusCode.error_timeout:
                raise errors.VisaIOError(constants.VI_ERROR_TMO)
            return chunk, status
        except AttributeError:
            return b'', constants.StatusCode.error_nonsupported_operation
Пример #17
0
    def disable_event(
        self,
        session: int,
        event_type: EventType,
        mechanism: EventMechanism,
    ) -> StatusCode:
        """Disable notification for an event type(s) via the specified mechanism(s).

        Corresponds to viDisableEvent function of the VISA library.

        Parameters
        ----------
        session : int
            Unique logical identifier to a session.
        event_type : EventType
            Event type.
        mechanism : EventMechanism
            Event handling mechanisms to be disabled.

        Returns
        -------
        StatusCode
            Return value of the library call.

        """
        try:
            cur_session = self._sessions[session]
        except KeyError as e:
            raise errors.VisaIOError(StatusCode.error_connection_lost) from e
        if mechanism != EventMechanism.queue:
            return StatusCode.success
        try:
            cur_session.disable_event(event_type=event_type)
        except (EventNotEnabledError, EventNotSupportedError):
            # Okay to re-disable an event or disable unsupported event
            pass
        return StatusCode.success
Пример #18
0
    def list_resources(self, session, query='?*::INSTR'):
        """Returns a tuple of all connected devices matching query.

        :param query: regular expression used to match devices.
        """

        # For each session type, ask for the list of connected resources and
        # merge them into a single list.

        resources = sum([
            st.list_resources()
            for key, st in sessions.Session.iter_valid_session_classes()
        ], [])

        query = query.replace('?*', '.*')
        matcher = re.compile(query, re.IGNORECASE)

        resources = tuple(res for res in resources if matcher.match(res))

        if resources:
            return resources

        raise errors.VisaIOError(
            errors.StatusCode.error_resource_not_found.value)
Пример #19
0
 def test_VisaIOError(self):
     self._test_pickle_unpickle(errors.VisaIOError(0))
Пример #20
0
 def false_read(session, size):
     raise errors.VisaIOError(constants.VI_ERROR_ABORT)