/*
 * Modifed from UIPEthernet EchoServer example.
 *
 * UIPEthernet is a TCP/IP stack that can be used with a enc28j60 based
 * Ethernet-shield.
 *
 */
#define DEBUG 1
#define MACADDRESS 0x00,0x01,0x02,0x03,0x04,0x05
#define MYIPADDR 192,168,20,177
#define MYIPMASK 255,255,255,0
#define MYDNS 192,168,20,1
#define MYGW 192,168,20,1
#define LISTENPORT 5025
#define UARTBAUD 115200

#include <UIPEthernet.h>
#include <UIPServer.h>
#include <UIPClient.h>
#include "utility/logging.h"

uint8_t mac[6] = {MACADDRESS};
uint8_t myIP[4] = {MYIPADDR};
uint8_t myMASK[4] = {MYIPMASK};
uint8_t myDNS[4] = {MYDNS};
uint8_t myGW[4] = {MYGW};

EthernetClient client;
EthernetServer server = EthernetServer(LISTENPORT);

void setup() {

  Serial.begin(9600);
  Ethernet.begin(mac,myIP,myDNS,myGW,myMASK);
  // start listening for clients
  server.begin();
}

void loop() {
  size_t size;

  String message = "";
  client = server.available();

  if (client){

    Serial.println("Client Connected!!!");
    while(client.connected()){
      // Recive Command
      if((size = client.available()) > 0){
        uint8_t* msg = (uint8_t*)malloc(size);

        size = client.read(msg,size);
        for(int i = 0 ; i < size ; i++){
            message += (char)msg[i];
        }
        if(size > 2){
          if((msg[size-1] == '\n') && (msg[size-2] == '\r')){
            #if DEBUG
              Serial.print(size);
              Serial.println("   >> " + message);
            #endif

            //cmd = demuxCMD(message, &cmdData);  // for IFB
            client.print(message);
            message = "";
          }
        }
        free(msg);

      }

      // Action by Command
      //if(cmd)

    }
    Serial.println("Client Disconnected...");
  }
}

