Oscilloskope utility – using Ethernet with GPS timemarks


In [ ]:
import matplotlib.pyplot as plt
import sys
import os
import time
import h5py
import numpy as np
import glob
import vxi11
import serial

import re
import struct
import datetime

import time, math

gpsport = '/dev/tty.usbmodem1421'

# Step 0:
# Connect oscilloscope via direct Ethernet link
# Step 1:
# Run this cell to verify the connection.

# This will need a rewrite
class TmcDriver:

    def __init__(self, device):
        print("Initializing connection to: " + device)
        self.device = device
        self.instr = vxi11.Instrument(device)
 
    def write(self, command):
        self.instr.write(command);

    def read(self, length = 500):
        return self.instr.read(length)

    def read_raw(self, length = 500):
        return self.instr.read_raw(length)
 
    def getName(self):
        self.write("*IDN?")
        return self.read(300)
    
    def ask(self, command):
        return self.instr.ask(command)
 
    def sendReset(self):
        self.write("*RST")  # Be carefull, this real resets an oscilloscope
        
# Default oscilloscope record timeout [s]
loop_sleep_time = 60
        
# For Ethernet
#osc = TmcDriver("TCPIP::147.231.24.72::INSTR")
osc = TmcDriver("TCPIP::10.1.1.254::INSTR")
print(osc.ask("*IDN?"))


Initializing connection to: TCPIP::10.1.1.254::INSTR

Read repeatedly records from oscilloscope


In [7]:
filename = 0

secsInWeek = 604800 
secsInDay = 86400 
gpsEpoch = (1980, 1, 6, 0, 0, 0)  # (year, month, day, hh, mm, ss) 

def UTCFromGps(gpsWeek, SOW, leapSecs=14): 
      """converts gps week and seconds to UTC 
   
      see comments of inverse function! 
   
      SOW = seconds of week 
      gpsWeek is the full number (not modulo 1024) 
      """ 
      secFract = SOW % 1 
      epochTuple = gpsEpoch + (-1, -1, 0)  
      t0 = time.mktime(epochTuple) - time.timezone  #mktime is localtime, correct for UTC 
      tdiff = (gpsWeek * secsInWeek) + SOW - leapSecs 
      t = t0 + tdiff 
      (year, month, day, hh, mm, ss, dayOfWeek, julianDay, daylightsaving) = time.gmtime(t) 
      #use gmtime since localtime does not allow to switch off daylighsavings correction!!! 
      return (year, month, day, hh, mm, ss + secFract) 

def parsegps(gpsdata):
    for msg in re.findall('\xb5b\r.{33}', gpsdata):
        (h1,h2,h3,h4,hl) = struct.unpack('<BBBBH', msg[0:6])
        (chan,flags) = struct.unpack('<BB',msg[6:8])
        print(hex(h1), hex(h2), hex(h3), hex(h4),hl)
        (count, wnR, wnF, towMsR, towSubMsR, towMsF, towSubMsF, accEst) = \
        struct.unpack('<HHHIIIII', msg[8:34])
        print(count,wnR, towMsR)
        print UTCFromGps(wnR, towMsR/1000, towSubMsR/1000000)

if (filename == 1):
    for f in glob.iglob("./data/*.h5"): # delete all .h5 files 
        print 'Deleting', f
        os.remove(f)
else:
    print 'Not removing old files, as filename {0} is not 1.'.format(filename)


osc.write(':STOP') # start recording
time.sleep(0.5)

# Get ready to read from GPS port
ser = serial.Serial(gpsport, gpsbaud, timeout=0)
print 'Serial port status: ' + str(ser)

while True:
    #print('  Enter to continue.')
    #raw_input() Wait for key press

    osc.write(':FUNC:WREC:OPER REC') # start recording
    run_start_time = time.time()
    print '  Capturing...'
    # flushnout buffer seriovky
    ser.reset_input_buffer()
    time.sleep(0.5)
    
    while True:
        # Pokud je co cist ze seriovky od GPS
        #if (ser.inWaiting()>0):
        gpsstream = ser.read(1000)
        #parsegps(gpsstream)
        # A zapsat to do souboru stejneho nazvu
        with open('./data/data'+'{:02.0f}'.format(filename)+'_'+str(int(round(run_start_time,0)))+'.gps', 'ab') as gpsf:
                gpsf.write(gpsstream)
        # Preptej se, jestli uz grabovani skoncilo
        osc.write(':FUNC:WREC:OPER?') # finish recording?
        reply = osc.read()
        if reply == 'STOP':
            run_time = round(time.time() - run_start_time, 2)
            print('  Subrun finished, capturing for %.2f seconds.' % run_time)
            break
        time.sleep(0.01)

    osc.write(':WAV:SOUR CHAN1')
    osc.write(':WAV:MODE NORM')
    osc.write(':WAV:FORM BYTE')
    osc.write(':WAV:POIN 1400')

    osc.write(':WAV:XINC?')
    xinc = float(osc.read(100))
    print 'XINC:', xinc,
    osc.write(':WAV:YINC?')
    yinc = float(osc.read(100))
    print 'YINC:', yinc,
    osc.write(':TRIGger:EDGe:LEVel?')
    trig = float(osc.read(100))
    print 'TRIG:', trig,
    osc.write(':WAVeform:YORigin?')
    yorig = float(osc.read(100))
    print 'YORIGIN:', yorig,
    osc.write(':WAVeform:XORigin?')
    xorig = float(osc.read(100))
    print 'XORIGIN:', xorig,
    

    osc.write(':FUNC:WREP:FEND?') # get number of last frame
    frames = int(osc.read(100))
    print 'FRAMES:', frames, 'SUBRUN', filename
    
    with h5py.File('./data/data'+'{:02.0f}'.format(filename)+'_'+str(int(round(run_start_time,0)))+'.h5', 'w') as hf:       
        hf.create_dataset('FRAMES', data=(frames)) # write number of frames
        hf.create_dataset('XINC', data=(xinc)) # write axis parameters
        hf.create_dataset('YINC', data=(yinc))
        hf.create_dataset('TRIG', data=(trig))
        hf.create_dataset('YORIGIN', data=(yorig))
        hf.create_dataset('XORIGIN', data=(xorig))
        hf.create_dataset('CAPTURING', data=(run_time))
        osc.write(':FUNC:WREP:FCUR 1') # skip to n-th frame
        time.sleep(0.5)
        for n in range(1,frames+1):
            osc.write(':FUNC:WREP:FCUR ' + str(n)) # skip to n-th frame
            time.sleep(0.001)

            osc.write(':WAV:DATA?') # read data
            #time.sleep(0.4)
            wave1 = bytearray(osc.read_raw(500))
            wave2 = bytearray(osc.read_raw(500))
            wave3 = bytearray(osc.read_raw(500))
            #wave4 = bytearray(osc.read(500))
            #wave = np.concatenate((wave1[11:],wave2[:(500-489)],wave3[:(700-489)]))
            wave = np.concatenate((wave1[11:],wave2,wave3[:-1]))
            hf.create_dataset(str(n), data=wave)
    filename = filename + 1


Not removing old files, as filename 0 is not 1.
Serial port status: Serial<id=0x1062b22d0, open=True>(port='/dev/tty.usbmodem1421', baudrate=115200, bytesize=8, parity='N', stopbits=1, timeout=0, xonxoff=False, rtscts=False, dsrdtr=False)
  Capturing...
  Subrun finished, capturing for 128.21 seconds.
XINC: 9.999999e-08 YINC: 0.02 TRIG: 0.11734 YORIGIN: -73.0 XORIGIN: -2.04e-05 FRAMES: 254 SUBRUN 0
  Capturing...
  Subrun finished, capturing for 122.35 seconds.
XINC: 9.999999e-08 YINC: 0.02 TRIG: 0.11734 YORIGIN: -73.0 XORIGIN: -2.04e-05 FRAMES: 254 SUBRUN 1
  Capturing...
  Subrun finished, capturing for 42.75 seconds.
XINC: 9.999999e-08 YINC: 0.02 TRIG: 0.11734 YORIGIN: -73.0 XORIGIN: -2.04e-05 FRAMES: 89 SUBRUN 2
  Capturing...
---------------------------------------------------------------------------
KeyboardInterrupt                         Traceback (most recent call last)
<ipython-input-7-ed8daa643422> in <module>()
     81             print('  Subrun finished, capturing for %.2f seconds.' % run_time)
     82             break
---> 83         time.sleep(0.01)
     84 
     85     osc.write(':WAV:SOUR CHAN1')

KeyboardInterrupt: 

In [ ]: