(*********************************************************************************
* Copyright: Bernecker+Rainer
* Author:    Mikael Regard
* Created:   May 13, 2019/8:21 AM 
* Updated:   Aug 19, 2019/09:00 AM
 *********************************************************************************
 * Description:
 * FuB to configure Digital input
 * Max 22 digital inputs can be configured per command.
 * 128 Digital inputs available. ID from 0-127.
 * 
 *Input:
 * MsgFrame  (Profinet output frame)
 * ReadFrame (Profinet reply frame)
 * Execute   (Edgepos, Execute = TRUE will run the FuB once)
 * CmdLabel  (Optional 2 byte Command label. Used to identify specfic commands.
 * NumOfDi   (Number of Digital input to configure. min 1 max 22)
 * DiID[0..21]		 (Array of digital input ID. min = 0 max 127)
 * DigitalID[0..21] (ActionID = 1, DigitalID, ActionID = 2, Motion Macro ID)
 * ActionID[0..21]  (0 = Trigger Only, 1 = Reset Digital Output, 2 = Run Motion Macro)
 * TriggerXbotID[0..21] (XbotID for trigger)
 *
 * Output:
 * Error (Indicates if there is an error)
 * Busy  (FuB will be Busy until reply)
 * Done  (When Accepted command is received, Done = TRUE) 
 * ErrorID (0x0001 = System Error, 0x2000 = Wrong PMC State, 0x2001 = No Mastership, 0x2002 = Mastership timeout,
 *		    0x2003 = Wrong group state, 0x2004 = Wrong Macro state, 0x2005 = Wrong Digital IO state,
 *          0x2006 = Wrong flyways state, 0x3000 = Wrong Xbot state, 0x4000 = Paramter Error: Invalid Parameters.
 *********************************************************************************)






FUNCTION_BLOCK PM_ConfigDigitalInput
	// Check Reply
	IF(Busy)THEN
		brsmemcpy(ADR(CmdLbl),ADR(ReadFrame[3]),2);
		IF(ReadFrame[0] = CmdCount AND
			ReadFrame[1] 	= 28  AND
			ReadFrame[2]	= 11 AND
			CmdLbl = CmdLabel)THEN
			Done 	:= TRUE;
			Busy 	:= FALSE;
			brsmemcpy(ADR(ErrorID),ADR(ReadFrame[5]),2);
			Error 	:= UINT_TO_BOOL(ErrorID);
			Done 	:= NOT(UINT_TO_BOOL(ErrorID));
		ELSE
			Busy := FALSE;
		END_IF;
	END_IF;
	//Send Command		
	IF(Execute AND NOT(Done) AND NOT(Error))THEN
		IF(NOT(Busy))THEN
			brsmemset(ADR(MsgFrame[1]),FALSE,98); //rs frame
			CmdCount 		:= ReadFrame[0] +1;
			MsgFrame[0] 	:= CmdCount; 
			MsgFrame[1] 	:= 28;
			MsgFrame[2] 	:= 11;
			brsmemcpy(ADR(MsgFrame[3]), ADR(CmdLabel), 2);
			MsgFrame[5]		:= 1;
			MsgFrame[10]	:= NumOfDi;	
			FOR count := 0 TO NumOfDi DO
				MsgFrame[11+(DI_BYTE_SEQUENCE*count)] := DiID[count];
				MsgFrame[12+(DI_BYTE_SEQUENCE*count)] := ActionID[count];
				IF(ActionID[count] = 1)THEN
					MsgFrame[13+(DI_BYTE_SEQUENCE*count)] := DigitalID[count];
				ELSIF(ActionID[count] = 2)THEN
					MsgFrame[13+(DI_BYTE_SEQUENCE*count)] := DigitalID[count];
					MsgFrame[14+(DI_BYTE_SEQUENCE*count)] := TriggerXbotID[count];
				END_IF;
			END_FOR;
			Busy := TRUE;	
		END_IF;
		//Reset Output
		
	ELSIF(NOT(Execute))THEN
		Busy := FALSE;
		Done := FALSE;
		Error := FALSE;
		ErrorID := 0;
	END_IF
	
	
	
END_FUNCTION_BLOCK
