From 525020109c5058b587c1296ac15ea8df245339e1 Mon Sep 17 00:00:00 2001 From: GhassanYusuf Date: Sun, 8 Jun 2025 13:01:54 +0300 Subject: [PATCH] first upload --- mqtt_nodered.ino | 104 +++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 104 insertions(+) create mode 100644 mqtt_nodered.ino diff --git a/mqtt_nodered.ino b/mqtt_nodered.ino new file mode 100644 index 0000000..2dd856d --- /dev/null +++ b/mqtt_nodered.ino @@ -0,0 +1,104 @@ + #include + #include + + // 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'."); + } + + } \ No newline at end of file