""" HM1507 for py3  
Remote viewer for HM1507 oscilloscope
programmed by jean-claude.feltes@education.lu

"""


# EDIT HERE

Port="/dev/ttyS4"     #ttyS4

# END EDIT AREA


#----------------------------------------------------------------------

import serial
import time
import matplotlib.pyplot as plt




class HM1507:
    """
    #  HM1507 Class with methods to connect and disconnect
    #  e. g. oszi=HM1507("/dev/ttyS0") creates object HM1507 on port /dev/ttyS0
    """    
    
    def __init__(self,COMport):
        
        self.ser = serial.Serial(COMport)  
    
    def OpenPort(self):
        # open serial  port
        print ("Opened " + self.ser.portstr)      
        self.ser.stopbits=2
        self.ser.trscts=1
        self.ser.timeout=200
        if self.ser.isOpen()==False:
            self.ser.open()
            
    def ClosePort(self):
        # close serial port 
        self.ser.close()  
        
    def SendCommand(self,s):
        # send command to oscilloscope
        # s is the command byte
        # <CR> and <LF> are appended to s
                       
        self.ser.write(s)
        self.ser.write(b'\x0D')
        self.ser.write(b'\x0A')
        
    def SendCommandReadAnswer(self,s):
        self.SendCommand(s)        
        ok=self.ser.readline()
        return ok        
        
    def Connect(self):
        print ("connect")
        self.OpenPort() 
        ok=self.SendCommandReadAnswer(b" " )
   
    
    def Disconnect(self):
        print ("disconnect")
        ok=self.SendCommandReadAnswer(b"rm0")
        print ("close port")
        self.ClosePort()
        
        
    def Version(self):
        return self.SendCommandReadAnswer(b"VERS?")
        
        
    def ID(self):
        return self.SendCommandReadAnswer(b"ID?")
        
    def PrintInfo(self):
        print (self.ID())
        print (self.Version())    
       
#-----------------------------------------------------------------------    
    def ReadDDF(self):
        # Read DEVICE DATA FIELD
        # returns (VoltsPerDIV1, VoltsPerDIV2,TimePerDIVValue,TimeperDIVUnit)

        self.SendCommand(b"DDF?")
        
        # read response (should be "DDF:" )
        ok=b""
        ok=self.ser.read(4)
        
        # read 14 bytes containing info
        DDF=b'\x00'              #  1 dummy byte   
        for i in range(0,14):    #read 14 bytes to DDF[1...14]
            DDF=DDF + self.ser.read()
        
        # VERMODE in DDF(1)...DDF(3)
        #ch1M, ch2M = scale factors + inverted + probe info
        
        # 10:1 probe CH1 ?
        if (DDF[3] & 64): ch1M = 10 
        else: ch1M = 1
            
        # 10:1 probe CH2 ?
        if (DDF[3] & 4):
            ch2M = 10
        else:
            ch2M = 1
            
        # Channel inverted?
        if DDF[1] & 32:
            ch1M = -ch1M           
        if DDF[2] & 32:
            ch2M = -ch2M
                        
        
        # CH1/CH2 Volt/DIV
        # array with volt/div  values .  Attention! all must be float otherwise error in calculation! 
        Volts=[0, 1.0, 2.0, 5.0, 10.0, 20.0, 50.0, 0.1, 0.2, 0.5, 1.0 ,2.0 ,5.0 , 10.0, 20.0]
        
        Counter = DDF[1] & 15
        VoltsPerDIV1 = Volts[Counter + 1] * ch1M
        if Counter < 7: 
            Yunit1= "mV"
        else:
            Yunit1 = "V"
                
        Counter = DDF[2] & 15
        VoltsPerDIV2 = Volts[Counter + 1] * ch2M
        if Counter < 7: 
            Yunit2= "mV"
        else:
            Yunit2 = "V"
            
        # X Time/DIV, value and unit
        # array with time values to select from (must be float!!)
        XVal = [1.0, 2.0, 5.0, 10.0, 20.0, 50.0, 100.0 ,200.0 ,500.0]
        Counter = DDF[4] & 31
        k = Counter + 5
        k = k % 9         # k mod 9
        TimePerDIVValue = XVal[k]
        
        #Time/DIV unit
        if Counter in range(0,4):
            TimeperDIVUnit = "ns"
        elif  Counter in range(4,13):
            TimeperDIVUnit = "us"   
        elif  Counter in range(13,22):
            TimeperDIVUnit = "ms"   
        elif  Counter in range(22,29):
            TimeperDIVUnit = "s"   
        else:
            print ("Error reading time/div")
                    
        return VoltsPerDIV1, VoltsPerDIV2,Yunit1, Yunit2, TimePerDIVValue,TimeperDIVUnit
#-----------------------------------------------------------------------
    def ReadWFMPRE(self):
        # Read Wave Form Preamble
        # returns XresPerDIV, YresPerDIV,Y1Position,Y2Position
    
        self.SendCommand(b"WFMPRE?")
        
        # read 14 bytes containing info
        WFMPRE=b' '                 #  1 dummy byte     
        
        for i in range(0,17):       #read 17 bytes to WFMPRE[1...17]
            WFMPRE+=self.ser.read()    
            
        XresPerDIV = WFMPRE[10] + WFMPRE[11] * 256
        YresPerDIV = WFMPRE[12] + WFMPRE[13] * 256
        Y1Position =WFMPRE[14]+WFMPRE[15]*256
        Y2Position =WFMPRE[16]+WFMPRE[17]*256
        
        # correction for negative values:
        if Y1Position & 0x8000: Y1Position = -(65536-Y1Position)
        if Y2Position & 0x8000: Y2Position = -(65536-Y2Position)
                        
        return XresPerDIV, YresPerDIV,Y1Position,Y2Position
#-----------------------------------------------------------------------        
        
    def ReadWaveform(self,channel):
        """ Read raw waveform data
            channel = 1/2
            returns bytearray with 2048 values (indexed ..."""
        
        # command:
        if channel==2: 
            sc=b"RDWFM2:"
        else: 
            sc=b"RDWFM1:"
        sc+=b'\x00\x00\x00\x08'
        self.SendCommand (sc)
        
             
        # read response (should be "RDWFM..." )
        ok=b""
        ok=self.ser.read(11)
                
        # read 2048 bytes containing waveform data
        w=bytearray ()         #create empty array w for data
        
        for i in range(0,2048):    #read 2048 bytes to w[0...2047]
            w.extend(self.ser.read())
            
        return w    
#-----------------------------------------------------------------------

    def ReadSettings(self):
        # calls ReadDDF and ReadWFMPRE to get the basic settings
        
        # read settings from oscilloscope
        (VoltsPerDIV1, VoltsPerDIV2, Yunit1, Yunit2, TimePerDIVValue,TimeperDIVUnit)=self.ReadDDF()
        (XresPerDIV, YresPerDIV,Y1Position,Y2Position)=self.ReadWFMPRE()
        
        # default values for Xres, Yres:
        if XresPerDIV==0: XresPerDIV = 200
        if YresPerDIV==0: YresPerDIV = 25
        
        
        # Voltage window:
        U1min = (-128 - Y1Position) / YresPerDIV * VoltsPerDIV1
        U1max = (128 - Y1Position) / YresPerDIV * VoltsPerDIV1
        U2min = (-128 - Y2Position) / YresPerDIV * VoltsPerDIV2
        U2max = (128 - Y2Position) / YresPerDIV * VoltsPerDIV2
        
        # print info
        print ("CH1",VoltsPerDIV1,"V/DIV")
        print ("CH2",VoltsPerDIV2,"V/DIV")
        print ("TIME/DIV: " ,TimePerDIVValue,TimeperDIVUnit)
        
        print ("X resolution: ", XresPerDIV)
        print ("Y resolution: ", YresPerDIV)
        print ("Y1 position: ", Y1Position)
        print ("Y2 position: ", Y2Position)

        print ("CH1 : ",U1min, " to ", U1max,"V")
        print ("CH2 : ",U2min, " to ", U2max,"V")
        
        # set self.attributes and return values 
        #(you can use one or the other)
        self.VperDIV1= VoltsPerDIV1
        self.VperDIV2= VoltsPerDIV2
        self.YresPerDIV=YresPerDIV
        self.Yunit1= Yunit1
        self.Yunit2= Yunit2
        self.XresPerDIV=XresPerDIV
        self.Y1Position = Y1Position
        self.Y2Position = Y2Position
        self.TimePerDIVValue=TimePerDIVValue
        self.Timeunit=TimeperDIVUnit
        self.U1min=U1min
        self.U2min=U2min
        self.U1max=U1max
        self.U2max=U2max
        self.tmax=10*TimePerDIVValue
        
        # optionnally return values of settings
        return (VoltsPerDIV1, VoltsPerDIV2, Yunit1, Yunit2, TimePerDIVValue,
           TimeperDIVUnit,XresPerDIV,YresPerDIV,Y1Position,Y2Position)

#-----------------------------------------------------------------------
    def ConvertY1(self,w):
        # converts Y1 values to voltage
        
        Scalefactor=self.VperDIV1/self.YresPerDIV
        v = [float(w_element-128-self.Y1Position)*Scalefactor for w_element in w ]
        return v
#-----------------------------------------------------------------------
    def ConvertY2(self,w):
        # converts Y2 values to voltage
        
        Scalefactor=self.VperDIV2/self.YresPerDIV
        v = [float(w_element-128-self.Y2Position)*Scalefactor for w_element in w ]
        return v
#-----------------------------------------------------------------------
    def get_timevector(self):
        # returns time values as a list 
        xi=range(0,2048)       
        Scalefactor=self.TimePerDIVValue/self.XresPerDIV
        t = [float(x_element)*Scalefactor for x_element in xi ]
        return t
        
#-----------------------------------------------------------------------


#***********************************************************************    
# High level functions for main program:  

    def get_CH1(self):
    # get CH1 into (t,v) vector
        print("Acquiring channel 1")
        
        # connect  
        self.Connect()
        self.PrintInfo()
        
        # read settings + waveform
        self.ReadSettings()
        w=self.ReadWaveform(1)
        
        # disconnect
        self.Disconnect()
        
        # generate plot values out of waveform + settings
        v=self.ConvertY1(w)
        t=self.get_timevector()
        return (t,v)
#-----------------------------------------------------------------------        
    def get_CH2(self):
    # get CH2 into (t,v) vector
        print("Acquiring channel 2")
        
        # connect  
        self.Connect()
        self.PrintInfo()
        
        # read settings + waveform
        self.ReadSettings()
        w=self.ReadWaveform(2)
        
        # disconnect
        self.Disconnect()
        
        # generate plot values out of waveform + settings
        v=self.ConvertY2(w)
        t=self.get_timevector()
        return (t,v)    
#***********************************************************************

# plot functions
def plot_CH1(t,v):
    # (t,v) = (time, voltage) as tuple
    plt.figure(1)
    plt.subplot(111)                # 1 row, 1 col, plot nb. 1 
    plt.axis([0, oszi.tmax,oszi.U1min, oszi.U1max])        #([]) !
    plt.grid(True)
    plt.plot(t, v)
    plt.xlabel("t/" +oszi.Timeunit)
    plt.ylabel("U_CH1/"+oszi.Yunit1)
    plt.show()
    
def plot_CH2(t,v):
    # (t,v) = (time, voltage) as tuple
    plt.figure(1)
    plt.subplot(111)                # 1 row, 1 col, plot nb. 1 
    plt.axis([0, oszi.tmax,oszi.U2min, oszi.U2max])        #([]) !
    plt.grid(True)
    plt.plot(t, v)
    plt.xlabel("t/" +oszi.Timeunit)
    plt.ylabel("U_CH2/"+oszi.Yunit2)
    plt.show()    
    
def plot_dual(t,v1,v2):
    # (t,v1, v2) = (time, voltage) as tuple
    
    
    plt.figure(1)
    
    # CH1
    plt.subplot(211)                # 2 rows, 1 col, plot nb. 1 
    plt.plot(t, v1)
    plt.xlabel("t/" +oszi.Timeunit)
    plt.ylabel("U_CH1/"+oszi.Yunit1)
    plt.axis([0, oszi.tmax,oszi.U1min, oszi.U1max])
    plt.grid(True)

    
    # CH1
    plt.subplot(212)                # 2 rows, 1 col, plot nb. 2 
    plt.plot(t, v2)
    plt.xlabel("t/" +oszi.Timeunit)
    plt.ylabel("U_CH2/"+oszi.Yunit2)
    plt.axis([0, oszi.tmax,oszi.U2min, oszi.U2max])
    plt.grid(True)

    
    
    plt.show()        


#***********************************************************************

if __name__ == "__main__":
    
    """
    main as Tkinter GUI
    """
    
    from tkinter import *
    window=Tk()
    
    oszi=HM1507(Port)
         
    def getCH1():
        t,v= oszi.get_CH1()
        plot_CH1(t,v)
        
    def getCH2():
        t,v= oszi.get_CH2()
        plot_CH2(t,v)
        
    def getCH12():
        t,v1= oszi.get_CH1()
        t,v2= oszi.get_CH2()
        plot_dual(t,v1, v2)
    
    btnCH1=Button(master=window, text="CH1", command = getCH1)
    btnCH2=Button(master=window, text="CH2", command = getCH2)
    btnCH12=Button(master=window, text="CH1 + CH2", command = getCH12)
    btnCH1.pack()
    btnCH2.pack()
    btnCH12.pack()
    
    window.mainloop()
        



