Skip to content

Instantly share code, notes, and snippets.

@kylejohnson
Created January 16, 2020 15:46
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save kylejohnson/3e0318c5eb19742fb673051db8b1477f to your computer and use it in GitHub Desktop.
Save kylejohnson/3e0318c5eb19742fb673051db8b1477f to your computer and use it in GitHub Desktop.
#include <WiFi.h>
#include <ESPmDNS.h>
#include <WiFiUdp.h>
#include <ArduinoOTA.h>
#include "DHT.h"
#include <PubSubClient.h>
#include <SimpleTimer.h> //https://github.com/jfturcot/SimpleTimer
//USER CONFIGURED SECTION START//
const char* ssid = "skynet_iot";
const char* password = "password!";
const char* mqtt_server = "192.168.11.16";
const int mqtt_port = 1883;
const char *mqtt_user = "garage";
const char *mqtt_pass = "garage";
const char *mqtt_client_name = "GarageMCU";
const char *willTopic = "checkIn/GarageMCU";
const int willQoS = 0;
const int willRetain = 1;
const char *willMessage = "offline";
const int dhtpin = 22;
#define dhttype DHT22
//USER CONFIGURED SECTION END//
// Pin definitions
const int RELAY_DOOR_1_PIN = 18;
const int RELAY_DOOR_2_PIN = 23;
const int SENSOR_DOOR_1_PIN = 5;
const int SENSOR_DOOR_2_PIN = 15;
const int SENSOR_GATE_PIN = 4;
// Pin definitions
bool Door1OldState = 1;
bool Door2OldState = 1;
bool GateOldState = 1;
char temperature[6];
char humidity[6];
DHT dht(dhtpin, dhttype);
WiFiClient espClient;
PubSubClient client(espClient);
SimpleTimer timer;
void setup_wifi() {
Serial.println();
Serial.print("Connecting to ");
Serial.print(ssid);
WiFi.begin(ssid, password);
while (WiFi.status() != WL_CONNECTED) {
delay(500);
Serial.print(".");
}
Serial.println("");
Serial.print("WiFi connected: ");
Serial.println(WiFi.localIP());
}
void callback(char* topic, byte* payload, unsigned int length) {
Serial.print("Message arrived [");
String newTopic = topic;
Serial.print(topic);
Serial.print("] ");
payload[length] = '\0';
String newPayload = String((char *)payload);
Serial.println(newPayload);
if (newTopic == "commands/GarageMCU/Door/1") {
if (newPayload == "toggle") {
pressButton(RELAY_DOOR_1_PIN);
}
}
if (newTopic == "commands/GarageMCU/Door/2") {
if (newPayload == "toggle") {
pressButton(RELAY_DOOR_2_PIN);
}
}
}
void pressButton(int door) {
// While closed, a button press will open
// While opening, a button press will stop
// While opened, a button press will close
// While closing, a button press will open
Serial.print("Toggling ");
Serial.println(door);
digitalWrite(door, LOW);
delay(100);
digitalWrite(door, HIGH);
}
void reconnect()
{
// Loop until we're reconnected
int retries = 0;
Serial.println(retries);
while (!client.connected()) {
if (retries < 15) {
Serial.print("Attempting MQTT connection...");
if (client.connect(mqtt_client_name, mqtt_user, mqtt_pass, willTopic, willQoS, willRetain, willMessage)) {
Serial.println("connected");
client.publish("checkIn/GarageMCU", "online", true);
client.subscribe("commands/GarageMCU/Door/+");
} else {
Serial.print("failed, rc=");
Serial.print(client.state());
Serial.println(" try again in 5 seconds");
retries++;
delay(5000);
}
}
if (retries > 14) {
ESP.restart();
}
}
}
void checkIn()
{
client.publish("checkIn/GarageMCU", "online", true);
}
void readDHT() {
float f = dht.readTemperature(true);
float h = dht.readHumidity();
if (isnan(h) || isnan(f)) {
Serial.println("Failed to read from DHT sensor!");
return;
}
Serial.println(f);
Serial.println(h);
dtostrf(f, 2, 2, temperature);
dtostrf(h, 2, 2, humidity);
// This should be influxdb
client.publish("environment/garage/temperature", temperature);
client.publish("environment/garage/humidity", humidity);
}
void getDoorState() {
bool Door1NewState = digitalRead(SENSOR_DOOR_1_PIN);
// Serial.println("Door 1");
// Serial.print("Old state: ");
// Serial.println(Door1OldState);
// Serial.print("New state: ");
// Serial.println(Door1NewState);
if (Door1NewState != Door1OldState && Door1NewState == 0) {
client.publish("state/GarageMCU/Door/1", "open", true);
Door1OldState = Door1NewState;
}
if (Door1NewState != Door1OldState && Door1NewState == 1) {
client.publish("state/GarageMCU/Door/1", "closed", true);
Door1OldState = Door1NewState;
}
bool Door2NewState = digitalRead(SENSOR_DOOR_2_PIN);
// Serial.println("Door 2");
// Serial.print("Old state: ");
// Serial.println(Door2OldState);
// Serial.print("New state: ");
// Serial.println(Door2NewState);
if (Door2NewState != Door2OldState && Door2NewState == 0) {
client.publish("state/GarageMCU/Door/2", "open", true);
Door2OldState = Door2NewState;
}
if (Door2NewState != Door2OldState && Door2NewState == 1) {
client.publish("state/GarageMCU/Door/2", "closed", true);
Door2OldState = Door2NewState;
}
bool GateNewState = digitalRead(SENSOR_GATE_PIN);
// Serial.println("Gate");
// Serial.print("Old state: ");
// Serial.println(GateOldState);
// Serial.print("New state: ");
// Serial.println(GateNewState);
if (GateNewState != GateOldState && GateNewState == 0) {
client.publish("state/GarageMCU/Gate", "open", true);
GateOldState = GateNewState;
}
if (GateNewState != GateOldState && GateNewState == 1) {
client.publish("state/GarageMCU/Gate", "closed", true);
GateOldState = GateNewState;
}
}
void setup() {
Serial.begin(115200);
pinMode(RELAY_DOOR_1_PIN, OUTPUT);
digitalWrite(RELAY_DOOR_1_PIN, HIGH);
pinMode(RELAY_DOOR_2_PIN, OUTPUT);
digitalWrite(RELAY_DOOR_2_PIN, HIGH);
pinMode(SENSOR_DOOR_1_PIN, INPUT_PULLUP);
pinMode(SENSOR_DOOR_2_PIN, INPUT_PULLUP);
pinMode(SENSOR_GATE_PIN, INPUT_PULLUP);
setup_wifi();
ArduinoOTA.setHostname("GarageMCU");
ArduinoOTA
.onStart([]() {
String type;
if (ArduinoOTA.getCommand() == U_FLASH)
type = "sketch";
else // U_SPIFFS
type = "filesystem";
// NOTE: if updating SPIFFS this would be the place to unmount SPIFFS using SPIFFS.end()
Serial.println("Start updating " + type);
})
.onEnd([]() {
Serial.println("\nEnd");
})
.onProgress([](unsigned int progress, unsigned int total) {
Serial.printf("Progress: %u%%\r", (progress / (total / 100)));
})
.onError([](ota_error_t error) {
Serial.printf("Error[%u]: ", error);
if (error == OTA_AUTH_ERROR) Serial.println("Auth Failed");
else if (error == OTA_BEGIN_ERROR) Serial.println("Begin Failed");
else if (error == OTA_CONNECT_ERROR) Serial.println("Connect Failed");
else if (error == OTA_RECEIVE_ERROR) Serial.println("Receive Failed");
else if (error == OTA_END_ERROR) Serial.println("End Failed");
});
ArduinoOTA.begin();
dht.begin();
client.setServer(mqtt_server, mqtt_port);
client.setCallback(callback);
timer.setInterval(60000, readDHT);
timer.setInterval(500, getDoorState);
}
void loop() {
if (!client.connected()) {
reconnect();
} else {
client.loop();
}
timer.run();
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment