#include <WiFi.h>
#include <Wire.h>
#include <Adafruit_GFX.h>
#include <Adafruit_SSD1306.h>

#define SCREEN_WIDTH 128
#define SCREEN_HEIGHT 64

Adafruit_SSD1306 display(SCREEN_WIDTH, SCREEN_HEIGHT, &Wire, -1);

const char* ssid = "OPPO";
const char* password = "123456789";

const char* serverIP = "10.148.189.202"; // CHANGE THIS
const uint16_t port = 80;

WiFiClient client;

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

  // OLED init
  if(!display.begin(SSD1306_SWITCHCAPVCC, 0x3C)) {
    Serial.println("OLED failed");
    while(1);
  }

  display.clearDisplay();
  display.setTextSize(1);
  display.setTextColor(WHITE);

  // WiFi connect
  WiFi.begin(ssid, password);
  displayMessage("Connecting WiFi...");

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

  displayMessage("WiFi Connected");

  // Connect to server
  if (client.connect(serverIP, port)) {
    displayMessage("Connected to Server");
  } else {
    displayMessage("Connection Failed");
  }
}

void loop() {

  // Send message
  if (Serial.available()) {
    String msg = Serial.readStringUntil('\n');
    client.println(msg);
    displayMessage("Me:\n" + msg);
  }

  // Receive message
  if (client.available()) {
    String response = client.readStringUntil('\n');
    Serial.println("Recv: " + response);
    displayMessage("Recv:\n" + response);
  }
}

// OLED display function
void displayMessage(String msg) {
  display.clearDisplay();
  display.setCursor(0, 10);
  display.println(msg);
  display.display();
}