TCP-Server

Description:
PLEASE ONLY USE THIS CODE IF YOU HAVE THE MODULE CONNECTED TO YOUR NETWORK.
This example shows how to communicate by a TCP-Server socket (module on server side).
To connect to the Server please use a TCP Client (like Putty) and connect to IP: 192.168.0.99 PORT:7777
You are now able to control the LED on the Wino board by the commands "led on" or "led off"
Command:


int LED_PIN = 2;

//TCP Server configuration
String port = "7777";
String clientIp = "192.168.0.99"; //This uses static IP

int listening = 0;
String answer = "";
bool wifi = false;

void setupWifi(void)
{
  //test if the module is ready
  while (!Serial.find("ready\r\n")) {}

  Serial.println("AT+CWMODE=3");
  while (!Serial.find("OK\r\n")) {}
  delay(100);

  Serial.println("AT+CWDHCP=1,1");
  while (!Serial.find("OK\r\n")) {}

  //set AP IP-adress
  Serial.println("AT+CIPAP=\"192.168.4.1\"");
  while (!Serial.find("OK\r\n")) {}

  //check for ip address
  while (!Serial.find("WIFI GOT IP")) {
  };

  //set static IP-address  
  Serial.println("AT+CIPSTA=\""+ clientIp +"\"");
  delay(100);  
  while (!Serial.find("OK\r\n")) {}

  //change to stationary mode and close AP
  Serial.println("AT+CWMODE=1");
  while (!Serial.find("OK\r\n")) {}

 digitalWrite(LED_PIN, HIGH);
 wifi = true;

}

void listenTCP() {

 if (listening == 0) {
  Serial.println("AT+CIPMUX=1");
  while (!Serial.find("OK\r\n")) {}
  delay(100);

  String connecttcp = "AT+CIPSERVER=1," + port;
  Serial.println(connecttcp);

  while (!Serial.find("OK\r\n")) {}

  listening = 1;
  } 

      while (Serial.available() > 0) {
      char character = Serial.read();
      answer.concat(character);
      if (answer.indexOf("CLOSED\r\n") > -1) {listening = 0;}
      if (answer.indexOf("+IPD") > -1 and answer.indexOf("\r\n") > -1) {
          int starti = answer.indexOf(":") + 1;
          int endi = answer.indexOf("\r");
          answer = answer.substring(starti,endi);
      }
      if (answer.indexOf("\r\n") > -1) {answer ="";}
      }

}

void setup() {

  pinMode(LED_PIN, OUTPUT);
  pinMode(WIFI_EN_PIN, OUTPUT);

  pinMode(12, OUTPUT);
  digitalWrite(12, HIGH);

  digitalWrite(WIFI_EN_PIN, LOW);
  delay(100);
  digitalWrite(WIFI_EN_PIN, HIGH);

  Serial.begin(115200);

  setupWifi();

}

String runcommand(String command) {

  String cmd = command.substring(0, command.indexOf(" "));
  String stringvalue = command.substring(command.indexOf(" ") + 1, command.length());
  float value = stringvalue.toFloat();
  if (stringvalue == "on") {value = 1;}
  if (stringvalue == "off") {value = 0;}
  Serial.println(value);
 //parses incoming TCP-data

  //WRITE DIGITAL PINS
  if (stringvalue == "on" or stringvalue == "off") {
    if (cmd == "led") {pinMode(LED_PIN, OUTPUT); digitalWrite(LED_PIN, value); return "OK\r\n";}
  }
}

void loop()
{

  if (wifi == 1) {
   listenTCP();
  }

  delay(10);
}