#================================================================
#================================================================
# API-DIO(WDM)
# Trigger Sample
#                                                CONTEC Co., Ltd.
#================================================================
#================================================================

import ctypes
import ctypes.wintypes
import sys
import cdio

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


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


#================================================================
# Call Back Function
#================================================================
def trg_callback(dev_id, wparam, lparam, param):
    #----------------------------------------
    # Process trigger message
    #----------------------------------------
    #----------------------------------------
    # Trigger bit No.
    #----------------------------------------
    BitNo = LOWORD(lparam)
    #----------------------------------------
    # Rising:1, Falling:2
    #----------------------------------------
    Kind = HIWORD(lparam)
    #----------------------------------------
    # Up count
    #----------------------------------------
    if Kind == cdio.DIO_INT_RISE:
        up_down = 'UP'
    #----------------------------------------
    # Down count
    #----------------------------------------
    if Kind == cdio.DIO_INT_FALL:
        up_down = 'DOWN'
    #----------------------------------------
    # Display trigger factor
    #----------------------------------------
    print(f'Trigger:id={dev_id} bit = {BitNo}, logic = {up_down}')

    return


ptrg_callback = cdio.PDIO_TRG_CALLBACK(trg_callback)


#================================================================
# main Function
#================================================================
def main():
    dio_id = ctypes.c_short()
    in_port_num = ctypes.c_short()
    out_port_num = ctypes.c_short()
    err_str = ctypes.create_string_buffer(256)

    #----------------------------------------
    # Initialization
    #----------------------------------------
    dev_name = input('Input device name: ')
    lret = cdio.DioInit(dev_name.encode(), ctypes.byref(dio_id))
    if lret != cdio.DIO_ERR_SUCCESS:
        cdio.DioGetErrorString(lret, err_str)
        print(f"DioInit = {lret}: {err_str.value.decode('sjis')}")
        sys.exit()
    #----------------------------------------
    # Retrieve the number of bits
    #----------------------------------------
    lret = cdio.DioGetMaxPorts(dio_id, ctypes.byref(in_port_num), ctypes.byref(out_port_num))
    if lret != cdio.DIO_ERR_SUCCESS:
        cdio.DioGetErrorString(lret, err_str)
        print(f"DioGetMaxPorts = {lret}: {err_str.value.decode('sjis')}")
        sys.exit()
    max_trg = 8 * in_port_num.value
    if max_trg == 0:
        print(f'Input bit number = 0')
        sys.exit()
    else:
        print(f'Trigger bit = 0 to {max_trg - 1}')
    #----------------------------------------
    # Set trigger call back
    #----------------------------------------
    lret = cdio.DioSetTrgCallBackProc (dio_id, ptrg_callback, 0)
    if lret != cdio.DIO_ERR_SUCCESS:
        cdio.DioGetErrorString(lret, err_str)
        print(f"DioSetTrgCallBackProc = {lret}: {err_str.value.decode('sjis')}")
        sys.exit()
    #----------------------------------------
    # Enable trigger
    #----------------------------------------
    for bit_no in range(max_trg):
        lret = cdio.DioNotifyTrg ( dio_id, bit_no, cdio.DIO_TRG_RISE | cdio.DIO_TRG_FALL, 100, 0)
        if lret != cdio.DIO_ERR_SUCCESS:
            cdio.DioGetErrorString(lret, err_str)
            print(f"DioNotifyTrg = {lret}: {err_str.value.decode('sjis')}")
            sys.exit()
    print("Waiting for trigger...")
    #----------------------------------------
    # Wait input
    #----------------------------------------
    while True:
        print("Input 'q' + 'enter' to quit")
        buf = input()
        #----------------------------------------
        # End
        #----------------------------------------
        if buf == 'q':
            print(f'quit.')
            break
    #----------------------------------------
    # Exit
    #----------------------------------------
    lret = cdio.DioExit(dio_id)
    if lret != cdio.DIO_ERR_SUCCESS:
        cdio.DioGetErrorString(lret, err_str)
        print(f"DioExit = {lret}: {err_str.value.decode('sjis')}")
    #----------------------------------------
    # Terminate application
    #----------------------------------------
    sys.exit()


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