#================================================================
#================================================================
# API-CAN(WDM)
# CAN communication sample
# Set the communication timing file
#                                                CONTEC Co., Ltd.
#================================================================
#================================================================
#----------------------------------------
# Import modules
#----------------------------------------
import ctypes
import ccan
from common_function import *


#========================================
# Function name    SetCommunicationTiming
# Parameter        id           Id get by CanInit
# Parameter        channel_no   Channel number
# Details          Function that displays and processes the CAN communication timing set menu
# Return value     None
#========================================
def SetCommunicationTiming(id, channel_no):
    error_buf = ctypes.create_string_buffer(256)    # Error code string
    lret = ctypes.c_int()                           # For return code
    bit_rate = ctypes.c_uint()                      # Bitrate
    tseg1 = ctypes.c_ushort()                       # Time Segment 1
    sjw = ctypes.c_ushort()                         # Synchronous jump width
    tseg2 = ctypes.c_ushort()                       # Time Segment 2
    arb_bit_rate = ctypes.c_uint()                  # Arbitration bitrate
    data_bit_rate = ctypes.c_uint()                 # Data bitrate
    arb_tseg1 = ctypes.c_ushort()                   # Arbitration time segment 1
    data_tseg1 = ctypes.c_ushort()                  # Data time segment 1
    arb_sjw = ctypes.c_ushort()                     # Arbitration synchronization jump width
    data_sjw = ctypes.c_ushort()                    # Data synchronization jump width
    arb_tseg2 = ctypes.c_ushort()                   # Arbitration time segment 2
    data_tseg2 = ctypes.c_ushort()                  # Data time segment 2

    #----------------------------------------
    # Loop that wait input
    #----------------------------------------
    while True:
        #----------------------------------------
        # Get setting parameters
        #----------------------------------------
        #--------------------
        # Get the CAN communication timing settings
        #--------------------
        lret.value = ccan.CanGetCanTiming(id, channel_no, ctypes.byref(bit_rate), ctypes.byref(tseg1), ctypes.byref(sjw), ctypes.byref(tseg2))
        if lret.value != ccan.CAN_ERR_SUCCESS:
            bit_rate_string = "-"
            tseg1_string = "-"
            sjw_string = "-"
            tseg2_string = "-"
        else:
            bit_rate_string = f"{bit_rate.value}[bps]"
            tseg1_string = f"{tseg1.value}"
            sjw_string = f"{sjw.value}"
            tseg2_string = f"{tseg2.value}"
        #--------------------
        # Get the CAN FD communication timing settings
        #--------------------
        lret.value = ccan.CanGetCanFdTiming(id, channel_no, ctypes.byref(arb_bit_rate), ctypes.byref(arb_tseg1), ctypes.byref(arb_sjw), ctypes.byref(arb_tseg2), ctypes.byref(data_bit_rate), ctypes.byref(data_tseg1), ctypes.byref(data_sjw), ctypes.byref(data_tseg2))
        if lret.value != ccan.CAN_ERR_SUCCESS:
            arb_bit_rate_string = "-"
            arb_tseg1_string = "-"
            arb_sjw_string = "-"
            arb_tseg2_string = "-"
            data_bit_rate_string = "-"
            data_tseg1_string = "-"
            data_sjw_string = "-"
            data_tseg2_string = "-"
        else:
            arb_bit_rate_string = f"{arb_bit_rate.value}[bps]"
            arb_tseg1_string = f"{arb_tseg1.value}"
            arb_sjw_string = f"{arb_sjw.value}"
            arb_tseg2_string = f"{arb_tseg2.value}"
            data_bit_rate_string = f"{data_bit_rate.value}[bps]"
            data_tseg1_string = f"{data_tseg1.value}"
            data_sjw_string = f"{data_sjw.value}"
            data_tseg2_string = f"{data_tseg2.value}"
        #----------------------------------------
        # Display the command
        #----------------------------------------
        print("=========================")
        print("Menu (Top > Communication Timing Setting)")
        print("=========================")
        print("1 : CAN")
        print("2 : CAN FD")
        print("b : Back")
        print("Please input the command : ", end='', flush=True)
        #----------------------------------------
        # Waiting for input
        #----------------------------------------
        buf = input()
        #----------------------------------------
        # Distinguish the command
        #----------------------------------------
        #--------------------
        # CAN
        #--------------------
        if buf == "1":
            #----------------------------------------
            # Loop that wait input
            #----------------------------------------
            while True:
                #----------------------------------------
                # Display the setting parameter
                #----------------------------------------
                print("=========================")
                print("CAN communication timing setting parameters")
                print("=========================")
                print(f"Bitrate           : {bit_rate_string}")
                print(f"Time segment 1    : {tseg1_string}")
                print(f"SJW               : {sjw_string}")
                print(f"Time segment 2    : {tseg2_string}")
                #----------------------------------------
                # Display the command
                #----------------------------------------
                print("=========================")
                print("Menu(Top > Communication Timing Setting > CAN)")
                print("=========================")
                print("1 : CanSetCanTiming")
                print("2 : CanGetCanTiming")
                print("b : Back")
                print("Please input the command : ", end='', flush=True)
                #----------------------------------------
                # Waiting for input
                #----------------------------------------
                buf = input()
                #----------------------------------------
                # Distinguish the command
                #----------------------------------------
                #--------------------
                # CanSetCanTiming
                #--------------------
                if buf == "1":
                    #----------------------------------------
                    # Loop that wait input
                    #----------------------------------------
                    while True:
                        #----------------------------------------
                        # Display the command
                        #----------------------------------------
                        print("=========================")
                        print("Menu(Top > Communication Timing Setting > CAN > CanSetCanTiming)")
                        print("=========================")
                        print("1 : Bitrate")
                        print("2 : Time segment 1")
                        print("3 : SJW")
                        print("4 : Time segment 2")
                        print("b : Back")
                        print("Please input the command : ", end='', flush=True)
                        #----------------------------------------
                        # Waiting for input
                        #----------------------------------------
                        buf = input()
                        #----------------------------------------
                        # Distinguish the command
                        #----------------------------------------
                        #--------------------
                        # Bitrate
                        #--------------------
                        if buf == "1":
                            while True:
                                print("\nPlease input the bitrate[bps] : ", end='', flush=True)
                                #----------------------------------------
                                # Waiting for input
                                #----------------------------------------
                                buf = input()
                                #----------------------------------------
                                # Check if the input value is a number
                                #----------------------------------------
                                if False == isnum(buf, 10):
                                    continue
                                break
                            bit_rate.value = int(buf)
                            print("\nBitrate setting Successful completion")
                            print(f"Bitrate = {bit_rate.value}\n")
                        #--------------------
                        # Time segment 1
                        #--------------------
                        elif buf == "2":
                            while True:
                                print("\nPlease input the time segment 1 : ", end='', flush=True)
                                #----------------------------------------
                                # Waiting for input
                                #----------------------------------------
                                buf = input()
                                #----------------------------------------
                                # Check if the input value is a number
                                #----------------------------------------
                                if False == isnum(buf, 10):
                                    continue
                                break
                            tseg1.value = int(buf)
                            print("\nTime segment 1 setting Successful completion")
                            print(f"Time segment 1 = {tseg1.value}\n")
                        #--------------------
                        # SJW
                        #--------------------
                        elif buf == "3":
                            while True:
                                print("\nPlease input the SJW : ", end='', flush=True)
                                #----------------------------------------
                                # Waiting for input
                                #----------------------------------------
                                buf = input()
                                #----------------------------------------
                                # Check if the input value is a number
                                #----------------------------------------
                                if False == isnum(buf, 10):
                                    continue
                                break
                            sjw.value = int(buf)
                            print("\nSJW setting Successful completion")
                            print(f"SJW = {sjw.value}\n")
                        #--------------------
                        # Time segment 2
                        #--------------------
                        elif buf == "4":
                            while True:
                                print("\nPlease input the time segment 2 : ", end='', flush=True)
                                #----------------------------------------
                                # Waiting for input
                                #----------------------------------------
                                buf = input()
                                #----------------------------------------
                                # Check if the input value is a number
                                #----------------------------------------
                                if False == isnum(buf, 10):
                                    continue
                                break
                            tseg2.value = int(buf)
                            print("\nTime segment 2 setting Successful completion")
                            print(f"Time segment 2 = {tseg2.value}\n")
                        #--------------------
                        # Back
                        #--------------------
                        elif buf == "b":
                            #----------------------------------------
                            # Set the CAN communication timing
                            #----------------------------------------
                            lret.value = ccan.CanSetCanTiming(id, channel_no, bit_rate, tseg1, sjw, tseg2)
                            ccan.CanGetErrorString(lret, error_buf)
                            if lret.value == ccan.CAN_ERR_SUCCESS:
                                print(f"\nCanSetCanTiming Ret = {lret.value} {error_buf.value.decode('sjis')}")
                                print(f"Bitrate           = {bit_rate.value}[bps]")
                                print(f"Time segment 1    = {tseg1.value}")
                                print(f"SJW               = {sjw.value}")
                                print(f"Time segment 2    = {tseg2.value}\n")
                            else:
                                print("\nCAN Communication Timing Setting Error")
                                print(f"CanSetCanTiming Ret = {lret.value} {error_buf.value.decode('sjis')}\n")
                            break
                        #--------------------
                        # Error Number
                        #--------------------
                        else:
                            print("\nThe number is out of range.\nPlease try again.\n")
                            continue
                #--------------------
                # CanGetCanTiming
                #--------------------
                elif buf == "2":
                    #----------------------------------------
                    # Get the CAN communication timing
                    #----------------------------------------
                    lret.value = ccan.CanGetCanTiming(id, channel_no, ctypes.byref(bit_rate), ctypes.byref(tseg1), ctypes.byref(sjw), ctypes.byref(tseg2))
                    ccan.CanGetErrorString(lret, error_buf)
                    if lret.value == ccan.CAN_ERR_SUCCESS:
                        print(f"\nCanGetCanTiming Ret = {lret.value} {error_buf.value.decode('sjis')}")
                        print(f"Bitrate           = {bit_rate.value}[bps]")
                        print(f"Time segment 1    = {tseg1.value}")
                        print(f"SJW               = {sjw.value}")
                        print(f"Time segment 2    = {tseg2.value}\n")
                    else:
                        print("\nGet CAN Communication Timing Setting Error")
                        print(f"CanGetCanTiming Ret = {lret.value} {error_buf.value.decode('sjis')}\n")
                #--------------------
                # Back
                #--------------------
                elif buf == "b":
                    break
                #--------------------
                # Error Number
                #--------------------
                else:
                    print("\nThe number is out of range.\nPlease try again.\n")
                    continue
        #--------------------
        # CAN FD
        #--------------------
        elif buf == "2":
            #----------------------------------------
            # Loop that wait input
            #----------------------------------------
            while True:
                #----------------------------------------
                # Display the setting parameter
                #----------------------------------------
                print("=========================")
                print("CAN FD communication timing setting parameters")
                print("=========================")
                print("<Arbitration>")
                print(f"Bitrate           : {arb_bit_rate_string}")
                print(f"Time segment 1    : {arb_tseg1_string}")
                print(f"SJW               : {arb_sjw_string}")
                print(f"Time segment 2    : {arb_tseg2_string}")
                print("<Data>")
                print(f"Bitrate           : {data_bit_rate_string}")
                print(f"Time segment 1    : {data_tseg1_string}")
                print(f"SJW               : {data_sjw_string}")
                print(f"Time segment 2    : {data_tseg2_string}")
                #----------------------------------------
                # Display the command
                #----------------------------------------
                print("=========================")
                print("Menu(Top > Communication Timing Setting > CAN FD)")
                print("=========================")
                print("1 : CanSetCanFdTiming")
                print("2 : CanGetCanFdTiming")
                print("b : Back")
                print("Please input the command : ", end='', flush=True)
                #----------------------------------------
                # Waiting for input
                #----------------------------------------
                buf = input()
                #----------------------------------------
                # Distinguish the command
                #----------------------------------------
                #--------------------
                # CanSetCanFdTiming
                #--------------------
                if buf == "1":
                    #----------------------------------------
                    # Loop that wait input
                    #----------------------------------------
                    while True:
                        #----------------------------------------
                        # Display the command
                        #----------------------------------------
                        print("=========================")
                        print("Menu(Top > Communication Timing Setting > CAN FD > CanSetCanFdTiming)")
                        print("=========================")
                        print("1 : Arbitration Area")
                        print("2 : Data Area")
                        print("b : Back")
                        print("Please input the command : ", end='', flush=True)
                        #----------------------------------------
                        # Waiting for input
                        #----------------------------------------
                        buf = input()
                        #----------------------------------------
                        # Distinguish the command
                        #----------------------------------------
                        #--------------------
                        # Arbitration Area
                        #--------------------
                        if buf == "1":
                            #----------------------------------------
                            # Loop that wait input
                            #----------------------------------------
                            while True:
                                #----------------------------------------
                                # Display the command
                                #----------------------------------------
                                print("=========================")
                                print("Menu(Top > Communication Timing Setting > CAN FD > CanSetCanFdTiming > Arbitration Area)")
                                print("=========================")
                                print("1 : Bitrate")
                                print("2 : Time segment 1")
                                print("3 : SJW")
                                print("4 : Time segment 2")
                                print("b : Back")
                                print("Please input the command : ", end='', flush=True)
                                #----------------------------------------
                                # Waiting for input
                                #----------------------------------------
                                buf = input()
                                #----------------------------------------
                                # Distinguish the command
                                #----------------------------------------
                                #--------------------
                                # Bitrate
                                #--------------------
                                if buf == "1":
                                    while True:
                                        print("\nPlease input the arbitration bitrate[bps] : ", end='', flush=True)
                                        #----------------------------------------
                                        # Waiting for input
                                        #----------------------------------------
                                        buf = input()
                                        #----------------------------------------
                                        # Check if the input value is a number
                                        #----------------------------------------
                                        if False == isnum(buf, 10):
                                            continue
                                        break
                                    arb_bit_rate.value = int(buf)
                                    print("\nArbitration bitrate setting Successful completion")
                                    print(f"Arbitration bitrate = {arb_bit_rate.value}\n")
                                #--------------------
                                # Time segment 1
                                #--------------------
                                elif buf == "2":
                                    while True:
                                        print("\nPlease input the arbitration time segment 1 : ", end='', flush=True)
                                        #----------------------------------------
                                        # Waiting for input
                                        #----------------------------------------
                                        buf = input()
                                        #----------------------------------------
                                        # Check if the input value is a number
                                        #----------------------------------------
                                        if False == isnum(buf, 10):
                                            continue
                                        break
                                    arb_tseg1.value = int(buf)
                                    print("\nArbitration time segment 1 setting Successful completion")
                                    print(f"Arbitration time segment 1 = {arb_tseg1.value}\n")
                                #--------------------
                                # SJW
                                #--------------------
                                elif buf == "3":
                                    while True:
                                        print("\nPlease input the arbitration SJW : ", end='', flush=True)
                                        #----------------------------------------
                                        # Waiting for input
                                        #----------------------------------------
                                        buf = input()
                                        #----------------------------------------
                                        # Check if the input value is a number
                                        #----------------------------------------
                                        if False == isnum(buf, 10):
                                            continue
                                        break
                                    arb_sjw.value = int(buf)
                                    print("\nArbitration SJW setting Successful completion")
                                    print(f"Arbitration SJW = {arb_sjw.value}\n")
                                #--------------------
                                # Time segment 2
                                #--------------------
                                elif buf == "4":
                                    while True:
                                        print("\nPlease input the arbitration time segment 2 : ", end='', flush=True)
                                        #----------------------------------------
                                        # Waiting for input
                                        #----------------------------------------
                                        buf = input()
                                        #----------------------------------------
                                        # Check if the input value is a number
                                        #----------------------------------------
                                        if False == isnum(buf, 10):
                                            continue
                                        break
                                    arb_tseg2.value = int(buf)
                                    print("\nArbitration time segment 2 setting Successful completion")
                                    print(f"Arbitration time segment 2 = {arb_tseg2.value}\n")
                                #--------------------
                                # Back
                                #--------------------
                                elif buf == "b":
                                    break
                                #--------------------
                                # Error Number
                                #--------------------
                                else:
                                    print("\nThe number is out of range.\nPlease try again.\n")
                                    continue
                        #--------------------
                        # Data Area
                        #--------------------
                        elif buf == "2":
                            #----------------------------------------
                            # Loop that wait input
                            #----------------------------------------
                            while True:
                                #----------------------------------------
                                # Display the command
                                #----------------------------------------
                                print("=========================")
                                print("Menu(Top > Communication Timing Setting > CAN FD > CanSetCanFdTiming > Data Area)")
                                print("=========================")
                                print("1 : Bitrate")
                                print("2 : Time segment 1")
                                print("3 : SJW")
                                print("4 : Time segment 2")
                                print("b : Back")
                                print("Please input the command : ", end='', flush=True)
                                #----------------------------------------
                                # Waiting for input
                                #----------------------------------------
                                buf = input()
                                #----------------------------------------
                                # Distinguish the command
                                #----------------------------------------
                                #--------------------
                                # Bitrate
                                #--------------------
                                if buf == "1":
                                    while True:
                                        print("\nPlease input the data bitrate[bps] : ", end='', flush=True)
                                        #----------------------------------------
                                        # Waiting for input
                                        #----------------------------------------
                                        buf = input()
                                        #----------------------------------------
                                        # Check if the input value is a number
                                        #----------------------------------------
                                        if False == isnum(buf, 10):
                                            continue
                                        break
                                    data_bit_rate.value = int(buf)
                                    print("\nData bitrate setting Successful completion")
                                    print(f"Data bitrate = {data_bit_rate.value}\n")
                                #--------------------
                                # Time segment 1
                                #--------------------
                                elif buf == "2":
                                    while True:
                                        print("\nPlease input the data time segment 1 : ", end='', flush=True)
                                        #----------------------------------------
                                        # Waiting for input
                                        #----------------------------------------
                                        buf = input()
                                        #----------------------------------------
                                        # Check if the input value is a number
                                        #----------------------------------------
                                        if False == isnum(buf, 10):
                                            continue
                                        break
                                    data_tseg1.value = int(buf)
                                    print("\nData time segment 1 setting Successful completion")
                                    print(f"Data time segment 1 = {data_tseg1.value}\n")
                                #--------------------
                                # SJW
                                #--------------------
                                elif buf == "3":
                                    while True:
                                        print("\nPlease input the data SJW : ", end='', flush=True)
                                        #----------------------------------------
                                        # Waiting for input
                                        #----------------------------------------
                                        buf = input()
                                        #----------------------------------------
                                        # Check if the input value is a number
                                        #----------------------------------------
                                        if False == isnum(buf, 10):
                                            continue
                                        break
                                    data_sjw.value = int(buf)
                                    print("\nData SJW setting Successful completion")
                                    print(f"Data SJW = {data_sjw.value}\n")
                                #--------------------
                                # Time segment 2
                                #--------------------
                                elif buf == "4":
                                    while True:
                                        print("\nPlease input the data time segment 2 : ", end='', flush=True)
                                        #----------------------------------------
                                        # Waiting for input
                                        #----------------------------------------
                                        buf = input()
                                        #----------------------------------------
                                        # Check if the input value is a number
                                        #----------------------------------------
                                        if False == isnum(buf, 10):
                                            continue
                                        break
                                    data_tseg2.value = int(buf)
                                    print("\nData time segment 2 setting Successful completion")
                                    print(f"Data time segment 2 = {data_tseg2.value}\n")
                                #--------------------
                                # Back
                                #--------------------
                                elif buf == "b":
                                    break
                                #--------------------
                                # Error Number
                                #--------------------
                                else:
                                    print("\nThe number is out of range.\nPlease try again.\n")
                                    continue
                        #--------------------
                        # Back
                        #--------------------
                        elif buf == "b":
                            #----------------------------------------
                            # Set the CAN FD communication timing
                            #----------------------------------------
                            lret.value = ccan.CanSetCanFdTiming(id, channel_no, arb_bit_rate, arb_tseg1, arb_sjw, arb_tseg2, data_bit_rate, data_tseg1, data_sjw, data_tseg2)
                            ccan.CanGetErrorString(lret, error_buf)
                            if lret.value == ccan.CAN_ERR_SUCCESS:
                                print(f"\nCanSetCanFdTiming Ret = {lret.value} {error_buf.value.decode('sjis')}")
                                print(f"<Arbitration>")
                                print(f"Bitrate           = {arb_bit_rate.value}[bps]")
                                print(f"Time segment 1    = {arb_tseg1.value}")
                                print(f"SJW               = {arb_sjw.value}")
                                print(f"Time segment 2    = {arb_tseg2.value}")
                                print(f"<Data>")
                                print(f"Bitrate           = {data_bit_rate.value}[bps]")
                                print(f"Time segment 1    = {data_tseg1.value}")
                                print(f"SJW               = {data_sjw.value}")
                                print(f"Time segment 2    = {data_tseg2.value}\n")
                            else:
                                print("\nSet the CAN FD communication timing Error")
                                print(f"CanSetCanFdTiming Ret = {lret.value} {error_buf.value.decode('sjis')}\n")
                            break
                        #--------------------
                        # Error Number
                        #--------------------
                        else:
                            print("\nThe number is out of range.\nPlease try again.\n")
                            continue
                #--------------------
                # CanGetCanFdTiming
                #--------------------
                elif buf == "2":
                    #----------------------------------------
                    # Get the CAN FD communication timing settings
                    #----------------------------------------
                        lret.value = ccan.CanGetCanFdTiming(id, channel_no, ctypes.byref(arb_bit_rate), ctypes.byref(arb_tseg1), ctypes.byref(arb_sjw), ctypes.byref(arb_tseg2), ctypes.byref(data_bit_rate), ctypes.byref(data_tseg1), ctypes.byref(data_sjw), ctypes.byref(data_tseg2))
                        ccan.CanGetErrorString(lret, error_buf)
                        if lret.value == ccan.CAN_ERR_SUCCESS:
                            print(f"\nCanGetCanFdTiming Ret = {lret.value} {error_buf.value.decode('sjis')}")
                            print(f"<Arbitration>")
                            print(f"Bitrate           = {arb_bit_rate.value}[bps]")
                            print(f"Time segment 1    = {arb_tseg1.value}")
                            print(f"SJW               = {arb_sjw.value}")
                            print(f"Time segment 2    = {arb_tseg2.value}")
                            print(f"<Data>")
                            print(f"Bitrate           = {data_bit_rate.value}[bps]")
                            print(f"Time segment 1    = {data_tseg1.value}")
                            print(f"SJW               = {data_sjw.value}")
                            print(f"Time segment 2    = {data_tseg2.value}\n")
                        else:
                            print("\nGet the CAN FD communication timing settings Error")
                            print(f"CanGetCanFdTiming Ret = {lret.value} {error_buf.value.decode('sjis')}\n")
                #--------------------
                # Back
                #--------------------
                elif buf == "b":
                    break
                #--------------------
                # Error Number
                #--------------------
                else:
                    print("\nThe number is out of range.\nPlease try again.\n")
                    continue
        #--------------------
        # Back
        #--------------------
        elif buf == "b":
            break
        #--------------------
        # Error Number
        #--------------------
        else:
            print("\nThe number is out of range.\nPlease try again.\n")
            continue