"""
 terminalwindow for tkinter
 by jean-claude.feltes@education.lu 25.1.2015

Class Terminalwindow defines a ScrolledTextbox that is attached to a serial port
Received text  from serial port is automatically written to text box
Keys typed in the text box are directly sent to serial port
    
    Usage:
    serial_textbox= Terminalwindow(1,38400)   # port COM1, 38400 baud
    serial_textbox.connect()    # for character oriented reading
    ....
    serial_textbox.disconnect()
    
    All serial methods and attributes are available for Terminalwindow
"""    

import threading, Queue
import Tkinter as tk
from ScrolledText import ScrolledText
import serial 
#----------------------------------------------------------------------        
class Terminalwindow( serial.Serial, ScrolledText):
    """inherits first from Serial, then from ScrolledText
       this is a little bit dangerous as methods with the same name
       from one and the other might conflict!
       But it is rather practical if there are no conflicts
    """        
    def __init__(self, COMport, baudrate, **kwargs):
        # init textbox and serial port
        ScrolledText.__init__(self, **kwargs)  
        serial.Serial.__init__(self)
        
        # set Serial port and baudrate
        self.port  = COMport-1
        self.baudrate = baudrate 
               
        # suppress carriage return ( CRLF -> LF only)
        self.suppress_CR=1
        
        # Create stop event (to terminate endless receiving loop)
        # and message queue for thread (to transmit received text to TextCtrl)
        self.stopevent=threading.Event() 
        self.msgQueue=Queue.Queue()
 
        # Bindings for Key event (send to RS232)
        # and Destroy -> stop serial thread
        self.bind("<Key>", self._OnKeypress )
        self.bind("<Destroy>", self._OnDestroy  )
        
        # start polling for message in queue
        self._poll_message()
        
    def _OnDestroy(self, event):
        # on destruction, tell serial thread to stop, otherwise it stays alive
        self.disconnect()
            
        
    def _poll_message(self):
        # regularily update text from message queue 
        while not self.msgQueue.empty():
            msg=self.msgQueue.get()
            self.insert(tk.END,msg)
            self.see(tk.END)  
        # do this again every 50ms
        self.after(50, self._poll_message )
                
        

    def disconnect(self):
        # set stop event so endless receiving loop is interrupted
        self.stopevent.set()
        
    
    def connect(self):
        """connect to COM port and read characters to Terminalwindow"""
        # create a new thread object that runs serial thread
        # to read serial characters
        self.serialthread = threading.Thread(group=None, target=self.readSerial , 
            name="ser_read",args=(), kwargs={})
        # clear stopevent and start thread
        self.stopevent.clear()
        self.serialthread.start()
       
        
    def readSerial(self):
        """ read characters of data to terminal textbox
            this runs in a separate thread  """ 
                
        if self.isOpen()==False:
            self.open()
        print "connected, port", self.portstr, "    ",self.baudrate,"baud"
        
        # endless receiving loop
        while True:
            try:
                # read bytes and put them to message queue:
                nbbytes = self.inWaiting()
                if nbbytes >0:
                    c = self.read(nbbytes)
                    
                    # eventually suppress CR
                    if self.suppress_CR:
                        c=c.replace("\r", "")
                    
                    self.msgQueue.put(c)
                   
            except:
                pass 
                
            # interrupt loop when stop event is set
            if self.stopevent.isSet():
                break 
                
        print "disconnected"  
        self.close()
        
    
          
        
    def _OnKeypress(self,event):
        # Respond to key press in text box
        ok = event.char
               
        try:
            # write to port
            if self.isOpen()== True: 
                self.write(ok)
        except:
            print "PORT ERROR",
            
        # don't send key event to textbox
        return "break"      
        
        
    def write_serial(s):
        """ write s to the connected serial port"""
        try:
            self.write(s)
        except:
            print "PORT ERROR"                         
#---------------------------------------------------------------------- 


def disconnect():
    serial_textbox.disconnect()
    

# Main test program 
if __name__ == "__main__":  
    mainwindow = tk.Tk()
   
    serial_textbox=Terminalwindow(1,38400)      # COM1, 38400baud
    serial_textbox.grid()
    serial_textbox.connect()
        
    b=tk.Button(mainwindow, text="Disconnect", command=disconnect)
    b.grid()
        
    mainwindow.mainloop()
    
