# 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

    #ポートオープン
    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

    #ポートのクローズ
    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
        
    #コマンドの送信
    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
    
    #コマンドの受信
    def receiveMsg(self, timeout):

        msgBuf = bytes(range(0))                    #受信データ

        try:
            self.inst.timeout = timeout * 1000
            while True:
                rcv = self.inst.read_bytes(1)       #1バイト受信
                if rcv == b"\n":                    #ターミネータ「LF」を受信したら終了
                    msgBuf = msgBuf.decode('utf-8')
                    break
                elif rcv == b"\r":                  #ターミネータ「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
    
    #コマンドの送受信
    def SendQueryMsg(self, strMsg, timeout):
        ret = Gpib.sendMsg(self, strMsg)
        if ret:
            msgBuf_str = Gpib.receiveMsg(self, timeout)   #送信が成功したら応答を受信
        else:
            msgBuf_str = "Error"

        return msgBuf_str
