//=====================================================================================================
//                                      M400, M100 2-wire                                                   
//=====================================================================================================
//                                                                                                     
//! file                                                                                      
//!                                                                                                    
//! brief      str file                                                                                       
//!                                                                                                    
//!                                                                                                    
//! (c) Copyright 2004-2016 Mettler-Toledo All Rights Reserved                                         
//! author                                                                          
//                                                                                                     
// $Date: 
// $State: Exp $:
// $Revision: 
//
//=============================================================================

#define SENSOR_CHANNEL_DIGITAL (sensorChannel == 1)
#define SENSOR_CHANNEL_ANALOG  (sensorChannel == 0)

#define SENSOR_PH ((sensortype_without_auto == 0) || (sensortype_without_auto == 14) )
#define SENSOR_PH_ALL ((sensortype_without_auto == 0) || (sensortype_without_auto == 14) )
#define SENSOR_O2 ((sensortype_without_auto == 1) || (sensortype_without_auto == 2) || (sensortype_without_auto == 3))
#define SENSOR_ODO (sensortype_without_auto == 12)
#define SENSOR_COND ((sensortype_without_auto == 5) || (sensortype_without_auto == 7) || (sensortype_without_auto == 8))
#define SENSOR_Cond ((sensortype_without_auto == 5) || (sensortype_without_auto == 7) || (sensortype_without_auto == 8))
#define SENSOR_CO2 (sensortype_without_auto == 16)
#define SENSOR_INPRO5000I (sensortype_without_auto == 16)
#define SENSOR_INPRO5500I (sensortype_without_auto == 17)
#define SENSOR_TDL (sensortype_without_auto == 21)
#define SENSOR_TOC (sensortype_without_auto == 4)
#define SENSOR_OZONE (sensortype_without_auto == 13)


#define SENSOR_ING_RS485 (sensortype_without_auto == 12)

#define SENSOR_PH_ORP (sensortype_without_auto == 0)
#define SENSOR_ISM_PNA (sensortype_without_auto == 14)

#define cal_error(command_num, rsp_code)        {display_response_status(command_num, rsp_code);process_abort();}


#define DEFAULT_SENSORTYPE      0

#if 1
#define IS_ONLINE_MODE  		(HART_Online_Actived == 1)
#define IS_OFFLINE_MODE  		(HART_Online_Actived == 0)
#else
//for debug using only,special testing
#define IS_ONLINE_MODE  		(HART_Online_Actived == 0)
#define IS_OFFLINE_MODE  		(HART_Online_Actived == 1)
#endif

#define CAL_VALUE_UPDATE_NUM     5
#define CAL_VALUE_TIME           2
#define DRAFT_AUTO_TIME          5
#define TIMER_5_MIN             330     // [s]
#define TIMER_10_MIN             600     // [s]
#define TIMER_60_MIN             3600     // [s]

//device_specific_status_5

#if 1
//#define ISM_SENSOR_CONNECTED    ((ISM_Connected_Status == 1)&&((device_specific_status_5&0x01) == 0))
#define ISM_SENSOR_CONNECTED    ((ISM_Connected_Status== 1))

#else		
//for debug using only,special testing
#define ISM_SENSOR_CONNECTED    (ISM_Connected_Status == 0)
#endif

#define RES_SUCCESS 									0
#define RES_INVALID_SELECTION 				2
#define RES_PARAM_TOO_LARGE 					3
#define RES_PARAM_TOO_SMALL 					4
#define RES_TOO_FEW_DATA 							5
#define RES_DEVICE_SPEC_CMD_ERROR			6
#define RES_IN_WRITE_PROTECT 					7
#define RES_ACCESS_RESTRICTED				 16
#define RES_DEVICE_BUSY							 32
#define RES_CMD_NOT_IMPL						 64

#define DEF_COMMON_CMD_SETTING(NUMBER_OF_RETRIES) \
                SET_NUMBER_OF_RETRIES(NUMBER_OF_RETRIES); \
                RETRY_ON_NO_DEVICE(); \
                IGNORE_ALL_RESPONSE_CODES(); \
                IGNORE_ALL_DEVICE_STATUS(); \
                XMTR_IGNORE_ALL_RESPONSE_CODES(); \
                XMTR_IGNORE_ALL_DEVICE_STATUS();

#define SEND_CMD_AND_CHECK_STATUS(CMD_NUM) send(CMD_NUM, status); \
		if(status[STATUS_RESPONSE_CODE] != RES_SUCCESS) \
		{ if((status[STATUS_RESPONSE_CODE] == RES_INVALID_SELECTION) \
			|| (status[STATUS_RESPONSE_CODE] == RES_PARAM_TOO_LARGE) \
			|| (status[STATUS_RESPONSE_CODE] == RES_PARAM_TOO_SMALL) \
			|| (status[STATUS_RESPONSE_CODE] == RES_TOO_FEW_DATA) \
			|| (status[STATUS_RESPONSE_CODE] == RES_DEVICE_SPEC_CMD_ERROR) \
			|| (status[STATUS_RESPONSE_CODE] == RES_IN_WRITE_PROTECT) \
			|| (status[STATUS_RESPONSE_CODE] == RES_ACCESS_RESTRICTED)) \
			{ display_response_status(CMD_NUM, status[STATUS_RESPONSE_CODE]);}}


// ISM_Func1_Flags
#define ISM_FUNC_CIP     		(1<<0)
#define ISM_FUNC_SIP			(1<<1)
#define ISM_FUNC_AUTOCLAVE		(1<<2)
#define ISM_FUNC_TTM			(1<<3)
#define ISM_FUNC_ACT			(1<<4)
#define ISM_FUNC_DLI			(1<<5)
#define ISM_FUNC_CIP_RESET		(1<<6)
#define ISM_FUNC_SIP_RESET		(1<<7)
#define ISM_FUNC_AUTOCLAVE_RESET	(1<<8)
#define ISM_FUNC_TTM_RESET		(1<<9)
#define ISM_FUNC_Electrolyte	(1<<10)
#define ISM_FUNC_DLI_RESET		(1<<11)
#define ISM_FUNC_PH_STRESS		(1<<12)
#define ISM_FUNC_OPERATION_DAY	(1<<13)
#define ISM_FUNC_MAX_TEMP		(1<<14)
#define ISM_FUNC_MAX_TEMP_DATE	(1<<15)
#define ISM_FUNC_SAN			(1<<16)
#define ISM_FUNC_UNICOND		(1<<17)
#define ISM_FUNC_DLI_Leaning    (1<<18)
#define ISM_FUNC_Rg_Rr          (1<<19)
#define ISM_FUNC_Rg_RgpNa       (1<<20)
#define ISM_FUNC_Tspot          (1<<21)
#define ISM_FUNC_ORP            (1<<22)
#define ISM_2_0_FUNC            (1<<23)    //TempCal, CIP/SIP Duration, ISM mode, ect

#define MT_MEAS_UNITS \
    { 170,      [mg_l],             [mg_l_help] },                  \
    { 171,      "Ohm*cm",           "Ohm*cm" },               		\
    { 172,      "KOhm*cm",           "KOhm*cm" },               	\
    { 173,      [mega_ohmCm],       [mega_ohm_centimeter_help] },   \
    { 174,      [hPa],              [hPa_help] },                   \
    { 240,      "   ",              "value for none unit" },                \
    { 241,      [mega_ohm],         [mega_ohm_help] },              \
    { 242,      [ppth],             [ppth_help] },                  \
    { 243,      "nA",               "nano ampere helps" },          \
    { 246,      "mS/m",             "mS/m" },          				\
    { 247,      "uS/m",             "uS/m" },          				\
    { 248,      "mV/pH",            "mV/pH" },          				\
    ALL_UNITS  


#define  MT_UNITS_CHANNEL  \
    IF(SENSOR_COND)\
    {\
		{25, "mS/cm"},\
		{26, "uS/cm"},\
		{54, "mS/m"},\
		{55, "uS/m"},\
		{27, "MOhm*cm"},\
		{28, "KOhm*cm"},\
		{29, "Ohm*cm"},\
		{30, "TDS NaCl(ppm)"},\
		{31, "TDS NaCl(ppb)"},\
		{32, "TDS NaCl(ppk)"},\
		{33, "TDS CaCO3(ppm)"},\
		{34, "TDS CaCO3(ppb)"},\
		{35, "TDS CaCO3(ppk)"},\
		{24, "%Conc"},\
		{36, "%NaOH"},\
		{37, "%NaCl"},\
		{38, "%H2SO4"},\
		{39, "%H3PO4"},\
		{40, "%HNO3"},\
		{41, "%HCl"}\
    }\
    ELSE\
    {\
        IF(SENSOR_PH)\
        {\
			{6, "pH"},\
			{7, "pH mV"},\
			{8, "ORP"},\
			{9, "Rg"}\
		}\
        IF(sensortype_without_auto == 0)\
        {\
            {11, "Rr"}\
        }\
        IF(sensortype_without_auto == 14)\
        {\
            {10, "RpNa"}\
        }\
        IF(SENSOR_O2||SENSOR_ODO)\
        {\
			{17, "%air"},\
			{12, "mg/L"},\
			{13, "ug/L"},\
			{14, "ppm"},\
			{15, "ppb"},\
		    {16, "%O2"},\
			{18, "%O2G"},\
			{19, "ppmO2G"},\
			{21, "ProcPress"}\
        }\
        IF(SENSOR_ODO)\
        {\
            {22, "tooCap"}\
        }\
        IF(SENSOR_O2)\
        {\
            {20, "nA"}\
        }\
        IF(SENSOR_CO2)\
        {\
            {48, "%CO2"},\
            {49, "mg/L"},\
            {50, "mV"}\
        }\
        IF(SENSOR_O2||SENSOR_ODO||SENSOR_CO2)\
        {\
            {100, "hPa"},\
            {101, "mbar"},\
            {102, "mmHg"}\
        }\
        {3, "DLI"},\
        {5, "ACT"}\
        IF(SENSOR_CHANNEL_DIGITAL && !SENSOR_PH_ORP)\
        {\
            {4, "TTM"}\
        }\
    }\
    {0, "DegC"},\
    {1, "DegF"},\
    {2, "None"}

#define  DEF_RESOLUTION(var)\
    SELECT(var)\
	{	CASE 0: ".0f";CASE 1: ".1f";CASE 2: ".2f";CASE 3: ".3f";CASE 4: ".4f";CASE 5: ".5f";DEFAULT:".4f";}

#define _CAL_SEND_CMD_AND_CHECK_STATUS(CMD_NUM) \
    send(CMD_NUM, status);                  \
    if (status[STATUS_RESPONSE_CODE])       \
	{                                       \
		display_response_status(CMD_NUM, status[STATUS_RESPONSE_CODE]);\
        process_abort();                    \
	}

#define _CAL_159_CMD_AND_CHECK_STATUS(CMD_NUM) \
    send(CMD_NUM, status);                  \
    if (status[STATUS_RESPONSE_CODE])       \
	{                                       \
		display_response_status(CMD_NUM, status[STATUS_RESPONSE_CODE]);\
        process_abort();                    \
	}										\
	if(DeviceCalStatus > 0)					\
	{										\
		process_abort();					\
	}								
	
#define _CAL_CHECK_ERROR(CMD_NUM)               \
    if (status[STATUS_RESPONSE_CODE])       \
	{                                       \
		display_response_status(CMD_NUM, status[STATUS_RESPONSE_CODE]);\
        process_abort();                    \
	} 

#define _CAL_CHECK_DEVICE_CAL_STATUS		\
	if(DeviceCalStatus > 0)					\
	{										\
        ACKNOWLEDGE("ERROR:Calibration failure");	\
	    process_abort();			        		\
	}							
  
	
//Calibration Define

//Calc proposed Calibration Values	
#define _CAL_CALIBRATE()                                        \
    _CAL_SEND_CMD_AND_CHECK_STATUS(160);                         \
    if(calculationStatus == 1)                                  \
    {                                                           \
		ACKNOWLEDGE("ERROR:Calibration Failure");               \
		process_abort();			                            \
	}                                                           \
    else                                                        \
    {                                                           \
       while(calculationStatus == 2)                        \
       {													\
           DELAY(3, "Reading calibration data,please wait...");\
           _CAL_SEND_CMD_AND_CHECK_STATUS(160);               \
    		if(calculationStatus == 1)                        \
    		{                                                 \
    			ACKNOWLEDGE("ERROR:Calibration Failure");     \
    			process_abort();			                  \
    		}                                                 \
       }                                                      \
       if(calculationStatus == 3)                             \
       {                                                      \
           CalibSaveMode = SELECT_FROM_LIST("Calibration data out of limit,continue?","Yes;No");\
           if(CalibSaveMode == 1)                      		\
           {                                                \
                ACKNOWLEDGE("Calibration Abort");           \
    			process_abort();			                \
           }                                                \
    	   write_unsigned8Selector = 73;                    \
    	   CalibEnterPoint = 4;                             \
    	   _CAL_SEND_CMD_AND_CHECK_STATUS(145);             \
    	   _CAL_SEND_CMD_AND_CHECK_STATUS(160);             \
    	   _CAL_SEND_CMD_AND_CHECK_STATUS(160);             \
    	}                                                   \
        if((calibrationMode >=1)&&(calibrationMode <=3)||(calibrationMode ==16)||(calibrationMode >=20)&&(calibrationMode <=22))        \
        {                                                       \
            select = ACKNOWLEDGE("Slope(Percent): %[.2f]{calslope}\n"          \
                        "Offset(PH): %[.2f]{caloffset}\n");           \
        }                                                       \
        else if((calibrationMode == 4)||(calibrationMode == 5)) \
        {                                                       \
            select = ACKNOWLEDGE("ORP Offset(mV): %[.1f]{caloffset}\n");       \
        }                                                       \
        else if((calibrationMode >=6)&&(calibrationMode <=9))   \
        {                                                       \
            select = ACKNOWLEDGE("Slope(nA): %[.3f]{calslope}\n"               \
                        "Offset(nA): %[.3f]{caloffset}\n");           \
        }                                                       \
        else if((calibrationMode >=10)&&(calibrationMode <=15)) \
        {                                                       \
            select = ACKNOWLEDGE("M: %[.4f]{calslope}\n"                       \
                        "A: %[.4f]{caloffset}\n");                    \
        }                                                       \
        else if((calibrationMode >=17)&&(calibrationMode <=19)) \
        {                                                       \
            select = ACKNOWLEDGE("P100: %[.2f]{calslope}\n"                    \
                        "P0: %[.2f]{caloffset}\n");                   \
        }                                                       \
        else                                                    \
        {                                                       \
            select = ACKNOWLEDGE("Slope:%[.4f]{calslope}%{calslopeUnit}\n"    \
                        "Offset:%[.4f]{caloffset}\n");          \
        }                                                       \
  		if(select != 0)\
  		{\
			process_abort();\
  		}\
  		if((calibrationMode ==19)&&(ODO_ProcScaling == 1) || SENSOR_CHANNEL_ANALOG)      \
        {                                                       \
            CalibSaveMode = SELECT_FROM_LIST("Complete calibration procedure.Select either Adjust or Abort:\n","Adjust;Abort");\
            if(CalibSaveMode == 1)                     			\
                CalibSaveMode = 2;                     			\
        }                                                       \
        else                                                    \
        {                                                       \
            CalibSaveMode = SELECT_FROM_LIST("Complete calibration procedure.Select either Adjust,Calibrate or Abort:\n","Adjust;Calibrate;Abort");\
        }                                                       \
        if(CalibSaveMode < 2)                          			\
        {                                                       \
        	write_unsigned8Selector = 72;                       \
        	CalibEnterPoint = 20;                             	\
        	_CAL_SEND_CMD_AND_CHECK_STATUS(145);                \
        	if(SENSOR_CHANNEL_DIGITAL)							\
	            DELAY(15, "Wait until new calc values have been stored");\
	        else\
				DELAY(5, "Wait until new calc values have been stored");\
            _CAL_159_CMD_AND_CHECK_STATUS(159);                 \
            if(CalSaveStatus == 1)                   			\
            {                                                   \
                ACKNOWLEDGE("ERROR:Stored Failed");             \
                process_abort();                                \
            }                                                   \
            else if(CalSaveStatus == 0)              			\
            {                                                   \
                processing = 0;                                 \
            }                                                   \
            else                                                \
            {                                                   \
        		processing = 1;		                            \
        		while(processing)                               \
                {                                               \
                    DELAY(3, "Wait until new calc values have been stored");\
                    _CAL_159_CMD_AND_CHECK_STATUS(159);         \
                    if(CalSaveStatus == 1)                      \
                    {                                           \
                        ACKNOWLEDGE("ERROR:Stored Failed");     \
                        process_abort();                        \
                    }                                           \
                    else if(CalSaveStatus == 0)                 \
                    {                                           \
                        processing = 0;                         \
                    }                                           \
                }                                               \
            }                                                   \
            send(138, status);                                  \
            cal_history_selector = 0;							\
            send(139, status);                                  \
            cal_history_selector = 1;							\
            send(139, status);                                  \
            cal_history_selector = 2;							\
            send(139, status);                                  \
            cal_history_selector = 3;							\
            send(139, status);                                  \
            cal_history_selector = 4;							\
            send(139, status);                                  \
        }                                                       \
        calmode = calibrationMode;                              \
        calibrationMode = 0;                                    \
        _CAL_SEND_CMD_AND_CHECK_STATUS(158);                    \
        send_command(48);                                       \
        if ((calmode != 3)&&(calmode != 5)&&(calmode != 6)&&(calmode!= 7)&&(calmode != 12)&&(calmode != 15)&&(calmode != 19)&&(calmode != 22) )\
        {                                                       \
            if(CalibSaveMode < 2)                      			\
            {                                                   \
                ACKNOWLEDGE("Calibration Done.\n"               \
                            "Re-Insert Sensor");                \
            }                                                   \
            else                                                \
            {                                                   \
                ACKNOWLEDGE("Calibration Not Done.\n"           \
                            "Re-Insert Sensor");                \
            }                                                   \
        }                                                       \
        else                                                    \
        {                                                       \
            if(CalibSaveMode < 2)                      			\
            {                                                   \
                ACKNOWLEDGE("Calibration Done");                \
            }                                                   \
            else                                                \
            {                                                   \
                ACKNOWLEDGE("Calibration Not Done");            \
            }                                                   \
        }                                                       \
    }



#define _CAL_VARIABLE_DEFINE()                \
	int result,i,calmode,retry,delay_time,ireturn;    \
    long select;                        \
	char status[STATUS_SIZE];           \
	unsigned char processing;           \
    float calslope1, caloffset1;        \
    int CalPressUnits;                  \
    float CalPressValue;                \
    IGNORE_ALL_DEVICE_STATUS();\
    XMTR_IGNORE_ALL_DEVICE_STATUS();\
    add_abort_method(cal_abort);\
	ABORT_ON_COMM_ERROR();\
    FixedCalTemp = 0;\
    Cal_CondCompCoef = 0;\
    Process_Cal_Step = 0;\
    First_cal_after_OptoCap = 0;\
    
		
                                
#define _CAL_ENTER(CMD_NUM)                     \
	calibrationMode = CMD_NUM;                  \
    _CAL_SEND_CMD_AND_CHECK_STATUS(158);        \
    DELAY(10, "Waiting for cal.initialization"); \
    add_abort_method(cal_abort);

//    MenuDisplay(CAL_Process_Cal_Display,str_abort_next,select); \

//AMS 12.0 bug: don't update value for DISPLAY API 
//DISPLAY("Sensor Value: %[.2f]{sensorValue} %{sensorValueUnit}\n"\
//        "Value Statue: %{rangeStatus}\n");\

#ifdef _DTM_OR_PDM_
#define _CAL_PRO_CAL_STEP1                                      \
    _CAL_159_CMD_AND_CHECK_STATUS(159);                        \
    _CAL_159_CMD_AND_CHECK_STATUS(159);                        \
    MenuDisplay(CAL_Process_Cal_Display,str_abort_next,select); \
	if(select == 0)\
	{\
		process_abort();\
	}\
    write_unsigned8Selector = 73;                               \
    CalibEnterPoint = 0;                                  		\
    _CAL_SEND_CMD_AND_CHECK_STATUS(145);                         \
    DELAY(3, "Check Status...");\
	_CAL_159_CMD_AND_CHECK_STATUS(159);                        \	
    ireturn = ACKNOWLEDGE("Captured value is stored.\n"                   \
                		 "Take a grab sample to be measured in the lab or perform a parallel measurement.");\
	if(ireturn == 0)\
	{\
	     _CAL_SEND_CMD_AND_CHECK_STATUS(48);\
	}\
  	if(ireturn != 0)\
  	{\
  	    cal_abort();\
		process_abort();\
  	}

#else
#define _CAL_PRO_CAL_STEP1                                      \
    _CAL_159_CMD_AND_CHECK_STATUS(159);                        \
    _CAL_159_CMD_AND_CHECK_STATUS(159);                        \
    MenuDisplay(CAL_Process_Cal_Display,str_abort_next,select); \
    write_unsigned8Selector = 73;                               \
    CalibEnterPoint = 0;                                  		\
    _CAL_SEND_CMD_AND_CHECK_STATUS(145);                         \
    DELAY(3, "Check Status...");\
	_CAL_159_CMD_AND_CHECK_STATUS(159);\
	ireturn = ACKNOWLEDGE("Captured value is stored.\n"                   \
                "Take a grab sample to be measured in the lab or perform a parallel measurement.");\
	if(ireturn == 0)\
	{\
  		_CAL_SEND_CMD_AND_CHECK_STATUS(48);\
	}\
  	if(ireturn != 0)\
  	{\
		process_abort();\
  	}
#endif


                
#define _CAL_PRO_CAL_STEP2                                          	\
    _CAL_159_CMD_AND_CHECK_STATUS(159);                            		\
	do																	\
	{																	\
    	_CAL_159_CMD_AND_CHECK_STATUS(159);								\
    	calibValue = sensorValue;                                       \
    	calibValueUnit = sensorValueUnit;                               \
    	calibPointSelection = 0;                                        \
    	select = GET_DEV_VAR_VALUE("|en zz|Captured value: %[.3f]{sensorValue} %{sensorValueUnit}\n Enter ref.value:"    \
                      "|en|Captured value: %[.3f]{sensorValue} \nEnter reference value:",  calibValue);     \
  		if(select != 0)\
  		{\
			process_abort();\
  		}\
  		send(161, status);  											\
		if(status[STATUS_RESPONSE_CODE] == 0)							\
			break;														\
		else if((status[STATUS_RESPONSE_CODE] == 3)||(status[STATUS_RESPONSE_CODE] == 4))\
		{\
			display_response_status(161, status[STATUS_RESPONSE_CODE]);	\
		}\
		else\
		{\
			display_response_status(161, status[STATUS_RESPONSE_CODE]);	\
			process_abort();											\
		}																\
	}while(1);																	\
    write_unsigned8Selector = 73;                               		\
    CalibEnterPoint = 2;                                  				\
    _CAL_SEND_CMD_AND_CHECK_STATUS(145);								\
    _CAL_CALIBRATE()
    												                       	