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

 
const char* ssid = "PT4ObjConnect";
const char* password =  "Admin2022";
const char* mqttServer = "192.168.1.64";
const int mqttPort = 1883;
const char* mqttUser = "patate";
const char* mqttPassword = "patate";

LiquidCrystal lcd(19, 23, 18, 17, 16, 15);
 
WiFiClient espClient;
PubSubClient client(espClient);
 
void callback(char* topic, byte* payload, unsigned int length) {
 
  Serial.print("Message arrived in topic: ");
  Serial.println(topic);
 
  Serial.print("Message:");
  lcd.clear();
  for (int i = 0; i < length; i++) {
    Serial.print((char)payload[i]);
    lcd.print((char)payload[i]);
  }
 
  Serial.println();
  Serial.println("-----------------------");

  
 
}
 
void setup() {
 
  Serial.begin(115200);
  lcd.begin(16, 2);
  WiFi.begin(ssid, password);
 
  while (WiFi.status() != WL_CONNECTED) {
    delay(500);
    Serial.println("Connecting to WiFi..");
  }
  Serial.println("Connected to the WiFi network");
 
  client.setServer(mqttServer, mqttPort);
  client.setCallback(callback);
 
  while (!client.connected()) {
    Serial.println("Connecting to MQTT...");
 
    if (client.connect("ESP32Client", mqttUser, mqttPassword )) {
 
      Serial.println("connected");  
 
    } else {
 
      Serial.print("failed with state ");
      Serial.print(client.state());
      delay(2000);
 
    }
  }
 
  client.subscribe("esp32/lcd");
 
}
 
void loop() {
  client.loop();
}
