fix comments

This commit is contained in:
Ronald Schaten 2016-02-24 09:00:11 +01:00
parent 8e71160516
commit 0bc473da09

View File

@ -60,16 +60,16 @@ void toggle_led() {
void configModeCallback (WiFiManager *myWiFiManager) { void configModeCallback (WiFiManager *myWiFiManager) {
Serial.println("Entered config mode"); Serial.println("Entered config mode");
Serial.println(WiFi.softAPIP()); Serial.println(WiFi.softAPIP());
//if you used auto generated SSID, print it
Serial.println(myWiFiManager->getConfigPortalSSID()); Serial.println(myWiFiManager->getConfigPortalSSID());
//entered config mode, make led toggle faster ticker.attach(0.1, toggle_led); // toggle led faster
ticker.attach(0.1, toggle_led);
} }
// compare float values
bool isEqual(float a, float b, float epsilon=0.001) { bool isEqual(float a, float b, float epsilon=0.001) {
return fabs(a - b) <= epsilon * fabs(a); return fabs(a - b) <= epsilon * fabs(a);
} }
// concatenate MQTT topic prefix to individual topic
char* topic(const char* this_topic) { char* topic(const char* this_topic) {
static char topic[34]; static char topic[34];
strcpy(topic, mqtt_topic); strcpy(topic, mqtt_topic);
@ -78,6 +78,7 @@ char* topic(const char* this_topic) {
return topic; return topic;
} }
// get values from DHT sensor
void read_sensor() { void read_sensor() {
// wait at least 2 seconds seconds between measurements // wait at least 2 seconds seconds between measurements
unsigned long currentMillis = millis(); unsigned long currentMillis = millis();
@ -89,8 +90,6 @@ void read_sensor() {
float previousHeatindex = heatindex; float previousHeatindex = heatindex;
humidity = dht.readHumidity(); // read humidity as a percent humidity = dht.readHumidity(); // read humidity as a percent
temperature = dht.readTemperature(); // read temperature as Celsius temperature = dht.readTemperature(); // read temperature as Celsius
// compute heat index
heatindex = dht.computeHeatIndex(temperature, humidity, false); heatindex = dht.computeHeatIndex(temperature, humidity, false);
// check if any reads failed and exit early (to try again) // check if any reads failed and exit early (to try again)
@ -126,7 +125,8 @@ void read_sensor() {
} }
} }
void callback(char* topic, byte* payload, unsigned int length) { // callback for MQTT, gets called if we receive a message
void mqtt_callback(char* topic, byte* payload, unsigned int length) {
Serial.print("Message arrived ["); Serial.print("Message arrived [");
Serial.print(topic); Serial.print(topic);
Serial.print("] "); Serial.print("] ");
@ -135,26 +135,25 @@ void callback(char* topic, byte* payload, unsigned int length) {
} }
Serial.println(); Serial.println();
// Switch on the LED if an 1 was received as first character // switch on the LED if an 1 was received as first character
if ((char)payload[0] == '1') { if ((char)payload[0] == '1') {
Serial.println("setting LED to low"); Serial.println("setting LED to low");
digitalWrite(BUILTIN_LED, LOW); // Turn the LED on (Note that LOW is the voltage level digitalWrite(BUILTIN_LED, LOW); // turn the LED on
// but actually the LED is on; this is because
// it is acive low on the ESP-01)
} else { } else {
Serial.println("setting LED to high"); Serial.println("setting LED to high");
digitalWrite(BUILTIN_LED, HIGH); // Turn the LED off by making the voltage HIGH digitalWrite(BUILTIN_LED, HIGH); // turn the LED off
} }
} }
void reconnect() { // make sure we're connected to MQTT broker
// Loop until we're reconnected void mqtt_reconnect() {
// loop until we're reconnected
while (!client.connected()) { while (!client.connected()) {
Serial.print("Attempting MQTT connection..."); Serial.print("Attempting MQTT connection...");
// Attempt to connect // attempt to connect
if (client.connect(wifi_station_get_hostname(), topic("online"), MQTTQOS1, true, "0")) { if (client.connect(wifi_station_get_hostname(), topic("online"), MQTTQOS1, true, "0")) {
Serial.println("connected"); Serial.println("connected");
// Once connected, publish an announcement... // once connected, publish an announcement...
client.publish(topic("online"), "1"); client.publish(topic("online"), "1");
// ... and resubscribe: // ... and resubscribe:
client.subscribe("inTopic"); client.subscribe("inTopic");
@ -162,12 +161,12 @@ void reconnect() {
Serial.print("failed, rc="); Serial.print("failed, rc=");
Serial.print(client.state()); Serial.print(client.state());
Serial.println(" try again in 5 seconds"); Serial.println(" try again in 5 seconds");
// Wait 5 seconds before retrying
delay(5000); delay(5000);
} }
} }
} }
// convert string to integer
int stringToNumber(String thisString) { int stringToNumber(String thisString) {
int i, value, length; int i, value, length;
length = thisString.length(); length = thisString.length();
@ -184,27 +183,27 @@ void setup() {
// put your setup code here, to run once: // put your setup code here, to run once:
Serial.begin(9600); Serial.begin(9600);
//set led pin as output // set led pin as output
pinMode(BUILTIN_LED, OUTPUT); pinMode(BUILTIN_LED, OUTPUT);
// start ticker with 0.5 because we start in AP mode and try to connect // start ticker with 0.5 because we start in AP mode and try to connect
ticker.attach(0.6, toggle_led); ticker.attach(0.6, toggle_led);
//clean FS, for testing // clean FS, for testing
//SPIFFS.format(); //SPIFFS.format();
//read configuration from FS json // read configuration from FS json
Serial.println("mounting FS..."); Serial.println("mounting FS...");
if (SPIFFS.begin()) { if (SPIFFS.begin()) {
Serial.println("mounted file system"); Serial.println("mounted file system");
if (SPIFFS.exists("/config.json")) { if (SPIFFS.exists("/config.json")) {
//file exists, reading and loading // file exists, reading and loading
Serial.println("reading config file"); Serial.println("reading config file");
File configFile = SPIFFS.open("/config.json", "r"); File configFile = SPIFFS.open("/config.json", "r");
if (configFile) { if (configFile) {
Serial.println("opened config file"); Serial.println("opened config file");
size_t size = configFile.size(); size_t size = configFile.size();
// Allocate a buffer to store contents of the file. // allocate a buffer to store contents of the file.
std::unique_ptr<char[]> buf(new char[size]); std::unique_ptr<char[]> buf(new char[size]);
configFile.readBytes(buf.get(), size); configFile.readBytes(buf.get(), size);
DynamicJsonBuffer jsonBuffer; DynamicJsonBuffer jsonBuffer;
@ -223,55 +222,48 @@ void setup() {
} else { } else {
Serial.println("failed to mount FS"); Serial.println("failed to mount FS");
} }
//end read
// The extra parameters to be configured (can be either global or just in the setup) // WiFiManager
// After connecting, parameter.getValue() will get you the configured value // extra parameters to be configured
// id/name placeholder/prompt default length
WiFiManagerParameter custom_mqtt_server("server", "mqtt server", mqtt_server, 40); WiFiManagerParameter custom_mqtt_server("server", "mqtt server", mqtt_server, 40);
WiFiManagerParameter custom_mqtt_port("port", "mqtt port", mqtt_port, 5); WiFiManagerParameter custom_mqtt_port("port", "mqtt port", mqtt_port, 5);
WiFiManagerParameter custom_mqtt_topic("topic", "mqtt topic", mqtt_topic, 32); WiFiManagerParameter custom_mqtt_topic("topic", "mqtt topic", mqtt_topic, 32);
//WiFiManager // local intialization
//Local intialization. Once its business is done, there is no need to keep it around
WiFiManager wifiManager; WiFiManager wifiManager;
//reset settings - for testing // reset settings - for testing
//wifiManager.resetSettings(); //wifiManager.resetSettings();
//set callback that gets called when connecting to previous WiFi fails, and enters Access Point mode // set callback that gets called when connecting to previous WiFi fails, and enters Access Point mode
wifiManager.setAPCallback(configModeCallback); wifiManager.setAPCallback(configModeCallback);
//set config save notify callback // set config save notify callback
wifiManager.setSaveConfigCallback(saveConfigCallback); wifiManager.setSaveConfigCallback(saveConfigCallback);
//add all your parameters here // add all your parameters here
wifiManager.addParameter(&custom_mqtt_server); wifiManager.addParameter(&custom_mqtt_server);
wifiManager.addParameter(&custom_mqtt_port); wifiManager.addParameter(&custom_mqtt_port);
wifiManager.addParameter(&custom_mqtt_topic); wifiManager.addParameter(&custom_mqtt_topic);
//fetches ssid and pass and tries to connect // fetches ssid and pass and tries to connect
//if it does not connect it starts an access point with the specified name // if it does not connect it starts an access point
//here "AutoConnectAP"
//and goes into a blocking loop awaiting configuration
if (!wifiManager.autoConnect()) { if (!wifiManager.autoConnect()) {
Serial.println("failed to connect and hit timeout"); Serial.println("failed to connect and hit timeout");
//reset and try again, or maybe put it to deep sleep // reset and try again
ESP.reset(); ESP.reset();
delay(1000); delay(1000);
} }
//if you get here you have connected to the WiFi Serial.println("connected to WiFi");
Serial.println("connected...yeey :)");
ticker.detach(); ticker.detach();
//keep LED on
digitalWrite(BUILTIN_LED, LOW); digitalWrite(BUILTIN_LED, LOW);
//read updated parameters // read updated parameters
strcpy(mqtt_server, custom_mqtt_server.getValue()); strcpy(mqtt_server, custom_mqtt_server.getValue());
strcpy(mqtt_port, custom_mqtt_port.getValue()); strcpy(mqtt_port, custom_mqtt_port.getValue());
strcpy(mqtt_topic, custom_mqtt_topic.getValue()); strcpy(mqtt_topic, custom_mqtt_topic.getValue());
//save the custom parameters to FS // save the custom parameters to FS
if (shouldSaveConfig) { if (shouldSaveConfig) {
Serial.println("saving config"); Serial.println("saving config");
DynamicJsonBuffer jsonBuffer; DynamicJsonBuffer jsonBuffer;
@ -288,21 +280,20 @@ void setup() {
json.printTo(Serial); json.printTo(Serial);
json.printTo(configFile); json.printTo(configFile);
configFile.close(); configFile.close();
//end save
} }
client.setServer(mqtt_server, stringToNumber(mqtt_port)); client.setServer(mqtt_server, stringToNumber(mqtt_port));
client.setCallback(callback); client.setCallback(mqtt_callback);
dht.begin(); dht.begin();
// Initial read // initial read
read_sensor(); read_sensor();
client.publish(topic("humidity"), str_humidity); client.publish(topic("humidity"), str_humidity);
client.publish(topic("temperature"), str_temperature); client.publish(topic("temperature"), str_temperature);
client.publish(topic("heatindex"), str_heatindex); client.publish(topic("heatindex"), str_heatindex);
// Handle http requests // handle http requests
server.on("/", [](){ server.on("/", [](){
read_sensor(); read_sensor();
String response = "<!DOCTYPE HTML>\r\n"; String response = "<!DOCTYPE HTML>\r\n";
@ -375,17 +366,17 @@ void setup() {
server.send(200, "text/plain", response); server.send(200, "text/plain", response);
}); });
// Start the web server // start the web server
server.begin(); server.begin();
Serial.println("HTTP server started"); Serial.println("HTTP server started");
} }
void loop() { void loop() {
// Listen for http requests // listen for http requests
server.handleClient(); server.handleClient();
if (!client.connected()) { if (!client.connected()) {
reconnect(); mqtt_reconnect();
} }
client.loop(); client.loop();