#================================================================
#================================================================
# API-CAN(WDM)
# CAN通信コールバックサンプル
# mainファイル
#                                                CONTEC Co., Ltd.
#================================================================
#================================================================
#----------------------------------------
# インポートモジュール
#----------------------------------------
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 *


#========================================
# 関数名    CallBackProc
# 引数      id          CanInitで取得したデバイスIDを指定します。
# 引数      wParam      ドライバーからパラメータが渡されます。
# 引数      lParam      受信データあるチャネル番号が渡されます。
# 引数      Param       CanNotifyEvent 関数で指定したパラメータが渡されます。
#                       パラメータにNULLが指定された場合、ここにはNULLが格納されます。
# 詳細      CanNotifyEvent関数で登録する関数になります
#          イベントが発生すると本関数が呼び出されます
# 戻り値    なし
#========================================
def CallBackProc(id, wParam, lParam, Param):
    error_buf = ctypes.create_string_buffer(256)                  # エラーコード文字列
    lret = ctypes.c_int()                                         # 戻り値取得用
    channel_no = ctypes.c_ushort()                                # チャネル番号
    message_num = ctypes.c_uint()                                 # 有効な受信メッセージ数
    message_type_type = ctypes.c_uint * MAX_RECEIVE_MESSAGE       # 受信メッセージタイプタイプ
    message_type = message_type_type()                            # 受信メッセージタイプ
    can_id_type = ctypes.c_uint * MAX_RECEIVE_MESSAGE             # 受信したCAN IDタイプ
    can_id = can_id_type()                                        # 受信したCAN ID
    data_length_type = ctypes.c_ushort * MAX_RECEIVE_MESSAGE      # 受信したメッセージデータ長タイプ
    data_length = data_length_type()                              # 受信したメッセージデータ長
    receive_data_type1 = ctypes.c_ubyte * MAX_RECEIVE_DATA        # 受信したデータタイプ1
    receive_data_type2 = receive_data_type1 * MAX_RECEIVE_MESSAGE # 受信したデータタイプ2
    receive_data = receive_data_type2()                           # 受信したデータ
    error_code_type = ctypes.c_uint * MAX_RECEIVE_MESSAGE         # 受信エラーカウント
    error_code = error_code_type()                                # 受信エラー
    tick_count_type = ctypes.c_ulonglong * MAX_RECEIVE_MESSAGE    # 受信時のティックカウント値タイプ
    tick_count = tick_count_type()                                # 受信時のティックカウント値

    #----------------------------------------
    # チャネル番号格納
    #----------------------------------------
    channel_no.value = lParam
    #----------------------------------------
    # 受信メッセージ数
    #----------------------------------------
    message_num.value = MAX_RECEIVE_MESSAGE
    #----------------------------------------
    # CAN / CAN FD受信
    #----------------------------------------
    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)
    #----------------------------------------
    # エラー処理
    #----------------------------------------
    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 message_num == 0:
        return
    #----------------------------------------
    # ファイルオープン
    #----------------------------------------
    try:
        file = open("./receive_data.csv", 'a')
    except:
        text_buf = f"\n受信 エラー\nファイル作成失敗"
        PrintOnMultiLines(text_buf, 2)
        return
    #----------------------------------------
    # 受信したメッセージごとに表示
    #----------------------------------------
    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]
        #----------------------------------------
        # ファイルに書き込むための文字列の生成
        #----------------------------------------
        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"
        #----------------------------------------
        # データ書き込み
        #----------------------------------------
        file.write(text_buf)
        ctypes.cast(Param, ctypes.POINTER(ctypes.c_int)).contents.value += 1
    #----------------------------------------
    # ファイルクローズ
    #----------------------------------------
    file.close()
    #----------------------------------------
    # 受信した最後の1メッセージだけを表示
    #----------------------------------------
    text_buf = ""
    text_buf += f"\nチャネル番号{channel_no.value}  受信\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)


#========================================
# 関数名    main
# 引数      なし
# 詳細      main処理を行う関数になります
# 戻り値    なし
#========================================
def main():
    id = ctypes.c_short(0)                                  # デバイスアクセス用ID
    error_buf = ctypes.create_string_buffer(256)            # エラーコード文字列
    lret = ctypes.c_int()                                   # 戻り値取得用
    channel_no = ctypes.c_ushort(0)                         # チャネル番号
    receive_no = ctypes.c_int(0)                            # 受信番号
    message_type = ctypes.c_uint(ccan.CCAN_MSG_TYPE_CAN)    # 送信メッセージタイプ
    can_id = ctypes.c_uint(0x100)                           # 送信CAN ID
    data_length = ctypes.c_ushort(8)                        # 送信メッセージデータ長
    data_type1 = ctypes.c_ubyte * MAX_RECEIVE_DATA          # 送信データタイプ1
    data_type2 = data_type1 * MAX_RECEIVE_MESSAGE           # 送信データタイプ2
    data = data_type2()                                     # 送信データ
    message_num = ctypes.c_uint()                           # 送信メッセージ数
    channel_status = ctypes.c_ushort()                      # チャネルのステータス
    tx_error_count = ctypes.c_ushort()                      # 送信エラーカウント
    rx_error_count = ctypes.c_ushort()                      # 受信エラーカウント
    global g_mutex_object                                   # ミューテックス
    global g_info_flag                                      # コールバックで情報表示されているフラグ

    #----------------------------------------
    # グローバル変数を初期化
    #----------------------------------------
    g_info_flag.value = 0
    for i in range(0, data_length.value):
        data[0][i] = i
    #----------------------------------------
    # ロック
    #----------------------------------------
    g_mutex_object.acquire()
    #----------------------------------------
    # 入力待ちループ
    #----------------------------------------
    while True:
        #----------------------------------------
        # コマンドの表示
        #----------------------------------------
        print("=========================")
        print("共通設定値")
        print("=========================")
        print(f"チャネル番号 : {channel_no.value}")
        print("=========================")
        print("メニュー(トップ)")
        print("=========================")
        print(" 1 : CanInit")
        print(" 2 : チャネル番号設定")
        print(" 3 : 通信タイミング設定")
        print(" 4 : 受信受容メッセージ設定")
        print(" 5 : CanBusConnect")
        print(" 6 : 送信設定")
        print(" 7 : CanTransmit")
        print(" 8 : 受信開始")
        print(" 9 : 受信停止")
        print("10 : CanGetChannelStatus")
        print("11 : CanBusDisconnect")
        print("12 : CanExit")
        print(" q : 終了")
        print("コマンドを入力してください : ", end='', flush=True)
        #----------------------------------------
        # ロック解除
        #----------------------------------------
        g_mutex_object.release()
        #----------------------------------------
        # 入力待ち
        #----------------------------------------
        buf = input()
        #----------------------------------------
        # ロック
        #----------------------------------------
        g_mutex_object.acquire()
        #----------------------------------------
        # コールバックで転送位置、ステータスが表示されている場合、改行を出力
        #----------------------------------------
        if g_info_flag.value == 1:
            print("\n\n\n\n\n\n\n")
            g_info_flag.value = 0
        #----------------------------------------
        # コマンドの識別
        #----------------------------------------
        #--------------------
        # CanInit
        #--------------------
        if buf == "1":
            #----------------------------------------
            # デバイス名を入力
            #----------------------------------------
            print("\nデバイス名を入力してください : ", end='', flush=True)
            #----------------------------------------
            # ロック解除
            #----------------------------------------
            g_mutex_object.release()
            #----------------------------------------
            # 入力待ち
            #----------------------------------------
            buf = input()
            #----------------------------------------
            # ロック
            #----------------------------------------
            g_mutex_object.acquire()
            #----------------------------------------
            # コールバックで転送位置、ステータスが表示されている場合、改行を出力
            #----------------------------------------
            if g_info_flag.value == 1:
                print("\n\n\n\n\n\n\n")
                g_info_flag.value = 0
            #----------------------------------------
            # 初期化
            #----------------------------------------
            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("\n初期化 エラー")
                print(f"CanInit Ret = {lret.value} {error_buf.value.decode('sjis')}\n")
        #--------------------
        # チャネル番号設定
        #--------------------
        elif buf == "2":
            #----------------------------------------
            # チャネル番号を入力
            #----------------------------------------
            while True:
                print("\nチャネル番号を入力してください : ", end='', flush=True)
                #----------------------------------------
                # ロック解除
                #----------------------------------------
                g_mutex_object.release()
                #----------------------------------------
                # 入力待ち
                #----------------------------------------
                buf = input()
                #----------------------------------------
                # ロック
                #----------------------------------------
                g_mutex_object.acquire()
                #----------------------------------------
                # コールバックで転送位置、ステータスが表示されている場合、改行を出力
                #----------------------------------------
                if g_info_flag.value == 1:
                    print("\n\n\n\n\n\n\n")
                    g_info_flag.value = 0
                #----------------------------------------
                # 入力値が数値かとうかをチェック
                #----------------------------------------
                if False == isnum(buf, 10):
                    continue
                break
            channel_no.value = int(buf)
            print(f"\nチャネル番号 = {channel_no.value}\n")
        #--------------------
        # 通信タイミング設定
        #--------------------
        elif buf == "3":
            #----------------------------------------
            # 通信タイミング設定メニュー表示
            #----------------------------------------
            SetCommunicationTiming(id, channel_no)
            print("")
        #--------------------
        # 受信受容メッセージ設定
        #--------------------
        elif buf == "4":
            #----------------------------------------
            # 受信受容メッセージ設定メニュー表示
            #----------------------------------------
            SetAcceptance(id, channel_no)
            print("")
        #--------------------
        # CanBusConnect
        #--------------------
        elif buf == "5":
            #----------------------------------------
            # バスに接続します
            #----------------------------------------
            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("\nバスに接続 エラー")
                print(f"CanBusConnect Ret = {lret.value} {error_buf.value.decode('sjis')}\n")
        #--------------------
        # 送信設定
        #--------------------
        elif buf == "6":
            #----------------------------------------
            # 送信設定メニュー表示
            #----------------------------------------
            message_type, can_id, data_length, data = SetTransmit(message_type, can_id, data_length, data)
            print("")
        #--------------------
        # CanTransmit
        #--------------------
        elif buf == "7":
            #----------------------------------------
            # 送信メッセージ数
            #----------------------------------------
            message_num.value = 1
            #----------------------------------------
            # CAN / CAN FD送信
            #----------------------------------------
            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("\n送信 エラー")
                print(f"CanTransmit Ret = {lret.value} {error_buf.value.decode('sjis')}\n")
        #--------------------
        # 受信開始
        #--------------------
        elif buf == "8":
            #----------------------------------------
            # 受信イベント開始
            #----------------------------------------
            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("\n受信開始 正常終了\n")
            else:
                print("\n受信開始 エラー")
                print(f"CanNotifyEvent Ret = {lret.value} {error_buf.value.decode('sjis')}\n")
                continue
            receive_no.value = 0
            #----------------------------------------
            # ファイルオープン
            #----------------------------------------
            try:
                file = open("./receive_data.csv", 'w')
            except:
                print("\n受信開始 エラー")
                print("ファイル作成失敗\n")
                continue
            #----------------------------------------
            # ファイルヘッダーの内容
            #----------------------------------------
            text_string = f"No.,ReceiveChannel,TickCount,MessageType,CanId,DataLength,Data[Hex],ErrorCode\n"
            #----------------------------------------
            # データ書き込み
            #----------------------------------------
            file.write(text_string)
            #----------------------------------------
            # ファイルクローズ
            #----------------------------------------
            file.close()
        #--------------------
        # 受信停止
        #--------------------
        elif buf == "9":
            #----------------------------------------
            # 受信イベント停止
            #----------------------------------------
            lret.value = ccan.CanStopNotifyEvent(id, channel_no, ccan.CCAN_EVENT_RECEIVE)
            ccan.CanGetErrorString(lret, error_buf)
            if lret.value == ccan.CAN_ERR_SUCCESS:
                print("\n受信停止 正常終了")
            else:
                print("\n受信停止 エラー")
                print(f"CanStopNotifyEvent Ret = {lret.value} {error_buf.value.decode('sjis')}\n")
                continue
            print("\"receive_data.csv\"に受信データを保存しました。")
            print("")
        #--------------------
        # CanGetChannelStatus
        #--------------------
        elif buf == "10":
            #----------------------------------------
            # チャネルステータス取得
            #----------------------------------------
            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')}")
                #----------------------------------------
                # チャネルステータス文字列の作成
                #----------------------------------------
                if channel_status.value == ccan.CCAN_CH_STATUS_ERR_ACTIVE:
                    buf = "エラーアクティブ"
                if channel_status.value == ccan.CCAN_CH_STATUS_ERR_PASSIVE:
                    buf = "エラーパッシブ"
                if channel_status.value == ccan.CCAN_CH_STATUS_BUS_OFF:
                    buf = "バスオフ"
                print(f"ステータス            = 0x{channel_status.value:04X}({buf})\n送信エラーカウント    = {tx_error_count.value}\n受信エラーカウント    = {rx_error_count.value}\n")
            else:
                print("\nステータス取得 エラー")
                print(f"CanGetChannelStatus Ret = {lret.value} {error_buf.value.decode('sjis')}\n")
        #--------------------
        # CanBusDisconnect
        #--------------------
        elif buf == "11":
            #----------------------------------------
            # バスへの接続を解除します
            #----------------------------------------
            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("\nバスへの接続を解除 エラー")
                print(f"CanBusDisconnect Ret = {lret.value} {error_buf.value.decode('sjis')}\n")
        #--------------------
        # CanExit
        #--------------------
        elif buf == "12":
            #----------------------------------------
            # 終了処理
            #----------------------------------------
            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("\n終了処理 エラー")
                print(f"CanExit Ret = {lret.value} {error_buf.value.decode('sjis')}\n")
        #--------------------
        # 終了
        #--------------------
        elif buf == "q":
            break
        #--------------------
        # Error Number
        #--------------------
        else:
            print("\n範囲外の番号になります。\nもう一度入力してください。\n")
            continue
    #----------------------------------------
    # 終了処理
    #----------------------------------------
    ccan.CanExit(id)
    #----------------------------------------
    # ロック解除
    #----------------------------------------
    g_mutex_object.release()
    #----------------------------------------
    # アプリケーション終了
    #----------------------------------------
    sys.exit()


#----------------------------------------
# main関数呼び出し
#----------------------------------------
if __name__ == "__main__":
    main()
