Skip to content

Instantly share code, notes, and snippets.

@structure7
Created June 13, 2017 12:25
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 structure7/442cbc6ad7135b043e34a69448b3e5e2 to your computer and use it in GitHub Desktop.
Save structure7/442cbc6ad7135b043e34a69448b3e5e2 to your computer and use it in GitHub Desktop.
#include <SimpleTimer.h>
#include <ESP8266WiFi.h>
#include <PubSubClient.h>
extern "C" {
uint16 readvdd33(void);
}
const char* ssid = "ssid";
const char* password = "pw";
const char* mqtt_server = "serverip";
const int gate = 5; // Mosfet gate on WeMos D1 Mini pin D1
WiFiClient espClient;
PubSubClient client(espClient);
char msg[50];
SimpleTimer timer;
void setup() {
pinMode(gate, OUTPUT);
digitalWrite(gate, LOW);
Serial.begin(9600);
setup_wifi();
client.setServer(mqtt_server, 1883);
}
void setup_wifi() {
delay(10);
// We start by connecting to a WiFi network
Serial.println();
Serial.print("Connecting to ");
Serial.println(ssid);
WiFi.begin(ssid, password);
while (WiFi.status() != WL_CONNECTED) {
delay(500);
Serial.print(".");
}
Serial.println("");
Serial.println("WiFi connected");
Serial.println("IP address: ");
Serial.println(WiFi.localIP());
timer.setTimeout(500L, mqttPub);
timer.setInterval(30000L, shutDown); // Shuts down the unit if it can't connect after 30 seconds
}
void loop() {
if (!client.connected()) {
reconnect();
}
client.loop();
timer.run();
}
void mqttPub() {
float vdd = readvdd33() / 1000.0;
String mailNotify = String("{\"body\": \"You've got mail! (") + vdd + "v)\"}";
Serial.println(String("You've got mail! (") + vdd + ")");
mailNotify.toCharArray(msg, 50);
client.publish("house/mailbox", msg);
timer.setTimeout(1000L, shutDown);
}
void reconnect() {
// Loop until we're reconnected
while (!client.connected()) {
Serial.print("Attempting MQTT connection...");
// Attempt to connect
if (client.connect("ESP8266Client")) {
Serial.println("connected");
// Once connected, publish an announcement...
client.publish("outTopic", "hello world");
// ... and resubscribe
client.subscribe("inTopic");
} else {
Serial.print("failed, rc=");
Serial.print(client.state());
Serial.println(" try again in 5 seconds");
// Wait 5 seconds before retrying
delay(5000);
}
}
}
void shutDown() {
Serial.println("Shut down");
digitalWrite(gate, HIGH);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment