from obspy.clients.seedlink.easyseedlink import create_client
from obspy import UTCDateTime
import matplotlib.pyplot as plt
from matplotlib import rcParams
import numpy as np
import threading

CHN = 'EHN'
SEC = 10
SPS = 250
AMAX = 5e6

time_0 = []
data_0 = []
time_1 = []
data_1 = []

now = UTCDateTime()
tlen = SEC*SPS

plt.figure(figsize=(8, 6), dpi=80, facecolor='w', edgecolor='k')
rcParams['axes.linewidth'] = 1.5

def get_data_0(trace):
    print(trace)
    global time_0, data_0, now
    time_0 += [i for i in trace.times(reftime=now)]
    data_0 += [i for i in trace.data]

def get_data_1(trace):
    print(trace)
    global time_1, data_1, now
    time_1 += [i for i in trace.times(reftime=now)]
    data_1 += [i for i in trace.data]

client_0 = create_client('192.168.1.108:18000', get_data_0)
client_0.select_stream('LK','GE008',CHN)
thread_0 = threading.Thread(target=client_0.run)
thread_0.daemon = True
thread_0.start()

client_1 = create_client('192.168.1.106:18000', get_data_1)
client_1.select_stream('LK','GE006',CHN)
thread_1 = threading.Thread(target=client_1.run)
thread_1.daemon = True
thread_1.start()

while 1:
    if len(data_0) > tlen and len(data_1) > tlen:
        plt.cla()

        plt.subplot(211)
        plt.plot(time_0[-tlen:], data_0[-tlen:] - np.mean(data_0[-tlen:]),
                 'b', linewidth=2)
        plt.xlabel('Time (s)', fontsize=14, fontweight='bold')
        plt.ylabel('Sensor 1 (Top)', fontsize=14, fontweight='bold')
        plt.xlim(min(time_0[-tlen:]), max(time_0[-tlen:]))
        AMAX = max(np.abs(data_0[-tlen:]))
        plt.ylim(-AMAX, AMAX)

        plt.subplot(212)
        plt.plot(time_1[-tlen:], data_1[-tlen:]- np.mean(data_1[-tlen:]),
                 'r', linewidth=2)
        plt.xlabel('Time (s)', fontsize=14, fontweight='bold')
        plt.ylabel('Sensor 2 (Bottom)', fontsize=14, fontweight='bold')
        plt.xlim(min(time_0[-tlen:]), max(time_0[-tlen:]))
        plt.ylim(-AMAX, AMAX)

        plt.show(block=False)
        plt.pause(0.5)


