import sys
import time
from ctypes import *
from wecg400 import *
import matplotlib
import matplotlib.pyplot as plt
import threading

the_lock = threading.Lock()

fig = plt.figure()
plt.xlabel('Time')
plt.ylabel('Voltage')
plt.title('ECG Output')
plt.ion()
plt.show(block=False)
plt.ylim(-2, 2)

data_x = []
data_y = []
last_plt_x = 0
last_plt_y = 0


def SingalOutputHandler(time, amplitude):
    global data_x
    global data_y

    with the_lock:
        data_x.append(time)
        data_y.append(amplitude)


def FrequencyScanHandler(value):
    if value == OutputFunction.Output_Off.value:
        print('done')


device = WECG400(get_lib_path())
if device.connect(-1, 5000) == False:
    print('Error: device is not connected')
    device.free()
    sys.exit()

print('output Sine frequency scan (0.675Hz-500Hz, 30sec) ...', end='')
sys.stdout.flush()


outputCb = SignalOutputCallback(SingalOutputHandler)
frequencyCb = FrequencyCallback(FrequencyScanHandler)

device.reset()
device.register_signal_output_callback(outputCb)
device.set_frequency(1.0)
device.set_amplitude(1.0)
device.set_output_lead(OutputDut.DUT1.value, OutputLead.Lead_RA.value)
device.register_frequency_callback(frequencyCb)

pause()

device.set_frequency_scan(c_bool(True), c_double(0.67),
                          c_double(500), c_int(30))

while last_plt_x < 30:
    data = [[last_plt_x], [last_plt_y]]
    with the_lock:
        data[0] += data_x
        data[1] += data_y
        last_plt_x = data_x[-1]
        last_plt_y = data_y[-1]
        data_x = []
        data_y = []

    plt.xlim(last_plt_x-0.2, last_plt_x+0.05)
    plt.plot(data[0], data[1], c='black')
    plt.draw()
    plt.pause(0.1)

    time.sleep(0.2)

device.set_output_function(OutputFunction.Output_Off.value)  # stop output
device.free()
