#================================================================
#================================================================
# API-CAN(WDM)
# CAN communication callback sample
# main file
#                                                CONTEC Co., Ltd.
#================================================================
#================================================================
#----------------------------------------
# Import modules
#----------------------------------------
import ctypes
import sys
import ctypes.wintypes
import ccan
from common_function import *
from can_setup_communication_timing import *
from can_setup_acceptance import *
from can_setup_transmit import *


#========================================
# Function name    CallBackProc
# Parameter        id          Id get by CanInit
# Parameter        wParam      Parameter passed from driver
# Parameter        lParam      Channel number on which the received data is located is passed
# Parameter        Param       Parameter specified in the CanNotifyEvent function
#                              It will be NULL when the Param parameter was specified to NULL.
# Details          Function registered with the CanNotifyEvent function
#                  This function is called when an event occurs
# Return value     None
#========================================
def CallBackProc(id, wParam, lParam, Param):
    error_buf = ctypes.create_string_buffer(256)                  # Error code string
    lret = ctypes.c_int()                                         # For return code
    channel_no = ctypes.c_ushort()                                # Channel number
    message_num = ctypes.c_uint()                                 # Number of valid received messages
    message_type_type = ctypes.c_uint * MAX_RECEIVE_MESSAGE       # Receive message type type
    message_type = message_type_type()                            # Receive message type
    can_id_type = ctypes.c_uint * MAX_RECEIVE_MESSAGE             # Receive CAN ID type
    can_id = can_id_type()                                        # Receive CAN ID
    data_length_type = ctypes.c_ushort * MAX_RECEIVE_MESSAGE      # Receive message data length type
    data_length = data_length_type()                              # Receive message data length
    receive_data_type1 = ctypes.c_ubyte * MAX_RECEIVE_DATA        # Receive data type 1
    receive_data_type2 = receive_data_type1 * MAX_RECEIVE_MESSAGE # Receive data type 2
    receive_data = receive_data_type2()                           # Receive data
    error_code_type = ctypes.c_uint * MAX_RECEIVE_MESSAGE         # Receive error type
    error_code = error_code_type()                                # Receive error
    tick_count_type = ctypes.c_ulonglong * MAX_RECEIVE_MESSAGE    # Tick count value when received type
    tick_count = tick_count_type()                                # Tick count value when received

    #----------------------------------------
    # Store channel number
    #----------------------------------------
    channel_no.value = lParam
    #----------------------------------------
    # Number of receive messages
    #----------------------------------------
    message_num.value = MAX_RECEIVE_MESSAGE
    #----------------------------------------
    # CAN / CAN FD Receive
    #----------------------------------------
    lret.value = ccan.CanReceive(id, channel_no, ctypes.byref(message_num), message_type, can_id, data_length, ctypes.cast(receive_data, ctypes.POINTER(ctypes.c_ubyte)), error_code, tick_count)
    #----------------------------------------
    # Error process
    #----------------------------------------
    ccan.CanGetErrorString(lret, error_buf)
    if lret.value != ccan.CAN_ERR_SUCCESS:
        text_buf = f"\nCanReceive Ret = {lret.value} {error_buf.value.decode('sjis')}"
        PrintOnMultiLines(text_buf, 1)
        return
    #----------------------------------------
    # If no message is received, return
    #----------------------------------------
    if message_num == 0:
        return
    #----------------------------------------
    # Open file
    #----------------------------------------
    try:
        file = open("./receive_data.csv", 'a')
    except:
        text_buf = f"\nReceive Error\nFailed to create the file"
        PrintOnMultiLines(text_buf, 2)
        return
    #----------------------------------------
    # Display for each received message
    #----------------------------------------
    for message_count in range(0, message_num.value):
        data = ""
        for data_count in range(0, data_length[message_count]):
            data += f"{receive_data[message_count][data_count]:02X}, "
        data = data[:-2]
        #----------------------------------------
        # File data contents
        #----------------------------------------
        text_buf = f"{ctypes.cast(Param, ctypes.POINTER(ctypes.c_int)).contents.value},{channel_no.value},{tick_count[message_count]},0x{message_type[message_count]:X},0x{can_id[message_count]:X},{data_length[message_count]},\"{data}\",0x{error_code[message_count]:X}\n"
        #----------------------------------------
        # Write data
        #----------------------------------------
        file.write(text_buf)
        ctypes.cast(Param, ctypes.POINTER(ctypes.c_int)).contents.value += 1
    #----------------------------------------
    # Close file
    #----------------------------------------
    file.close()
    #----------------------------------------
    # Display only the last message received
    #----------------------------------------
    text_buf = ""
    text_buf += f"\nChannel No{channel_no.value}  Receive\n"
    text_buf += f"No.            {ctypes.cast(Param, ctypes.POINTER(ctypes.c_int)).contents.value - 1}\n"
    text_buf += f"TickCount      {tick_count[message_num.value - 1]}\n"
    text_buf += f"MessageType    0x{message_type[message_num.value - 1]:X}\n"
    text_buf += f"CanID          0x{can_id[message_num.value - 1]:X}\n"
    text_buf += f"DataLength     {data_length[message_num.value - 1]}\n"
    text_buf += f"Data[Hex]      {data}\n"
    text_buf += f"ErrorCode      0x{error_code[message_num.value - 1]:X}"
    PrintOnMultiLines(text_buf, 8)


pcan_callback = ccan.PCAN_EVENT_CALLBACK(CallBackProc)


#========================================
# Function name    main
# Parameter        None
# Details          Function that performs main processing
# Return value     None
#========================================
def main():
    id = ctypes.c_short(0)                                  # Device access ID
    error_buf = ctypes.create_string_buffer(256)            # Error code string
    lret = ctypes.c_int()                                   # For return code
    channel_no = ctypes.c_ushort(0)                         # Channel number
    receive_no = ctypes.c_int(0)                            # Receive No.
    message_type = ctypes.c_uint(ccan.CCAN_MSG_TYPE_CAN)    # Transmit message type
    can_id = ctypes.c_uint(0x100)                           # Transmit CAN ID
    data_length = ctypes.c_ushort(8)                        # Transmit message data length
    data_type1 = ctypes.c_ubyte * MAX_RECEIVE_DATA          # Transmit data type 1
    data_type2 = data_type1 * MAX_RECEIVE_MESSAGE           # Transmit data type 2
    data = data_type2()                                     # Transmit data
    message_num = ctypes.c_uint()                           # Transmit message number
    channel_status = ctypes.c_ushort()                      # Channel status
    tx_error_count = ctypes.c_ushort()                      # Transmit error count
    rx_error_count = ctypes.c_ushort()                      # Receive error count
    global g_mutex_object                                   # Mutex
    global g_info_flag                                      # Flags message displayed in the callback

    #----------------------------------------
    # Initialize the variable
    #----------------------------------------
    g_info_flag.value   = 0
    for i in range(0, data_length.value):
        data[0][i] = i
    #----------------------------------------
    # Lock
    #----------------------------------------
    g_mutex_object.acquire()
    #----------------------------------------
    # Loop that wait input
    #----------------------------------------
    while True:
        #----------------------------------------
        # Display the command
        #----------------------------------------
        print("=========================")
        print("Common setting value")
        print("=========================")
        print(f"Channel No : {channel_no.value}")
        print("=========================")
        print("Menu (Top)")
        print("=========================")
        print(" 1 : CanInit")
        print(" 2 : Channel No Setting")
        print(" 3 : Communication Timing Setting")
        print(" 4 : Receive Acceptance Message Setting")
        print(" 5 : CanBusConnect")
        print(" 6 : Transmit Setting")
        print(" 7 : CanTransmit")
        print(" 8 : Receive Start")
        print(" 9 : Receive Stop")
        print("10 : CanGetChannelStatus")
        print("11 : CanBusDisconnect")
        print("12 : CanExit")
        print(" q : Quit")
        print("Please input the command : ", end='', flush=True)
        #----------------------------------------
        # Unlock
        #----------------------------------------
        g_mutex_object.release()
        #----------------------------------------
        # Waiting for input
        #----------------------------------------
        buf = input()
        #----------------------------------------
        # Lock
        #----------------------------------------
        g_mutex_object.acquire()
        #----------------------------------------
        # If message displayed in the callback, output 8 lines
        #----------------------------------------
        if g_info_flag.value == 1:
            print("\n\n\n\n\n\n\n")
            g_info_flag.value = 0
        #----------------------------------------
        # Distinguish the command
        #----------------------------------------
        #--------------------
        # CanInit
        #--------------------
        if buf == "1":
            #----------------------------------------
            # Input the device name
            #----------------------------------------
            print("\nPlease input the device name : ", end='', flush=True)
            #----------------------------------------
            # Unlock
            #----------------------------------------
            g_mutex_object.release()
            #----------------------------------------
            # Waiting for input
            #----------------------------------------
            buf = input()
            #----------------------------------------
            # Lock
            #----------------------------------------
            g_mutex_object.acquire()
            #----------------------------------------
            # If message displayed in the callback, output 8 lines
            #----------------------------------------
            if g_info_flag.value == 1:
                print("\n\n\n\n\n\n\n")
                g_info_flag.value = 0
            #----------------------------------------
            # Initialization
            #----------------------------------------
            lret.value = ccan.CanInit(buf.encode(), ctypes.byref(id))
            ccan.CanGetErrorString(lret, error_buf)
            if lret.value == ccan.CAN_ERR_SUCCESS:
                print(f"\nCanInit Ret = {lret.value} {error_buf.value.decode('sjis')}\n")
            else:
                print("\nCanInit Error")
                print(f"CanInit Ret = {lret.value} {error_buf.value.decode('sjis')}\n")
        #--------------------
        # Channel No Setting
        #--------------------
        elif buf == "2":
            #----------------------------------------
            # Input the channel number
            #----------------------------------------
            while True:
                print("\nPlease input the channel number : ", end='', flush=True)
                #----------------------------------------
                # Unlock
                #----------------------------------------
                g_mutex_object.release()
                #----------------------------------------
                # Waiting for input
                #----------------------------------------
                buf = input()
                #----------------------------------------
                # Lock
                #----------------------------------------
                g_mutex_object.acquire()
                #----------------------------------------
                # If message displayed in the callback, output 8 lines
                #----------------------------------------
                if g_info_flag.value == 1:
                    print("\n\n\n\n\n\n\n")
                    g_info_flag.value = 0
                #----------------------------------------
                # Check if the input value is a number
                #----------------------------------------
                if False == isnum(buf, 10):
                    continue
                break
            channel_no.value = int(buf)
            print(f"\nChannel No = {channel_no.value}\n")
        #--------------------
        # Communication Timing Setting
        #--------------------
        elif buf == "3":
            #----------------------------------------
            # Communication Timing Setting menu display
            #----------------------------------------
            SetCommunicationTiming(id, channel_no)
            print("")
        #--------------------
        # Receive Acceptance Message Setting
        #--------------------
        elif buf == "4":
            #----------------------------------------
            # Receive Acceptance Message Setting menu display
            #----------------------------------------
            SetAcceptance(id, channel_no)
            print("")
        #--------------------
        # CanBusConnect
        #--------------------
        elif buf == "5":
            #----------------------------------------
            # Connect to the bus
            #----------------------------------------
            lret.value = ccan.CanBusConnect(id, channel_no)
            ccan.CanGetErrorString(lret, error_buf)
            if lret.value == ccan.CAN_ERR_SUCCESS:
                print(f"\nCanBusConnect Ret = {lret.value} {error_buf.value.decode('sjis')}\n")
            else:
                print("\nCanBusConnect Error")
                print(f"CanBusConnect Ret = {lret.value} {error_buf.value.decode('sjis')}\n")
        #--------------------
        # Transmit Setting
        #--------------------
        elif buf == "6":
            #----------------------------------------
            # Transmit Setting menu display
            #----------------------------------------
            message_type, can_id, data_length, data = SetTransmit(message_type, can_id, data_length, data)
            print("")
        #--------------------
        # CanTransmit
        #--------------------
        elif buf == "7":
            #----------------------------------------
            # Transmit message number
            #----------------------------------------
            message_num.value = 1
            #----------------------------------------
            # CAN or CAN FD transmit
            #----------------------------------------
            lret.value = ccan.CanTransmit(id, channel_no, message_num, ctypes.byref(message_type), ctypes.byref(can_id), ctypes.byref(data_length), ctypes.cast(data, ctypes.POINTER(ctypes.c_ubyte)))
            ccan.CanGetErrorString(lret, error_buf)
            if lret.value == ccan.CAN_ERR_SUCCESS:
                print(f"\nCanTransmit Ret = {lret.value} {error_buf.value.decode('sjis')}\n")
            else:
                print("\nCanTransmit Error")
                print(f"CanTransmit Ret = {lret.value} {error_buf.value.decode('sjis')}\n")
        #--------------------
        # Receive Start
        #--------------------
        elif buf == "8":
            #----------------------------------------
            # Receive event start
            #----------------------------------------
            lret.value = ccan.CanNotifyEvent(id, channel_no, ccan.CCAN_EVENT_RECEIVE, pcan_callback, ctypes.byref(receive_no))
            ccan.CanGetErrorString(lret, error_buf)
            if lret.value == ccan.CAN_ERR_SUCCESS:
                print("\nReceive Start Successful completion\n")
            else:
                print("\nReceive Start Error")
                print(f"CanNotifyEvent Ret = {lret.value} {error_buf.value.decode('sjis')}\n")
                continue
            receive_no.value = 0
            #----------------------------------------
            # File open
            #----------------------------------------
            try:
                file = open("./receive_data.csv", 'w')
            except:
                print("\nReceive Start Error")
                print("Failed to create the file\n")
                continue
            #----------------------------------------
            # File header contents
            #----------------------------------------
            text_string = f"No.,ReceiveChannel,TickCount,MessageType,CanId,DataLength,Data[Hex],ErrorCode\n"
            #----------------------------------------
            # Write data
            #----------------------------------------
            file.write(text_string)
            #----------------------------------------
            # Close file
            #----------------------------------------
            file.close()
        #--------------------
        # Receive Stop
        #--------------------
        elif buf == "9":
            #----------------------------------------
            # Receive event stop
            #----------------------------------------
            lret.value = ccan.CanStopNotifyEvent(id, channel_no, ccan.CCAN_EVENT_RECEIVE)
            ccan.CanGetErrorString(lret, error_buf)
            if lret.value == ccan.CAN_ERR_SUCCESS:
                print("\nReceive Stop Successful completion")
            else:
                print("\nReceive Stop Error")
                print(f"CanStopNotifyEvent Ret = {lret.value} {error_buf.value.decode('sjis')}\n")
                continue
            print("Save data to \"receive_data.csv\".")
            print("")
        #--------------------
        # CanGetChannelStatus
        #--------------------
        elif buf == "10":
            #----------------------------------------
            # Get channel status
            #----------------------------------------
            lret.value = ccan.CanGetChannelStatus(id, channel_no, ctypes.byref(channel_status), ctypes.byref(tx_error_count), ctypes.byref(rx_error_count))
            ccan.CanGetErrorString(lret, error_buf)
            if lret.value == ccan.CAN_ERR_SUCCESS:
                print(f"\nCanGetChannelStatus Ret = {lret.value} {error_buf.value.decode('sjis')}")
                #----------------------------------------
                # Create the channel status string
                #----------------------------------------
                if channel_status.value == ccan.CCAN_CH_STATUS_ERR_ACTIVE:
                    buf = "Error Active"
                if channel_status.value == ccan.CCAN_CH_STATUS_ERR_PASSIVE:
                    buf = "Error Passive"
                if channel_status.value == ccan.CCAN_CH_STATUS_BUS_OFF:
                    buf = "Bus OFF"
                print(f"Status                  = 0x{channel_status.value:04X}({buf})\nTransmit error count    = {tx_error_count.value}\nReceive error count     = {rx_error_count.value}\n")
            else:
                print("\nCanGetChannelStatus Error")
                print(f"CanGetChannelStatus Ret = {lret.value} {error_buf.value.decode('sjis')}\n")
        #--------------------
        # CanBusDisconnect
        #--------------------
        elif buf == "11":
            #----------------------------------------
            # Disconnect to the bus
            #----------------------------------------
            lret.value = ccan.CanBusDisconnect(id, channel_no)
            ccan.CanGetErrorString(lret, error_buf)
            if lret.value == ccan.CAN_ERR_SUCCESS:
                print(f"\nCanBusDisconnect Ret = {lret.value} {error_buf.value.decode('sjis')}\n")
            else:
                print("\nCanBusDisconnect Error")
                print(f"CanBusDisconnect Ret = {lret.value} {error_buf.value.decode('sjis')}\n")
        #--------------------
        # CanExit
        #--------------------
        elif buf == "12":
            #----------------------------------------
            # Exit process
            #----------------------------------------
            lret.value = ccan.CanExit(id)
            ccan.CanGetErrorString(lret, error_buf)
            if lret.value == ccan.CAN_ERR_SUCCESS:
                print(f"\nCanExit Ret = {lret.value} {error_buf.value.decode('sjis')}\n")
            else:
                print("\nCanExit Error")
                print(f"CanExit Ret = {lret.value} {error_buf.value.decode('sjis')}\n")
        #--------------------
        # Quit
        #--------------------
        elif buf == "q":
            break
        #--------------------
        # Error Number
        #--------------------
        else:
            print("\nThe number is out of range.\nPlease try again.\n")
            continue
    #----------------------------------------
    # Exit process
    #----------------------------------------
    ccan.CanExit(id)
    #----------------------------------------
    # Unlock
    #----------------------------------------
    g_mutex_object.release()
    #----------------------------------------
    # Application exit
    #----------------------------------------
    sys.exit()


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