From d96289e5d49ae39fe74fbf4dc14f0fdb11eb1da9 Mon Sep 17 00:00:00 2001 From: Hendrik Langer Date: Tue, 5 Jun 2018 20:47:02 +0200 Subject: [PATCH] add mqtt publishing --- platformio.ini | 1 + src/main.cpp | 38 ++++++++++++++++++++++++++++++++++++-- 2 files changed, 37 insertions(+), 2 deletions(-) diff --git a/platformio.ini b/platformio.ini index 44ac371..3ff2ee7 100644 --- a/platformio.ini +++ b/platformio.ini @@ -20,3 +20,4 @@ lib_deps = ; SDS011 sensor Library https://github.com/Zanop/SDS011.git#more-sensor-modes RunningAverage + MQTT diff --git a/src/main.cpp b/src/main.cpp index 311be45..0f34c49 100644 --- a/src/main.cpp +++ b/src/main.cpp @@ -14,6 +14,8 @@ extern "C" { #include #include +#define MQTT_MAX_PACKET_SIZE 512 +#include #include #include @@ -29,6 +31,10 @@ const char* server = "ingress.opensensemap.org"; //const char* ssid = "Freifunk"; //const char* password = ""; +const char* mqttserver = "home.xd0.de"; +const char* mqttusername = "esp-weatherstation"; +const char* mqttpassword = "password"; + constexpr unsigned int postingInterval = 60000; //Uploadintervall in Millisekunden constexpr unsigned int dhcp_interval = 60*60*1000; @@ -97,7 +103,7 @@ struct __attribute__((packed)) SENSOR_DATA { float rssi; } sd; - +/* void sendESPNOW() { // unsigned long espnowmillis = millis(); uint8_t remoteMac[] = {0x5C, 0xCF, 0x7F, 0x5, 0xFD, 0xF0}; @@ -131,7 +137,7 @@ void sendESPNOW() { digitalWrite(LED_BUILTIN, HIGH); // Serial.printf("sendESPNOW() took %d ms\n", millis()-espnowmillis); } - +*/ void ICACHE_FLASH_ATTR sendValues() { sd.temperature = dht.readTemperature(); @@ -298,6 +304,34 @@ void ICACHE_FLASH_ATTR sendValues() { } + WiFiClientSecure net; + MQTTClient mqttclient; + + mqttclient.begin(mqttserver, 8883, net); + int tries = 0; + constexpr unsigned int retry_delay = 500; + constexpr unsigned int max_retry_delay = 5000; + while (!mqttclient.connect(mqttusername, mqttusername, mqttpassword)) { + tries++; + Serial.print("."); + if (tries*retry_delay >= max_retry_delay) { + Serial.println(" [ERROR]"); + Serial.println("Rebooting.."); + ESP.restart(); + } + delay(retry_delay); + } + + mqttclient.loop(); + Serial.println(buffer); + if (mqttclient.publish("sensor/esp-weatherstation/json", buffer, sizeof(buffer))) { + Serial.println("mqtt done"); + } else { + Serial.println("mqtt failed"); + } + mqttclient.loop(); + mqttclient.disconnect(); + last_wifi_activity = millis(); WiFi.disconnect(); WiFi.mode(WIFI_OFF);