Exemple #1
0
class VisaInterfaceAnritsuM8475A(VisaInterface):
    """
    Add error handling wrapper to Anritsu M8475A visa command
    """
    __CLEAR_STATUS_CMD = "*CLS"
    __GET_LAST_ERR_CMD = "ERROR?"

    def __init__(self, transport, **kwargs):
        VisaInterface.__init__(self, transport, **kwargs)
        self._logger = Factory().create_logger(
            "%s.%s.VISA_ANRITSU_M8475A" % (ACS_LOGGER_NAME, EQT_LOGGER_NAME))

    def send_command(self, command, bts=None):
        """
        Send a GPIB Command.

        :type command: str
        :param command: String representing a well formed GPIB command.

        :type bts: str
        :param bts: the BTS to apply the command
        """
        # Clear Status command. Clears the whole status structure
        self.write(VisaInterfaceAnritsuM8475A.__CLEAR_STATUS_CMD)
        # Send command to the equipment
        self._logger.debug("Send GPIB command: %s", command)
        # Add the BTS number if the GPIB finish with a ,
        if command[-1] == ",":
            command += str(bts)
        self.write(command)

        # Check errors
        self.error_check()

    def query_command(self, command):
        """
        Send a GPIB Command.

        :type command: str
        :param command: String representing a well formed GPIB command.

        :rtype: String
        :return: Message from equipment giving the value of a dedicated GPIB command
        """
        # Clear Status command. Clears the whole status structure
        self.write(VisaInterfaceAnritsuM8475A.__CLEAR_STATUS_CMD)
        # Send command to the equipment
        self._logger.debug("Send GPIB command: %s", command)
        response = self.query(command)

        return response

    def error_check(self):
        """
        Error checking and warning reporting
        :raise TestEquipmentException: if err != SUCCESS
        """
        error_code = self.query(VisaInterfaceAnritsuM8475A.__GET_LAST_ERR_CMD)
        if error_code != "0":
            error_msg = "Anritsu M8475A error during GPIB command (Error code: {0}: {1})".format(
                error_code, AnritsuM8475A_ErrorCodes[int(error_code)])
            raise TestEquipmentException(
                TestEquipmentException.SPECIFIC_EQT_ERROR, error_msg)
Exemple #2
0
class VisaInterface(object):

    """
    Visa interface to control equipment in full python
    supported transports are "GPIB", "SERIAL", "TCPIP"
    each transport needs specific additional arguments
    "GPIB": "GPIBBoardId", "GPIBAddress"
    "SERIAL": "ComPort"
    "TCPIP": "TcpIpAddress"
    """

    SUPPORTED_TRANSPORT = ["GPIB", "SERIAL", "TCPIP"]
    """
    List of supported transports to connect to the equipment
    """

    GPIB_TRANSPORT = "GPIB"
    SERIAL_TRANSPORT = "SERIAL"
    TCPIP_TRANSPORT = "TCPIP"
    """
    Global variable used for transport connection
    """

    def __init__(self, transport, **kwargs):
        """
        Constructor
        :type transport: str
        :param transport: the bench configuration name of the equipment
        :type kwargs: dict
        :param kwargs: various needed parameters depending on the transport
        """

        # Initialize attributes
        self.__logger = Factory().create_logger("%s.%s.VISA" % (ACS_LOGGER_NAME, EQT_LOGGER_NAME))
        self.__args = dict(kwargs)
        self.connect_via_transport(transport)

    def get_logger(self):
        """
        Gets the internal logger of the equipment
        """
        return self.__logger

    def get_handle(self):
        """
        Gets the connection handle
        :rtype: unsigned long
        :return: the handle of connection with the equipment, None if no
        equipment is connected
        """
        return self.__handle

    def check_handle(self):
        """
        Check if the handle for equipment is created

        :return: None
        """
        # Check if equipment is connected first
        if self.get_handle() is None:
            error_msg = "Connection is not initialized with the equipment."
            self.get_logger().error(error_msg)
            raise TestEquipmentException(TestEquipmentException.INSTANTIATION_ERROR, error_msg)

    def _set_handle(self, handle):
        """
        Sets the connection handle of the equipment
        """
        self.__handle = handle

    def __connect_via_gpib(self):
        """
        Connect to equipment via GPIB
        """
        if "GPIBBoardId" in self.__args.keys():
            board_id = int(self.__args["GPIBBoardId"])
        else:
            raise AcsBaseException(AcsBaseException.INVALID_PARAMETER,
                                   "The parameter 'GPIBBoardId' is required for configuring GPIB connection")
        if "GPIBAddress" in self.__args.keys():
            gpib_addr = int(self.__args["GPIBAddress"])
        else:
            raise AcsBaseException(AcsBaseException.INVALID_PARAMETER,
                                   "The parameter 'GPIBAddress' is required for configuring GPIB connection")
        try:
            # Initialize GPIB connection to the equipment
            handle = pyvisa.GpibInstrument(gpib_addr, board_id)
            # Update handle value
            self._set_handle(handle)
        except (visaexception.VisaIOError,
                visaexception.VisaIOWarning,
                visaexception.VisaTypeError) as ex:
            msg = "Connection via GPIB failed. "
            msg += str(ex)
            self.get_logger().error(msg)
            raise TestEquipmentException(TestEquipmentException.VISA_LIBRARY_ERROR, msg)

    def __connect_via_serial(self):
        """
        Connect to equipment via SERIAL
        """
        if "ComPort" in self.__args.keys():
            com_port = str(self.__args["ComPort"])
        else:
            raise AcsBaseException(AcsBaseException.INVALID_PARAMETER,
                                   "The parameter 'ComPort' is required for configuring serial connection")

        try:
            # Initialize Serial connection to the equipment
            handle = pyvisa.SerialInstrument(com_port)
            # Update handle value
            self._set_handle(handle)
        except (visaexception.VisaIOError,
                visaexception.VisaIOWarning,
                visaexception.VisaTypeError) as ex:
            msg = "Connection via Serial failed. "
            msg += str(ex)
            self.get_logger().error(msg)
            raise TestEquipmentException(TestEquipmentException.VISA_LIBRARY_ERROR, msg)

    def __connect_via_tcpip(self):
        """
        Connect to equipment via TCPIP
        """
        if "TcpIpAddress" in self.__args.keys():
            ip_addr = str(self.__args["TcpIpAddress"])
        else:
            raise AcsBaseException(AcsBaseException.INVALID_PARAMETER,
                                   "The parameter 'TcpIpAddress' is required for configuring TCP/IP connection")
        board_id = ""
        if "TcpIpBoardId" in self.__args.keys():
            board_id = str(self.__args["TcpIpBoardId"])
        device_name = "INST0"
        if "TcpIpDeviceName" in self.__args.keys():
            device_name = str(self.__args["TcpIpDeviceName"])

        try:
            # Initialize TCP/IP connection to the equipment
            resource_name = "TCPIP%s::%s::%s::INSTR" % (board_id, ip_addr, device_name)
            self.get_logger().debug("TCPIP ressource name: %s" % resource_name)
            handle = pyvisa.Instrument(resource_name)
            handle.timeout = 10000

            # Update handle value
            self._set_handle(handle)
        except (visaexception.VisaIOError,
                visaexception.VisaIOWarning,
                visaexception.VisaTypeError) as ex:
            msg = "Connection via TCP/IP failed. "
            msg += str(ex)
            self.get_logger().error(msg)
            raise TestEquipmentException(TestEquipmentException.VISA_LIBRARY_ERROR, msg)

    def connect_via_transport(self, transport):
        """
        Connect to equipment using parameter transport

        :type transport: str
        :param transport: The transport use to connect to the equipment
        """

        if transport == self.GPIB_TRANSPORT:
            self.__connect_via_gpib()
        elif transport == self.SERIAL_TRANSPORT:
            self.__connect_via_serial()
        elif transport == self.TCPIP_TRANSPORT:
            self.__connect_via_tcpip()
        else:
            error_msg = "Unsupported transport mode '%s'." % str(transport)
            self.get_logger().error(error_msg)
            raise TestEquipmentException(TestEquipmentException.READ_PARAMETER_ERROR, error_msg)

    def disconnect(self):
        """
        Disconnect from the equipment and all associated resources
        """

        try:
            self.get_logger().info("Disconnection")

            if self.get_handle() is not None:
                self.get_handle().clear()
                self.get_handle().close()
                # Update handle value
                self._set_handle(None)

        except (visaexception.VisaIOError,
                visaexception.VisaIOWarning,
                visaexception.VisaTypeError) as ex:
            msg = "Fail to disconnect from the equipment. "
            msg += str(ex)
            self.get_logger().error(msg)
            raise TestEquipmentException(TestEquipmentException.VISA_LIBRARY_ERROR, msg)

    def write(self, command):
        """
        Send message to the equipment

        :type command: str
        :param command: write command to send
        """

        try:
            # Check handle of the equipment
            self.check_handle()

            self.__logger.debug("sending write command '%s'" % command)
            # Send write command on equipment
            self.get_handle().write(command)

        except (visaexception.VisaIOError,
                visaexception.VisaIOWarning,
                visaexception.VisaTypeError) as ex:
            msg = "Write command failed. "
            msg += str(ex)
            self.get_logger().error(msg)
            raise TestEquipmentException(TestEquipmentException.VISA_LIBRARY_ERROR, msg)

    def query(self, command, log=True):
        """
        Send query message to the equipment

        :type command: str
        :param command: query command to send

        :rtype: str
        :return: the message returned by the equipment
        """

        try:
            # Check handle of the equipment
            self.check_handle()
            if log:
                self.__logger.debug("sending query command '%s'" % command)
            # Send query command to the equipment
            result = self.get_handle().ask(command)
            if log:
                self.__logger.debug("got result '%s'" % result)
            return result

        except (visaexception.VisaIOError,
                visaexception.VisaIOWarning,
                visaexception.VisaTypeError) as ex:
            msg = "Query command failed. "
            msg += str(ex)
            self.get_logger().error(msg)
            raise TestEquipmentException(TestEquipmentException.VISA_LIBRARY_ERROR, msg)

    def read(self):
        """
        Read str message from the equipment

        :rtype: str
        :return: read command

        :raise: TestEquipmentException

        """

        try:
            # Check handle of the equipment
            self.check_handle()

            # Read message from equipment
            return self.get_handle().read()

        except (visaexception.VisaIOError,
                visaexception.VisaIOWarning,
                visaexception.VisaTypeError) as ex:
            msg = "Read command failed. "
            msg += str(ex)
            self.get_logger().error(msg)
            raise TestEquipmentException(TestEquipmentException.VISA_LIBRARY_ERROR, msg)

    def send_command(self, command, bts=None):
        """
        Send a GPIB Command.

        :type command: str
        :param command: String representing a well formed GPIB command.

        :type bts: str
        :param bts: the BTS to apply the command
        """
        # Clear Status command. Clears the whole status structure
        self.write(command)
Exemple #3
0
class VisaInterfaceCMW500(VisaInterface):
    """
    Add error handling wrapper to Anritsu M8475A visa command
    """
    """
    The string message returned by the equipment when no error occured
    after sending a gpib command
    """

    __GET_LAST_ERR_CMD = "SYST:ERR?"
    """
    GPIB command used to retrieve the last error.
    This command returns an error code (and an error message):
        - equal to zero if no error occurs
        - greater than zero for warning messages
        - lower than zero for error messages
    """
    __CLEAR_STATUS_CMD = "*CLS"
    """
    Clear Status command. Clears the whole status structure
    """
    __FILTERED_ERROR_CODES = []

    def __init__(self, transport, **kwargs):
        VisaInterface.__init__(self, transport, **kwargs)
        self._logger = Factory().create_logger("%s.%s.VISA_R&S_CMW500" % (ACS_LOGGER_NAME, EQT_LOGGER_NAME))

    def send_command(self, command, bts=None):
        """
        Send a GPIB Command.

        :type command: str
        :param command: String representing a well formed GPIB command.

        :type bts: str
        :param bts: the BTS to apply the command
        """
        # Clear Status command. Clears the whole status structure
        self.write(VisaInterfaceCMW500.__CLEAR_STATUS_CMD)
        # Send command to the equipment
        self._logger.debug("Send GPIB command: %s", command)
        # Add the BTS number if the GPIB finish with a ,
        if command[-1] == ",":
            command += str(bts)
        self.write(command)

        # Check errors
        self.error_check()

    def query_command(self, command):
        """
        Send a GPIB Command.

        :type command: str
        :param command: String representing a well formed GPIB command.

        :rtype: String
        :return: Message from equipment giving the value of a dedicated GPIB command
        """
        # Clear Status command. Clears the whole status structure
        self.write(VisaInterfaceCMW500.__CLEAR_STATUS_CMD)
        # Send command to the equipment
        self._logger.debug("Send GPIB command: %s", command)
        response = self.query(command)

        return response

    def error_check(self):
        """
        Error checking and warning reporting
        :raise TestEquipmentException: if err != SUCCESS
        """
        # query the last error
        return_msg = self.query(VisaInterfaceCMW500.__GET_LAST_ERR_CMD)
        (err_code, msg) = return_msg.split(',', 1)
        msg = msg.replace("\r", "")
        msg = msg.replace("\n", "")
        msg = str(msg).strip('"')
        # we can check error thanks to error code
        if err_code.isdigit() or err_code.startswith("-"):
            err_code = int(err_code)
            if err_code > 0 or err_code in VisaInterfaceCMW500.__FILTERED_ERROR_CODES:
                # Warning
                self.get_logger().warning(msg)
            elif err_code < 0:
                # Error
                self.get_logger().error(msg)
                raise TestEquipmentException(TestEquipmentException.SPECIFIC_EQT_ERROR, msg)
            # else command has been executed correctly!
        # if we can't retrieve error code,
        # we check that error message say that no
        # error occurred
        elif msg != VisaInterfaceCMW500.GPIB_SUCCESS:
            self.get_logger().error(msg)
            raise TestEquipmentException(TestEquipmentException.SPECIFIC_EQT_ERROR, msg)