/********************************************************************
 * COPYRIGHT -- Bernecker + Rainer
 ********************************************************************
 * Program: FloodAsUdp
 * File: FloodAsUdp.c
 * Author: 
 * Created: February 05, 2014
 ********************************************************************
 * Implementation of program FloodAsUdp
 ********************************************************************/

#include <bur/plctypes.h>

#ifdef _DEFAULT_INCLUDES
	#include <AsDefault.h>
#endif

void _INIT FloodAsUdp_init(void)
{
	/* Open UDP */
	fbkUdpOpen.enable = 1;
	fbkUdpOpen.pIfAddr = 0;
	fbkUdpOpen.port = 0;
	fbkUdpOpen.options = udpOPT_BROADCAST;
	
	/* Call fbk until it is finished */
	do
	{
		UdpOpen(&fbkUdpOpen);
	} while (fbkUdpOpen.status == 65535);

	/* store ident */
	if (fbkUdpOpen.status == 0)
	{
		udpIdent = fbkUdpOpen.ident;
		
		fbkUdpSend.enable = 1;
		fbkUdpSend.ident = udpIdent;
		fbkUdpSend.pHost = (UDINT)"192.168.101.255";
		fbkUdpSend.port = 9;
		fbkUdpSend.pData = (UDINT)&buffer;
		fbkUdpSend.datalen = sizeof(buffer);
		fbkUdpSend.flags = 0;
	}
}

void _CYCLIC FloodAsUdp_cyclic(void)
{
	if (enable)
	{
		if (!error)
		{
			/* Call fbk */
			UdpSend(&fbkUdpSend);
			
			switch (fbkUdpSend.status)
			{
				case 0:
				case 32507:
				case 65535:
					break;
			
				default:
					error = 1;
					break;
			}
		}
	}
	else
	{
		/* reset error */
		error = 0;
	}
}

void _EXIT FloodAsUdp_exit(void)
{
	fbkUdpClose.enable = 1;
	fbkUdpClose.ident = udpIdent;
		
	/* Call fbk until it is finished */
	do
	{
		UdpClose(&fbkUdpClose);
	} while (fbkUdpClose.status == 65535);
}
