#include <MsTimer2.h> // Timer
#include <Ethernet2.h>

#include <avr/wdt.h>  // ??

#include "SC_AI.h"  // Differential analog input collector
#include "SC_MC9.h"  // MC9 Tempreture Controller

#define RcvOK "OK\r\n"
#define RcvErr "ER\r\n"
#define MODE_DEBUG  false

// Enter a MAC address and IP address for your controller below.
// The IP address will be dependent on your local network.
// gateway and subnet are optional:
byte mac[] = { 0xDE, 0xAD, 0xBE, 0xEF, 0xFE, 0x00 };
IPAddress ip(192, 168, 20, 177);
IPAddress gateway(192, 168, 20, 1);
IPAddress subnet(255, 255, 255, 0);

// SCPI defaults to port 5025
EthernetServer server(5025);
EthernetClient client;

// HTTP defaults to port 5025
EthernetServer web(80);

unsigned long lastDataReceivedTime;
unsigned long timeoutPeriod = 5000;  // 타임아웃 시간 (5초)

bool busy = false;
bool connection = false;
char buffer[1024];

int Size_AI = 16;
int AI_VALUES[] = {
  0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0
};
int msCnt = 0;
unsigned long timer = 0;

void setup() {
  // put your setup code here, to run once:
  Serial.begin(9600);
  Serial.println("Start!");

  TCPIP_setup(mac, ip, gateway, subnet);

  // scitech korea Library
  SC_AI_setup();
  SC_MC9_setup();

  // Timer set
  MsTimer2::set(10, periodic_10ms);
  MsTimer2::start();

  // Report address
  Serial.print("MAC>>");
  for (int i = 0; i < 6; i++) {
    if (mac[i] < 16) {
      Serial.print("0");
    }
    Serial.print(mac[i], HEX);
    if (i < 5) {
      Serial.print(":");
    }
  }
  Serial.println();
  Serial.print("IP >>");
  Serial.println(Ethernet.localIP());

}

void loop() {
  // wait for a new client:

  webReponse();
  client = server.available();
  

  if (client) {
    // check if client is connected
    Serial.println("Client Connected!!!");

    // Do What Message Command
    while(client.connected()){

      int buffCnt = 0;
      
      // check for command byte
      if (client.available() > 0) {
        char c;

        String command;
        String cmd;
        unsigned int data[32];
        int dataSize;

        busy = true;
        // Read message by byte
        while ((c = client.read())) {
          // Read data until LF or CR
          if((c != 10) && (c != 13)){
            command += c;
          }else{
            break;
          }     
        }

        cmd = demuxCMD(command, data, &dataSize);

        if(cmd=="AI"){
          client.print(Prcss_AI());
        }else if(cmd=="AO"){
          client.print(Prcss_AO(data, dataSize));
        }else{
          client.print(RcvErr);
        }
        
        
        // Debug
        if(MODE_DEBUG){
          //Serial.print("Received command: ");
          //Serial.println(command);
        }

        busy = false;
        // 데이터를 수신했으므로 타임아웃 타이머 초기화
        lastDataReceivedTime = millis();

      }// if end, client.available()
      //Serial.println("end client available");

      // 타임아웃 확인
      if (millis() - lastDataReceivedTime > timeoutPeriod) {
        Serial.println("Client Disconnected... (Timeout)");
        client.stop();
      }

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

}


void TCPIP_setup(byte mac[], IPAddress ip, IPAddress gateway, IPAddress subnet){
  mac[5] = ip[3] & 0xFF;
  // initialize the ethernet device
  Ethernet.begin(mac, ip, gateway, subnet);
  // start listening for clients
  server.begin();
  web.begin();
}

void periodic_10ms(){

  
  msCnt += 10;
  if(!busy){
    
    SC_AI(AI_VALUES, Size_AI);
  
    // periodic_1s
    if (msCnt > 1000){
      msCnt = 0;
      periodic_1s();
    }  
  }
  
}

void periodic_1s(){
  
  //AnalogIn_Print();
}


void AnalogIn_Print(){
  for (int i = 0; i < Size_AI; i++) {
    Serial.print(AI_VALUES[i]);
    Serial.print("\t");
  }
  Serial.println();
}



void webReponse(){
  EthernetClient webClient = web.available();
  if (webClient) {
    Serial.println("Web client connected");
    while (webClient.connected()) {
      if (webClient.available()) {
        // 웹 브라우저에서 요청이 도착한 경우
        String request = webClient.readStringUntil('\r');
        //Serial.println(request);
        webClient.flush();
        
        // 웹 브라우저에 출력할 문구 작성
        String response = "HTTP/1.1 200 OK\r\n";
        response += "Content-Type: text/html\r\n\r\n";
        response += "<html><body>";
        response += Prcss_AI();
        //response += "<h1>Hello, World!</h1>";
        response += "</body></html>";
        
        // 문구를 웹 브라우저로 전송
        webClient.print(response);
        delay(1);
        
        // 클라이언트 연결 종료
        webClient.stop();
      }
    }
  }

}