Your new topic does not fit any of the above??? Check first. Then post here. Thanks.

Moderator: igrr

User avatar
By martinayotte
#29735 Hi Kakhan,

There was errors with the missing }, they were misplaced, but also the fact that server.begin() can't be called until the Wifi connection is ready. I've modified it accordingly and do quick tests, here is the corrected version :

Code: Select all#include <ESP8266WiFi.h>

const char* ssid     = "DOVADO";
const char* password = "5AEDDAD24D";
const int Port = 23;
const char* host = "192.168.1.30";
unsigned long previousMillis = 0;

// Use WiFiClient class to create TCP connections
WiFiClient client;
WiFiServer server(23);//listen on port 23
boolean tcp_server_started = false;

void setup() {
  Serial.begin(115200);
  delay(1000);

  // We start by connecting to a WiFi network

  Serial.println();

  WiFi.begin(ssid, password);
//  server.begin();
  Serial.println("Server started");
  Serial.println();
  Serial.print("Connecting to ");
  Serial.println(ssid);

  while (WiFi.status() != WL_CONNECTED) {
    delay(500);
    Serial.print(".");
  }

  Serial.println("");
  Serial.println("WiFi connected");
  Serial.println("IP address: ");
  Serial.println(WiFi.localIP());
}


void SendDataToServer() {
  WiFiClient client;
  if (!client.connect(host, Port)) {
    Serial.println("connection failed");
  }
  else {
    Serial.println("Sending ...");
    client.print("TEST DATA TO MLServer\r\n");
    delay(100);
    /* maybe you can verify an acknowledge here, but facultative */
  }
}

void loop()
{
  if (!tcp_server_started && WiFi.status() == WL_CONNECTED) {
    server.begin();
    tcp_server_started = true;
  } 
  if (client) {
    if (client.status() == CLOSED) {
      client.stop();
      Serial.println("connection closed !");
    }
    if (client.available()) {
      String req = client.readStringUntil('\r');
      req.trim();
      if (req.equals("hello")) {
        client.println("Hello from ESPDuino !!!");
      }
      else if (req.equals("command2")) {
        client.println("Response for Command2");
      }
    }
  }
  else {
    client = server.available();
  }
  delay(1);
  unsigned long currentMillis = millis();
  if (currentMillis - previousMillis > 3000) {
    previousMillis = currentMillis;
    // It is time to send something here ...
    SendDataToServer();
  }
}