#include <WiFi.h>
#include <PubSubClient.h>

// Update these with values suitable for your network.
const char* ssid = "ipoga";
const char* password = "---";
const char* mqtt_server = "192.168.1.41";
const int mqtt_port = 1883;

WiFiClient espClient;
PubSubClient client(espClient);

String serialData = ""; // to store data from the serial port

void setup_wifi() {
  delay(10);
  // Connect to WiFi network
  Serial.println();
  Serial.print("Connecting to ");
  Serial.println(ssid);

  WiFi.begin(ssid, password);

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

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

void reconnect() {
  // Loop until we're reconnected
  while (!client.connected()) {
    Serial.print("Attempting MQTT connection...");
    // Attempt to connect
    if (client.connect("ESP32Client")) {
      Serial.println("connected");
    } else {
      Serial.print("failed, rc=");
      Serial.print(client.state());
      Serial.println(" try again in 5 seconds");
      // Wait 5 seconds before retrying
      delay(5000);
    }
  }
}

void setup() {
  Serial.begin(115200);
  setup_wifi();
  client.setServer(mqtt_server, 1883);
}

void loop() {
  if (!client.connected()) {
    reconnect();
  }
  client.loop();

  while (Serial.available()) {
    char inChar = (char)Serial.read();
    serialData += inChar; 

    // if newline detected, publish the data
    if (inChar == '\n') {
      serialData.trim();  // Remove any leading/trailing whitespace
      client.publish("classification", serialData.c_str());
      
      serialData = "";  // Clear the string
    }
  }
}
