# coding: UTF-8

import pyvisa
import time
import tkinter.messagebox

rm = pyvisa.ResourceManager()

class Gpib:

    def __init__(self, gui=False):
        self.inst = rm
        self.gui = gui

    #Open port
    def open(self, boardID, primaryAddress, timeout):
        ret = False
        device = "GPIB" + boardID + "::" + primaryAddress + "::" + "INSTR"
        try:
            self.inst = rm.open_resource(device)
            self.inst.timeout = timeout
            ret = True
        except Exception as e:
            if self.gui == True:
                tkinter.messagebox.showerror("Open Error", e)
            else:
                print("Open error")
                print(e)
        
        return ret

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

        try:   
            self.inst.close()
            ret = True
        except Exception as e:
            if self.gui == True:
                tkinter.messagebox.showerror("Close Error", e)
            else:
                print("Close error")
                print(e)
        
        return ret
        
    #Send command
    def sendMsg(self, strMsg):
        ret = False

        try:
            self.inst.write(strMsg)
            ret = True
        except Exception as e:
            if self.gui == True:
                tkinter.messagebox.showerror("Send Error", e)
            else:
                print("Send Error")
                print(e)

        return ret
    
    #Receive
    def receiveMsg(self, timeout):

        msgBuf = bytes(range(0))                    #Received Data

        try:
            self.inst.timeout = timeout * 1000
            while True:
                rcv = self.inst.read_bytes(1)       #Receive 1 byte
                if rcv == b"\n":                    #End the loop when LF is received
                    msgBuf = msgBuf.decode('utf-8')
                    break
                elif rcv == b"\r":                  #Ignore the terminator CR
                    pass
                else:
                    msgBuf = msgBuf + rcv
        except pyvisa.VisaIOError as e:
            if self.gui == True:
                tkinter.messagebox.showerror("Receive Error", e)
            else:
                print("Receive Error")
                print(e)
            msgBuf = "Timeout Error"
        except Exception as e:
            if self.gui == True:
                tkinter.messagebox.showerror("Receive Error", e)
            else:
                print("Receive Error")
                print(e)
            msgBuf = "Error"

        return msgBuf
    
    #Transmit and receive commands
    def SendQueryMsg(self, strMsg, timeout):
        ret = Gpib.sendMsg(self, strMsg)
        if ret:
            msgBuf_str = Gpib.receiveMsg(self, timeout)   #Receive response when command transmission is succeeded
        else:
            msgBuf_str = "Error"

        return msgBuf_str
