#include <WiFi.h>
#include <PubSubClient.h>
const char* ssid = "J7 pro";
const char* password = "fzao2408";
/* Details from the instance created */
const char* mqttServer = "m16.cloudmqtt.com";
const int mqttPort = 18215;
const char* mqttUser = "ofmydmjh";
const char* mqttPassword = "c5g0IEjTCGRn";
WiFiClient espClient;
PubSubClient client(espClient);
void setup(void)
{
Serial.begin(115200);
WiFi.begin(ssid, password);
/* Connecting ESP8266 to WiFi */
while (WiFi.status() != WL_CONNECTED)
{
delay(500);
Serial.write('.');
}
Serial.println("Connected to the WiFi network");
client.setServer(mqttServer, mqttPort);
client.setCallback(callback);
/* Connecting to CloudMqtt */
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);
}
}
/* Sending message to Topic "test1" */
client.publish("Sub", "Hello from RDL_IOT");
client.subscribe("test"); //Receives message sent to the topic "test"
}
/* This function is used to print the incoming data sent to the topic "test" */
void callback(char* topic, byte* payload, unsigned int length)
{
uint8_t s;
Serial.print("Message arrived in topic: ");
Serial.println(topic);
Serial.print("Message:");
for (int i = 0; i < length; i++)
{
s= payload[i];
Serial.write(s);
}
}
void loop(void)
{
client.loop();
}