/*
UDP_Clie.c: Implement one UDP client connection.

Compiler: BC++ 3.1, 
          Turbo C++ 1.01(3.01) (free from http://cc.codegear.com/free/cpp)

Compile mode: Large

Project: Client.c
         ..\lib\7186el.Lib
         ..\lib\tcp_dm32.lib
         ..\lib\FW_nnnnn.LIB
         
Hordware: uPAC-7186EX

[Nov 04, 2008] by Liam
*/

#include<conio.h>
#include<stdio.h>
#include "..\lib\7186e.h"
#include "..\lib\Tcpip32.h"
#include "..\lib\MFW.h"

#define _SHOW_IP_ADDRESS_ 

#define BUFSIZE 1460       /* read/write buffer size */

void MyUdpFun(int skt);
UDP_SOCKET Udp23={
    -1,             // int socket;
    0,              // unsigned MyPort;
    "10.0.9.47",    // char *RemoteIp; 
    10000,          // unsigned RemotePort;
    1,              // int fNonBlock;
    1,              // int fEnableBroadcast;
    0,              // int status; 
    MyUdpFun        // void (*CallBackFun)(int skt);
}; 

void XS_UserInit(int argc,char *argv[])
{
    extern int bAcceptBroadcast;
    extern unsigned long ACKDELAY;  /* vaariable in tcp.c */
    extern long MAXTXTOUT;
    void UserLoop(void);
    char version[20];
    
    InitLib();

    bAcceptBroadcast=0;
    ACKDELAY=200;
    XS_GetVersion(version);
    Print("[X-Server library]: version=%s ",version);
    XS_GetLibDate(version);
    Print("date=%s\r\n",version);
    GetTcpipLibDate(version);
    Print("Tcpip library version:%X, Library Date is %s\r\n", GetTcpipLibVer(), version);

    XS_AddSystemLoopFun(UserLoop);

    /* Add UDP search function */ 
    bAcceptBroadcast=1;     // allow to receive the UDP broadcast
    
    /* Add UDP telnet client */
    XS_AddUdpSocket(&Udp23);
    
    EnableWDT();
    MAXTXTOUT=6000UL; 

    XS_AddSystemLoopFun(XS_SocketLoopFun);
    XS_StartSocket();
}

void XS_UserEnd(void)
{
    XS_StopSocket();
    DisableWDT();
}

extern int errno;
void UserLoop(void)
{   
    long tmpt;
    int key,err; 

    RefreshWDT();
    if(Kbhit()){
        switch((key=Getch())){
            case 27:
                QuitMain=1;
                break;
            default:
                if(Udp23.socket>=0){
                    err= writesocket(Udp23.socket,&key,1);
                    if (err < 0) {               /* write error */
                        Print( "UDP write error %d,errno=%d\n\r", err,errno );
                        XS_RemoveUdpSocket(&Udp23);
                    }
                }   
                break;
        }
    }
}

void MyUdpFun(int skt)
{ 
    char buf[100];
    int len;
    int i; 
 
    len=readsocket(skt, buf, sizeof(buf)-1);
    if(len>0){
        buf[len]=0;
        //Puts(buf);
        Print("%s\r\n", buf);
    }
    else{
        Print("Udp read error:%d(srrno=%d)\r\n", len, errno);
    } 
}

void main(int argc,char *argv[])
{
    XS_main(argc,argv); /* call the XS library main function. */
}
