#================================================================
#================================================================
# API-CNT(WDM) for サンプリング機能搭載デバイス
# 無限サンプリングサンプル
#                                                CONTEC Co., Ltd.
#================================================================
#================================================================
import ctypes
import ctypes.wintypes
import sys
import ccnt
sys.path.append(r'..\common')
import TermLib


#================================================================
# LOWORD
#================================================================
def LOWORD(a):
    return a & 0xffff


#================================================================
# HOWORD
#================================================================
def HIWORD(a):
    return (a >> 16) & 0xffff


#================================================================
# マクロ定義
#================================================================
MENU_CNT_OPEN = 0                   # CNTを初期化
MENU_COUNTER_MODE = 1               # カウンターモードを設定
MENU_CONDITION = 2                  # 条件を設定
MENU_START = 3                      # サンプリングを開始
MENU_STOP = 4                       # サンプリングを停止
MENU_COUNT = 5                      # サンプリング数を取得
MENU_STATUS = 6                     # サンプリングステータスを取得
MENU_CNT_CLOSE = 7                  # CNTを終了
MENU_EXIT = 8                       # サンプルを終了
SET_MENU_START = 0                  # サンプリングスタート条件を設定
SET_MENU_CLOCK = 1                  # サンプリングクロック条件を設定
SET_MENU_STOP = 2                   # サンプリングストップ条件を設定
SET_MENU_NOTIF = 3                  # 通知を設定
SET_MENU_COUNTER_START_MODE = 4     # カウント開始モードを設定
SET_MENU_COUNTER_STOP_MODE = 5      # カウントストップモードを設定
SET_MENU_OK = 6                     # OK処理
SET_MENU_CANCEL = 7                 # Cancel処理
SET_MENU_Z_PHASE_MODE = 0           # Z相使用方法を設定
SET_MENU_Z_PHASE_LOGIC = 1          # Z相論理を設定
SET_MENU_SIGNAL_TYPE = 2            # 外部信号源を設定
SET_MENU_COUNT_DIRECTION = 3        # カウント方向を設定
SET_MENU_PHASE = 4                  # 相数を設定
SET_MENU_MULTIPE = 5                # 逓倍を設定
SET_MENU_CLEAR = 6                  # クリア方法を設定
SET_MENU_COUNT_MODE = 7             # カウントモードを設定
STS_COUNT_POS = "Count"             # ステータス項目を設定(カウント)
STS_COUNT_MATCH_POS = "CountMatch"  # ステータス項目を設定(カウント一致)
STS_STATUS_POS = "\n Status"        # ステータス項目を設定(状態)
STS_ERROR_POS = "Error"             # ステータス項目を設定(エラー)
STS_RET_POS = "\n Ret"              # ステータス項目を設定(戻り値)
SET_NUM_START_COMP_VALUE = 0        # 開始の比較値を設定
SET_NUM_CLOCK = 1                   # 内部クロック値を設定
SET_NUM_STOP_COMP_VALUE = 2         # 停止の比較値を設定
SET_NUM_STOP_NUM = 3                # 指定個数転送完了を設定
SET_NUM_NOTIF = 4                   # 通知を行うサンプリング回数を指定することを設定
SET_NUM_DIGITAL_FILTER = 0          # デジタルフィルター値を設定

DATA_NUM = 1000                     # データサイズ
CHANNEL_NUM = 4                     # チャンネル数
#================================================================
# 外部変数
#================================================================
file_name = 'infinite.txt'                                      # 保存ファイル名
sampling_data_type = ctypes.c_ulong * (DATA_NUM * CHANNEL_NUM)  # 配列タイプを作成(データバッファ)
sampling_data = sampling_data_type()                            # データバッファ
count_match_type = ctypes.c_ulong * CHANNEL_NUM                 # 配列タイプを作成(カウント一致)
count_match = count_match_type()                                # カウント一致
read_index = ctypes.c_ulong(0)                                  # リードポインタ
write_index = ctypes.c_ulong(0)                                 # ライトポインタ
pre_count = ctypes.c_ulong(0)                                   # 前回カウント値
pre_carry  = ctypes.c_ulong(0)                                  # 前回キャリー値
#----------------------------------------
# メイン画面データ
#----------------------------------------
main_scr = {
    #----------------------------------------
    # アプリケーション名
    #----------------------------------------
    'app_name':'<< Infinite Sample >>',
    #----------------------------------------
    # 上部ステータスエリア名
    #----------------------------------------
    'status_top_name':'',
    #----------------------------------------
    # 下部ステータスエリア名
    #----------------------------------------
    'status_buttom_name':'',
    #----------------------------------------
    # メニュー[階層][メニュー個数]
    #----------------------------------------
    'menu':[['CntInit','Counter Mode','Condition...','Start','Stop','CntGetSamplingCount','CntGetSamplingStatus','CntExit','終了'],[]],
    #----------------------------------------
    # 上部ステータスエリアデータ
    #----------------------------------------
    'status_top':[],
    #----------------------------------------
    # 下部ステータスエリアデータ
    #----------------------------------------
    'status_buttom':['Count','Status','Error','Ret']
}
#----------------------------------------
# 設定画面データ
#----------------------------------------
set_scr = {
    #----------------------------------------
    # 設定画面名
    #----------------------------------------
    'window_name':'<< Condition… >>',
    #----------------------------------------
    # メニュー[階層][メニュー個数]
    #----------------------------------------
    'menu':[['Start','Clock','Stop','Notification','Counter Start Mode','Counter Stop Mode','OK','Cancel'],[]],
    #----------------------------------------
    # 項目選択タイプ用設定データ
    #----------------------------------------
    'select_item':[{'pos_y':0,                          # 設定値表示画面で何段目に表示するか？
                    'set_item_name':'Start',            # 項目名
                    #----------------------------------------
                    # 選択肢, メニューに対応するマクロ
                    #----------------------------------------
                    'item':[{'name':'Software Start','num':ccnt.CNTS_START_SOFT},
                            {'name':'External UP','num':ccnt.CNTS_START_EXT_RISE},
                            {'name':'External DOWN','num':ccnt.CNTS_START_EXT_FALL},
                            {'name':'Count Match Channel 0 Compare Register 0','num':ccnt.CNTS_START_CNTMATCH_CH0_REG0},
                            {'name':'Count Match Channel 1 Compare Register 0','num':ccnt.CNTS_START_CNTMATCH_CH1_REG0},
                            {'name':'Count Match Channel 2 Compare Register 0','num':ccnt.CNTS_START_CNTMATCH_CH2_REG0},
                            {'name':'Count Match Channel 3 Compare Register 0','num':ccnt.CNTS_START_CNTMATCH_CH3_REG0},
                            {'name':'Count Match Channel 0 Compare Register 1','num':ccnt.CNTS_START_CNTMATCH_CH0_REG1},
                            {'name':'Count Match Channel 1 Compare Register 1','num':ccnt.CNTS_START_CNTMATCH_CH1_REG1},
                            {'name':'Count Match Channel 2 Compare Register 1','num':ccnt.CNTS_START_CNTMATCH_CH2_REG1},
                            {'name':'Count Match Channel 3 Compare Register 1','num':ccnt.CNTS_START_CNTMATCH_CH3_REG1}],
                    'set_num':0                         # 設定値(何番目の選択肢か)
                    },
                    {'pos_y':2,
                    'set_item_name':'Clock',
                    'item':[{'name':'Internal Clock','num':ccnt.CNTS_CLOCK_CLOCK},
                            {'name':'External Clock','num':ccnt.CNTS_CLOCK_EXT_TRG}],
                    'set_num':0
                    },
                    {'pos_y':3,
                    'set_item_name':'Stop',
                    'item':[{'name':'Software Stop','num':ccnt.CNTS_STOP_SOFT},
                            {'name':'External UP','num':ccnt.CNTS_STOP_EXT_RISE},
                            {'name':'External DOWN','num':ccnt.CNTS_STOP_EXT_FALL},
                            {'name':'Stop Number','num':ccnt.CNTS_STOP_NUM},
                            {'name':'Count Match Channel 0 Compare Register 0','num':ccnt.CNTS_STOP_CNTMATCH_CH0_REG0},
                            {'name':'Count Match Channel 1 Compare Register 0','num':ccnt.CNTS_STOP_CNTMATCH_CH1_REG0},
                            {'name':'Count Match Channel 2 Compare Register 0','num':ccnt.CNTS_STOP_CNTMATCH_CH2_REG0},
                            {'name':'Count Match Channel 3 Compare Register 0','num':ccnt.CNTS_STOP_CNTMATCH_CH3_REG0},
                            {'name':'Count Match Channel 0 Compare Register 1','num':ccnt.CNTS_STOP_CNTMATCH_CH0_REG1},
                            {'name':'Count Match Channel 1 Compare Register 1','num':ccnt.CNTS_STOP_CNTMATCH_CH1_REG1},
                            {'name':'Count Match Channel 2 Compare Register 1','num':ccnt.CNTS_STOP_CNTMATCH_CH2_REG1},
                            {'name':'Count Match Channel 3 Compare Register 1','num':ccnt.CNTS_STOP_CNTMATCH_CH3_REG1}],
                    'set_num':0
                    },
                    {'pos_y':0,
                    'set_item_name':'',
                    'item':[],
                    'set_num':0
                    },
                    {'pos_y':2,
                    'set_item_name':'CountStartMode',
                    'item':[{'name':'Start counter regardless of sampling','num':ccnt.CNTS_START_CNT_NOT_WITH_SAMP},
                            {'name':'Start counter when sampling starts','num':ccnt.CNTS_START_CNT_WITH_SAMP}],
                    'set_num':0
                    },
                    {'pos_y':2,
                    'set_item_name':'CountStopMode',
                    'item':[{'name':'Stop counter regardless of sampling','num':ccnt.CNTS_STOP_CNT_NOT_WITH_SAMP},
                            {'name':'Stop counter when sampling Stops','num':ccnt.CNTS_STOP_CNT_WITH_SAMP}],
                    'set_num':0
                    }],
    #----------------------------------------
    # 数値入力タイプ用設定データ
    #----------------------------------------
    'input_num':[{'pos_y':0,                                # 設定値表示画面で何段目に表示するか？
                  'set_item_name':'Start Compare Value',    # 項目名
                  'unit_name':'Hex',                        # 単位名
                  'set_num':0x100,                          # 設定値
                  'hex_or_dec':TermLib.HEX_NUM              # 何進数か？ HEX_NUM or DEC_NUM
                },
                {'pos_y':1,
                  'set_item_name':'Internal Clock',
                  'unit_name':'ns',
                  'set_num':100000,
                  'hex_or_dec':TermLib.DEC_NUM
                },
                {'pos_y':2,
                  'set_item_name':'Stop Compare Value',
                  'unit_name':'Hex',
                  'set_num':0x200,
                  'hex_or_dec':TermLib.HEX_NUM
                },
                {'pos_y':3,
                  'set_item_name':'Stop Number',
                  'unit_name':'',
                  'set_num':1000,
                  'hex_or_dec':TermLib.DEC_NUM
                },
                {'pos_y':4,
                  'set_item_name':'Number of Data',
                  'unit_name':'',
                  'set_num':500,
                  'hex_or_dec':TermLib.DEC_NUM
                }]
}
#----------------------------------------
# カウンターモード設定画面データ
#----------------------------------------
set_scr_counter_mode = {
    #----------------------------------------
     # 設定画面名
     #----------------------------------------
    'window_name':'<< カウンターモード >>',
    #----------------------------------------
    # メニュー[階層][メニュー個数]
    #----------------------------------------
    'menu':[[]],
    #----------------------------------------
    # 項目選択タイプ用設定データ
    #----------------------------------------
    'select_item':[{'pos_y':0, # 設定値表示画面で何段目に表示するか？
                    'set_item_name':'Z相使用方法の設定', # 項目名
                    #----------------------------------------
                    # 選択肢, メニューに対応するマクロ
                    #----------------------------------------
                    'item':[{'name':'未使用','num':ccnt.CNT_ZPHASE_NOT_USE},
                            {'name':'１回','num':ccnt.CNT_ZPHASE_NEXT_ONE},
                            {'name':'毎回','num':ccnt.CNT_ZPHASE_EVERY_TIME}],
                    'set_num':0 # 設定値(何番目の選択肢か)
                    },
                    {'pos_y':2,
                    'set_item_name':'Z相論理の設定',
                    'item':[{'name':'正論理','num':ccnt.CNT_ZLOGIC_POSITIVE},
                            {'name':'負論理','num':ccnt.CNT_ZLOGIC_NEGATIVE}],
                    'set_num':0
                    },
                    {'pos_y':4,
                    'set_item_name':'外部信号源の設定',
                    'item':[{'name':'フォトカプラ','num':ccnt.CNT_SIGTYPE_ISOLATE},
                            {'name':'TTL','num':ccnt.CNT_SIGTYPE_TTL},
                            {'name':'差動','num':ccnt.CNT_SIGTYPE_LINERECEIVER}],
                    'set_num':0
                    },
                    {'pos_y':2,
                    'set_item_name':'カウント方向の設定',
                    'item':[{'name':'ダウンカウント','num':ccnt.CNT_DIR_DOWN},
                            {'name':'アップカウント','num':ccnt.CNT_DIR_UP}],
                    'set_num':0
                    },
                    {'pos_y':2,
                    'set_item_name':'相数の設定',
                    'item':[{'name':'単相入力','num':ccnt.CNT_MODE_1PHASE},
                            {'name':'２相入力','num':ccnt.CNT_MODE_2PHASE},
                            {'name':'ゲートコントロール付き単相入力','num':ccnt.CNT_MODE_GATECONTROL}],
                    'set_num':0
                    },
                    {'pos_y':2,
                    'set_item_name':'逓倍の設定',
                    'item':[{'name':'1逓倍','num':ccnt.CNT_MUL_X1},
                            {'name':'2逓倍','num':ccnt.CNT_MUL_X2},
                            {'name':'4逓倍','num':ccnt.CNT_MUL_X4}],
                    'set_num':0
                    },
                    {'pos_y':2,
                    'set_item_name':'同期クリアの設定',
                    'item':[{'name':'非同期クリア','num':ccnt.CNT_CLR_ASYNC},
                            {'name':'同期クリア','num':ccnt.CNT_CLR_SYNC}],
                    'set_num':0
                    },
                    {'pos_y':2,
                    'set_item_name':'カウントモードの設定',
                    'item':[{'name':'積算','num':ccnt.CNTS_MODE_NORMAL},
                            {'name':'差分','num':ccnt.CNTS_MODE_DIFF}],
                    'set_num':0
                    }],
    #----------------------------------------
    # 数値入力タイプ用設定データ
    #----------------------------------------
    'input_num':[{'pos_y':0,                                  # 設定値表示画面で何段目に表示するか？
                  'set_item_name':'デジタルフィルタの設定',     # 項目名
                  'unit_name':'0x0-0xF',                      # 単位名
                  'set_num':0x00,                             # 設定値
                  'hex_or_dec':TermLib.HEX_NUM                # 何進数か？ HEX_NUM or DEC_NUM
                }]
}


#================================================================
# カウント一致コールバック関数
#================================================================
def count_call_back(dev_id, wparam, lparam, param):
    global count_match
    #----------------------------------------
    # カウント一致メッセージの処理
    #----------------------------------------
    #----------------------------------------
    # カウント一致チャネル番号
    #----------------------------------------
    ChNo = LOWORD(wparam)
    #----------------------------------------
    # 立ち上がり:1, 立ち下がり:2
    #----------------------------------------
    Kind = HIWORD(wparam)
    #----------------------------------------
    # 比較値
    #----------------------------------------
    Count = lparam

    if ChNo == 0:       # カウント一致: 0CH
        count_match[0] = count_match[0] + 1
        if Kind == 1:
            buf = str.format('カウント一致! チャネル番号: 0, UP, カウント: {:08x}(16進数) 一致回数: {:d} 回', Count, count_match[0])
        else:
            buf = str.format('カウント一致! チャネル番号: 0, DOWN, カウント: {:08x}(16進数) 一致回数: {:d} 回', Count, count_match[0])
        TermLib.TermSetStatus(TermLib.STATUS_AREA_BOTTOM, STS_COUNT_MATCH_POS, buf)
    elif ChNo == 1:     # カウント一致: 1CH
        count_match[1] = count_match[1] + 1
        if Kind == 1:
            buf = str.format('カウント一致! チャネル番号: 1, UP, カウント: {:08x}(16進数) 一致回数: {:d} 回', Count, count_match[1])
        else:
            buf = str.format('カウント一致! チャネル番号: 1, DOWN, カウント: {:08x}(16進数) 一致回数: {:d} 回', Count, count_match[1])
        TermLib.TermSetStatus(TermLib.STATUS_AREA_BOTTOM, STS_COUNT_MATCH_POS, buf)
    elif ChNo == 2:     # カウント一致: 2CH
        count_match[2] = count_match[2] + 1
        if Kind == 1:
            buf = str.format('カウント一致! チャネル番号: 2, UP, カウント: {:08x}(16進数) 一致回数: {:d} 回', Count, count_match[2])
        else:
            buf = str.format('カウント一致! チャネル番号: 2, DOWN, カウント: {:08x}(16進数) 一致回数: {:d} 回', Count, count_match[2])
        TermLib.TermSetStatus(TermLib.STATUS_AREA_BOTTOM, STS_COUNT_MATCH_POS, buf)
    elif ChNo == 3:     # カウント一致: 3CH
        count_match[3] = count_match[3] + 1
        if Kind == 1:
            buf = str.format('カウント一致! チャネル番号: 3, UP, カウント: {:08x}(16進数) 一致回数: {:d} 回', Count, count_match[3])
        else:
            buf = str.format('カウント一致! チャネル番号: 3, DOWN, カウント: {:08x}(16進数) 一致回数: {:d} 回', Count, count_match[3])
        TermLib.TermSetStatus(TermLib.STATUS_AREA_BOTTOM, STS_COUNT_MATCH_POS, buf)
    return


#================================================================
# 指定個数転送完了コールバック関数
#================================================================
def sampling_count_call_back(dev_id, wparam, lparam, param):
    count = ctypes.c_ulong()
    carry = ctypes.c_ulong()
    err_str = ctypes.create_string_buffer(256)

    #----------------------------------------
    # ライトポインタ取得
    #----------------------------------------
    lret = ccnt.CntGetSamplingWritePointer(dev_id, ctypes.byref(write_index), ctypes.byref(count), ctypes.byref(carry))
    if lret != ccnt.CNT_ERR_SUCCESS:
        ccnt.CntGetErrorString(lret, err_str)
        buf = str.format('CntGetSamplingWritePointer {}:{}', lret, err_str.value.decode('sjis'))
        TermLib.TermSetStatus(TermLib.STATUS_AREA_BOTTOM, STS_RET_POS, buf)
        return
    #----------------------------------------
    # オーバーランエラーチェック
    #----------------------------------------
    if carry.value == pre_carry.value:
        if count.value > (pre_count.value + DATA_NUM):
            buf = str.format('Overrun Error! (Count = {})', count.value)
            TermLib.TermSetStatus(TermLib.STATUS_AREA_BOTTOM, STS_ERROR_POS, buf, False)
            return
    #----------------------------------------
    # 前回と同じカウント値であれば終了
    # (転送完了メッセージから呼ばれた場合のため)
    #----------------------------------------
    if count.value == pre_count.value and carry.value == pre_carry.value:
        return
    #----------------------------------------
    # ファイルにデータを書き込む
    #----------------------------------------
    #----------------------------------------
    # ファイルオープン
    #----------------------------------------
    try:
        the_file = open(file_name, 'a')
    except:
        buf = str.format('open : file open error.')
        TermLib.TermSetStatus(TermLib.STATUS_AREA_BOTTOM, STS_RET_POS, buf)
        return
    #----------------------------------------
    # ファイルに書き込み
    #----------------------------------------
    if write_index.value > read_index.value:
        cnt = count.value - (write_index.value - read_index.value)
        for data_count in range(read_index.value, write_index.value):
            buf = str.format('{0:8d}:  ', cnt)
            for ch_no in range(0, CHANNEL_NUM):
                index = data_count * CHANNEL_NUM + ch_no
                buf = buf + str.format('{0:08X} ', sampling_data[index])
            buf = buf + "\n"
            the_file.write(buf) 
            cnt += 1
    else:
        cnt = count.value - (DATA_NUM - read_index.value + write_index.value)
        for data_count in range(read_index.value, DATA_NUM):
            buf = str.format('{0:8d}:  ', cnt)
            for ch_no in range(0, CHANNEL_NUM):
                index = data_count * CHANNEL_NUM + ch_no
                buf = buf + str.format('{0:08X} ', sampling_data[index])
            buf = buf + "\n"
            the_file.write(buf) 
            cnt += 1
        for data_count in range(0, write_index.value):
            buf = str.format('{0:8d}:  ', cnt)
            for ch_no in range(0, CHANNEL_NUM):
                index = data_count * CHANNEL_NUM + ch_no
                buf = buf + str.format('{0:08X} ', sampling_data[index])
            buf = buf + "\n"
            the_file.write(buf) 
            cnt += 1
    #----------------------------------------
    # ファイルクローズ
    #----------------------------------------
    the_file.close()
    #----------------------------------------
    # カウント値を表示
    #----------------------------------------
    read_index.value = write_index.value
    pre_count.value = count.value
    pre_carry.value = carry.value
    #----------------------------------------
    # カウント値を表示
    #----------------------------------------
    buf = str.format('{:<30d}', count.value)
    TermLib.TermSetStatus(TermLib.STATUS_AREA_BOTTOM, STS_COUNT_POS, buf, False)
    return


#================================================================
# 転送完了コールバック関数
#================================================================
def sampling_stop_call_back(dev_id, wparam, lparam, param):
    #----------------------------------------
    # 割り込みメッセージの処理
    #----------------------------------------
    sampling_count_call_back(dev_id, wparam, lparam, param)
    TermLib.TermSetStatus(TermLib.STATUS_AREA_BOTTOM, STS_STATUS_POS, 'Stopped!')
    return


pcount_callback = ccnt.PCNT_MATCH_CALLBACK(count_call_back)
psampling_stop_callback = ccnt.PCNT_SAMPLING_STOP_CALLBACK(sampling_stop_call_back)
psampling_count_callback = ccnt.PCNT_SAMPLING_COUNT_CALLBACK(sampling_count_call_back)


#================================================================
# カウンターモード設定関数
#================================================================
def counter_mode(dev_id, err_str):
    get_str = ctypes.create_string_buffer(256)
    #----------------------------------------
    # 設定データ初期化
    #----------------------------------------
    def_set_num = set_scr_counter_mode['select_item'][SET_MENU_Z_PHASE_MODE]['set_num']
    z_phase_mode = set_scr_counter_mode['select_item'][SET_MENU_Z_PHASE_MODE]['item'][def_set_num]['num']
    def_set_num = set_scr_counter_mode['select_item'][SET_MENU_Z_PHASE_LOGIC]['set_num']
    z_phase_logic = set_scr_counter_mode['select_item'][SET_MENU_Z_PHASE_LOGIC]['item'][def_set_num]['num']
    def_set_num = set_scr_counter_mode['select_item'][SET_MENU_SIGNAL_TYPE]['set_num']
    signal_type = set_scr_counter_mode['select_item'][SET_MENU_SIGNAL_TYPE]['item'][def_set_num]['num']
    def_set_num = set_scr_counter_mode['select_item'][SET_MENU_COUNT_DIRECTION]['set_num']
    count_direction = set_scr_counter_mode['select_item'][SET_MENU_COUNT_DIRECTION]['item'][def_set_num]['num']
    def_set_num = set_scr_counter_mode['select_item'][SET_MENU_PHASE]['set_num']
    phase = set_scr_counter_mode['select_item'][SET_MENU_PHASE]['item'][def_set_num]['num']
    def_set_num = set_scr_counter_mode['select_item'][SET_MENU_MULTIPE]['set_num']
    multiple = set_scr_counter_mode['select_item'][SET_MENU_MULTIPE]['item'][def_set_num]['num']
    def_set_num = set_scr_counter_mode['select_item'][SET_MENU_CLEAR]['set_num']
    clear = set_scr_counter_mode['select_item'][SET_MENU_CLEAR]['item'][def_set_num]['num']
    def_set_num = set_scr_counter_mode['select_item'][SET_MENU_COUNT_MODE]['set_num']
    count_mode = set_scr_counter_mode['select_item'][SET_MENU_COUNT_MODE]['item'][def_set_num]['num']
    digital_filter = set_scr_counter_mode['input_num'][SET_NUM_DIGITAL_FILTER]['set_num']

    #----------------------------------------
    # 設定ウインドウ初期化
    #----------------------------------------
    lret = TermLib.TermSetWindowOpen(set_scr_counter_mode)
    if lret != TermLib.TERM_ERR_SUCCESS:
        err_str = 'TermSetWindowOpen ' + str(lret)
        return 1, err_str
    #----------------------------------------
    # メニュー処理
    #----------------------------------------
    err_str = ''
    #----------------------------------------
    # 前回エラーだったら設定画面終了
    #----------------------------------------
    if err_str != '':
        TermLib.TermSetWindowClose()
        return 1, err_str
    #----------------------------------------
    # Z相使用方法の設定
    #----------------------------------------
    lret, z_phase_mode = TermLib.TermGetSelectItem(set_scr_counter_mode, SET_MENU_Z_PHASE_MODE, z_phase_mode)
    if lret != TermLib.TERM_ERR_SUCCESS:
        err_str = 'TermGetSelectItem ' + str(lret)
        return 1, err_str
    for ch_no in range(0, CHANNEL_NUM):
        lret = ccnt.CntSetZMode(dev_id, ch_no, z_phase_mode)
        if lret != ccnt.CNT_ERR_SUCCESS:
            ccnt.CntGetErrorString(lret, get_str)
            print("CntSetZMode : ret = {0:X} h\n {1:s}", lret, get_str.value.decode('sjis'))
            break
    #----------------------------------------
    # Z相論理の設定
    #----------------------------------------
    lret, z_phase_logic = TermLib.TermGetSelectItem(set_scr_counter_mode, SET_MENU_Z_PHASE_LOGIC, z_phase_logic)
    if lret != TermLib.TERM_ERR_SUCCESS:
        err_str = 'TermGetSelectItem ' + str(lret)
        return 1, err_str
    for ch_no in range(0, CHANNEL_NUM):
        lret = ccnt.CntSetZLogic(dev_id, ch_no, z_phase_logic)
        if lret != ccnt.CNT_ERR_SUCCESS:
            ccnt.CntGetErrorString(lret, get_str)
            print("CntSetZLogic : ret = {0:X} h\n {1:s}", lret, get_str.value.decode('sjis'))
            break
    #----------------------------------------
    # 外部信号源の設定
    #----------------------------------------
    lret, signal_type = TermLib.TermGetSelectItem(set_scr_counter_mode, SET_MENU_SIGNAL_TYPE, signal_type)
    if lret != TermLib.TERM_ERR_SUCCESS:
        err_str = 'TermGetSelectItem ' + str(lret)
        return 1, err_str
    for ch_no in range(0, CHANNEL_NUM):
        lret = ccnt.CntSelectChannelSignal(dev_id, ch_no, signal_type)
        if lret != ccnt.CNT_ERR_SUCCESS:
            ccnt.CntGetErrorString(lret, get_str)
            print("CntSelectChannelSignal : ret = {0:X} h\n {1:s}", lret, get_str.value.decode('sjis'))
            break
    #----------------------------------------
    # カウント方向の設定
    #----------------------------------------
    lret, count_direction = TermLib.TermGetSelectItem(set_scr_counter_mode, SET_MENU_COUNT_DIRECTION, count_direction)
    if lret != TermLib.TERM_ERR_SUCCESS:
        err_str = 'TermGetSelectItem ' + str(lret)
        return 1, err_str
    for ch_no in range(0, CHANNEL_NUM):
        lret = ccnt.CntSetCountDirection(dev_id, ch_no, count_direction)
        if lret != ccnt.CNT_ERR_SUCCESS:
            ccnt.CntGetErrorString(lret, get_str)
            print("CntSetCountDirection : ret = {0:X} h\n {1:s}", lret, get_str.value.decode('sjis'))
            break
    #----------------------------------------
    # デジタルフィルターの設定
    #----------------------------------------
    lret, digital_filter = TermLib.TermGetInputNum(set_scr_counter_mode, SET_NUM_DIGITAL_FILTER, digital_filter)
    if lret != TermLib.TERM_ERR_SUCCESS:
        err_str = 'TermGetInputNum ' + str(lret)
        return 1, err_str
    for ch_no in range(0, CHANNEL_NUM):
        lret = ccnt.CntSetDigitalFilter(dev_id, ch_no, digital_filter)
        if lret != ccnt.CNT_ERR_SUCCESS:
            ccnt.CntGetErrorString(lret, get_str)
            print("CntSetDigitalFilter : ret = {0:X} h\n {1:s}", lret, get_str.value.decode('sjis'))
            break
    #----------------------------------------
    # 動作モードの設定
    #----------------------------------------
    lret, phase = TermLib.TermGetSelectItem(set_scr_counter_mode, SET_MENU_PHASE, phase)
    if lret != TermLib.TERM_ERR_SUCCESS:
        err_str = 'TermGetSelectItem ' + str(lret)
        return 1, err_str
    lret, multiple = TermLib.TermGetSelectItem(set_scr_counter_mode, SET_MENU_MULTIPE, multiple)
    if lret != TermLib.TERM_ERR_SUCCESS:
        err_str = 'TermGetSelectItem ' + str(lret)
        return 1, err_str
    lret, clear = TermLib.TermGetSelectItem(set_scr_counter_mode, SET_MENU_CLEAR, clear)
    if lret != TermLib.TERM_ERR_SUCCESS:
        err_str = 'TermGetSelectItem ' + str(lret)
        return 1, err_str
    for ch_no in range(0, CHANNEL_NUM):
        lret = ccnt.CntSetOperationMode(dev_id, ch_no, phase, multiple, clear)
        if lret != ccnt.CNT_ERR_SUCCESS:
            ccnt.CntGetErrorString(lret, get_str)
            print("CntSetOperationMode : ret = {0:X} h\n {1:s}", lret, get_str.value.decode('sjis'))
            break
    #----------------------------------------
    # カウントモードの設定
    #----------------------------------------
    lret, count_mode = TermLib.TermGetSelectItem(set_scr_counter_mode, SET_MENU_COUNT_MODE, count_mode)
    if lret != TermLib.TERM_ERR_SUCCESS:
        err_str = 'TermGetSelectItem ' + str(lret)
        return 1, err_str
    for ch_no in range(0, CHANNEL_NUM):
        lret = ccnt.CntSetCounterMode(dev_id, ch_no, count_mode)
        if lret != ccnt.CNT_ERR_SUCCESS:
            ccnt.CntGetErrorString(lret, get_str)
            print("CntSetCounterMode : ret = {0:X} h\n {1:s}", lret, get_str.value.decode('sjis'))
            break
    TermLib.TermSetWindowClose()
    return 0, err_str


#================================================================
# 転送条件設定関数
#================================================================
def condition(dev_id, err_str):
    menu_num = 0
    get_str = ctypes.create_string_buffer(256)
    #----------------------------------------
    # 設定データ初期化
    #----------------------------------------
    def_set_num = set_scr['select_item'][SET_MENU_START]['set_num']
    start = set_scr['select_item'][SET_MENU_START]['item'][def_set_num]['num']
    def_set_num = set_scr['select_item'][SET_MENU_CLOCK]['set_num']
    clock = set_scr['select_item'][SET_MENU_CLOCK]['item'][def_set_num]['num']
    def_set_num = set_scr['select_item'][SET_MENU_STOP]['set_num']
    stop = set_scr['select_item'][SET_MENU_STOP]['item'][def_set_num]['num']
    def_set_num = set_scr['select_item'][SET_MENU_COUNTER_START_MODE]['set_num']
    counter_start_mode = set_scr['select_item'][SET_MENU_COUNTER_START_MODE]['item'][def_set_num]['num']
    def_set_num = set_scr['select_item'][SET_MENU_COUNTER_STOP_MODE]['set_num']
    counter_stop_mode = set_scr['select_item'][SET_MENU_COUNTER_STOP_MODE]['item'][def_set_num]['num']
    start_comp_value = set_scr['input_num'][SET_NUM_START_COMP_VALUE]['set_num']
    stop_comp_value = set_scr['input_num'][SET_NUM_STOP_COMP_VALUE]['set_num']
    internal_clock = set_scr['input_num'][SET_NUM_CLOCK]['set_num']
    stop_num = set_scr['input_num'][SET_NUM_STOP_NUM]['set_num']
    notification = set_scr['input_num'][SET_NUM_NOTIF]['set_num']

    #----------------------------------------
    # 設定ウインドウ初期化
    #----------------------------------------
    lret = TermLib.TermSetWindowOpen(set_scr)
    if lret != TermLib.TERM_ERR_SUCCESS:
        err_str = 'TermSetWindowOpen ' + str(lret)
        return 1, err_str
    #----------------------------------------
    # メニュー処理
    #----------------------------------------
    err_str = ''
    while True:
        #----------------------------------------
        # 前回エラーだったら設定画面終了
        #----------------------------------------
        if err_str != '':
            TermLib.TermSetWindowClose()
            return 1, err_str
        #----------------------------------------
        # メニュー番号入力
        #----------------------------------------
        lret, menu_num = TermLib.TermGetMenuNum('Please input a menu number(0-7)', menu_num)
        if lret != TermLib.TERM_ERR_SUCCESS:
            err_str = 'TermGetMenuNum ' + str(lret)
            return 1, err_str
        #----------------------------------------
        # スタート条件設定
        #----------------------------------------
        if menu_num == SET_MENU_START:
            lret, start = TermLib.TermGetSelectItem(set_scr, SET_MENU_START, start)
            if lret != TermLib.TERM_ERR_SUCCESS:
                err_str = 'TermGetSelectItem ' + str(lret)
            if start != ccnt.CNTS_START_SOFT and start != ccnt.CNTS_START_EXT_RISE and start != ccnt.CNTS_START_EXT_FALL:
                lret, start_comp_value = TermLib.TermGetInputNum(set_scr, SET_NUM_START_COMP_VALUE, start_comp_value)
                if lret != TermLib.TERM_ERR_SUCCESS:
                    err_str = 'TermGetInputNum ' + str(lret)
        #----------------------------------------
        # クロック条件設定
        #----------------------------------------
        elif menu_num == SET_MENU_CLOCK:
            lret, clock = TermLib.TermGetSelectItem(set_scr, SET_MENU_CLOCK, clock)
            if lret != TermLib.TERM_ERR_SUCCESS:
                err_str = 'TermGetSelectItem ' + str(lret)
            if clock == ccnt.CNTS_CLOCK_CLOCK:
                lret, internal_clock = TermLib.TermGetInputNum(set_scr, SET_NUM_CLOCK, internal_clock)
                if lret != TermLib.TERM_ERR_SUCCESS:
                    err_str = 'TermGetInputNum ' + str(lret)
        #----------------------------------------
        # ストップ条件設定
        #----------------------------------------
        elif menu_num == SET_MENU_STOP:
            lret, stop = TermLib.TermGetSelectItem(set_scr, SET_MENU_STOP, stop)
            if lret != TermLib.TERM_ERR_SUCCESS:
                err_str = 'TermGetSelectItem ' + str(lret)
            if stop != ccnt.CNTS_STOP_SOFT and stop != ccnt.CNTS_STOP_EXT_RISE and stop != ccnt.CNTS_STOP_EXT_FALL and stop != ccnt.CNTS_STOP_NUM:
                lret, stop_comp_value = TermLib.TermGetInputNum(set_scr, SET_NUM_STOP_COMP_VALUE, stop_comp_value)
                if lret != TermLib.TERM_ERR_SUCCESS:
                    err_str = 'TermGetInputNum ' + str(lret)
            if stop == ccnt.CNTS_STOP_NUM:
                lret, stop_num = TermLib.TermGetInputNum(set_scr, SET_NUM_STOP_NUM, stop_num)
                if lret != TermLib.TERM_ERR_SUCCESS:
                    err_str = 'TermGetInputNum ' + str(lret)
        #----------------------------------------
        # カウンタースタートモード設定
        #----------------------------------------
        elif menu_num == SET_MENU_COUNTER_START_MODE:
            lret, counter_start_mode = TermLib.TermGetSelectItem(set_scr, SET_MENU_COUNTER_START_MODE, counter_start_mode)
            if lret != TermLib.TERM_ERR_SUCCESS:
                err_str = 'TermGetSelectItem ' + str(lret)
        #----------------------------------------
        # カウンターストップモード設定
        #----------------------------------------
        elif menu_num == SET_MENU_COUNTER_STOP_MODE:
            lret, counter_stop_mode = TermLib.TermGetSelectItem(set_scr, SET_MENU_COUNTER_STOP_MODE, counter_stop_mode)
            if lret != TermLib.TERM_ERR_SUCCESS:
                err_str = 'TermGetSelectItem ' + str(lret)
        #----------------------------------------
        # 通知カウント設定
        #----------------------------------------
        elif menu_num == SET_MENU_NOTIF:
            lret, notification = TermLib.TermGetInputNum(set_scr, SET_NUM_NOTIF, notification)
            if lret != TermLib.TERM_ERR_SUCCESS:
                err_str = 'TermGetInputNum ' + str(lret)
        #----------------------------------------
        # OK処理
        #----------------------------------------
        elif menu_num == SET_MENU_OK:
            #----------------------------------------
            # サンプリング条件を設定
            #----------------------------------------
            #----------------------------------------
            # スタンドアローン
            #----------------------------------------
            lret = ccnt.CntSetStandAlone(dev_id)
            if lret != ccnt.CNT_ERR_SUCCESS:
                ccnt.CntGetErrorString(lret, get_str)
                err_str = 'CntSetStandAlone ret = ' + str(lret) + ': ' +str(get_str.value.decode('sjis'))
                continue
            #----------------------------------------
            # スタート条件設定
            #----------------------------------------
            lret = ccnt.CntSetSamplingStartTrigger(dev_id, start, counter_start_mode, CHANNEL_NUM)
            if lret != ccnt.CNT_ERR_SUCCESS:
                ccnt.CntGetErrorString(lret, get_str)
                err_str = 'CntSetSamplingStartTrigger ret = ' + str(lret) + ': ' + str(get_str.value.decode('sjis'))
                continue
            if start == ccnt.CNTS_START_CNTMATCH_CH0_REG0:
                comp_ch_no = 0
                comp_reg_no = 0
            elif start == ccnt.CNTS_START_CNTMATCH_CH1_REG0:
                comp_ch_no = 1
                comp_reg_no = 0
            elif start == ccnt.CNTS_START_CNTMATCH_CH2_REG0:
                comp_ch_no = 2
                comp_reg_no = 0
            elif start == ccnt.CNTS_START_CNTMATCH_CH3_REG0:
                comp_ch_no = 3
                comp_reg_no = 0
            elif start == ccnt.CNTS_START_CNTMATCH_CH4_REG0:
                comp_ch_no = 4
                comp_reg_no = 0
            elif start == ccnt.CNTS_START_CNTMATCH_CH5_REG0:
                comp_ch_no = 5
                comp_reg_no = 0
            elif start == ccnt.CNTS_START_CNTMATCH_CH6_REG0:
                comp_ch_no = 6
                comp_reg_no = 0
            elif start == ccnt.CNTS_START_CNTMATCH_CH7_REG0:
                comp_ch_no = 7
                comp_reg_no = 0
            elif start == ccnt.CNTS_START_CNTMATCH_CH0_REG1:
                comp_ch_no = 0
                comp_reg_no = 1
            elif start == ccnt.CNTS_START_CNTMATCH_CH1_REG1:
                comp_ch_no = 1
                comp_reg_no = 1
            elif start == ccnt.CNTS_START_CNTMATCH_CH2_REG1:
                comp_ch_no = 2
                comp_reg_no = 1
            elif start == ccnt.CNTS_START_CNTMATCH_CH3_REG1:
                comp_ch_no = 3
                comp_reg_no = 1
            elif start == ccnt.CNTS_START_CNTMATCH_CH4_REG1:
                comp_ch_no = 4
                comp_reg_no = 1
            elif start == ccnt.CNTS_START_CNTMATCH_CH5_REG1:
                comp_ch_no = 5
                comp_reg_no = 1
            elif start == ccnt.CNTS_START_CNTMATCH_CH6_REG1:
                comp_ch_no = 6
                comp_reg_no = 1
            elif start == ccnt.CNTS_START_CNTMATCH_CH7_REG1:
                comp_ch_no = 7
                comp_reg_no = 1
            else:
                comp_ch_no = 0xfff
                comp_reg_no = 0xfff
            if comp_ch_no != 0xfff and comp_reg_no != 0xfff:
                lret = ccnt.CntNotifyCountUp(dev_id, comp_ch_no, comp_reg_no, start_comp_value, 0)
                if lret != ccnt.CNT_ERR_SUCCESS:
                    ccnt.CntGetErrorString(lret, get_str)
                    err_str = 'CntNotifyCountUp ret = ' + str(lret) + ': ' + str(get_str.value.decode('sjis'))
                    continue
                #----------------------------------------
                # カウントマッチコールバック設定
                #----------------------------------------
                lret = ccnt.CntCountUpCallbackProc(dev_id, pcount_callback, "Match Count")
                if lret != ccnt.CNT_ERR_SUCCESS:
                    ccnt.CntGetErrorString(lret, get_str)
                    err_str = 'CntCountUpCallbackProc ret = ' + str(lret) + ': ' + str(get_str.value.decode('sjis'))
                    continue
            #----------------------------------------
            # クロック条件設定
            #----------------------------------------
            lret = ccnt.CntSetSamplingClockTrigger(dev_id, clock)
            if lret != ccnt.CNT_ERR_SUCCESS:
                ccnt.CntGetErrorString(lret, get_str)
                err_str = 'CntSetSamplingClockTrigger ret = ' + str(lret) + ': ' + str(get_str.value.decode('sjis'))
                continue
            #----------------------------------------
            # 内部クロック値設定
            #----------------------------------------
            if clock == ccnt.CNTS_CLOCK_CLOCK:
                lret = ccnt.CntSetSamplingInternalClock(dev_id, internal_clock, ccnt.CNTS_TIM_UNIT_NS)
                if lret != ccnt.CNT_ERR_SUCCESS:
                    ccnt.CntGetErrorString(lret, get_str)
                    err_str = 'CntSetSamplingInternalClock ret = ' + str(lret) + ': ' + str(get_str.value.decode('sjis'))
                    continue
            #----------------------------------------
            # ストップ条件設定
            #----------------------------------------
            lret = ccnt.CntSetSamplingStopTrigger(dev_id, stop, counter_stop_mode, CHANNEL_NUM)
            if lret != ccnt.CNT_ERR_SUCCESS:
                ccnt.CntGetErrorString(lret, get_str)
                err_str = 'CntSetSamplingStopTrigger ret = ' + str(lret) + ': ' + str(get_str.value.decode('sjis'))
                continue
            if stop == ccnt.CNTS_STOP_CNTMATCH_CH0_REG0:
                comp_ch_no = 0
                comp_reg_no = 0
            elif stop == ccnt.CNTS_STOP_CNTMATCH_CH1_REG0:
                comp_ch_no = 1
                comp_reg_no = 0
            elif stop == ccnt.CNTS_STOP_CNTMATCH_CH2_REG0:
                comp_ch_no = 2
                comp_reg_no = 0
            elif stop == ccnt.CNTS_STOP_CNTMATCH_CH3_REG0:
                comp_ch_no = 3
                comp_reg_no = 0
            elif stop == ccnt.CNTS_STOP_CNTMATCH_CH4_REG0:
                comp_ch_no = 4
                comp_reg_no = 0
            elif stop == ccnt.CNTS_STOP_CNTMATCH_CH5_REG0:
                comp_ch_no = 5
                comp_reg_no = 0
            elif stop == ccnt.CNTS_STOP_CNTMATCH_CH6_REG0:
                comp_ch_no = 6
                comp_reg_no = 0
            elif stop == ccnt.CNTS_STOP_CNTMATCH_CH7_REG0:
                comp_ch_no = 7
                comp_reg_no = 0
            elif stop == ccnt.CNTS_STOP_CNTMATCH_CH0_REG1:
                comp_ch_no = 0
                comp_reg_no = 1
            elif stop == ccnt.CNTS_STOP_CNTMATCH_CH1_REG1:
                comp_ch_no = 1
                comp_reg_no = 1
            elif stop == ccnt.CNTS_STOP_CNTMATCH_CH2_REG1:
                comp_ch_no = 2
                comp_reg_no = 1
            elif stop == ccnt.CNTS_STOP_CNTMATCH_CH3_REG1:
                comp_ch_no = 3
                comp_reg_no = 1
            elif stop == ccnt.CNTS_STOP_CNTMATCH_CH4_REG1:
                comp_ch_no = 4
                comp_reg_no = 1
            elif stop == ccnt.CNTS_STOP_CNTMATCH_CH5_REG1:
                comp_ch_no = 5
                comp_reg_no = 1
            elif stop == ccnt.CNTS_STOP_CNTMATCH_CH6_REG1:
                comp_ch_no = 6
                comp_reg_no = 1
            elif stop == ccnt.CNTS_STOP_CNTMATCH_CH7_REG1:
                comp_ch_no = 7
                comp_reg_no = 1
            else:
                comp_ch_no = 0xfff
                comp_reg_no = 0xfff
            if comp_ch_no != 0xfff and comp_reg_no != 0xfff:
                lret = ccnt.CntNotifyCountUp(dev_id, comp_ch_no, comp_reg_no, stop_comp_value, 0)
                if lret != ccnt.CNT_ERR_SUCCESS:
                    ccnt.CntGetErrorString(lret, get_str)
                    err_str = 'CntNotifyCountUp ret = ' + str(lret) + ': ' + str(get_str.value.decode('sjis'))
                    continue
                #----------------------------------------
                # カウントマッチコールバック設定
                #----------------------------------------
                lret = ccnt.CntCountUpCallbackProc(dev_id, pcount_callback, "Match Count")
                if lret != ccnt.CNT_ERR_SUCCESS:
                    ccnt.CntGetErrorString(lret, get_str)
                    err_str = 'CntCountUpCallbackProc ret = ' + str(lret) + ': ' + str(get_str.value.decode('sjis'))
                    continue
            #----------------------------------------
            # 停止個数設定
            #----------------------------------------
            if stop == ccnt.CNTS_STOP_NUM:
                lret = ccnt.CntSetSamplingStopNumber(dev_id, stop_num)
                if lret != ccnt.CNT_ERR_SUCCESS:
                    ccnt.CntGetErrorString(lret, get_str)
                    err_str = 'CntSetSamplingStopNumber ret = ' + str(lret) + ': ' + str(get_str.value.decode('sjis'))
                    continue
            #----------------------------------------
            # 設定画面終了
            #----------------------------------------
            TermLib.TermSetWindowClose()
            return 0, err_str
        #----------------------------------------
        # Cancel処理
        #----------------------------------------
        elif menu_num == SET_MENU_CANCEL:
            #----------------------------------------
            # 設定画面終了
            #----------------------------------------
            TermLib.TermSetWindowClose()
            return 0, err_str
    return 0, err_str


#================================================================
# メイン関数
#================================================================
def main():
    cnt_id = ctypes.c_short()
    count = ctypes.c_ulong()
    carry = ctypes.c_ulong()
    status = ctypes.c_ulong()
    err = ctypes.c_ulong()
    notification = ctypes.c_long()
    get_str = ctypes.create_string_buffer(256)
    ch_no_type = ctypes.c_short * CHANNEL_NUM
    ch_no = ch_no_type()
    menu_num = -1
    dev_name = ''
    err_str = ''
    
    #----------------------------------------
    # TermLib初期化
    #----------------------------------------
    lret = TermLib.TermInit(main_scr)
    if lret != TermLib.TERM_ERR_SUCCESS:
        print('TermInit RetCode = {}'.format(lret))
        sys.exit()
    #----------------------------------------
    # メニュー処理
    #----------------------------------------
    while True:
        lret, menu_num = TermLib.TermGetMenuNum('Please input a menu number(0-8)', menu_num)
        if lret != TermLib.TERM_ERR_SUCCESS:
            print('RetCode = {}'.format(lret))
            break
        #----------------------------------------
        # 初期化処理
        #----------------------------------------
        if menu_num == MENU_CNT_OPEN:
            lret, dev_name = TermLib.TermGetStr('Please input a device name.', dev_name)
            if lret != TermLib.TERM_ERR_SUCCESS:
                print('TermGetMenuNum RetCode = {}'.format(lret))
                break
            lret = ccnt.CntInit(dev_name.encode(), ctypes.byref(cnt_id))
            ccnt.CntGetErrorString(lret, get_str)
            buf = str.format('CntInit {}:{}', lret, get_str.value.decode('sjis'))
            TermLib.TermSetStatus(TermLib.STATUS_AREA_BOTTOM, STS_RET_POS, buf)
        #----------------------------------------
        # カウンターモードの設定
        #----------------------------------------
        if menu_num == MENU_COUNTER_MODE:
            lret, err_str = counter_mode(cnt_id, err_str)
            if  lret == 1:
                TermLib.TermSetStatus(TermLib.STATUS_AREA_BOTTOM, STS_RET_POS, err_str)
        #----------------------------------------
        # 設定
        #----------------------------------------
        elif menu_num == MENU_CONDITION:
            lret, err_str = condition(cnt_id, err_str)
            if  lret == 1:
                TermLib.TermSetStatus(TermLib.STATUS_AREA_BOTTOM, STS_RET_POS, err_str)
        #----------------------------------------
        # 転送スタート
        #----------------------------------------
        elif menu_num == MENU_START:
            #----------------------------------------
            # メッセージ通知設定
            #----------------------------------------
            lret = ccnt.CntNotifySamplingStop(cnt_id, 0)
            if lret != ccnt.CNT_ERR_SUCCESS:
                ccnt.CntGetErrorString(lret, get_str)
                buf = str.format('CntNotifySamplingStop ret = {}:{}', lret, get_str.value.decode('sjis'))
                TermLib.TermSetStatus(TermLib.STATUS_AREA_BOTTOM, STS_RET_POS, buf)
                continue
            lret = ccnt.CntSamplingStopCallbackProc(cnt_id, psampling_stop_callback, "sampling stop call back!")
            if lret != ccnt.CNT_ERR_SUCCESS:
                ccnt.CntGetErrorString(lret, get_str)
                buf = str.format('CntSamplingStopCallbackProc ret = {}:{}', lret, get_str.value.decode('sjis'))
                TermLib.TermSetStatus(TermLib.STATUS_AREA_BOTTOM, STS_RET_POS, buf)
                continue
            notification_temp = set_scr['input_num'][SET_NUM_NOTIF]['set_num']
            notification.value = notification_temp
            lret = ccnt.CntNotifySamplingCount(cnt_id, notification, 0)
            if lret != ccnt.CNT_ERR_SUCCESS:
                ccnt.CntGetErrorString(lret, get_str)
                buf = str.format('CntNotifySamplingCount ret = {}:{}', lret, get_str.value.decode('sjis'))
                TermLib.TermSetStatus(TermLib.STATUS_AREA_BOTTOM, STS_RET_POS, buf)
                continue
            lret = ccnt.CntSamplingCountCallbackProc(cnt_id, psampling_count_callback, "sampling count call back!")
            if lret != ccnt.CNT_ERR_SUCCESS:
                ccnt.CntGetErrorString(lret, get_str)
                buf = str.format('CntSamplingCountCallbackProc ret = {}:{}', lret, get_str.value.decode('sjis'))
                TermLib.TermSetStatus(TermLib.STATUS_AREA_BOTTOM, STS_RET_POS, buf)
                continue
            #----------------------------------------
            # FIFOのリセット(入力)
            #----------------------------------------
            lret = ccnt.CntSamplingFifoReset(cnt_id)
            if lret != ccnt.CNT_ERR_SUCCESS:
                ccnt.CntGetErrorString(lret, get_str)
                buf = str.format('CntSamplingFifoReset ret = {}:{}', lret, get_str.value.decode('sjis'))
                TermLib.TermSetStatus(TermLib.STATUS_AREA_BOTTOM, STS_RET_POS, buf)
                continue
            #----------------------------------------
            # データバッファを設定
            #----------------------------------------
            lret = ccnt.CntSamplingSetBuffer(cnt_id, sampling_data, CHANNEL_NUM, DATA_NUM, ccnt.CNTS_WRITE_RING)
            if lret != ccnt.CNT_ERR_SUCCESS:
                ccnt.CntGetErrorString(lret, get_str)
                buf = str.format('CntSamplingSetBuffer ret = {}:{}', lret, get_str.value.decode('sjis'))
                TermLib.TermSetStatus(TermLib.STATUS_AREA_BOTTOM, STS_RET_POS, buf)
                continue
            #----------------------------------------
            # パラメータのセット
            #----------------------------------------
            for i in range(0, CHANNEL_NUM):
                ch_no[i] = i
            #----------------------------------------
            # カウント開始処理
            #----------------------------------------
            lret = ccnt.CntStartCount(cnt_id, ch_no, CHANNEL_NUM)
            if lret != ccnt.CNT_ERR_SUCCESS:
                ccnt.CntGetErrorString(lret, get_str)
                buf = str.format('CntStartCount ret = {}:{}', lret, get_str.value.decode('sjis'))
                TermLib.TermSetStatus(TermLib.STATUS_AREA_BOTTOM, STS_RET_POS, buf)
                continue
            #----------------------------------------
            # カウント初期化
            #----------------------------------------
            global read_index, write_index, pre_count, pre_carry
            read_index.value = 0       # リードポインタ
            write_index.value = 0      # ライトポインタ
            pre_count.value = 0        # 前回カウント値
            pre_carry.value = 0        # 前回キャリー値
            #----------------------------------------
            # 転送スタート
            #----------------------------------------
            lret = ccnt.CntSamplingStart(cnt_id)
            if lret != ccnt.CNT_ERR_SUCCESS:
                ccnt.CntGetErrorString(lret, get_str)
                buf = str.format('CntSamplingStart ret = {}:{}', lret, get_str.value.decode('sjis'))
                TermLib.TermSetStatus(TermLib.STATUS_AREA_BOTTOM, STS_RET_POS, buf)
                continue
        #----------------------------------------
        # 転送ストップ
        #----------------------------------------
        elif menu_num == MENU_STOP:
            lret = ccnt.CntSamplingStop(cnt_id)
            ccnt.CntGetErrorString(lret, get_str)
            buf = str.format('CntSamplingStop {}:{}', lret, get_str.value.decode('sjis'))
            TermLib.TermSetStatus(TermLib.STATUS_AREA_BOTTOM, STS_RET_POS, buf)
        #----------------------------------------
        # 転送カウント取得
        #----------------------------------------
        elif menu_num == MENU_COUNT:
            lret = ccnt.CntGetSamplingCount(cnt_id, ctypes.byref(count), ctypes.byref(carry))
            ccnt.CntGetErrorString(lret, get_str)
            buf = str.format('CntGetSamplingCount {}:{}', lret, get_str.value.decode('sjis'))
            TermLib.TermSetStatus(TermLib.STATUS_AREA_BOTTOM, STS_COUNT_POS, buf)
            if lret == ccnt.CNT_ERR_SUCCESS:
                buf = str.format('{}', count.value)
                TermLib.TermSetStatus(TermLib.STATUS_AREA_BOTTOM, STS_COUNT_POS, buf)
        #----------------------------------------
        # ステータス取得
        #----------------------------------------
        elif menu_num == MENU_STATUS:
            lret = ccnt.CntGetSamplingStatus(cnt_id, ctypes.byref(status), ctypes.byref(err))
            ccnt.CntGetErrorString(lret, get_str)
            buf = str.format('CntGetSamplingStatus {}:{}', lret, get_str.value.decode('sjis'))
            TermLib.TermSetStatus(TermLib.STATUS_AREA_BOTTOM, STS_RET_POS, buf)
            if lret == TermLib.TERM_ERR_SUCCESS:
                #----------------------------------------
                # 状態
                #----------------------------------------
                buf = ''
                if status.value & ccnt.CNTS_STATUS_BMSTOP:    buf = 'BmStop,'
                if status.value & ccnt.CNTS_STATUS_CNTSTART:  buf += 'CntStart,'
                if status.value & ccnt.CNTS_STATUS_CNTSTOP:   buf += 'CntStop,'
                if status.value & ccnt.CNTS_STATUS_TRGIN:     buf += 'TrgIn,'
                if status.value & ccnt.CNTS_STATUS_OVERRUN:   buf += 'Overrun'
                TermLib.TermSetStatus(TermLib.STATUS_AREA_BOTTOM, STS_STATUS_POS, buf)
                #----------------------------------------
                # エラー
                #----------------------------------------
                buf = ''
                if err.value & ccnt.CNTS_STATUS_FIFOFULL:     buf += 'FifoFull,'
                if err.value & ccnt.CNTS_STATUS_SGOVERIN:     buf += 'S/GOverIn,'
                if err.value & ccnt.CNTS_STATUS_TRGERR:       buf += 'TrgErr,'
                if err.value & ccnt.CNTS_STATUS_CLKERR:       buf += 'ClkErr,'
                if err.value & ccnt.CNTS_STATUS_SLAVEHALT:    buf += 'SlaveHalt,'
                if err.value & ccnt.CNTS_STATUS_MASTERHALT:   buf += 'MasterHalt'
                TermLib.TermSetStatus(TermLib.STATUS_AREA_BOTTOM, STS_ERROR_POS, buf)
        #----------------------------------------
        # 終了処理
        #----------------------------------------
        elif menu_num == MENU_CNT_CLOSE:
            lret = ccnt.CntExit(cnt_id)
            ccnt.CntGetErrorString(lret, get_str)
            buf = str.format('CntExit {}:{}', lret, get_str.value.decode('sjis'))
            TermLib.TermSetStatus(TermLib.STATUS_AREA_BOTTOM, STS_RET_POS, buf)
        #----------------------------------------
        # サンプル終了
        #----------------------------------------
        elif menu_num == MENU_EXIT:    
            TermLib.TermExit()
            break
    sys.exit()


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