#================================================================
#================================================================
# API-CAN(WDM)
# CAN communication 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    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.
    transmit_message_type = ctypes.c_uint(ccan.CCAN_MSG_TYPE_CAN)       # Transmit message type
    transmit_can_id = ctypes.c_uint(0x100)                              # Transmit CAN ID
    transmit_data_length = ctypes.c_ushort(8)                           # Transmit message data length
    transmit_data_type1 = ctypes.c_ubyte * MAX_RECEIVE_DATA             # Transmit data type 1
    transmit_data_type2 = transmit_data_type1 * MAX_RECEIVE_MESSAGE     # Transmit data type 2
    transmit_data = transmit_data_type2()                               # Transmit data
    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
    message_num = ctypes.c_uint()                                       # Number of valid received messages
    receive_message_type_type = ctypes.c_uint * MAX_RECEIVE_MESSAGE     # Receive message type type
    receive_message_type = receive_message_type_type()                  # Receive message type
    receive_can_id_type = ctypes.c_uint * MAX_RECEIVE_MESSAGE           # Receive CAN ID type
    receive_can_id = receive_can_id_type()                              # Receive CAN ID
    receive_data_length_type = ctypes.c_ushort * MAX_RECEIVE_MESSAGE    # Receive message data length type
    receive_data_length = receive_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

    #----------------------------------------
    # Initialize the variable
    #----------------------------------------
    for i in range(0, transmit_data_length.value):
        transmit_data[0][i] = i
    #----------------------------------------
    # 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 : CanReceive")
        print(" 9 : CanGetChannelStatus")
        print("10 : CanBusDisconnect")
        print("11 : CanExit")
        print(" q : Quit")
        print("Please input the command : ", end='', flush=True)
        #----------------------------------------
        # Waiting for input
        #----------------------------------------
        buf = input()
        #----------------------------------------
        # Distinguish the command
        #----------------------------------------
        #--------------------
        # CanInit
        #--------------------
        if buf == "1":
            #----------------------------------------
            # Input the device name
            #----------------------------------------
            print("\nPlease input the device name : ", end='', flush=True)
            #----------------------------------------
            # Waiting for input
            #----------------------------------------
            buf = input()
            #----------------------------------------
            # 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)
                #----------------------------------------
                # Waiting for input
                #----------------------------------------
                buf = input()
                #----------------------------------------
                # 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
            #----------------------------------------
            transmit_message_type, transmit_can_id, transmit_data_length, transmit_data = SetTransmit(transmit_message_type, transmit_can_id, transmit_data_length, transmit_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(transmit_message_type), ctypes.byref(transmit_can_id), ctypes.byref(transmit_data_length), ctypes.cast(transmit_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")
        #--------------------
        # CanReceive
        #--------------------
        elif buf == "8":
            receive_no.value = 0
            #----------------------------------------
            # Receive message number
            #----------------------------------------
            message_num.value = MAX_RECEIVE_MESSAGE
            #----------------------------------------
            # CAN / CAN FD received
            #----------------------------------------
            lret.value = ccan.CanReceive(id, channel_no, ctypes.byref(message_num), receive_message_type, receive_can_id, receive_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:
                print(f"\nCanReceive Ret = {lret.value} {error_buf.value.decode('sjis')}")
                #----------------------------------------
                # If no message is received, continue the next loop
                #----------------------------------------
                if message_num.value == 0:
                    print("")
                    continue
                #----------------------------------------
                # Open file
                #----------------------------------------
                try:
                    file = open("./receive_data.csv", 'w')
                except:
                    print("\nReceive Error")
                    print("Failed to create the file\n")
                    continue
                #----------------------------------------
                # File header contents
                #----------------------------------------
                text_string = f"ChannelNo{channel_no.value} received\nNo.,TickCount,MessageType,CanId,DataLength,Data[Hex],ErrorCode\n"
                #----------------------------------------
                # Write data
                #----------------------------------------
                file.write(text_string)
                #----------------------------------------
                # Write file for each received message
                #----------------------------------------
                for message_count in range(0, message_num.value):
                    data = ""
                    for data_count in range(0, receive_data_length[message_count]):
                        data += f"{receive_data[message_count][data_count]:02X}, "
                    data = data[:-2]
                    #----------------------------------------
                    # Generate string to write to file
                    #----------------------------------------
                    text_buf = f"{receive_no.value},{tick_count[message_count]},0x{receive_message_type[message_count]:X},0x{receive_can_id[message_count]:X},{receive_data_length[message_count]},\"{data}\",0x{error_code[message_count]:X}\n"
                    #----------------------------------------
                    # Write data
                    #----------------------------------------
                    file.write(text_buf)
                    receive_no.value += 1
                #----------------------------------------
                # Close file
                #----------------------------------------
                file.close()
                print("Save data to \"receive_data.csv\".")
                #----------------------------------------
                # Display only the last message received
                #----------------------------------------
                text_buf = ""
                text_buf += f"No.            {receive_no.value - 1}\n"
                text_buf += f"TickCount      {tick_count[message_num.value - 1]}\n"
                text_buf += f"MessageType    0x{receive_message_type[message_num.value - 1]:X}\n"
                text_buf += f"CanID          0x{receive_can_id[message_num.value - 1]:X}\n"
                text_buf += f"DataLength     {receive_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}"
                print(f"{text_buf}")
            else:
                print("\nReceive Error")
                print(f"CanReceive Ret = {lret.value} {error_buf.value.decode('sjis')}")
            print("")
        #--------------------
        # CanGetChannelStatus
        #--------------------
        elif buf == "9":
            #----------------------------------------
            # 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 == "10":
            #----------------------------------------
            # 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 == "11":
            #----------------------------------------
            # 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)
    #----------------------------------------
    # Application exit
    #----------------------------------------
    sys.exit()


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