Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- /********* Pleasedontcode.com **********
- Pleasedontcode thanks you for automatic code generation! Enjoy your code!
- - Terms and Conditions:
- You have a non-exclusive, revocable, worldwide, royalty-free license
- for personal and commercial use. Attribution is optional; modifications
- are allowed, but you're responsible for code maintenance. We're not
- liable for any loss or damage. For full terms,
- please visit pleasedontcode.com/termsandconditions.
- - Project: # WiFi Relays
- - Version: 003
- - Source Code NOT compiled for: ESP32 DevKit V1
- - Source Code created on: 2026-03-09 05:17:30
- ********* Pleasedontcode.com **********/
- /****** SYSTEM REQUIREMENTS *****/
- /****** SYSTEM REQUIREMENT 1 *****/
- /* Control 8 relay outputs independently via GPIO */
- /* pins. Each relay can be turned ON or OFF */
- /* individually. */
- /****** SYSTEM REQUIREMENT 2 *****/
- /* Initialize all 8 relay pins at startup and set */
- /* them to LOW (OFF) state. */
- /****** SYSTEM REQUIREMENT 3 *****/
- /* Provide relay control functions to toggle each */
- /* relay between ON and OFF states. */
- /****** SYSTEM REQUIREMENT 4 *****/
- /* Enable WiFi connectivity on ESP32 to connect to */
- /* home network. Support WiFi credential */
- /* configuration. */
- /****** SYSTEM REQUIREMENT 5 *****/
- /* Connect to MQTT broker and subscribe to relay */
- /* control topics to receive ON/OFF commands */
- /* remotely. */
- /****** SYSTEM REQUIREMENT 6 *****/
- /* Publish relay state changes to MQTT broker so */
- /* other IoT devices can monitor relay status in */
- /* real-time. */
- /****** SYSTEM REQUIREMENT 7 *****/
- /* Implement MQTT reconnection logic to automatically */
- /* reconnect if broker connection is lost. */
- /****** END SYSTEM REQUIREMENTS *****/
- /* START CODE */
- /****** DEFINITION OF LIBRARIES *****/
- #include <MQUnifiedsensor.h>
- #include <WiFi.h>
- #include <PubSubClient.h>
- /****** WIFI AND MQTT CONFIGURATION CONSTANTS *****/
- // WiFi network credentials
- const char* WIFI_SSID = "YOUR_SSID";
- const char* WIFI_PASSWORD = "YOUR_PASSWORD";
- // MQTT broker configuration
- const char* MQTT_BROKER = "broker.hivemq.com";
- const int MQTT_PORT = 1883;
- const char* MQTT_CLIENT_ID = "ESP32_Relay_Controller";
- const char* MQTT_USERNAME = "";
- const char* MQTT_PASSWORD = "";
- // MQTT topic base path
- const char* MQTT_BASE_TOPIC = "home/relays";
- const char* MQTT_RELAY_CONTROL_TOPIC_BASE = "home/relays/relay";
- const char* MQTT_RELAY_STATE_TOPIC_BASE = "home/relays/state/relay";
- // Reconnection timing constants
- const unsigned long WIFI_RECONNECT_INTERVAL = 5000;
- const unsigned long MQTT_RECONNECT_INTERVAL = 5000;
- const unsigned long MQTT_KEEPALIVE_INTERVAL = 60000;
- /****** FUNCTION PROTOTYPES *****/
- void setup(void);
- void loop(void);
- void initializeRelayPins(void);
- void relayON(uint8_t relayNumber);
- void relayOFF(uint8_t relayNumber);
- void relayToggle(uint8_t relayNumber);
- void initializeWiFi(void);
- void checkWiFiConnection(void);
- void initializeMQTT(void);
- void checkMQTTConnection(void);
- void mqttCallback(char* topic, byte* payload, unsigned int length);
- void publishRelayState(uint8_t relayNumber);
- void publishAllRelayStates(void);
- void handleMQTTMessage(char* topic, byte* payload, unsigned int length);
- void subscribeToAllRelayTopics(void);
- /***** DEFINITION OF DIGITAL INPUT PINS *****/
- const uint8_t RelayModule8Ch_MQ309A_DOUT_PIN_D4 = 4;
- /***** DEFINITION OF ANALOG INPUT PINS *****/
- const uint8_t RelayModule8Ch_MQ309A_AOUT_PIN_D32 = 32;
- /***** DEFINITION OF RELAY CONTROL PINS *****/
- // SYSTEM REQUIREMENT 1: Control 8 relay outputs independently via GPIO pins
- // Relay pins for ESP32 DevKit V1
- const uint8_t RELAY_PIN_1 = 12;
- const uint8_t RELAY_PIN_2 = 13;
- const uint8_t RELAY_PIN_3 = 14;
- const uint8_t RELAY_PIN_4 = 15;
- const uint8_t RELAY_PIN_5 = 16;
- const uint8_t RELAY_PIN_6 = 17;
- const uint8_t RELAY_PIN_7 = 18;
- const uint8_t RELAY_PIN_8 = 19;
- // Array to store relay pins for easier management
- const uint8_t relayPins[8] = {
- RELAY_PIN_1, RELAY_PIN_2, RELAY_PIN_3, RELAY_PIN_4,
- RELAY_PIN_5, RELAY_PIN_6, RELAY_PIN_7, RELAY_PIN_8
- };
- // Array to store relay states
- uint8_t relayStates[8] = {LOW, LOW, LOW, LOW, LOW, LOW, LOW, LOW};
- /****** WIFI AND MQTT CLIENT INSTANCES *****/
- WiFiClient espClient;
- PubSubClient mqttClient(espClient);
- /****** TIMING VARIABLES FOR RECONNECTION LOGIC *****/
- unsigned long lastWiFiCheckTime = 0;
- unsigned long lastMQTTCheckTime = 0;
- unsigned long lastMQTTKeepAliveTime = 0;
- /****** DEFINITION OF LIBRARIES CLASS INSTANCES *****/
- void setup(void)
- {
- // Serial communication initialization for debugging
- Serial.begin(115200);
- delay(100);
- Serial.println("\n\nStarting Relay Controller with IoT Functionality...");
- // Initialize MQ309A sensor pins
- pinMode(RelayModule8Ch_MQ309A_DOUT_PIN_D4, INPUT_PULLUP);
- pinMode(RelayModule8Ch_MQ309A_AOUT_PIN_D32, INPUT);
- // SYSTEM REQUIREMENT 2: Initialize all 8 relay pins at startup
- // and set them to LOW (OFF) state
- initializeRelayPins();
- // Initialize WiFi connectivity
- // SYSTEM REQUIREMENT 4: Enable WiFi connectivity on ESP32
- initializeWiFi();
- // Initialize MQTT client and configuration
- // SYSTEM REQUIREMENT 5: Connect to MQTT broker
- initializeMQTT();
- Serial.println("System initialized successfully");
- Serial.println("All 8 relays are set to OFF state");
- Serial.println("WiFi and MQTT initialization in progress...");
- }
- void loop(void)
- {
- // Check WiFi connection status and reconnect if needed
- // SYSTEM REQUIREMENT 7: Implement MQTT reconnection logic
- checkWiFiConnection();
- // Check MQTT connection status and reconnect if needed
- checkMQTTConnection();
- // Maintain MQTT connection
- if (mqttClient.connected())
- {
- mqttClient.loop();
- }
- // Small delay to prevent overwhelming the MCU
- delay(10);
- }
- /****** RELAY CONTROL FUNCTIONS *****/
- // SYSTEM REQUIREMENT 2: Initialize all 8 relay pins at startup
- // and set them to LOW (OFF) state
- void initializeRelayPins(void)
- {
- // Configure all 8 relay pins as OUTPUT and set to LOW (OFF)
- for (uint8_t i = 0; i < 8; i++)
- {
- pinMode(relayPins[i], OUTPUT);
- digitalWrite(relayPins[i], LOW);
- relayStates[i] = LOW;
- }
- Serial.println("All relay pins initialized to LOW (OFF) state:");
- for (uint8_t i = 0; i < 8; i++)
- {
- Serial.print("Relay ");
- Serial.print(i + 1);
- Serial.print(" (GPIO ");
- Serial.print(relayPins[i]);
- Serial.println(") = OFF");
- }
- }
- // SYSTEM REQUIREMENT 3: Provide relay control functions to toggle
- // each relay between ON and OFF states
- // Function to turn ON a specific relay (1-8)
- void relayON(uint8_t relayNumber)
- {
- // Validate relay number (1-8)
- if (relayNumber < 1 || relayNumber > 8)
- {
- Serial.print("Error: Invalid relay number ");
- Serial.println(relayNumber);
- return;
- }
- // Convert relay number (1-8) to array index (0-7)
- uint8_t index = relayNumber - 1;
- // Set relay to HIGH (ON)
- digitalWrite(relayPins[index], HIGH);
- relayStates[index] = HIGH;
- Serial.print("Relay ");
- Serial.print(relayNumber);
- Serial.print(" (GPIO ");
- Serial.print(relayPins[index]);
- Serial.println(") turned ON");
- // SYSTEM REQUIREMENT 6: Publish relay state changes to MQTT broker
- publishRelayState(relayNumber);
- }
- // SYSTEM REQUIREMENT 3: Provide relay control functions to toggle
- // each relay between ON and OFF states
- // Function to turn OFF a specific relay (1-8)
- void relayOFF(uint8_t relayNumber)
- {
- // Validate relay number (1-8)
- if (relayNumber < 1 || relayNumber > 8)
- {
- Serial.print("Error: Invalid relay number ");
- Serial.println(relayNumber);
- return;
- }
- // Convert relay number (1-8) to array index (0-7)
- uint8_t index = relayNumber - 1;
- // Set relay to LOW (OFF)
- digitalWrite(relayPins[index], LOW);
- relayStates[index] = LOW;
- Serial.print("Relay ");
- Serial.print(relayNumber);
- Serial.print(" (GPIO ");
- Serial.print(relayPins[index]);
- Serial.println(") turned OFF");
- // SYSTEM REQUIREMENT 6: Publish relay state changes to MQTT broker
- publishRelayState(relayNumber);
- }
- // SYSTEM REQUIREMENT 3: Provide relay control functions to toggle
- // each relay between ON and OFF states
- // Function to toggle a specific relay (1-8)
- void relayToggle(uint8_t relayNumber)
- {
- // Validate relay number (1-8)
- if (relayNumber < 1 || relayNumber > 8)
- {
- Serial.print("Error: Invalid relay number ");
- Serial.println(relayNumber);
- return;
- }
- // Convert relay number (1-8) to array index (0-7)
- uint8_t index = relayNumber - 1;
- // Toggle relay state
- if (relayStates[index] == LOW)
- {
- digitalWrite(relayPins[index], HIGH);
- relayStates[index] = HIGH;
- Serial.print("Relay ");
- Serial.print(relayNumber);
- Serial.print(" (GPIO ");
- Serial.print(relayPins[index]);
- Serial.println(") toggled to ON");
- }
- else
- {
- digitalWrite(relayPins[index], LOW);
- relayStates[index] = LOW;
- Serial.print("Relay ");
- Serial.print(relayNumber);
- Serial.print(" (GPIO ");
- Serial.print(relayPins[index]);
- Serial.println(") toggled to OFF");
- }
- // SYSTEM REQUIREMENT 6: Publish relay state changes to MQTT broker
- publishRelayState(relayNumber);
- }
- /****** WIFI CONNECTIVITY FUNCTIONS *****/
- // SYSTEM REQUIREMENT 4: Enable WiFi connectivity on ESP32 to connect to home network
- // Initialize WiFi connection with network credentials
- void initializeWiFi(void)
- {
- Serial.println("\n--- WiFi Initialization ---");
- Serial.print("Connecting to WiFi SSID: ");
- Serial.println(WIFI_SSID);
- // Set WiFi mode to station mode
- WiFi.mode(WIFI_STA);
- // Start WiFi connection with credentials
- WiFi.begin(WIFI_SSID, WIFI_PASSWORD);
- // Wait for connection with timeout
- int connectionAttempts = 0;
- const int maxAttempts = 20;
- while (WiFi.status() != WL_CONNECTED && connectionAttempts < maxAttempts)
- {
- delay(500);
- Serial.print(".");
- connectionAttempts++;
- }
- if (WiFi.status() == WL_CONNECTED)
- {
- Serial.println("\nWiFi connected successfully!");
- Serial.print("IP Address: ");
- Serial.println(WiFi.localIP());
- Serial.print("Signal Strength: ");
- Serial.print(WiFi.RSSI());
- Serial.println(" dBm");
- }
- else
- {
- Serial.println("\nWiFi connection failed!");
- Serial.println("Will attempt to reconnect automatically...");
- }
- }
- // Check WiFi connection and attempt reconnection if disconnected
- void checkWiFiConnection(void)
- {
- unsigned long currentTime = millis();
- // Check WiFi status at regular intervals
- if (currentTime - lastWiFiCheckTime >= WIFI_RECONNECT_INTERVAL)
- {
- lastWiFiCheckTime = currentTime;
- if (WiFi.status() != WL_CONNECTED)
- {
- Serial.println("WiFi connection lost. Attempting to reconnect...");
- WiFi.reconnect();
- }
- }
- }
- /****** MQTT FUNCTIONS *****/
- // SYSTEM REQUIREMENT 5: Connect to MQTT broker and subscribe to relay control topics
- // Initialize MQTT client and set broker connection parameters
- void initializeMQTT(void)
- {
- Serial.println("\n--- MQTT Initialization ---");
- // Set MQTT broker server and port
- mqttClient.setServer(MQTT_BROKER, MQTT_PORT);
- // Set callback function for incoming MQTT messages
- mqttClient.setCallback(mqttCallback);
- // Configure buffer sizes for topic and payload handling
- mqttClient.setBufferSize(512);
- Serial.print("MQTT Broker: ");
- Serial.print(MQTT_BROKER);
- Serial.print(":");
- Serial.println(MQTT_PORT);
- Serial.println("MQTT initialization complete. Will connect when WiFi is available.");
- }
- // Check MQTT connection and attempt reconnection if disconnected
- void checkMQTTConnection(void)
- {
- unsigned long currentTime = millis();
- // Check MQTT connection status
- if (!mqttClient.connected())
- {
- // Try to reconnect at regular intervals
- if (currentTime - lastMQTTCheckTime >= MQTT_RECONNECT_INTERVAL)
- {
- lastMQTTCheckTime = currentTime;
- // Only attempt MQTT connection if WiFi is connected
- if (WiFi.status() == WL_CONNECTED)
- {
- Serial.println("Attempting MQTT connection...");
- // Create MQTT client ID with unique identifier
- String clientId = String(MQTT_CLIENT_ID) + "_" + String(ESP.getChipId(), HEX);
- // Attempt to connect to MQTT broker with credentials if provided
- boolean connected = false;
- if (strlen(MQTT_USERNAME) > 0)
- {
- connected = mqttClient.connect(
- clientId.c_str(),
- MQTT_USERNAME,
- MQTT_PASSWORD
- );
- }
- else
- {
- connected = mqttClient.connect(clientId.c_str());
- }
- if (connected)
- {
- Serial.println("MQTT connected successfully!");
- Serial.print("Client ID: ");
- Serial.println(clientId);
- // Subscribe to all relay control topics
- // SYSTEM REQUIREMENT 5: Subscribe to relay control topics
- subscribeToAllRelayTopics();
- // Publish all relay states on connection
- // SYSTEM REQUIREMENT 6: Publish relay state changes
- publishAllRelayStates();
- }
- else
- {
- Serial.print("MQTT connection failed, rc=");
- Serial.println(mqttClient.state());
- }
- }
- else
- {
- Serial.println("WiFi not connected. Skipping MQTT connection attempt.");
- }
- }
- }
- else
- {
- // Keep MQTT connection alive by sending keepalive message periodically
- if (currentTime - lastMQTTKeepAliveTime >= MQTT_KEEPALIVE_INTERVAL)
- {
- lastMQTTKeepAliveTime = currentTime;
- // The PubSubClient library handles PINGREQ automatically, no manual action needed
- }
- }
- }
- // Callback function for incoming MQTT messages
- // SYSTEM REQUIREMENT 5: Connect to MQTT broker and subscribe to relay control topics
- // to receive ON/OFF commands remotely
- void mqttCallback(char* topic, byte* payload, unsigned int length)
- {
- Serial.print("MQTT Message received on topic: ");
- Serial.println(topic);
- // Handle received MQTT message
- handleMQTTMessage(topic, payload, length);
- }
- // Process incoming MQTT message and control relays accordingly
- void handleMQTTMessage(char* topic, byte* payload, unsigned int length)
- {
- // Convert payload to string
- String payloadStr = "";
- for (unsigned int i = 0; i < length; i++)
- {
- payloadStr += (char)payload[i];
- }
- Serial.print("Payload: ");
- Serial.println(payloadStr);
- // Parse topic and extract relay number
- String topicStr = String(topic);
- // Check if topic is a relay control topic
- if (topicStr.startsWith("home/relays/relay") && topicStr.endsWith("/control"))
- {
- // Extract relay number from topic
- // Topic format: home/relays/relay<N>/control
- int startIndex = String("home/relays/relay").length();
- int endIndex = topicStr.indexOf("/control");
- if (startIndex < endIndex)
- {
- String relayNumStr = topicStr.substring(startIndex, endIndex);
- uint8_t relayNumber = relayNumStr.toInt();
- // Validate relay number
- if (relayNumber >= 1 && relayNumber <= 8)
- {
- // Process command
- if (payloadStr == "ON" || payloadStr == "on" || payloadStr == "1")
- {
- Serial.print("Turning ON relay ");
- Serial.println(relayNumber);
- relayON(relayNumber);
- }
- else if (payloadStr == "OFF" || payloadStr == "off" || payloadStr == "0")
- {
- Serial.print("Turning OFF relay ");
- Serial.println(relayNumber);
- relayOFF(relayNumber);
- }
- else if (payloadStr == "TOGGLE" || payloadStr == "toggle")
- {
- Serial.print("Toggling relay ");
- Serial.println(relayNumber);
- relayToggle(relayNumber);
- }
- }
- }
- }
- }
- // Subscribe to all relay control topics
- void subscribeToAllRelayTopics(void)
- {
- // Subscribe to individual relay control topics (relay1 to relay8)
- for (uint8_t i = 1; i <= 8; i++)
- {
- String topic = String("home/relays/relay") + String(i) + String("/control");
- if (mqttClient.subscribe(topic.c_str()))
- {
- Serial.print("Subscribed to: ");
- Serial.println(topic);
- }
- else
- {
- Serial.print("Failed to subscribe to: ");
- Serial.println(topic);
- }
- }
- // Subscribe to broadcast control topic for all relays
- if (mqttClient.subscribe("home/relays/all/control"))
- {
- Serial.println("Subscribed to: home/relays/all/control");
- }
- }
- // Publish the current state of a specific relay
- // SYSTEM REQUIREMENT 6: Publish relay state changes to MQTT broker
- // so other IoT devices can monitor relay status in real-time
- void publishRelayState(uint8_t relayNumber)
- {
- // Validate relay number
- if (relayNumber < 1 || relayNumber > 8)
- {
- return;
- }
- // Only publish if MQTT is connected
- if (!mqttClient.connected())
- {
- Serial.println("MQTT not connected. State not published.");
- return;
- }
- // Build topic
- String topic = String("home/relays/state/relay") + String(relayNumber);
- // Get relay state
- uint8_t index = relayNumber - 1;
- String state = (relayStates[index] == HIGH) ? "ON" : "OFF";
- // Publish state
- if (mqttClient.publish(topic.c_str(), state.c_str(), true))
- {
- Serial.print("Published relay ");
- Serial.print(relayNumber);
- Serial.print(" state: ");
- Serial.print(state);
- Serial.print(" to topic: ");
- Serial.println(topic);
- }
- else
- {
- Serial.print("Failed to publish relay state for relay ");
- Serial.println(relayNumber);
- }
- }
- // Publish the current state of all relays
- void publishAllRelayStates(void)
- {
- Serial.println("Publishing all relay states...");
- for (uint8_t i = 1; i <= 8; i++)
- {
- publishRelayState(i);
- delay(100);
- }
- Serial.println("All relay states published.");
- }
- /* END CODE */
Advertisement
Add Comment
Please, Sign In to add comment