# coding: UTF-8

import pyvisa

BUFSIZE = 4096

class Myvisa:
    msg_buf = ""

	# Constructor
    def __init__(self):
        self.rm = pyvisa.ResourceManager()

    # Get library information
    def get_lib(self):
        return self.rm


    # Get resource list
    def get_resources(self):
        return self.rm.list_resources()


    # Open port
    def open(self, resource):
        ret = False

        try:
            self.inst = self.rm.open_resource(resource)
            self.inst.write_termination = '\r\n'    # Set transmit terminator (CR+LF)
            self.inst.read_termination = '\n'       # Set receive terminator (LF)
            self.rm.visalib.set_buffer(self.inst.session, pyvisa.constants.VI_READ_BUF, BUFSIZE)    # Set receive buffer size

            ret = True
        except Exception as e:
            print("Open error")
            print(e)
        
        return ret


    # Close port
    def close(self):
        ret = False

        try:
            self.rm.close()
            ret = True
        except Exception as e:
            print("Close error")
            print(e)
        
        return ret


    # Send command
    def send_msg(self, str_msg):
        ret = False

        try:
            self.inst.write(str_msg)                # Send
            ret = True
        except Exception as e:
            print("Write error")
            print(e)

        return ret
    
    
    # Transmit and receive commands
    def send_query_msg(self, str_msg, timeout_ms):
        ret = False

        try:
            if "?" in str_msg :
                Myvisa.msg_buf = ""                         # Clear receive buffer
                self.inst.timeout = timeout_ms              # Set timeout
                Myvisa.msg_buf = self.inst.query(str_msg)   # Transmit and receive
                Myvisa.msg_buf = Myvisa.msg_buf.replace('\r', '')
            else :
                self.send_msg(str_msg)                      # Transmit only
            
            ret = True

        except Exception as e:
            print("Query error")
            print(e)
            Myvisa.msg_buf = "Error"

        return ret