from tdms.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 )
    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.1)   # V
    current = -107.5   * (data['current'] - 0.15)  # mA
    strpot  = -6.8     * (data['str_pot'] + 3.8)   # mm
    encoder = -0.01309 * data['encoder']           # rad

    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 (rad)")
    plt.grid()

    plt.ion()
    plt.show()
    plt.pause(0.001)

if __name__ == "__main__":

    data_folder = "C:\\Users\\mkemp\\Documents\\MATLAB\\galene calibration\\2019-04-02-15iterations\\"
    timecode = "2019-04-02-18-21-17"
    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)
