# coding: UTF-8

import serial
import time
import tkinter.messagebox

class Usb_rs:

    def __init__(self, gui=False):
        self.ser = serial
        self.gui = gui
    
    #ポートオープン
    def open(self, port, speed):
        ret = False

        try:
            self.ser = serial.Serial(port, speed,timeout=0)
            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.ser.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:
            strMsg = strMsg + '\r\n'                #ターミネータ「CR+LF」を付加
            self.ser.write(bytes(strMsg, 'utf-8'))  #バイト型に変換し送信
            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:
            start = time.time()                     #タイムアウト用に時間を記録
            while True:
                if self.ser.inWaiting() > 0:        #受信バッファにデータがあるか
                    rcv = self.ser.read(1)          #1バイト受信
                    if rcv == b"\n":                #ターミネータ「LF」を受信したら終了
                        msgBuf = msgBuf.decode('utf-8')
                        break
                    elif rcv == b"\r":              #ターミネータ「CR」は無視
                        pass
                    else:
                        msgBuf = msgBuf + rcv
                
                #タイムアウト処理
                if  time.time() - start > timeout:
                    msgBuf = "Timeout Error"
                    break
        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 = Usb_rs.sendMsg(self, strMsg)
        if ret:
            msgBuf_str = Usb_rs.receiveMsg(self, timeout)   #送信が成功したら応答を受信
        else:
            msgBuf_str = "Error"

        return msgBuf_str



