Untitled

mail@pastecode.io avatar
unknown
plain_text
a month ago
2.3 kB
1
Indexable
Never
#include <ESP8266WiFi.h>
#include <PubSubClient.h>

const char* ssid = "admin";
const char* password = "12345689";
const char* mqtt_server = "1dbffb0b093d45fdb5a1feeee3f2a23c.s1.eu.hivemq.cloud";
const int mqtt_port = 8883;
const char* mqtt_username = "20521266";
const char* mqtt_password = "Z7hKqHW@8AH4QfN";

WiFiClientSecure espClient;
PubSubClient client(espClient);

const int ledPin = D8;  // LED connected to GPIO pin D8

void setup_wifi() {
  delay(10);
  Serial.println();
  Serial.print("Connecting to ");
  Serial.println(ssid);

  WiFi.begin(ssid, password);

  while (WiFi.status() != WL_CONNECTED) {
    delay(500);
    Serial.print(".");
  }

  Serial.println("");
  Serial.println("WiFi connected");
  Serial.println("IP address: ");
  Serial.println(WiFi.localIP());
}

void callback(char* topic, byte* payload, unsigned int length) {
  Serial.print("Message arrived [");
  Serial.print(topic);
  Serial.print("] ");

  String message = "";
  for (int i = 0; i < length; i++) {
    message += (char)payload[i];
  }
  Serial.println(message);

  // If message is "ON", turn on the LED
  if (message.equals("ON")) {
    digitalWrite(ledPin, HIGH);
  }
  // If message is "OFF", turn off the LED
  else if (message.equals("OFF")) {
    digitalWrite(ledPin, LOW);
  }
}

void reconnect() {
  while (!client.connected()) {
    Serial.print("Attempting MQTT connection...");

    if (client.connect("ESP8266Client", mqtt_username, mqtt_password)) {
      Serial.println("connected");
      client.subscribe("tt21/20521266-19521468/check");
    } else {
      Serial.print("failed, rc=");
      Serial.print(client.state());
      Serial.println(" try again in 5 seconds");
      delay(3000);
    }
  }
}

void setup() {
  pinMode(ledPin, OUTPUT);
  Serial.begin(115200);
  setup_wifi();
  // Set MQTT server and port
  client.setServer(mqtt_server, mqtt_port);

  // Configure WiFiClientSecure to use SSL/TLS
  espClient.setInsecure(); // Replace with appropriate certificate handling

  // Attach WiFiClientSecure to PubSubClient
  client.setClient(espClient);

  // Callback function for incoming messages
  client.setCallback(callback);
}

void loop() {
  if (!client.connected()) {
    reconnect();
  }
  client.loop();
}
Leave a Comment