#include <WiFi.h>
#include "Adafruit_MQTT.h"
#include "Adafruit_MQTT_Client.h"
#include <NewPing.h>
#include <LiquidCrystal_I2C.h>
#define TRIG_PIN 13
#define ECHO_PIN 14
#define MAX_DIST 412
#define ssid "Wokwi-GUEST"
#define pass ""
#define server "mqtt-dashboard.com"
#define port 1883
WiFiClient client;
LiquidCrystal_I2C lcd(0x27, 16, 2);
NewPing sonar(TRIG_PIN, ECHO_PIN, MAX_DIST);
Adafruit_MQTT_Client mqtt(&client, server, port);
Adafruit_MQTT_Publish level = Adafruit_MQTT_Publish(&mqtt, "level");
int sa = 0;
int counter = 0;
void MQTT_connect() {
  int8_t ret;
  if (mqtt.connected()) {
    return;
  }
  Serial.print("Connecting to MQTT... ");
  uint8_t retries = 3;
  while ((ret = mqtt.connect()) != 0) {
    Serial.println(mqtt.connectErrorString(ret));
    Serial.println("Retrying MQTT connection in 5 seconds...");
    mqtt.disconnect();
    delay(5000);
    retries--;
    if (retries == 0) {
      while (1);
    }
  }
  Serial.println("MQTT Connected!");
}
void setup() {
  Serial.begin(115200);
  Serial.print("Connecting to ");
  Serial.println(ssid);
  WiFi.begin(ssid, pass);
  while (WiFi.status() != WL_CONNECTED) {
    delay(500);
    Serial.print(".");
    if (counter > 10) {
      ESP.restart();
    }
    counter++;
  }
  Serial.println("WiFi connected");
  Serial.println("IP address: ");
  Serial.println(WiFi.localIP());
  lcd.init();
  lcd.backlight();
}
void loop() {
  MQTT_connect();
  mqtt.processPackets(5000);
  if (! mqtt.ping()) {
    mqtt.disconnect();
  }
  int a = 412 - sonar.ping_cm();
  if (a != sa) {
    String b = "{\"level\":" + String(a) + "}";
    level.publish(b.c_str());
    Serial.print("level: ");
    Serial.print(a);
    Serial.println(" cm");
    lcd.setCursor(0, 0);
    lcd.print("level:    ");
    lcd.setCursor(7, 0);
    if (a < 10) lcd.print(" ");
    if (a < 100) lcd.print(" ");
    lcd.print(a);
    lcd.setCursor(11, 0);
    lcd.println("cm");
  } sa = a;
}