#================================================================
#================================================================
# API-CAN(WDM)
# CAN communication callback sample
# Common function file
#                                                CONTEC Co., Ltd.
#================================================================
#================================================================
#----------------------------------------
# Import modules
#----------------------------------------
import ctypes
import threading
import subprocess
import ccan
#----------------------------------------
# Macro definition
#----------------------------------------
MAX_TRANSMIT_DATA = 8        # Maximum number of transmitted data
MAX_RECEIVE_MESSAGE = 100    # Maximum number of received messages
MAX_RECEIVE_DATA = 64        # Maximum number of received data


#----------------------------------------
# Global variables
#----------------------------------------
g_mutex_object = threading.Lock()    # Mutex
g_info_flag = ctypes.c_short()       # Flags message displayed 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)
        elif 16 == base:
            int(str, 16)
        else:
            float(str)
    except:
        return False
    return True


#========================================
# Function name    GetMessageTypeMaskString
# Parameter        message_type_mask           Receive message type mask
# Parameter        type                        Receive message type mask string type(0: Multi-line display, 1: Single line display)
# Details          Function to get the string from the setting value of the received message type
# Return value     message_type_mask_string    eceive message type mask string
#========================================
def GetMessageTypeMaskString(message_type_mask, type):
    message_type_mask_string = ""
    #----------------------------------------
    # Create the receive message type mask string
    #----------------------------------------
    #--------------------
    # Not specified
    #--------------------
    if (message_type_mask.value | ccan.CCAN_MSG_TYPE_DISABLE) == ccan.CCAN_MSG_TYPE_DISABLE:
        message_type_mask_string = "Not specified (all message types will be received)"
        return message_type_mask_string
    #--------------------
    # When CAN message is enabled
    #--------------------
    if (message_type_mask.value & ccan.CCAN_MSG_TYPE_CAN) == ccan.CCAN_MSG_TYPE_CAN:
        if type == 0:
            message_type_mask_string += "CAN\n"
        else:
            message_type_mask_string += "CAN, "
    #--------------------
    # When CAN FD message is enabled
    #--------------------
    if (message_type_mask.value & ccan.CCAN_MSG_TYPE_CAN_FD) == ccan.CCAN_MSG_TYPE_CAN_FD:
        if type == 0:
            if message_type_mask_string == "":
                message_type_mask_string += "CAN FD\n"
            else:
                message_type_mask_string += "                       CAN FD\n"
        else:
            message_type_mask_string += "CAN FD, "
    #--------------------
    # When remote frame is enabled
    #--------------------
    if (message_type_mask.value & ccan.CCAN_MSG_TYPE_REMOTE_FRAME) == ccan.CCAN_MSG_TYPE_REMOTE_FRAME:
        if type == 0:
            if message_type_mask_string == "":
                message_type_mask_string += "Remote frame\n"
            else:
                message_type_mask_string += "                       Remote frame\n"
        else:
            message_type_mask_string += "Remote frame, "
    #--------------------
    # When bitrate switch is enabled
    #--------------------
    if (message_type_mask.value & ccan.CCAN_MSG_TYPE_BITRATE_SWITCH) == ccan.CCAN_MSG_TYPE_BITRATE_SWITCH:
        if type == 0:
            if message_type_mask_string == "":
                message_type_mask_string += "Bitrate switch\n"
            else:
                message_type_mask_string += "                       Bitrate switch\n"
        else:
            message_type_mask_string += "Bitrate switch, "
    #--------------------
    # When standard format is enabled
    #--------------------
    if (message_type_mask.value & ccan.CCAN_MSG_TYPE_STANDARD_FORMAT) == ccan.CCAN_MSG_TYPE_STANDARD_FORMAT:
        if type == 0:
            if message_type_mask_string == "":
                message_type_mask_string += "Standard format\n"
            else:
                message_type_mask_string += "                       Standard format\n"
        else:
            message_type_mask_string += "Standard format, "
    #--------------------
    # When extended format is enabled
    #--------------------
    if (message_type_mask.value & ccan.CCAN_MSG_TYPE_EXTENDED_FORMAT) == ccan.CCAN_MSG_TYPE_EXTENDED_FORMAT:
        if type == 0:
            if message_type_mask_string == "":
                message_type_mask_string += "Extended format\n"
            else:
                message_type_mask_string += "                       Extended format\n"
        else:
            message_type_mask_string += "Extended format, "
    #----------------------------------------
    # Delete the last characters
    #----------------------------------------
    if len(message_type_mask_string) > 0:
        if type == 0:
            message_type_mask_string = message_type_mask_string[:-1]
        else:
            message_type_mask_string = message_type_mask_string[:-2]
    return message_type_mask_string


#========================================
# Function name    GetMessageTypeString
# Parameter        message_type           Transmit message type
# Parameter        type                   Transmit message type string type(0: Multi-line display, 1: Single line display)
# Details          Function to get the string from the setting value of the transmit message type
# Return value     message_type_string    Transmit message type string
#========================================
def GetMessageTypeString(message_type, type):
    message_type_string = ""
    #----------------------------------------
    # Create the transmit message type string
    #----------------------------------------
    #--------------------
    # Not specified
    #--------------------
    if (message_type.value | ccan.CCAN_MSG_TYPE_DISABLE) == ccan.CCAN_MSG_TYPE_DISABLE:
        message_type_string += "Not specified (all message types will be received)"
        return message_type_string
    #--------------------
    # When CAN message is enabled
    #--------------------
    if (message_type.value & ccan.CCAN_MSG_TYPE_CAN) == ccan.CCAN_MSG_TYPE_CAN:
        if type == 0:
            message_type_string += "CAN\n"
        else:
            message_type_string += "CAN, "
    #--------------------
    # When CAN FD message is enabled
    #--------------------
    if (message_type.value & ccan.CCAN_MSG_TYPE_CAN_FD) == ccan.CCAN_MSG_TYPE_CAN_FD:
        if type == 0:
            if message_type_string == "":
                message_type_string += "CAN FD\n"
            else:
                message_type_string += "                  CAN FD\n"
        else:
            message_type_string += "CAN FD, "
    #--------------------
    # When remote frame is enabled
    #--------------------
    if (message_type.value & ccan.CCAN_MSG_TYPE_REMOTE_FRAME) == ccan.CCAN_MSG_TYPE_REMOTE_FRAME:
        if type == 0:
            if message_type_string == "":
                message_type_string += "Remote frame\n"
            else:
                message_type_string += "                  Remote frame\n"
        else:
            message_type_string += "Remote frame, "
    #--------------------
    # When bitrate switch is enabled
    #--------------------
    if (message_type.value & ccan.CCAN_MSG_TYPE_BITRATE_SWITCH) == ccan.CCAN_MSG_TYPE_BITRATE_SWITCH:
        if type == 0:
            if message_type_string == "":
                message_type_string += "Bitrate switch\n"
            else:
                message_type_string += "                  Bitrate switch\n"
        else:
            message_type_string += "Bitrate switch, "
    #--------------------
    # When extended format is enabled
    #--------------------
    if (message_type.value & ccan.CCAN_MSG_TYPE_EXTENDED_FORMAT) == ccan.CCAN_MSG_TYPE_EXTENDED_FORMAT:
        if type == 0:
            if message_type_string == "":
                message_type_string += "Extended format\n"
            else:
                message_type_string += "                  Extended format\n"
        else:
            message_type_string += "Extended format, "
    #----------------------------------------
    # Delete the last characters
    #----------------------------------------
    if len(message_type_string) > 0:
        if type == 0:
            message_type_string = message_type_string[:-1]
        else:
            message_type_string = message_type_string[:-2]
    return message_type_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_mutex_object    # Mutex
    global g_info_flag       # Flags message displayed in the callback

    #----------------------------------------
    # Lock
    #----------------------------------------
    g_mutex_object.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_mutex_object.release()