#include <WiFi.h>
#include "PubSubClient.h"
#include <Wire.h>
#include <LiquidCrystal_I2C.h>

const char * MQTTServer = "broker.hivemq.com";
const char * MQTT_Topic = "LCD";

// Tạo ID ngẫu nhiên tại: https://www.guidgen.com/
const char * MQTT_ID = "thachlai";
int Port = 1883;

WiFiClient espClient;
PubSubClient client(espClient);

LiquidCrystal_I2C LCD = LiquidCrystal_I2C(0x27, 16, 2); // them thu vien liquidCrystal_I2c

void WIFIConnect() {
  Serial.println("Connecting to SSID: Wokwi-GUEST");
  WiFi.begin("Wokwi-GUEST", "");
  while (WiFi.status() != WL_CONNECTED) {
    delay(500);
    Serial.print(".");
  }
  Serial.println("");
  Serial.print("WiFi connected");
  Serial.print(", IP address: ");
  Serial.println(WiFi.localIP());
}

void MQTT_Reconnect() {
  while (!client.connected()) {
    if (client.connect(MQTT_ID)) {
      Serial.print("MQTT Topic: ");
      Serial.print(MQTT_Topic);
      Serial.print(" connected");
      client.subscribe(MQTT_Topic);
      Serial.println("");
    } else {
      Serial.print("failed, rc=");
      Serial.print(client.state());
      Serial.println(" try again in 5 seconds");
      delay(5000);
    }
  }
}

void callback(char* topic, byte* message, unsigned int length) {
  Serial.print("Message arrived on topic: ");
  Serial.println(topic);
  Serial.print("Message: ");
  String stMessage;

  for (int i = 0; i < length; i++) {
    Serial.print((char)message[i]);
    stMessage += (char)message[i];
  }
  Serial.println();
  
  LCD.setCursor(0, 0);
  LCD.println(stMessage);
}

void setup() {
  Serial.begin(115200);
  WIFIConnect(); //ket noi với wifi
  client.setServer(MQTTServer, Port);
  client.setCallback(callback);
  LCD.init();
  LCD.backlight();
}

void loop() {
  delay(10);
  if (!client.connected()) {
    MQTT_Reconnect();
  }
  client.loop();
  // LCD.setCursor(0, 1);
  // LCD.println("Connection Err");
}