#================================================================
#================================================================
# API-AIO(WDM)
# Finite sampling using attached data 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 transfer position, status in the callback


#========================================
# Function name    isnum
# Parameter        str     String
# Parameter        base    Base
# Details          Function to checks 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         ai_range           Range
# Details           Function to get range string
# Return value      ai_range_string    Range string
#========================================
def GetRangeString(ai_range):
    if ai_range.value == caio.PM10:
        ai_range_string = "+/-10[V]"
    elif ai_range.value == caio.PM5:
        ai_range_string = "+/-5[V]"
    elif ai_range.value == caio.PM25:
        ai_range_string = "+/-2.5[V]"
    elif ai_range.value == caio.PM125:
        ai_range_string = "+/-1.25[V]"
    elif ai_range.value == caio.P10:
        ai_range_string = "0-10[V]"
    elif ai_range.value == caio.P5:
        ai_range_string = "0-5[V]"
    elif ai_range.value == caio.P25:
        ai_range_string = "0-2.5[V]"
    elif ai_range.value == caio.P125:
        ai_range_string = "0-1.25[V]"
    elif ai_range.value == caio.P20MA:
        ai_range_string = "0-20[mA]"
    elif ai_range.value == caio.P4TO20MA:
        ai_range_string = "4-20[mA]"
    elif ai_range.value == caio.PM20MA:
        ai_range_string = "+/-20[mA]"
    elif ai_range.value == caio.P1TO5:
        ai_range_string = "1-5[V]"
    else:
        ai_range_string = "-"
    return ai_range_string


#========================================
# Function name     GetInputMethodString
# Parameter         ai_input_method           Input method
# Details           Function to get input method string
# Return value      ai_input_method_string    Input method string
#========================================
def GetInputMethodString(ai_input_method):
    if ai_input_method.value == 0:
        ai_input_method_string = "Single-end input"
    elif ai_input_method.value == 1:
        ai_input_method_string = "Differential input"
    else:
        ai_input_method_string = "-"
    return ai_input_method_string


#========================================
# Function name     GetStatusString
# Parameter         ai_status           Status
# Details           Function to get status string
# Return value      ai_status_string    Status string
#========================================
def GetStatusString(ai_status):
    #----------------------------------------
    # Create the analog input status string
    #----------------------------------------
    #--------------------
    # When status 'Device is running' is ON
    #--------------------
    if (ai_status.value & caio.AIS_BUSY) == caio.AIS_BUSY:
        ai_status_string = "Operating"
    #--------------------
    # When status 'Device is running' is OFF
    #--------------------
    else:
        ai_status_string = "Stop"
    #--------------------
    # When status 'Wait the start trigger' is ON
    #--------------------
    if (ai_status.value & caio.AIS_START_TRG) == caio.AIS_START_TRG:
        ai_status_string += ", Wait the start trigger"
    #--------------------
    # When status 'The specified number of data are stored' is ON
    #--------------------
    if (ai_status.value & caio.AIS_DATA_NUM) == caio.AIS_DATA_NUM:
        ai_status_string += ", The specified number of data are stored"
    #--------------------
    # When status 'Overflow' is ON
    #--------------------
    if (ai_status.value & caio.AIS_OFERR) == caio.AIS_OFERR:
        ai_status_string += ", Overflow"
    #--------------------
    # When status 'Sampling clock error' is ON
    #--------------------
    if (ai_status.value & caio.AIS_SCERR) == caio.AIS_SCERR:
        ai_status_string += ", Sampling clock error"
    #--------------------
    # When status 'AD conversion error' is ON
    #--------------------
    if (ai_status.value & caio.AIS_AIERR) == caio.AIS_AIERR:
        ai_status_string += ", AD conversion error"
    #--------------------
    # When status 'Driver spec error' is ON
    #--------------------
    if (ai_status.value & caio.AIS_DRVERR) == caio.AIS_DRVERR:
        ai_status_string += ", Driver spec error"
    return ai_status_string


#========================================
# Function name     GetAttachedDataString
# Parameter         attached_data            Attached data
# Details           Function to get attached data string
# Return value      attached_data_string     Attached data string
#========================================
def GetAttachedDataString(attached_data):
    attached_data_string = ""
    #----------------------------------------
    # Create attached data string
    #----------------------------------------
    #--------------------
    # When attached data 'Attached information of analog input' is valid
    #--------------------
    if (attached_data.value & caio.AIAT_AI) == caio.AIAT_AI:
        attached_data_string = "Attached information of analog input"
    #--------------------
    # When attached data 'Data of analog output' is valid
    #--------------------
    if (attached_data.value & caio.AIAT_AO0) == caio.AIAT_AO0:
        if len(attached_data_string):
            attached_data_string += ", Data of analog output"
        else:
            attached_data_string = "Data of analog output"
    #--------------------
    # When attached data 'Data of digital input and output' is valid
    #--------------------
    if (attached_data.value & caio.AIAT_DIO0) == caio.AIAT_DIO0:
        if len(attached_data_string):
            attached_data_string += ", Data of digital input and output"
        else:
            attached_data_string = "Data of digital input and output"
    #--------------------
    # When attached data 'Data of counter channel 0' is valid
    #--------------------
    if (attached_data.value & caio.AIAT_CNT0) == caio.AIAT_CNT0:
        if len(attached_data_string):
            attached_data_string += ", Data of counter channel 0"
        else:
            attached_data_string = "Data of counter channel 0"
    #--------------------
    # When attached data 'Data of counter channel 1' is valid
    #--------------------
    if (attached_data.value & caio.AIAT_CNT1) == caio.AIAT_CNT1:
        if len(attached_data_string):
            attached_data_string += ", Data of counter channel 1"
        else:
            attached_data_string = "Data of counter channel 1"
    return attached_data_string


#========================================
# Function name    PrintOnMultiLines
# Parameter        buf      String to display
# Parameter        lines    Number of lines of string to display
# Details          Display string in multi line,
#                  move the cursor to a fixed position
# Return value     None
#========================================
def PrintOnMultiLines(buf, lines):
    global g_lock         # Mutex
    global g_info_flag    # A flag showing the transfer position, 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 'lines' line
    #----------------------------------------
    if g_info_flag.value == 0:
        print(f"\033[{lines}A", end='', flush=True)
    g_info_flag.value = 1
    #----------------------------------------
    # Unlock
    #----------------------------------------
    g_lock.release()
