from tdms_file import TDMSFile
import numpy as np
import matplotlib.pyplot as plt
from scipy.io import savemat as sio_savemat

def read_file(analog_file, encoder_file):       
    # create the tdms file object & link to nilibddc.dll
    file = TDMSFile(bin_path = "C:\\Users\\mkemp\\Documents\\Python\\tdms\\bin")  # bin_path = location of nilibddc.dll

    # load the analog data
    file.open(file_name = analog_file )
    print(analog_file)
    data, period, npoints = file.read()
    file.close()

    # load the encoder data
    file.open(file_name = encoder_file)
    encoder_data, period, npoints = file.read()
    file.close()

    # merge the two data sets and add a time array
    data['time'] = np.arange(npoints) * period
    data.update(encoder_data)  # merge dicts

    return data

def save_to_mat(file_name, data):
    sio_savemat(file_name, data)

def plot(data):
    time = data['time']
    voltage = 2.15    * (data['voltage'] + 0.012)
    current = 107.5   * (data['current'] + 0.016)
    str_pot = 6.8     * data['str_pot']
    encoder = 2.45e-5 * data['encoder']

    plt.figure(1)
    plt.plot(time, voltage)
    plt.xlabel("time (s)")
    plt.ylabel("voltage (V)")
    plt.grid()

    plt.figure(2)
    plt.plot(time, current)
    plt.xlabel("time (s)")
    plt.ylabel("current (mA)")
    plt.grid()

    plt.figure(3)
    plt.plot(time, str_pot)
    plt.xlabel("time (s)")
    plt.ylabel("string pot (mm)")
    plt.grid()

    plt.figure(4)
    plt.plot(time, encoder)
    plt.xlabel("time (s)")
    plt.ylabel("encoder (mm)")
    plt.grid()

    plt.ion()
    plt.show()
    plt.pause(0.001)

if __name__ == "__main__":

    data_folder = "C:\\Users\\mkemp\\Desktop\\null_fwd_rev_experiments_2019-02-25\\"
    timecode = "2019-02-25-15-43-45"
    analog_file  = data_folder + "analog-"  + timecode + ".tdms"
    encoder_file = data_folder + "encoder-" + timecode + ".tdms"
    matlab_file  = data_folder + "data-"    + timecode + ".mat"

    data = read_file(analog_file, encoder_file)

    save_to_mat(matlab_file, data)

    #plot(data)

    
    
    


