#  
# 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
scope=win32com.client.Dispatch("LeCroy.ActiveDSOCtrl.1")  #creates instance of the ActiveDSO control
scope.MakeConnection("IP:192.168.147.152") #Connects to the oscilloscope.  Substitute your IP address
import re
import binascii
import functools
import numpy
import time
from struct import unpack
import matplotlib.pyplot as plt
scope.WriteString("COMM_HEADER OFF",1)
scope.WriteString("COMM_FORMAT DEF9,word,BIN",1) # set scope to format header off and #word (2 bytes x sample) data transfer
#
#scope.WriteString("COMM_FORMAT OFF, BYTE, BIN",1) # set scope to format header off and word (1 bytes x sample) data transfer
#
# stop trigger and check if the scope is in stop mode
# during long acquisitions the scope may still be recording data
#

scope.WriteString("CFMT?",1)
value = scope.ReadString(80)
print (value)
scope.WriteString("VBS? 'return=app.Acquisition.C1.VerScale",1)
value = scope.ReadString(80)
print (value)
vertical_Scale= float(value)
scope.WriteString("VBS? 'return=app.Acquisition.C1.VerOffset",1)
value = scope.ReadString(80)
print (" vertical offset = " + value)
Voffset= float(value)
scope.WriteString("VBS? 'return=app.Acquisition.Horizontal.HorScale",1)
value = scope.ReadString(80)
T= float(value)
print (T)



plt.ion()
scope.WriteString("C1:WF? DAT1",1)
#read first 15 bytes, to determine how many bytes need to be transferred 
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) 
print data
plt.ylim(-vertical_Scale*4,vertical_Scale*4)
plt.xlim(0, rlen/2)
plt.figure(1)
plt.plot(data)
plt.show(1)
time.sleep(10)
plt.close()
plt.ioff()
exit()
