Browse Source

add mqtt publishing

lightsleep
Hendrik Langer 7 years ago
parent
commit
d96289e5d4
  1. 1
      platformio.ini
  2. 38
      src/main.cpp

1
platformio.ini

@ -20,3 +20,4 @@ lib_deps =
; SDS011 sensor Library
https://github.com/Zanop/SDS011.git#more-sensor-modes
RunningAverage
MQTT

38
src/main.cpp

@ -14,6 +14,8 @@ extern "C" {
#include <ESP8266HTTPClient.h>
#include <ArduinoJson.h>
#define MQTT_MAX_PACKET_SIZE 512
#include <MQTTClient.h>
#include <Wire.h>
#include <SPI.h>
@ -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);

Loading…
Cancel
Save