#================================================================
#================================================================
# C-WaveformGenerator
# MultiChannelWave
# main file
#                                                CONTEC Co., Ltd.
#================================================================
#================================================================
#----------------------------------------
# Import modules
#----------------------------------------
import ctypes
import ctypes.wintypes
import sys
import cgen_api
from CommonFunction import *
from DeviceSetting import *
from ChannelSetting import *


#========================================
# Function name    main
# Parameter        None
# Details          Function that performs main processing
# Return value     None
#========================================
def main():
    device_name = ctypes.create_string_buffer(256)    # Device name
    error_buf = ctypes.create_string_buffer(256)      # Error code string
    lret = ctypes.c_long()                            # For return code
    appid = ctypes.c_short()                          # ID for device access
    open_mode = ctypes.c_ushort()                     # Screen size
    aochannels = ctypes.c_ushort(1)                   # Number of channel
    frequency = ctypes.c_float(1.0)                   # Frequency
    unit_window = ctypes.c_ushort(0)                  # frequency unit
    frequency_type = ctypes.c_ushort(0)               # Frequency or Period
    frequency_unit = ctypes.c_ushort(0)               # Hz(sec) Or kHz(msec)
    oscillation_type = ctypes.c_ushort(0)             # Oscillation type
    oscillation_start = ctypes.c_ushort(1)            # Number of oscillation waveform
    oscillation_stop = ctypes.c_float(1.0)            # Number of oscillation stop waveform or Time of oscillation stop
    aochannel = ctypes.c_ushort(0)                    # Channel
    amplitude = ctypes.c_float(0.0)                   # Amplitude
    offset = ctypes.c_float(0.0)                      # Offset
    amplitude_type = ctypes.c_ushort(0)               # Amplitude type
    amplitude_unit = ctypes.c_ushort(0)               # Amplitude unit
    duty = ctypes.c_float(0.0)                        # Duty
    phase = ctypes.c_float(0.0)                       # Phase
    sweep_type = ctypes.c_ushort(0)                   # Simple sweep
    sweep_time = ctypes.c_ushort(1)                   # Sweep time
    sweep_start = ctypes.c_float(0.0)                 # Sweep before change
    sweep_stop = ctypes.c_float(0.0)                  # Sweep after change
    wave_type = ctypes.c_ushort()                     # Wave type
    status = ctypes.c_ulong()                         # Status


    #----------------------------------------
    # Loop that wait input
    #----------------------------------------
    while True:
        #----------------------------------------
        # Get setting parameters
        #----------------------------------------
        #--------------------
        # Get the device name
        #--------------------
        lret.value = cgen_api.GenGetDeviceName(appid, device_name)
        if lret.value != 0:
            device_name_string = "-"
        else:
            device_name_string = device_name.value.decode('sjis')
        #----------------------------------------
        # Display the setting parameters
        #----------------------------------------
        print("========================================")
        print("Setting Parameter")
        print("========================================")
        print(f"Device Name : {device_name_string}")
        #----------------------------------------
        # Display the command
        #----------------------------------------
        print("========================================")
        print("Menu")
        print("========================================")
        print("1 : GenOpenApplication")
        print("2 : Device Settings")
        print("3 : Channel Settings")
        print("4 : GenSetWaveType")
        print("5 : GenStartOperation")
        print("6 : GenGetApplicationStatus")
        print("7 : GenStopOperation")
        print("8 : GenCloseApplication")
        print("q : Quit")
        print("Please input the command : ", end='', flush=True)
        #----------------------------------------
        # Waiting for input
        #----------------------------------------
        buf = input()
        #----------------------------------------
        # Distinguish the command
        #----------------------------------------
        #--------------------
        # GenOpenApplication
        #--------------------
        if buf == "1":
            #----------------------------------------
            # Input the device name
            #----------------------------------------
            print("\nPlease input the device name : ", end='', flush=True)
            #----------------------------------------
            # Waiting for input
            #----------------------------------------
            buf = input()
            device_name.value = buf.encode()
            #----------------------------------------
            # Input the screen size
            #----------------------------------------
            print("\n----------------------------------------")
            print("Parameter(Screen size)")
            print("----------------------------------------")
            print("0 : Minimize")
            print("1 : Normal")
            print("2 : Maximize")
            while True:
                print("Please select the screen size : ", end='', flush=True)
                #----------------------------------------
                # Waiting for input
                #----------------------------------------
                buf = input()
                #----------------------------------------
                # Check if the input value is a number
                #----------------------------------------
                if False == isnum(buf, 10):
                    continue
                break
            open_mode = ctypes.c_ushort(int(buf))
            #----------------------------------------
            # Initialize the application
            #----------------------------------------
            lret.value = cgen_api.GenOpenApplication(device_name, ctypes.byref(appid), open_mode)
            cgen_api.GenGetErrorString(lret, error_buf)
            print(f"\nGenOpenApplication Ret = {lret.value} {error_buf.value.decode('sjis')}\n")
        #--------------------
        # Device Settings
        #--------------------
        elif buf == "2":
            #----------------------------------------
            # Get the device information
            #----------------------------------------
            lret.value = cgen_api.GenGetDeviceSetting(appid, ctypes.byref(aochannels), ctypes.byref(frequency), ctypes.byref(frequency_type), ctypes.byref(frequency_unit))
            unit_window.value = ((frequency_type.value << 1) + frequency_unit.value)
            #----------------------------------------
            # Get the oscillation
            #----------------------------------------
            lret.value = cgen_api.GenGetOscillation(appid, ctypes.byref(oscillation_type), ctypes.byref(oscillation_start), ctypes.byref(oscillation_stop))
            #----------------------------------------
            # Go to device settings screen
            #----------------------------------------
            devinfo_data_set(aochannels, frequency, unit_window, oscillation_type, oscillation_start, oscillation_stop)
            #----------------------------------------
            # Display device settings menu
            #----------------------------------------
            #----------------------------------------
            # If OK is selected, process
            #----------------------------------------
            if DeviceSetting() == True:
                #----------------------------------------
                # Get data form device settings screen
                #----------------------------------------
                devinfo_data_get(aochannels, frequency, unit_window, oscillation_type, oscillation_start, oscillation_stop)
                #----------------------------------------
                # Change from frequency unit to type and unit
                #----------------------------------------
                frequency_type.value = ((unit_window.value & 0x2) >> 1)
                frequency_unit.value = (unit_window.value & 0x1)
                #----------------------------------------
                # Set the device information
                #----------------------------------------
                lret.value = cgen_api.GenSetDeviceSetting(appid, aochannels, frequency, frequency_type, frequency_unit)
                #----------------------------------------
                # Display the error code if not completed normally
                #----------------------------------------
                if lret.value != 0:
                    cgen_api.GenGetErrorString(lret, error_buf)
                    print("\nDevice Settings Error")
                    print(f"GenSetDeviceSetting Ret = {lret.value} {error_buf.value.decode('sjis')}\n")
                    continue
                #----------------------------------------
                # Set oscillation
                #----------------------------------------
                lret.value = cgen_api.GenSetOscillation(appid, oscillation_type, oscillation_start, oscillation_stop)
                #----------------------------------------
                # Display the error code if not completed normally
                #----------------------------------------
                if lret.value != 0:
                    cgen_api.GenGetErrorString(lret, error_buf)
                    print("\nDevice Settings Error")
                    print(f"GenSetOscillation Ret = {lret.value} {error_buf.value.decode('sjis')}\n")
                    continue
                #----------------------------------------
                # Display the message that device settings is completed
                #----------------------------------------
                print("\nDevice Settings: Successful completion\n")
            #----------------------------------------
            # If Cancel is selected, process
            #----------------------------------------
            else:
                print("")
                continue
        #--------------------
        # Channel Settings
        #--------------------
        elif buf == "3":
            #----------------------------------------
            # Input the channel number
            #----------------------------------------
            print("")
            while True:
                print(f"Please input the channel number(0-15) : ", end='', flush=True)
                #----------------------------------------
                # Waiting for input
                #----------------------------------------
                buf = input()
                #----------------------------------------
                # Check if the input value is a number
                #----------------------------------------
                if False == isnum(buf, 10):
                    continue
                break
            aochannel = ctypes.c_ushort(int(buf))
            #----------------------------------------
            # Get the wave type
            #----------------------------------------
            lret.value = cgen_api.GenGetWaveType(appid, aochannel, ctypes.byref(wave_type))
            #----------------------------------------
            # Get the channel information
            #----------------------------------------
            lret.value = cgen_api.GenGetChannelSetting(appid, aochannel, ctypes.byref(amplitude), ctypes.byref(offset), ctypes.byref(amplitude_type), ctypes.byref(amplitude_unit), ctypes.byref(duty), ctypes.byref(phase))
            #----------------------------------------
            # Get the simple sweep
            #----------------------------------------
            lret.value = cgen_api.GenGetAoSweep(appid, aochannel, ctypes.byref(sweep_type), ctypes.byref(sweep_time), ctypes.byref(sweep_start), ctypes.byref(sweep_stop))
            #----------------------------------------
            # Go to channel settings screen
            #----------------------------------------
            chinfo_data_set(aochannel, amplitude, offset, amplitude_type, amplitude_unit, duty, phase, sweep_type, sweep_time, sweep_start, sweep_stop, wave_type)
            #----------------------------------------
            # Display channel settings menu
            #----------------------------------------
            #----------------------------------------
            # If OK is selected, process
            #----------------------------------------
            if ChannelSetting() == True:
                #----------------------------------------
                # Get data from channel settings screen
                #----------------------------------------
                chinfo_data_get(aochannels, amplitude, offset, amplitude_type, amplitude_unit, duty, phase, sweep_type, sweep_time, sweep_start, sweep_stop)
                #----------------------------------------
                # Set the channel settings
                #----------------------------------------
                lret.value = cgen_api.GenSetChannelSetting(appid, aochannel, amplitude, offset, amplitude_type, amplitude_unit, duty, phase)
                #----------------------------------------
                # Display the error code if not completed normally
                #----------------------------------------
                if lret.value != 0:
                    cgen_api.GenGetErrorString(lret, error_buf)
                    print("\nChannel Settings Error")
                    print(f"GenSetChannelSetting Ret = {lret.value} {error_buf.value.decode('sjis')}\n")
                    continue
                #----------------------------------------
                # Set the simple sweep
                #----------------------------------------
                lret.value = cgen_api.GenSetAoSweep(appid, aochannel, sweep_type, sweep_time, sweep_start, sweep_stop)
                #----------------------------------------
                # Display the error code if not completed normally
                #----------------------------------------
                if lret.value != 0:
                    cgen_api.GenGetErrorString(lret, error_buf)
                    print("\nChannel Settings Error")
                    print(f"GenSetAoSweep Ret = {lret.value} {error_buf.value.decode('sjis')}\n")
                    continue
                #----------------------------------------
                # Display the message that channel setting is completed
                #----------------------------------------
                print("\nChannel Settings: Successful completion\n")
            #----------------------------------------
            # If Cancel is selected, process
            #----------------------------------------
            else:
                print("")
                continue
        #--------------------
        # GenSetWaveType
        #--------------------
        elif buf == "4":
            print("\n----------------------------------------")
            print("Start GenSetWaveType")
            print("----------------------------------------")
            #----------------------------------------
            # Input the channel number
            #----------------------------------------
            while True:
                print(f"Please input the channel number(0-15) : ", end='', flush=True)
                #----------------------------------------
                # Waiting for input
                #----------------------------------------
                buf = input()
                #----------------------------------------
                # Check if the input value is a number
                #----------------------------------------
                if False == isnum(buf, 10):
                    continue
                break
            aochannel = ctypes.c_ushort(int(buf))
            #----------------------------------------
            # Input the wave type
            #----------------------------------------
            print("\n----------------------------------------")
            print("Parameter(Wave type)")
            print("----------------------------------------")
            print("0 : Sinewave")
            print("1 : Constant")
            print("2 : Triangular")
            print("3 : Ramp")
            print("4 : Square")
            print("5 : Noise")
            print("6 : Arbitrary")
            while True:
                print("Please select the wave type : ", end='', flush=True)
                #----------------------------------------
                # Waiting for input
                #----------------------------------------
                buf = input()
                #----------------------------------------
                # Check if the input value is a number
                #----------------------------------------
                if False == isnum(buf, 10):
                    continue
                break
            wave_type = ctypes.c_ushort(int(buf))
            #----------------------------------------
            # Set the wave type
            #----------------------------------------
            lret.value = cgen_api.GenSetWaveType(appid, aochannel, wave_type)
            cgen_api.GenGetErrorString(lret, error_buf)
            print(f"\nGenSetWaveType Ret = {lret.value} {error_buf.value.decode('sjis')}\n")
        #--------------------
        # GenStartOperation
        #--------------------
        elif buf == "5":
            #----------------------------------------
            # Start the output of the application
            #----------------------------------------
            lret.value = cgen_api.GenStartOperation(appid)
            cgen_api.GenGetErrorString(lret, error_buf)
            print(f"\nGenStartOperation Ret = {lret.value} {error_buf.value.decode('sjis')}\n")
        #--------------------
        # GenGetApplicationStatus
        #--------------------
        elif buf == "6":
            #----------------------------------------
            # Get the operating status
            #----------------------------------------
            lret.value = cgen_api.GenGetApplicationStatus(appid, ctypes.byref(status))
            cgen_api.GenGetErrorString(lret, error_buf)
            print(f"\nGenGetApplicationStatus Ret = {lret.value} {error_buf.value.decode('sjis')}")
            #----------------------------------------
            # Display the status
            #----------------------------------------
            if status.value == 0:
                status_string = "00H(Stopped)"
            elif status.value == 1:
                status_string = "01H(Running)"
            elif status.value == 2:
                status_string = "02H(Waiting for start trigger)"
            elif status.value == 3:
                status_string = "03H(Running, Waiting for start trigger)"
            else:
                status_string = f"{status.value}"
            print(f"Status = {status_string}\n")
        #--------------------
        # GenStopOperation
        #--------------------
        elif buf == "7":
            #----------------------------------------
            # Stop the output of the application
            #----------------------------------------
            lret.value = cgen_api.GenStopOperation(appid)
            cgen_api.GenGetErrorString(lret, error_buf)
            print(f"\nGenStopOperation Ret = {lret.value} {error_buf.value.decode('sjis')}\n")
        #--------------------
        # GenCloseApplication
        #--------------------
        elif buf == "8":
            #----------------------------------------
            # Perform application close process
            #----------------------------------------
            lret.value = cgen_api.GenCloseApplication(appid, ctypes.byref(status))
            cgen_api.GenGetErrorString(lret, error_buf)
            print(f"\nGenCloseApplication Ret = {lret.value} {error_buf.value.decode('sjis')}")
            #----------------------------------------
            # Display the status
            #----------------------------------------
            if status.value == 0:
                status_string = "0(Normal completed)"
            elif status.value == 1:
                status_string = "1(C-WaveformGenerator completed error)"
            else:
                status_string = f"{status.value}"
            print(f"Status = {status_string}\n")
        #--------------------
        # Quit
        #--------------------
        elif buf == "q":
            break
        #--------------------
        # Out-of-range command
        #--------------------
        else:
            print("\nThe number is out of range.\nPlease try again.\n")
            continue
    #----------------------------------------
    # Terminate application
    #----------------------------------------
    sys.exit()


#----------------------------------------
# Call main function
#----------------------------------------
if __name__ == "__main__":
    main()
