#================================================================
#================================================================
# API-AIO(WDM)
# Infinite generating using device buffer sample
# Common function file
#                                                CONTEC Co., Ltd.
#================================================================
#================================================================
#----------------------------------------
# Import modules
#----------------------------------------
import ctypes
import ctypes.wintypes
import threading
import subprocess
import caio
#----------------------------------------
# Declaration of global variables
#----------------------------------------
g_lock = threading.Lock()         # Mutex
g_info_flag = ctypes.c_short()    # A flag showing the total generating count, setting generating count, status in the callback


#========================================
# Function name    isnum
# Parameter        str     String
# Parameter        base    Base
# Details          Function to check if a string can be converted to a number
# Return value     True: Can be converted
#                  False: Can not be converted
#========================================
def isnum(str, base):
    try:
        if 10 == base:
            int(str, 10)
        else:
            float(str)
    except:
        return False
    return True


#========================================
# Function name    GetRangeString
# Parameter        ao_range           Range
# Details          Function to get range string
# Return value     ao_range_string    Range string
#========================================
def GetRangeString(ao_range):
    if ao_range.value == caio.PM10:
        ao_range_string = "+/-10[V]"
    elif ao_range.value == caio.PM5:
        ao_range_string = "+/-5[V]"
    elif ao_range.value == caio.PM25:
        ao_range_string = "+/-2.5[V]"
    elif ao_range.value == caio.PM125:
        ao_range_string = "+/-1.25[V]"
    elif ao_range.value == caio.P10:
        ao_range_string = "0-10[V]"
    elif ao_range.value == caio.P5:
        ao_range_string = "0-5[V]"
    elif ao_range.value == caio.P25:
        ao_range_string = "0-2.5[V]"
    elif ao_range.value == caio.P125:
        ao_range_string = "0-1.25[V]"
    elif ao_range.value == caio.P20MA:
        ao_range_string = "0-20[mA]"
    elif ao_range.value == caio.P4TO20MA:
        ao_range_string = "4-20[mA]"
    elif ao_range.value == caio.P1TO5:
        ao_range_string = "1-5[V]"
    else:
        ao_range_string = "-"
    return ao_range_string


#========================================
# Function name    GetSineCoefficient
# Parameter        ao_range        Range
# Details          Function to get sine waveform coefficient
# Return value     gain, offset    Sine waveform gain, offset
#========================================
def GetSineCoefficient(ao_range):
    if ao_range.value == caio.PM10:
        gain = 10
        offset = 0
    elif ao_range.value == caio.PM5:
        gain = 5
        offset = 0
    elif ao_range.value == caio.PM25:
        gain = 2.5
        offset = 0
    elif ao_range.value == caio.PM125:
        gain = 1.25
        offset = 0
    elif ao_range.value == caio.P10:
        gain = 5
        offset = 5
    elif ao_range.value == caio.P5:
        gain = 2.5
        offset = 2.5
    elif ao_range.value == caio.P25:
        gain = 1.25
        offset = 1.25
    elif ao_range.value == caio.P125:
        gain = 0.625
        offset = 0.625
    elif ao_range.value == caio.P20MA:
        gain = 10
        offset = 10
    elif ao_range.value == caio.P4TO20MA:
        gain = 8
        offset = 12
    elif ao_range.value == caio.P1TO5:
        gain = 2
        offset = 3
    else:
        gain = 10
        offset = 0
    return gain, offset


#========================================
# Function name    GetStartTriggerString
# Parameter        ao_start_trigger           Start condition
# Details          Function to get start condition string
# Return value     ao_start_trigger_string    Start condition string
#========================================
def GetStartTriggerString(ao_start_trigger):
    if ao_start_trigger.value == 0:
        ao_start_trigger_string = "Software"
    elif ao_start_trigger.value == 1:
        ao_start_trigger_string = "External trigger rising edge"
    elif ao_start_trigger.value == 2:
        ao_start_trigger_string = "External trigger falling edge"
    else:
        ao_start_trigger_string = "-"
    return ao_start_trigger_string


#========================================
# Function name    GetClockTypeString
# Parameter        ao_clock_type           Generating clock condition
# Details          Function to get generating clock condition string
# Return value     ao_clock_type_string    Generating clock condition string
#========================================
def GetClockTypeString(ao_clock_type):
    if ao_clock_type.value == 0:
        ao_clock_type_string = "Internal clock"
    elif ao_clock_type.value == 1:
        ao_clock_type_string = "External clock"
    else:
        ao_clock_type_string = "-"
    return ao_clock_type_string


#========================================
# Function name    GetClockEdgeString
# Parameter        ao_clock_edge           Timing of external clock input
# Details          Function to get timing of external clock input string
# Return value     ao_clock_edge_string    Timing of external clock input string
#========================================
def GetClockEdgeString(ao_clock_edge):
    if ao_clock_edge.value == 0:
        ao_clock_edge_string = "External input falling edge"
    elif ao_clock_edge.value == 1:
        ao_clock_edge_string = "External input rising edge"
    else:
        ao_clock_edge_string = "-"
    return ao_clock_edge_string


#========================================
# Function name    GetStopTriggerString
# Parameter        ao_stop_trigger           Stop condition
# Details          Function to get stop condition string
# Return value     ao_stop_trigger_string    Stop condition string
#========================================
def GetStopTriggerString(ao_stop_trigger):
    if ao_stop_trigger.value == 0:
        ao_stop_trigger_string = "Stop conversion by the specified times"
    elif ao_stop_trigger.value == 1:
        ao_stop_trigger_string = "External trigger rising edge"
    elif ao_stop_trigger.value == 2:
        ao_stop_trigger_string = "External trigger falling edge"
    else:
        ao_stop_trigger_string = "-"
    return ao_stop_trigger_string


#========================================
# Function name    GetStatusString
# Parameter        ao_status           Status
# Details          Function to get status string
# Return value     ao_status_string    Status string
#========================================
def GetStatusString(ao_status):
    #----------------------------------------
    # Create the analog output status string
    #----------------------------------------
    #--------------------
    # When status 'Device is running' is ON
    #--------------------
    if (ao_status.value & caio.AOS_BUSY) == caio.AOS_BUSY:
        ao_status_string = "Operating"
    #--------------------
    # When status 'Device is running' is OFF
    #--------------------
    else:
        ao_status_string = "Stop"
    #--------------------
    # When status 'Wait the start trigger' is ON
    #--------------------
    if (ao_status.value & caio.AOS_START_TRG) == caio.AOS_START_TRG:
        ao_status_string += ", Wait the start trigger"
    #--------------------
    # When status 'The specified number of data are output' is ON
    #--------------------
    if (ao_status.value & caio.AOS_DATA_NUM) == caio.AOS_DATA_NUM:
        ao_status_string += ", The specified number of data are output"
    #--------------------
    # When status 'Sampling clock error' is ON
    #--------------------
    if (ao_status.value & caio.AOS_SCERR) == caio.AOS_SCERR:
        ao_status_string += ", Sampling clock error"
    #--------------------
    # When status 'DA conversion error' is ON
    #--------------------
    if (ao_status.value & caio.AOS_AOERR) == caio.AOS_AOERR:
        ao_status_string += ", DA conversion error"
    #--------------------
    # When status 'Driver spec error' is ON
    #--------------------
    if (ao_status.value & caio.AOS_DRVERR) == caio.AOS_DRVERR:
        ao_status_string += ", Driver spec error"
    return ao_status_string


#========================================
# Function name    PrintOnOneLine
# Parameter        buf    String to display
# Details          Display string in one line,
#                  move the cursor to a fixed position
# Return value     None
#========================================
def PrintOnOneLine(buf):
    global g_lock         # Mutex
    global g_info_flag    # A flag showing the total generating count, setting generating count, status in the callback

    #----------------------------------------
    # Lock
    #----------------------------------------
    g_lock.acquire()
    #----------------------------------------
    # Specify the default shell
    #----------------------------------------
    subprocess.run('', shell=True)
    #----------------------------------------
    # Erase from cursor position to bottom right of screen
    #----------------------------------------
    print("\033[0J", end='', flush=True)
    #----------------------------------------
    # Save the cursor position
    #----------------------------------------
    print("\033[s", end='', flush=True)
    #----------------------------------------
    # Display the string
    #----------------------------------------
    print(buf, end='\r', flush=True)
    #----------------------------------------
    # Restore the cursor position
    #----------------------------------------
    print("\033[u", end='', flush=True)
    #----------------------------------------
    # Move the cursor up one line
    #----------------------------------------
    if g_info_flag.value == 0:
        print("\033[1A", end='', flush=True)
    g_info_flag.value = 1
    #----------------------------------------
    # Unlock
    #----------------------------------------
    g_lock.release()