#include "iqi_mst_example.h"
#include "iqi_mst.h"

int16 mst_example_SetOperateUsbAuto(uchar08* p_connected_port, char08* cpErrMsg)
{
    int16 error_resut = ERR_CUSTOM;

    do
    {
		uchar08 ucPortNoStart = 1;
		uchar08 ucPortNoFinish = 0xFF;

		// Search iqInterface between comport numbers ucPortNoStart and ucPortNoFinish
		// and try to connect it as IO-Link master.
		int16 error_resut_helper = mst_Connect(ucPortNoStart, ucPortNoFinish, cpErrMsg);
		if (error_resut_helper < ERR_NONE)
		{
			error_resut = error_resut_helper;
			break;
		}
		else
		{
			*p_connected_port = (uchar08)error_resut_helper;
		}
		printf("iqInterface Master found on comport %d\n", *p_connected_port);

		//disable cached and fast processing mode
		mst_SwitchISDUCachedMode(*p_connected_port, 0, cpErrMsg); //disable cached mode

		// try to set operating mode to Operate
		uchar08 ucState;
		error_resut = mst_SetOperatingMode(
			*p_connected_port, 
			MST_OPERATING_MODE_OPERATE,
			MST_STATE_OPERATE, 
			&ucState, 
			cpErrMsg);
		if (*p_connected_port < ERR_NONE)
		{
			break;
		}
		mst_StateT state = (mst_StateT)ucState;
		printf("go to operate: state %d\n", state);

		//read vendor name
		uint16 uiISDUErr = 0;
		uchar08 buffer[256] = { 0 };
		mst_ReadOD(*p_connected_port, 0x0010, 0x00, buffer, MAX_OD_BUF_LEN, &uiISDUErr, cpErrMsg);
		printf("Vendor name: %s\n", buffer);

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