#include <ESP8266WiFi.h> 
#include <PubSubClient.h>

const char *ssid = "Redmi"; // Enter your WiFi name
const char *password = "11051961";  // Enter WiFi password

const char* mqtt_broker   = "74af2e12f35e4de485e634c659b59f8e.s1.eu.hivemq.cloud";
const char* topic         = "esp8266/test";
const char* mqtt_username = "work2";
const char* mqtt_password = "Cloud11051961";
const int   mqtt_port     = 8883;

WiFiClientSecure espClient;
PubSubClient client(espClient);


unsigned long lastMsg = 0;
int counter = 0;

void setup() {
  Serial.begin(115200);

  
  WiFi.begin(ssid, password);
  while (WiFi.status() != WL_CONNECTED) {
    delay(500);
    Serial.println("Connecting to WiFi...");
  }
  Serial.println("Connected to the WiFi network");

  espClient.setInsecure();

  client.setServer(mqtt_broker, mqtt_port);
  client.setCallback(callback);

  while (!client.connected()) {
    String client_id = "esp8266-client-";
    client_id += String(WiFi.macAddress());

    Serial.printf("The client %s connects to the MQTT broker\n", client_id.c_str());

    if (client.connect(client_id.c_str(), mqtt_username, mqtt_password)) {
      Serial.println("HiveMQ Cloud MQTT broker connected");
    } else {
      Serial.print("failed with state ");
      Serial.println(client.state());
      delay(2000);
    }
  }

  client.subscribe(topic);
}

void callback(char* topic, byte* payload, unsigned int length) {
  Serial.print("Message arrived in topic: ");
  Serial.println(topic);

  Serial.print("Message: ");
  for (int i = 0; i < length; i++) {
    Serial.print((char)payload[i]);
  }
  Serial.println();
  Serial.println("-----------------------");
}

void loop() {
  client.loop();

  unsigned long now = millis();
  if (now - lastMsg > 5000) {
    lastMsg = now;

    counter++;
    String msg = "ESP message #" + String(counter);

    client.publish(topic, msg.c_str());
    Serial.println("Sent: " + msg);
  }
}
