99 lines
2.3 KiB
C++
99 lines
2.3 KiB
C++
// Include the esp wifi lib
|
|
#include <ESP8266WiFi.h>
|
|
// Include the mqtt client lib
|
|
#include <PubSubClient.h>
|
|
|
|
// Include the settings.h.
|
|
#include "window_control_settings.h"
|
|
|
|
#define buzzer 2
|
|
#define motorForward 1
|
|
#define motorReverse 0
|
|
#define sense 3
|
|
|
|
WiFiClient espClient;
|
|
PubSubClient client;
|
|
|
|
void setup() {
|
|
setup_wifi();
|
|
client.setClient(espClient);
|
|
client.setServer(MQTT_SERVER, MQTT_PORT);
|
|
client.setCallback(callback);
|
|
|
|
// Initalize some pins!
|
|
// Initalize buzzer pin
|
|
pinMode(buzzer, OUTPUT);
|
|
digitalWrite(buzzer, LOW);
|
|
}
|
|
|
|
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(buzzer, 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(buzzer, 2000, 500);
|
|
delay(1000);
|
|
}
|