104 lines
2.3 KiB
C++
104 lines
2.3 KiB
C++
#include <WiFi.h>
|
|
#include <PubSubClient.h>
|
|
|
|
// Wi-Fi settings
|
|
const char* ssid = "Guest WiFi";
|
|
const char* password = "";
|
|
|
|
// MQTT server settings
|
|
const char* mqtt_server = "87.237.194.228";
|
|
const int mqtt_port = 1883;
|
|
|
|
WiFiClient espClient;
|
|
PubSubClient client(espClient);
|
|
|
|
// Callback function to handle incoming messages
|
|
void callback(char* topic, byte* payload, unsigned int length) {
|
|
|
|
Serial.print("Message arrived on topic: ");
|
|
Serial.println(topic);
|
|
|
|
Serial.print("Message: ");
|
|
String message;
|
|
for (unsigned int i = 0; i < length; i++) {
|
|
message += (char)payload[i];
|
|
}
|
|
Serial.println(message);
|
|
|
|
message.trim();
|
|
// You can add code here to handle the message content
|
|
// For example, control GPIO pins based on received commands
|
|
|
|
if(message == "on") {
|
|
Serial.println("Light On");
|
|
} else {
|
|
Serial.println("Light Off");
|
|
}
|
|
|
|
}
|
|
|
|
void setup_wifi() {
|
|
|
|
delay(10);
|
|
Serial.println();
|
|
Serial.print("Connecting to ");
|
|
Serial.println(ssid);
|
|
|
|
WiFi.mode(WIFI_STA);
|
|
WiFi.begin(ssid, password);
|
|
|
|
while (WiFi.status() != WL_CONNECTED) {
|
|
delay(1000);
|
|
Serial.print(".");
|
|
}
|
|
|
|
Serial.println("\nWiFi connected!");
|
|
Serial.print("IP address: ");
|
|
Serial.println(WiFi.localIP());
|
|
|
|
}
|
|
|
|
void reconnect() {
|
|
|
|
while (!client.connected()) {
|
|
Serial.print("Attempting MQTT connection...");
|
|
if (client.connect("ESP32C6Client")) {
|
|
Serial.println("connected");
|
|
// Subscribe to the topic to receive messages
|
|
client.subscribe("Outgoing");
|
|
} else {
|
|
Serial.print("failed, rc=");
|
|
Serial.print(client.state());
|
|
Serial.println(" try again in 5 seconds");
|
|
delay(5000);
|
|
}
|
|
}
|
|
|
|
}
|
|
|
|
void setup() {
|
|
|
|
Serial.begin(115200);
|
|
setup_wifi();
|
|
client.setServer(mqtt_server, mqtt_port);
|
|
client.setCallback(callback); // Set callback for incoming messages
|
|
|
|
}
|
|
|
|
void loop() {
|
|
|
|
if(!client.connected()) {
|
|
reconnect();
|
|
}
|
|
client.loop();
|
|
|
|
// Publish a message to "outgoing" every 10 seconds
|
|
static unsigned long lastMsg = 0;
|
|
unsigned long now = millis();
|
|
if (now - lastMsg > 10000) {
|
|
lastMsg = now;
|
|
client.publish("Incoming", "Ping from ESP32-C6!");
|
|
Serial.println("Message sent to 'Incoming'.");
|
|
}
|
|
|
|
} |