// Include the esp wifi lib #include // Include the mqtt client lib #include // Include the settings.h. #include "window_control_settings.h" #define window_name "window_0" #define mqtt_root "home/upstairs_lab/actuators/" window_name #define in_topic "/testing/in" #define out_topic "/testing/out" // Replace by 2 if you aren't enable to use Serial Monitor... Don't forget to Rewire R1 to GPIO2! #define in_led 2 WiFiClient espClient; PubSubClient client; void setup() { Serial.begin(115200); setup_wifi(); client.setClient(espClient); client.setServer(MQTT_SERVER, MQTT_PORT); client.setCallback(callback); // initialize digital pin LED_BUILTIN as an output. pinMode(in_led, OUTPUT); digitalWrite(in_led, HIGH); } void setup_wifi() { delay(10); // We start by connecting to a WiFi network Serial.println(); WiFi.hostname("ESP-" window_name); Serial.print("Connecting to "); Serial.println(WIFI_SSID); WiFi.begin(WIFI_SSID, WIFI_PASS); while (WiFi.status() != WL_CONNECTED) { delay(950); tone(2, 1200, 50); Serial.println("Not yet connected.. Waiting 1s to check again.."); } Serial.println(""); Serial.println("WiFi connected"); Serial.println("IP address: "); Serial.println(WiFi.localIP()); } void reconnect() { // Loop until we're reconnected while (!client.connected()) { Serial.print("Attempting MQTT connection..."); // Attempt to connect if (client.connect("ESP8266Client", MQTT_USER, MQTT_PASS)) { Serial.println("connected"); } else { Serial.print("failed, rc="); Serial.print(client.state()); Serial.println(" try again in 5 seconds"); // Wait 5 seconds before retrying delay(5000); } } } void callback(char* topic, byte* payload, unsigned int length) { Serial.print("Message arrived ["); Serial.print(topic); Serial.print("] "); for (int i = 0; i < length; i++) { char receivedChar = (char)payload[i]; Serial.print(receivedChar); if (receivedChar == '0') digitalWrite(in_led, LOW); if (receivedChar == '1') digitalWrite(in_led, HIGH); } Serial.println(); } void loop() { // If we ever disconnect, reconnect. if (!client.connected()) { reconnect(); } // Run the client loop client.loop(); // Publishes a random 0 and 1 like someone switching off and on randomly (random(2)) client.publish(mqtt_root "/random", String(random(2)).c_str(), true); delay(1000); client.subscribe(mqtt_root "/in"); tone(2, 2000, 500); delay(1000); }