#================================================================
#================================================================
# API-GPIB(98PC)
# Slave Sample
#                                                CONTEC Co., Ltd.
#================================================================
#================================================================
import ctypes
import sys
import GpibPy
import threading


#================================================================
# Macro definition
#================================================================
MENU_NUM_MAIN = 0                               # Main menu
MENU_NUM_DELIMITER = 1                          # The delimiter of send data
MENU_NUM_SEND_DATA = 2                          # Send data
MENU_NUM_STATUS_BYTE = 3                        # Status byte
MENU_DELIMITER_SET = 1                          # Setting delimiter
MENU_SEND_DATA = 2                              # Send data
MENU_RECEIVE_DATA = 3                           # Receive data
MENU_SRQ_ON = 4                                 # SRQ on
MENU_SRQ_OFF = 5                                # SRQ off
MENU_BACK = 998                                 # Menu back
MENU_END = 999                                  # Menu end

GPIB_DELIMITER_NOT_USE = 0                      # Not use delimiter
GPIB_DELIMITER_CR_LF = 1                        # Use CR+LF delimiter
GPIB_DELIMITER_CR = 2                           # Use CR delimiter
GPIB_DELIMITER_LF = 3                           # Use LF delimiter
TIMERCOUNT = 0.1                                # 0.1s
#================================================================
# External variables
#================================================================
my_addr = ctypes.c_ulong()                      # MyAddress
delim = ctypes.c_ulong()                        # Delimiter
eoi = ctypes.c_ulong()                          # Delimiter
sr_len = ctypes.c_ulong()                       # Length of buffers
cmd_type = ctypes.c_ulong * 32                  # Create cmd type
cmd = cmd_type()                                # Command array
p_stb = ctypes.c_ulong()                        # StatusByte
p_eoi = ctypes.c_ulong()                        # EOI
sr_buffer_type = ctypes.c_ubyte * 10000         # Buffer type
sr_buffer = sr_buffer_type()                    # Buffer of send data or receive data
cs_buf = ""                                     # String of cs_buf
u_timer_event = None                            # Used Timer


#================================================================
# Function that checks if a string can be converted to a number
#================================================================
def isnum(str, base):
    try:
        if 16 == base:
            int(str, 16)
        else:
            int(str)
    except:
        return False
    return True


#================================================================
# Check return value function
#================================================================
def check_ret(function_name, ret_code, err_str):
    #----------------------------------------
    # Normality
    #----------------------------------------
    ret_code_type = 0
    #----------------------------------------
    # 0xFF Masking
    #----------------------------------------
    lret = ret_code & 0xff
    #----------------------------------------
    # Unusual
    #----------------------------------------
    if lret >= 3:
        #----------------------------------------
        # Return of function(Unusual)
        #----------------------------------------
        ret_code_type = 1
        #----------------------------------------
        # 0x03
        #----------------------------------------
        if lret == 3:
            err_str = function_name + " : Data remains in the FIFO."
        #----------------------------------------
        # 0x50
        #----------------------------------------
        elif lret == 80:
            err_str = function_name + " : I/O address error."
        #----------------------------------------
        # 0x52
        #----------------------------------------
        elif lret == 82:
            err_str = function_name + " : Registry setting error. Review resistry setting."
        #----------------------------------------
        # 0x80
        #----------------------------------------
        elif lret == 128:
            err_str = function_name + " : The reception capacity has been exceeded or SRQ has not been received."
        #----------------------------------------
        # 0xC8
        #----------------------------------------
        elif lret == 200:
            err_str = function_name + " : Unable to create thread."
        #----------------------------------------
        # 0xC9
        #----------------------------------------
        elif lret == 201:
            err_str = function_name + " : Another event is running."
        #----------------------------------------
        # 0xD2
        #----------------------------------------
        elif lret == 210:
            err_str = function_name + " : DMA cannot be set."
        #----------------------------------------
        # 0xF0
        #----------------------------------------
        elif lret == 240:
            err_str = function_name + " : [Esc] key was pushed."
        #----------------------------------------
        # 0xF1
        #----------------------------------------
        elif lret == 241:
            err_str = function_name + " : File I/O error."
        #----------------------------------------
        # 0xF2
        #----------------------------------------
        elif lret == 242:
            err_str = function_name + " : The address is specified incorrectly."
        #----------------------------------------
        # 0xF3
        #----------------------------------------
        elif lret == 243:
            err_str = function_name + " : Buffer specification error."
        #----------------------------------------
        # 0xF4
        #----------------------------------------
        elif lret == 244:
            err_str = function_name + " : Array size error."
        #----------------------------------------
        # 0xF5
        #----------------------------------------
        elif lret == 245:
            err_str = function_name + " : The buffer is too small."
        #----------------------------------------
        # 0xF6
        #----------------------------------------
        elif lret == 246:
            err_str = function_name + " : Illegal object name."
        #----------------------------------------
        # 0xF7
        #----------------------------------------
        elif lret == 247:
            err_str = function_name + " : The check next to the device name is invalid."
        #----------------------------------------
        # 0xF8
        #----------------------------------------
        elif lret == 248:
            err_str = function_name + " : Illegal data type."
        #----------------------------------------
        # 0xF9
        #----------------------------------------
        elif lret == 249:
            err_str = function_name + " : No more devices can be added."
        #----------------------------------------
        # 0xFA
        #----------------------------------------
        elif lret == 250:
            err_str = function_name + " : Device name not found."
        #----------------------------------------
        # 0xFB
        #----------------------------------------
        elif lret == 251:
            err_str = function_name + " : Delimiters are different between devices."
        #----------------------------------------
        # 0xFC
        #----------------------------------------
        elif lret == 252:
            err_str = function_name + " : GPIB error."
        #----------------------------------------
        # 0xFD
        #----------------------------------------
        elif lret == 253:
            err_str = function_name + " : Received only the delimiter."
        #----------------------------------------
        # 0xFE
        #----------------------------------------
        elif lret == 254:
            err_str = function_name + " : Timed out."
        #----------------------------------------
        # 0xFF
        #----------------------------------------
        elif lret == 255:
            err_str = function_name + " : Parameter error."
    else:
        err_str = function_name + " : Completed normally."
    #----------------------------------------
    # It was message when [Ifc] [Srq] received
    #----------------------------------------
    #----------------------------------------
    # 0xFF Masking
    #----------------------------------------
    lret = ret_code & 0xff00
    #----------------------------------------
    # [256]decimal
    #----------------------------------------
    if lret == 0x100:
        err_str = function_name + "-[SRQ] was receiving.<STATUS>"
    #----------------------------------------
    # [512]decimal
    #----------------------------------------
    elif lret == 0x200:
        err_str = function_name + "-[IFC] was receiving.<STATUS>"
    #----------------------------------------
    # [768]decimal
    #----------------------------------------
    elif lret == 0x300:
        err_str = function_name + "-[SRQ],[IFC] was receiving.<STATUS>"
    return ret_code_type, err_str


#================================================================
# Initialize Function
#================================================================
def gpib_init():
    time_out = ctypes.c_ulong()
    ifc_time = ctypes.c_ulong()
    lret = ctypes.c_ulong()
    master = ctypes.c_ulong()
    err_str = ''
    global cs_buf

    #----------------------------------------
    # Prevents double initialization
    #----------------------------------------
    lret.value = GpibPy.GpExit()
    #----------------------------------------
    # GP-IB initialize
    #----------------------------------------
    lret.value = GpibPy.GpIni()
    #----------------------------------------
    # Check of GpIni
    #----------------------------------------
    ret, err_str = check_ret("GpIni", lret.value, err_str)
    if lret.value & 0xFF != 0:
        print(err_str)
        return 1
    #----------------------------------------
    # Get Master/Slave mode
    #----------------------------------------
    GpibPy.GpBoardsts(0x0a, ctypes.byref(master))
    if master.value == 0:
        #----------------------------------------
        # Default
        #----------------------------------------
        ifc_time.value = 1
        lret.value = GpibPy.GpIfc(ifc_time)
        #----------------------------------------
        # Check of GpIfc
        #----------------------------------------
        ret, err_str = check_ret("GpIfc", lret.value, err_str)
        if lret.value & 0xFF != 0:
            print(err_str)
            return 1
        #----------------------------------------
        # Check of GpRen
        #----------------------------------------
        lret.value = GpibPy.GpRen()
        ret, err_str = check_ret("GpRen", lret.value, err_str)
        if lret.value & 0xFF != 0:
            print(err_str)
            return 1
    #----------------------------------------
    # Default
    #----------------------------------------
    delim.value = 1
    eoi.value = 1
    lret.value = GpibPy.GpDelim(delim, eoi)
    #----------------------------------------
    # Check of GpDelim
    #----------------------------------------
    ret, err_str = check_ret("GpDelim", lret.value, err_str)
    if lret.value & 0xFF != 0:
        print(err_str)
        return 1
    #----------------------------------------
    # Default(ms)
    #----------------------------------------
    time_out.value = 10000
    lret.value = GpibPy.GpTimeout(time_out)
    #----------------------------------------
    # Check of GpTimeout
    #----------------------------------------
    ret, err_str = check_ret("GpTimeout", lret.value, err_str)
    if lret.value & 0xFF != 0:
        print(err_str)
        return 1
    #----------------------------------------
    # Normality Ended
    #----------------------------------------
    cs_buf = "Initialized."
    return 0


#================================================================
# Exit Function
#================================================================
def gpib_exit():
    master = ctypes.c_ulong()                            # Master/Slave mode flag
    lret = ctypes.c_ulong()                              # Return value
    err_str = ''                                         # Error string
    
    #----------------------------------------
    # Mode check
    #----------------------------------------
    lret.value = GpibPy.GpBoardsts(0x0a, ctypes.byref(master))
    if lret.value == 80:
        #----------------------------------------
        # If found error then not doing
        #----------------------------------------
        return
    #----------------------------------------
    # When mode is Master
    #----------------------------------------
    if master.value == 0:
        #----------------------------------------
        # Command count
        #----------------------------------------
        cmd[0] = 2
        #----------------------------------------
        # Unlisten / UNL
        #----------------------------------------
        cmd[1] = 0x3f
        #----------------------------------------
        # UnTalken / UNT
        #----------------------------------------
        cmd[2] = 0x5f
        #----------------------------------------
        # Send command
        #----------------------------------------
        lret.value = GpibPy.GpComand(cmd)
        ret, err_str = check_ret("GpComand", lret.value, err_str)
        #----------------------------------------
        # Cancel remote
        #----------------------------------------
        lret.value = GpibPy.GpResetren()
    lret.value = GpibPy.GpExit()


#================================================================
# Process the input data from keyboard
#================================================================
def input_data(MenuNum):
    input_str = input()
    return input_str


#================================================================
# Timer Function
#================================================================
def on_timer():
    lret = ctypes.c_ulong()                               # Return value
    err_str = ''                                          # Error string
    global u_timer_event                                  # Used Timer
    
    lret.value = GpibPy.GpChkstb(ctypes.byref(p_stb), ctypes.byref(p_eoi))
    ret, err_str = check_ret("StatusByte", lret.value, err_str)
    #----------------------------------------
    # 0x40 mask
    #----------------------------------------
    if (p_stb.value & 0x40) != 0x40:
        print("[SRQ] was received by master.")
        #----------------------------------------
        # Kill timer
        #----------------------------------------
        u_timer_event.cancel()
        u_timer_event = None
        return
    #----------------------------------------
    # Start timer
    #----------------------------------------
    u_timer_event = threading.Timer(TIMERCOUNT, on_timer)
    u_timer_event.start()


#================================================================
# Function that menu is displayed
#================================================================
def menu(MenuNum):
    #----------------------------------------
    # Initialize the menu
    #----------------------------------------
    MenuDat = [
        #----------------------------------------
        # Main Menu Data
        #----------------------------------------
        {
            #----------------------------------------
            # Use line..1   Not use..0
            #----------------------------------------
            'Line':1,
            #----------------------------------------
            # Title
            #----------------------------------------
            'StrMenu':'Menu',
            #----------------------------------------
            # Number of items
            #----------------------------------------
            'ItemCount':6,
            #----------------------------------------
            # Item    #Menu item     #Macro that correspond with the menu
            #----------------------------------------
            'Item':[{'Str':'(1).Set delimiter', 'Num':MENU_DELIMITER_SET},
                    {'Str':'(2).Send data', 'Num':MENU_SEND_DATA},
                    {'Str':'(3).Receive data', 'Num':MENU_RECEIVE_DATA},
                    {'Str':'(4).SRQ send', 'Num':MENU_SRQ_ON},
                    {'Str':'(5).SRQ stop', 'Num':MENU_SRQ_OFF},
                    {'Str':'(q).Exit', 'Num':MENU_END}],
            #----------------------------------------
            # Question
            #----------------------------------------
            'Question':'Please select the executing command.',
            #----------------------------------------
            # Prompt
            #----------------------------------------
            'Prompt':'(1-5 or q):',
        },
        #----------------------------------------
        # delimiter Setting--1 Menu Data
        #----------------------------------------
        {
            'Line':1,
            'StrMenu':'Set delimiter of send data',
            'ItemCount':5,
            'Item':[{'Str':'(1).Not Use', 'Num':GPIB_DELIMITER_NOT_USE},
                    {'Str':'(2).CR+LF', 'Num':GPIB_DELIMITER_CR_LF},
                    {'Str':'(3).CR', 'Num':GPIB_DELIMITER_CR},
                    {'Str':'(4).LF', 'Num':GPIB_DELIMITER_LF},
                    {'Str':'(5).Back', 'Num':MENU_BACK}],
            'Question':'Please input the setting number.',
            'Prompt':'',
        },
        #----------------------------------------
        # Send Data--2 Menu Data
        #----------------------------------------
        {
            'Line':0,
            'StrMenu':'',
            'ItemCount':0,
            'Item':[],
            'Question':'Please input the send data',
            'Prompt':'',
        },
        #----------------------------------------
        # Status byte--3 Menu Data
        #----------------------------------------
        {
            'Line':0,
            'StrMenu':'',
            'ItemCount':0,
            'Item':[],
            'Question':'Please input status byte(0x40-0xFF).',
            'Prompt':'',
        }]

    #----------------------------------------
    # Display the Menu and acquisition of input data
    #----------------------------------------
    while True:
        if MenuDat[MenuNum]['Line'] != 0:
            print("\n===================================")
            print(f"{MenuDat[MenuNum]['StrMenu']}")
            print("===================================")
            print("-----------------------------------")
            for i in range(0, (MenuDat[MenuNum]['ItemCount'])):
                #----------------------------------------
                # Display Item
                #----------------------------------------
                print(f"{MenuDat[MenuNum]['Item'][i]['Str']}")
            print("-----------------------------------\n")
            print(f"{MenuDat[MenuNum]['Question']}")    
            print(f"{MenuDat[MenuNum]['Prompt']}", end='')
        else:
            print(f"{MenuDat[MenuNum]['Question']}")
            print(f"{MenuDat[MenuNum]['Prompt']}", end='')
        #----------------------------------------
        # Get the input data
        #----------------------------------------
        input_str = input_data(MenuNum)
        #----------------------------------------
        # Check the input data
        #----------------------------------------
        #----------------------------------------
        # The end macro is returned if the item of end is selected
        #----------------------------------------
        if MenuNum == MENU_NUM_MAIN:
            if input_str == 'q' or input_str == 'Q':
                return MENU_END
        #----------------------------------------
        # The input data is returned if the menu item is 0
        #----------------------------------------
        if MenuDat[MenuNum]['ItemCount'] == 0:
            if MenuNum == MENU_NUM_SEND_DATA:
                return input_str
            elif MenuNum == MENU_NUM_STATUS_BYTE:
                if isnum(input_str, 16):
                    return int(input_str, 16)
                else:
                    continue
            else:
                if isnum(input_str, 10):
                    return int(input_str)
                else:
                    continue
        #----------------------------------------
        # Check whether the input data is a number 
        #----------------------------------------
        if isnum(input_str, 10) == False:
            continue
        #----------------------------------------
        # Check whether the input data is outside of the number of items
        #----------------------------------------
        if 0 < int(input_str) and int(input_str) <= MenuDat[MenuNum]['ItemCount']:
            if MenuDat[MenuNum]['Item'][int(input_str) - 1]['Num'] == MENU_END:
                print("\nThe used range is outside.\nPlease input once again.")
                continue
            return MenuDat[MenuNum]['Item'][int(input_str) - 1]['Num']
        print("\nThe used range is outside.\nPlease input once again.")


#================================================================
# Main function
#================================================================
def main():
    master = ctypes.c_ulong()                       # Master(0) or Slave(1)
    input_data = ctypes.c_short()                   # Return value of menu function
    send_data = sr_buffer_type()                    # Send data
    lret = ctypes.c_ulong()                         # Return value
    status_byte = ctypes.c_ulong()                  # Status
    global u_timer_event                            # Used Timer
    err_str = ''                                    # Error string

    print("<<< Slave Sample Program >>>")
    #----------------------------------------
    # [gpib_init] Function
    #----------------------------------------
    gpib_init()
    #----------------------------------------
    # Get MyAddress
    #----------------------------------------
    GpibPy.GpBoardsts(0x08, ctypes.byref(my_addr))
    #----------------------------------------
    # Check if it is a slave
    #----------------------------------------
    GpibPy.GpBoardsts(0x0a, ctypes.byref(master))
    if master.value == 0:
        print("This device is not Slave.")
        gpib_exit()
        sys.exit()
    else:
        print(cs_buf)
        print(f"My address: {my_addr.value}")
    while True:
        input_data.value = menu( MENU_NUM_MAIN)
        if input_data.value == MENU_END:
            gpib_exit()
            break
        #----------------------------------------
        # Set delimiter
        #----------------------------------------
        if input_data.value == MENU_DELIMITER_SET:    
            #----------------------------------------
            # Set the delimiter
            #----------------------------------------
            EOI = 1
            input_data.value = menu( MENU_NUM_DELIMITER)
            if input_data.value == MENU_BACK:
                continue
            delim.value = input_data.value
            #----------------------------------------
            # Check of [GpDelim]
            #----------------------------------------
            lret.value = GpibPy.GpDelim(EOI, delim)
            ret, err_str = check_ret("GpDelim", (lret.value & 0xFF), err_str)
            print(err_str)
        #----------------------------------------
        # Send data
        #----------------------------------------
        elif input_data.value == MENU_SEND_DATA:
            input_str = menu( MENU_NUM_SEND_DATA)
            sr_len.value = len(input_str)
            ctypes.memmove(send_data, input_str.encode('UTF-8'), sr_len.value)
            if len != 0x0:
                print("Data sending...")
                #----------------------------------------
                # Talker + Listener
                #----------------------------------------
                cmd[0] = 0
                #----------------------------------------
                # Send Data
                #----------------------------------------
                lret.value = GpibPy.GpTalk(cmd, sr_len, send_data)
                #----------------------------------------
                # Check of [GpTalk]
                #----------------------------------------
                ret, err_str = check_ret("GpTalk", (lret.value & 0xFF), err_str)
                print(err_str)
            else:
                print("There is no data.")
        #----------------------------------------
        # Receive data
        #----------------------------------------
        elif input_data.value == MENU_RECEIVE_DATA:
            print("Receiving...")
            #----------------------------------------
            # Talker + Listener
            #----------------------------------------
            cmd[0] = 0
            #----------------------------------------
            # Measure the length of sr_buffer
            #----------------------------------------
            sr_len.value = len(sr_buffer)
            #----------------------------------------
            # Receive Data
            #----------------------------------------
            lret.value = GpibPy.GpListen(cmd, ctypes.byref(sr_len), sr_buffer)
            #----------------------------------------
            # Check of [GpListen]
            #----------------------------------------
            ret, err_str = check_ret("GpListen", (lret.value & 0xFF), err_str)
            if ret == 0:
                #----------------------------------------
                # Add NULL to the end of the received data
                #----------------------------------------
                sr_buffer[sr_len.value] = 0x0
                print(f"{sr_len.value} Bytes Received.")
                #----------------------------------------
                # Show sr_buffer
                #----------------------------------------
                recv_buffer = str(sr_buffer, 'UTF-8').rstrip('\x00')
                print(f"Receive data: {recv_buffer}")
            else:
                print(err_str)
        #----------------------------------------
        # SRQ on
        #----------------------------------------
        elif input_data.value == MENU_SRQ_ON:
            while True:
                status_byte.value = menu(MENU_NUM_STATUS_BYTE)
                if 0x40 <= status_byte.value and status_byte.value <= 0xFF:
                    break
                else:
                    print("The used range is outside, pelase input once again")
            #----------------------------------------
            # Parelell mode set
            #----------------------------------------
            lret.value = GpibPy.GpPpollmode(2)
            #----------------------------------------
            # Error check
            #----------------------------------------
            ret, err_str = check_ret("GpPollmode", lret.value, err_str)
            #----------------------------------------
            # SRQ mode set
            #----------------------------------------
            lret.value = GpibPy.GpSrqEx(status_byte, 1, 1)
            #----------------------------------------
            # Error check
            #----------------------------------------
            ret, err_str = check_ret("GpSrqEx", lret.value, err_str)
            #----------------------------------------
            # TimerEvent
            #----------------------------------------
            u_timer_event = threading.Timer(TIMERCOUNT, on_timer)
            if u_timer_event == None:
                print("Failed to create timer.")
            else:
                print("Waitting for polling by Master...")
                u_timer_event.start()
        #----------------------------------------
        # SRQ off
        #----------------------------------------
        elif input_data.value == MENU_SRQ_OFF:
            if u_timer_event == None:
                print("Send to SRQ stopped.")
                continue
            u_timer_event.cancel()
            u_timer_event = None
            print("Send to SRQ stopped.")
    sys.exit()


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