#include "iqi_interference_mode_example.h"
#include "iqi_mst.h"
#include "iqi_interference_mode.h"

int16 interference_mode_example_StartTest(
    uint16 uiPortNo,
    char08* cpErrMsg)
{
    int16 error_resut = ERR_CUSTOM;
    //Interference mode is applied only for PREOPERATE and OPERATE mode
    
    do
    {
        uchar08 recv_buffer[256];
        // try to set operating mode to Inactive (Fallback)
        int16 error_resut_help = mst_SetOperatingMode(uiPortNo, MST_OPERATING_MODE_INACTIVE,
            MST_STATE_INACTIVE, recv_buffer, cpErrMsg);
        if (error_resut_help != ERR_NONE)
        {
            error_resut = error_resut_help;
            break;
        }
        mst_StateT state = (mst_StateT)recv_buffer[0];
        printf("go to inactive: state %d\n", state);

        error_resut_help = mst_DeactivateInvalidMSeq(uiPortNo, cpErrMsg);
        if (error_resut_help != ERR_NONE)
        {
            error_resut = error_resut_help;
            break;
        }

        // try to set operating mode to Auto (permanent seach of IO-Link device)
        error_resut_help = mst_SetOperatingMode(uiPortNo, MST_OPERATING_MODE_AUTO,
            MST_STATE_OPERATE, recv_buffer, cpErrMsg);
        if (error_resut_help != ERR_NONE)
        {
            error_resut = error_resut_help;
            break;
        }
        state = (mst_StateT)recv_buffer[0];
        printf("go to operate: state %d\n", state);

        //activate 
        error_resut_help = mst_ActivateInvalidMSeq(uiPortNo, 1, INTERFERENCE_MODE_WRONG_CRC, cpErrMsg);
        if (error_resut_help != ERR_NONE)
        {
            error_resut = error_resut_help;
            break;
        }

        //wait 10 second
        Sleep(10000);

        //check if comm lost event appeared
        EventQualifierT eventQualifier;
        uchar08 ucEventQualifier;
        uint16 uiEventCode;
        error_resut_help = mst_ReadEvent(uiPortNo, &ucEventQualifier, &uiEventCode, cpErrMsg);
        if (error_resut_help == ERR_NONE)
        {
            //event appeared, what is not expected, but check an error code
            eventQualifier.Byte = ucEventQualifier;
            printf("read event instance %d, source %d, type %d, mode %d and code 0x%04X\n",
                eventQualifier.Fields.Instance, eventQualifier.Fields.Source,
                eventQualifier.Fields.Type, eventQualifier.Fields.Mode, uiEventCode);
            if (uiEventCode == 0xFF22)
            {
                error_resut = ERR_OPERATION;
                break;
            }
        }

        error_resut = ERR_NONE;
    } while (0);
    return error_resut;
}