from api import EmscopeConnection
import asyncio
import time
import matplotlib.pyplot as plt

#def customParser(val):
#    print("Received",val.keys())

valsx = []
valsy = []

async def main():

    # Instantiate emscope connection
    emscope = EmscopeConnection("ws://10.10.14.51:8010")
    model_rx4 = True
    rbw = '9'                   # RBW. Availables (depending on the model): 
                                #   {'200'-->200Hz, '1'-->1k, 
                                #       '9'-->9k, '10'-->10k, '120'-->120k]
                                # Also configures the frequency band to be measured.
    detector_type = 'pk'        # Availables: ['pk','qp','av']
    channel = 'l3'              # Channels: 
                                #   On RX4: ['l1','n', 'l2', 'l3']
                                #   On RX2: ['lg','ng']
    amp_units = 'dbuv'          # Available: ['dbuv','dbmv','volts','watts','dbm']
    trace_type = 'clearwrite'   # ['clearwrite','maxhold','minhold','average']
    reference_level = str(115)  # Lookout. It is MUST be in accordance to amplitude units.
    
    # Connect
    await emscope.connect()

    # Set desired values
    await emscope.setValue("session_UUID", "12345")
    await emscope.setRBW(rbw, model_rx4)
    await emscope.setValue("detector_type", detector_type)
    await emscope.setValue("measure_channel", channel)
    await emscope.setValue("trace_type", trace_type)
    await emscope.setValue("amp_units", amp_units)
    
    await emscope.setValue("reference_level", reference_level)
    await emscope.setValue("input_attenuator", "auto")
    await emscope.setValue("sweep_time", "1")
    await emscope.setValue("visible", True)
    
    await emscope.setValue("display_range", [150000, 30000000]) # Frequencies to display. Related to the measured band.

    # Measure for 2 seconds
    starttime = time.time()
    while starttime+2 >= time.time():
        # Get messages
        rec = await emscope.parseMessages()
        print("Received", rec.keys())

    
    valsx = []
    valsy = []

    for val in emscope.values:
        valsx.append(val[0])
        valsy.append(val[1])

    plt.plot(valsx, valsy)
    plt.title(f'Emscope - {detector_type} {channel} {trace_type} {amp_units} RBW {rbw} \
              RL {reference_level} IA auto')
    plt.ylabel(f'{amp_units}')
    plt.xlabel('Hz')
    plt.show()
    await emscope.disconnect()

asyncio.get_event_loop().run_until_complete(main())