#  
# M.Mastrofini Example of Scope remote control using Python
#  July 2014 -  ver 1.0
#  example using direct commands and VBS commands
#  Wincom extension must be installed
#
import win32com.client #imports the pywin32 library
#from GimpGradientFile import SEGMENTS
scope=win32com.client.Dispatch("LeCroy.ActiveDSOCtrl.1")  #creates instance of the ActiveDSO control
scope.MakeConnection("IP:127.0.0.1") #Connects to the oscilloscope.  Substitute your IP address
import re
import os
import binascii
import functools
import numpy as np
import time

import matplotlib.pyplot as plt
source_dir= "D:\\Waveforms\\temp"
os.chdir(source_dir)
data = open("byte.trc", "rb").read()
RL = int(data[2:11])- int(data[8:11])
data = data[11:]
for i in range(0,322): 
    a=int(np.fromstring(data[i], dtype = "uint8"))
    print i, a, chr(a)

#BW = np.fromstring(data[52:54], dtype=np.int16)
#Vgain = np.fromstring(data[156:160], dtype=np.float32)
#Voffset = np.fromstring(data[160:164], dtype=np.float32)
BW = np.fromstring(data[51:52], dtype = "uint8")

Voffset1 = np.unpackbits(np.fromstring(data[159], dtype = "uint8"))
Voffset2 = np.unpackbits(np.fromstring(data[160], dtype = "uint8"))
Voffset3 = np.unpackbits(np.fromstring(data[161], dtype = "uint8"))
Voffset4 = np.unpackbits(np.fromstring(data[162], dtype = "uint8"))
Vgain1 = np.unpackbits(np.fromstring(data[155], dtype = "uint8"))
Vgain2 = np.unpackbits(np.fromstring(data[156], dtype = "uint8"))
Vgain3 = np.unpackbits(np.fromstring(data[157], dtype = "uint8"))
Vgain4 = np.unpackbits(np.fromstring(data[158], dtype = "uint8"))
Unit = np.fromstring(data[195], dtype = "uint8")
print RL, np.unpackbits(BW), Vgain1,Vgain2,Vgain3,Vgain4, Voffset1, Voffset2,Voffset3,Voffset4,Unit
temp =[]
for item in data:
    temp.append(item.split(':'))
count=0    
while (count <3):
    plt.ion()
    
    header = scope.ReadBinary(16)
    print (header)
    rlen = int(header[7:16])
    print (rlen)
    T0=-T*5
    print (T0)
    T1=T*5
    print (T1)
    #read from scope the waveform data
    dataword = scope.ReadBinary(rlen-2)
    last_2bytes = scope.ReadBinary(2)
    x=numpy.arange(T0, T1, rlen-2)# horizontal scale vector in uS
    # converting the binary data to 16 bit integers because reading 2 byte per sample. Modify accordingly if readin 1 byte per sample
    #data = numpy.fromstring(dataword, dtype=numpy.int16)
    rlen = (rlen -2)
    data = numpy.array(unpack('%sh' %(len(dataword) / 2) ,dataword))
    data = (data * vertical_Scale/8192) - Voffset
    print data
    plt.ylim(-vertical_Scale*4,vertical_Scale*4)
    plt.xlim(0, rlen/2)
    plt.figure(2)
    plt.subplot(211)
    plt.plot(data)
    plt.show(2)
    time.sleep(1)
    plt.close()
    count += 1
plt.ioff()
exit()
