#include <WiFi.h>
#include "PubSubClient.h"
//#include "WebSocketStreamClient.h"
#include <LiquidCrystal_I2C.h>

const char* ssid = "Wokwi-GUEST";
const char* password = "";
const char* MqttServer = "test.mosquitto.org";
//const int wsMqttPort = 1883;
//const char* wsMqttPath = "";
const char* mqttTopic = "/tandon/tinggi";

char clientId[50];

const int trigPin = 2;
const int echoPin = 15;


LiquidCrystal_I2C lcd(0x27,20,4);  // set the LCD address to 0x27 for a 16 chars and 2 line display

//define sound speed in cm/uS
#define SOUND_SPEED 0.034
//#define CM_TO_INCH 0.393701

long duration;
float distanceCm;
//float distanceInch;

WiFiClient espClient;
//WebSocketClient wsClient(espClient, wsMqttServer, wsMqttPort);
//WebSocketStreamClient wsStreamClient(wsClient, wsMqttPath);
PubSubClient client(espClient);

void setup() {
  Serial.begin(115200);
  //randomSeed(analogRead(0));

  Serial.print("\nConnecting to ");
  Serial.println(ssid);

  wifiConnect();

  Serial.println("\nWiFi connected");
  Serial.print("IP address: ");
  Serial.println(WiFi.localIP());
  
  client.setServer(MqttServer, 1883);

  mqttReconnect();

  Serial.begin(115200); // Starts the serial communication
  pinMode(trigPin, OUTPUT); // Sets the trigPin as an Output
  pinMode(echoPin, INPUT); // Sets the echoPin as an Input

  lcd.init();                      // initialize the lcd
  // Print a message to the LCD.
  lcd.backlight();
  lcd.setCursor(2,0);
  lcd.print("Pengukur Tinggi Air Tandon");
  lcd.setCursor(6,3);
  lcd.print("DYD-2024");
  delay(2000);
  lcd.clear();
}

void loop() {
  // Clears the trigPin
     digitalWrite(trigPin, LOW);
     delayMicroseconds(2);
  // Sets the trigPin on HIGH state for 10 micro seconds
     digitalWrite(trigPin, HIGH);
     delayMicroseconds(10);
     digitalWrite(trigPin, LOW);
  
  // Reads the echoPin, returns the sound wave travel time in microseconds
     duration = pulseIn(echoPin, HIGH);
  
  // Calculate the distance
     distanceCm = 400-(duration * SOUND_SPEED/2);

  // set cursor to first column, first row
     lcd.setCursor(0, 0);
  // print message
     lcd.print("Tinggi Air:");
  //lcd.setCursor(0,1);
     lcd.println(distanceCm);
     lcd.println("cm");
     Serial.print("Tinggi:");
     Serial.println(distanceCm);
     Serial.println("cm");

     lcd.setCursor(2,3);
     lcd.print("Terima Kasih :)");
  
     delay(30000);
     lcd.clear();

    delay(10);
    if (!client.connected()) {
      mqttReconnect();
      }
  char str2[5];
  itoa( distanceCm, str2, 10);
  client.publish(mqttTopic, str2);

  client.loop();
}

void wifiConnect() {
  WiFi.mode(WIFI_STA);
  WiFi.begin(ssid, password);
  while (WiFi.status() != WL_CONNECTED) {
    delay(500);
    Serial.print(".");
  }
}

void mqttReconnect() {
  while (!client.connected()) {
    Serial.println("Attempting MQTT connection...");
    //long r = random(1000);
    //sprintf(clientId, "clientId-%ld", r);
    String clientId = "ESP8266Client";
    clientId += String(random(0xffff), HEX);
    if (client.connect(clientId.c_str())) {
      Serial.print(clientId);
      Serial.println(" connected");
    } else {
      Serial.print("failed, rc=");
      Serial.print(client.state());
      Serial.println(" try again in 5 seconds");
      delay(5000);
    }
  }
}