Things/things.ino

404 lines
13 KiB
Arduino
Raw Normal View History

2016-02-23 10:12:04 +00:00
// based on example code from the used libraries
#include <FS.h> // this needs to be first, or it all crashes and burns...
2016-02-23 10:12:04 +00:00
extern "C" {
#include <user_interface.h>
}
#include <ESP8266WiFi.h> // https://github.com/esp8266/Arduino
#include <ESP8266WebServer.h>
#include <WiFiManager.h> // https://github.com/tzapu/WiFiManager
#include <DNSServer.h>
#include <Ticker.h>
#include <PubSubClient.h> // https://github.com/knolleary/pubsubclient
#include <DHT.h> // https://github.com/adafruit/DHT-sensor-library
#include <ArduinoJson.h> // https://github.com/bblanchon/ArduinoJson
2016-02-23 10:12:04 +00:00
2016-03-21 08:25:13 +00:00
#define HARDWARE_WITTY
2016-02-23 10:12:04 +00:00
// configure DHT sensor
#define DHTPIN D4 // what pin the DHT is connected to
//#define DHTTYPE DHT11 // DHT11
//#define DHTTYPE DHT21 // DHT21 (AM2301)
#define DHTTYPE DHT22 // DHT22 (AM2302)
2016-03-21 08:25:13 +00:00
#ifdef HARDWARE_WITTY
#define CONFIGPIN D2 // config-button is connected to this pin
#else
#define CONFIGPIN D3 // config-button is connected to this pin
#endif
#define RGBRED D8 // red led channel on witty module
#define RGBGRN D6 // green led channel on witty module
#define RGBBLU D7 // blue led channel on witty module
#define LDRPIN A0 // analog LDR input on witty module
2016-02-24 08:46:19 +00:00
// define default values here, overwritten by values from config.json
char mqtt_server[40];
char mqtt_port[6] = "1883";
char mqtt_topic[34] = "OutTopic";
2016-02-24 06:43:01 +00:00
// flag for saving data
bool shouldSaveConfig = false;
2016-02-24 06:43:01 +00:00
// callback notifying us of the need to save config
void saveConfigCallback() {
Serial.println("Should save config");
shouldSaveConfig = true;
}
2016-02-23 10:12:04 +00:00
// initialize modules
2016-02-24 08:05:35 +00:00
ESP8266WebServer http_server(80); // webserver
DHT dht(DHTPIN, DHTTYPE); // DHT sensor
Ticker ticker; // LED status
2016-02-23 10:12:04 +00:00
WiFiClient wifiClient;
2016-02-24 08:05:35 +00:00
PubSubClient mqtt_client(wifiClient);
2016-02-23 10:12:04 +00:00
2016-03-21 08:52:50 +00:00
bool dhtvalid = false; // indicate if measurement is valid
2016-02-23 10:12:04 +00:00
float humidity, temperature; // raw values from the sensor
float heatindex; // computed value from the sensor
char str_humidity[10], str_temperature[10]; // rounded values as strings
char str_heatindex[10]; // rounded value as string
unsigned long previousMillis = 0; // last sensor read
const long interval = 2000; // interval between readings
long lastMsg = 0;
// toggle LED state
void toggle_led() {
int state = digitalRead(BUILTIN_LED); // get the current state LED
digitalWrite(BUILTIN_LED, !state); // set the opposite state
}
// gets called when WiFiManager enters configuration mode
void configModeCallback (WiFiManager *myWiFiManager) {
Serial.println("Entered config mode");
Serial.println(WiFi.softAPIP());
Serial.println(myWiFiManager->getConfigPortalSSID());
2016-02-24 08:00:11 +00:00
ticker.attach(0.1, toggle_led); // toggle led faster
2016-02-23 10:12:04 +00:00
}
2016-02-24 08:00:11 +00:00
// compare float values
bool isEqual(float a, float b, float epsilon=0.001) {
2016-02-24 06:43:01 +00:00
return fabs(a - b) <= epsilon * fabs(a);
}
2016-02-24 08:00:11 +00:00
// concatenate MQTT topic prefix to individual topic
2016-02-24 07:43:44 +00:00
char* topic(const char* this_topic) {
static char topic[34];
strcpy(topic, mqtt_topic);
strcat(topic, "/");
strcat(topic, this_topic);
return topic;
}
2016-02-24 08:00:11 +00:00
// get values from DHT sensor
2016-02-23 10:12:04 +00:00
void read_sensor() {
// wait at least 2 seconds seconds between measurements
unsigned long currentMillis = millis();
if (currentMillis - previousMillis >= interval) {
previousMillis = currentMillis;
float previousHumidity = humidity;
float previousTemperature = temperature;
float previousHeatindex = heatindex;
humidity = dht.readHumidity(); // read humidity as a percent
temperature = dht.readTemperature(); // read temperature as Celsius
heatindex = dht.computeHeatIndex(temperature, humidity, false);
// check if any reads failed and exit early (to try again)
if (isnan(humidity) || isnan(temperature)) {
2016-03-21 08:52:50 +00:00
dhtvalid = false;
2016-02-23 10:12:04 +00:00
Serial.println("Failed to read from DHT sensor!");
2016-03-21 08:52:50 +00:00
strcpy(str_humidity, "invalid");
strcpy(str_temperature, "invalid");
strcpy(str_heatindex, "invalid");
2016-02-23 10:12:04 +00:00
return;
2016-03-21 08:52:50 +00:00
} else {
dhtvalid = true;
2016-02-23 10:12:04 +00:00
}
// convert the floats to strings and round to 2 decimal places
dtostrf(humidity, 1, 2, str_humidity);
dtostrf(temperature, 1, 2, str_temperature);
dtostrf(heatindex, 1, 2, str_heatindex);
if (!isEqual(humidity, previousHumidity)) {
2016-02-24 08:05:35 +00:00
mqtt_client.publish(topic("humidity"), str_humidity);
2016-02-23 10:12:04 +00:00
}
if (!isEqual(temperature, previousTemperature)) {
2016-02-24 08:05:35 +00:00
mqtt_client.publish(topic("temperature"), str_temperature);
2016-02-23 10:12:04 +00:00
}
if (!isEqual(heatindex, previousHeatindex)) {
2016-02-24 08:05:35 +00:00
mqtt_client.publish(topic("heatindex"), str_heatindex);
2016-02-23 10:12:04 +00:00
}
Serial.print("Humidity: ");
Serial.print(str_humidity);
Serial.print(" %\t");
Serial.print("Temperature: ");
Serial.print(str_temperature);
Serial.print(" °C\t");
Serial.print("Heat Index: ");
Serial.print(str_heatindex);
Serial.println(" °C");
}
}
2016-02-24 08:00:11 +00:00
// callback for MQTT, gets called if we receive a message
void mqtt_callback(char* topic, byte* payload, unsigned int length) {
char inData[length+1];
for(int i = 0; i < length; i++) {
inData[i] = (char)payload[i];
}
inData[length] = 0;
2016-02-23 10:12:04 +00:00
Serial.print("Message arrived [");
Serial.print(topic);
Serial.print("] ");
Serial.println(inData);
StaticJsonBuffer<200> jsonBuffer;
JsonObject& json = jsonBuffer.parseObject(inData);
analogWrite(RGBRED, json["red"]);
analogWrite(RGBGRN, json["green"]);
analogWrite(RGBBLU, json["blue"]);
2016-02-23 10:12:04 +00:00
}
2016-02-24 08:00:11 +00:00
// make sure we're connected to MQTT broker
void mqtt_reconnect() {
// loop until we're reconnected
2016-02-24 08:05:35 +00:00
while (!mqtt_client.connected()) {
2016-02-23 10:12:04 +00:00
Serial.print("Attempting MQTT connection...");
2016-02-24 08:00:11 +00:00
// attempt to connect
2016-02-24 08:05:35 +00:00
if (mqtt_client.connect(wifi_station_get_hostname(), topic("online"), MQTTQOS1, true, "0")) {
2016-02-23 10:12:04 +00:00
Serial.println("connected");
2016-02-24 08:00:11 +00:00
// once connected, publish an announcement...
2016-02-24 08:52:58 +00:00
mqtt_client.publish(topic("online"), "1", true);
2016-02-23 10:12:04 +00:00
// ... and resubscribe:
mqtt_client.subscribe("setrgb");
2016-02-23 10:12:04 +00:00
} else {
Serial.print("failed, rc=");
2016-02-24 08:05:35 +00:00
Serial.print(mqtt_client.state());
2016-02-23 10:12:04 +00:00
Serial.println(" try again in 5 seconds");
delay(5000);
}
}
}
2016-02-24 08:00:11 +00:00
// convert string to integer
2016-02-24 06:43:01 +00:00
int stringToNumber(String thisString) {
int i, value, length;
length = thisString.length();
char blah[(length + 1)];
for (i = 0; i < length; i++) {
blah[i] = thisString.charAt(i);
}
blah[i] = 0;
value = atoi(blah);
return value;
}
2016-02-23 10:12:04 +00:00
void setup() {
// put your setup code here, to run once:
Serial.begin(9600);
pinMode(BUILTIN_LED, OUTPUT); // set led pin as output
2016-02-24 08:46:19 +00:00
ticker.attach(0.5, toggle_led); // toggle led slowly during initialization
2016-02-23 10:12:04 +00:00
pinMode(RGBRED, OUTPUT);
pinMode(RGBGRN, OUTPUT);
pinMode(RGBBLU, OUTPUT);
pinMode(CONFIGPIN, INPUT); // flash-button on nodemcu
pinMode(LDRPIN, INPUT);
2016-02-24 08:00:11 +00:00
// clean FS, for testing
2016-02-24 06:43:01 +00:00
//SPIFFS.format();
2016-02-24 08:00:11 +00:00
// read configuration from FS json
2016-02-24 06:43:01 +00:00
Serial.println("mounting FS...");
if (SPIFFS.begin()) {
Serial.println("mounted file system");
if (SPIFFS.exists("/config.json")) {
2016-02-24 08:00:11 +00:00
// file exists, reading and loading
2016-02-24 06:43:01 +00:00
Serial.println("reading config file");
File configFile = SPIFFS.open("/config.json", "r");
if (configFile) {
Serial.println("opened config file");
size_t size = configFile.size();
2016-02-24 08:00:11 +00:00
// allocate a buffer to store contents of the file.
2016-02-24 06:43:01 +00:00
std::unique_ptr<char[]> buf(new char[size]);
configFile.readBytes(buf.get(), size);
DynamicJsonBuffer jsonBuffer;
JsonObject& json = jsonBuffer.parseObject(buf.get());
json.printTo(Serial);
if (json.success()) {
Serial.println("\nparsed json");
strcpy(mqtt_server, json["mqtt_server"]);
strcpy(mqtt_port, json["mqtt_port"]);
strcpy(mqtt_topic, json["mqtt_topic"]);
} else {
Serial.println("failed to load json config");
}
}
2016-02-24 06:43:01 +00:00
}
} else {
Serial.println("failed to mount FS");
}
2016-02-24 08:00:11 +00:00
// WiFiManager
// extra parameters to be configured
2016-02-24 06:43:01 +00:00
WiFiManagerParameter custom_mqtt_server("server", "mqtt server", mqtt_server, 40);
WiFiManagerParameter custom_mqtt_port("port", "mqtt port", mqtt_port, 5);
WiFiManagerParameter custom_mqtt_topic("topic", "mqtt topic", mqtt_topic, 32);
2016-02-24 08:00:11 +00:00
// local intialization
2016-02-23 10:12:04 +00:00
WiFiManager wifiManager;
// reset settings if config-button is pressed
if (!digitalRead(CONFIGPIN)) {
Serial.println("config-button pressed, resetting wifi settings");
wifiManager.resetSettings();
}
2016-02-23 10:12:04 +00:00
2016-02-24 08:00:11 +00:00
// set callback that gets called when connecting to previous WiFi fails, and enters Access Point mode
2016-02-23 10:12:04 +00:00
wifiManager.setAPCallback(configModeCallback);
2016-02-24 08:00:11 +00:00
// set config save notify callback
2016-02-24 06:43:01 +00:00
wifiManager.setSaveConfigCallback(saveConfigCallback);
2016-02-24 08:00:11 +00:00
// add all your parameters here
2016-02-24 06:43:01 +00:00
wifiManager.addParameter(&custom_mqtt_server);
wifiManager.addParameter(&custom_mqtt_port);
wifiManager.addParameter(&custom_mqtt_topic);
2016-02-24 08:00:11 +00:00
// fetches ssid and pass and tries to connect
// if it does not connect it starts an access point
2016-02-23 10:12:04 +00:00
if (!wifiManager.autoConnect()) {
Serial.println("failed to connect and hit timeout");
2016-02-24 08:00:11 +00:00
// reset and try again
2016-02-23 10:12:04 +00:00
ESP.reset();
delay(1000);
}
2016-02-24 08:00:11 +00:00
Serial.println("connected to WiFi");
2016-02-23 10:12:04 +00:00
ticker.detach();
digitalWrite(BUILTIN_LED, LOW);
2016-02-24 08:00:11 +00:00
// read updated parameters
2016-02-24 06:43:01 +00:00
strcpy(mqtt_server, custom_mqtt_server.getValue());
strcpy(mqtt_port, custom_mqtt_port.getValue());
strcpy(mqtt_topic, custom_mqtt_topic.getValue());
2016-02-24 08:00:11 +00:00
// save the custom parameters to FS
2016-02-24 06:43:01 +00:00
if (shouldSaveConfig) {
Serial.println("saving config");
DynamicJsonBuffer jsonBuffer;
JsonObject& json = jsonBuffer.createObject();
json["mqtt_server"] = mqtt_server;
json["mqtt_port"] = mqtt_port;
json["mqtt_topic"] = mqtt_topic;
File configFile = SPIFFS.open("/config.json", "w");
if (!configFile) {
Serial.println("failed to open config file for writing");
}
2016-02-24 06:43:01 +00:00
json.printTo(Serial);
json.printTo(configFile);
configFile.close();
}
2016-02-24 08:05:35 +00:00
mqtt_client.setServer(mqtt_server, stringToNumber(mqtt_port));
mqtt_client.setCallback(mqtt_callback);
2016-02-23 10:12:04 +00:00
dht.begin();
2016-02-24 08:00:11 +00:00
// initial read
2016-02-23 10:12:04 +00:00
read_sensor();
2016-02-24 08:05:35 +00:00
mqtt_client.publish(topic("humidity"), str_humidity);
mqtt_client.publish(topic("temperature"), str_temperature);
mqtt_client.publish(topic("heatindex"), str_heatindex);
2016-02-23 10:12:04 +00:00
2016-02-24 08:00:11 +00:00
// handle http requests
2016-02-24 08:05:35 +00:00
http_server.on("/", [](){
2016-02-23 10:12:04 +00:00
read_sensor();
String response = "<!DOCTYPE HTML>\r\n";
response += "<html lang=\"en\">\r\n";
response += "<head>\r\n";
response += "<meta http-equiv=\"content-type\" content=\"text/html; charset=windows-1252\">\r\n";
response += "<meta name=\"viewport\" content=\"width=device-width, initial-scale=1\">\r\n";
response += "<title>Status</title>\r\n";
response += "<style>\r\n";
response += "div,input{padding:5px;font-size:1em;}\r\n";
response += "input{width:95%;}\r\n";
response += "body{text-align:center;font-family:verdana;}\r\n";
response += "button{border:0;border-radius:0.3rem;background-color:#1fa3ec;color:#fff;line-height:2.4rem;font-size:1.2rem;width:100%;}\r\n";
response += "</style>\r\n";
response += "</head>\r\n";
response += "<body>\r\n";
response += "<div style=\"text-align: left; display: inline-block;\">\r\n";
response += "<h1>";
response += wifi_station_get_hostname();
response += "</h1>\r\n";
response += "<h3>Sensor Status</h3>\r\n";
response += "<table>\r\n";
response += "<tr><td>Temperature</td><td>";
response += str_temperature;
response += "&deg;C</td></tr>\r\n";
response += "<tr><td>Humidity</td><td>";
response += str_humidity;
response += "%RH</td></tr>\r\n";
response += "<tr><td>Heat Index</td><td>";
response += str_heatindex;
response += "&deg;C</td></tr>\r\n";
response += "</table>\r\n";
response += "<form action=\"/\" method=\"get\"><button>Reload</button></form>\r\n";
response += "</div>\r\n";
response += "</body>\r\n";
response += "</html>\n";
2016-02-24 08:05:35 +00:00
http_server.send(200, "text/html", response);
2016-02-23 10:12:04 +00:00
delay(100);
});
2016-02-24 08:05:35 +00:00
http_server.on("/values", [](){
2016-02-23 10:12:04 +00:00
read_sensor();
String response = "updatetime\t";
response += previousMillis;
response += "\n";
response += "temperature\t";
response += str_temperature;
response += "\n";
response += "humidity\t";
response += str_humidity;
response += "\n";
response += "heatindex\t";
response += str_heatindex;
response += "\n";
2016-02-24 08:05:35 +00:00
http_server.send(200, "text/plain", response);
2016-02-23 10:12:04 +00:00
delay(100);
});
2016-02-24 08:00:11 +00:00
// start the web server
2016-02-24 08:05:35 +00:00
http_server.begin();
2016-02-23 10:12:04 +00:00
Serial.println("HTTP server started");
}
void loop() {
2016-02-24 08:00:11 +00:00
// listen for http requests
2016-02-24 08:05:35 +00:00
http_server.handleClient();
2016-02-23 10:12:04 +00:00
2016-02-24 08:05:35 +00:00
if (!mqtt_client.connected()) {
2016-02-24 08:00:11 +00:00
mqtt_reconnect();
2016-02-23 10:12:04 +00:00
}
2016-02-24 08:05:35 +00:00
mqtt_client.loop();
2016-02-23 10:12:04 +00:00
long now = millis();
if (now - lastMsg > 10000) {
lastMsg = now;
read_sensor();
}
}