Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- // Need to create a payload function for publish a json string
- #include <ESP8266WiFi.h>
- #include <Ethernet.h>
- #include "PubSubClient.h"
- #include "time.h"
- #include "Adafruit_Sensor.h"
- #include "DHT.h"
- #include "U8glib.h" //https://github.com/olikraus/u8glib/wiki
- // Erzwinge Deep Sleep
- //#define FORCE_DEEPSLEEP
- // DHT Sensor auswahl
- #define DHTTYPE DHT22
- // define Batterie Staus
- // unsigned int batt;
- // double battV;
- // WiFi credentials.
- const char* WIFI_SSID = "xxxxx";
- const char* WIFI_PASS = "xxx";
- // MQTT credentials.
- const char* MQTT_USER = "xxx";
- const char* MQTT_PASS = "xxx";
- const char* MQTT_CLIENT = "ESP8266-IOT-DH22";
- const char* MQTT_BROKER = "x";
- const char* MQTT_Topic = "ESP01/DHT22";
- char buf [4];
- int timezone = 0; //4 = Sommerzeit
- int dst = 0;
- String clientName;
- // On a ESP32-01
- int DHTPIN = 2; // DHT22 PIN
- U8GLIB_SSD1306_128X64 u8g(U8G_I2C_OPT_NO_ACK);
- WiFiClient net;
- PubSubClient client(net);
- DHT dht(DHTPIN, DHTTYPE);
- void callback(char* topic, byte* payload, unsigned int length)
- {
- // handle message arrived
- }
- //PubSubClient client(MQTT_BROKER, 1883, callback, net);
- void reconnect();
- void connectwifi();
- void draw(float temperatur, float feuchtigkeit);
- // setup () only run once
- void setup()
- {
- // put your setup code here, to run once:
- Serial.begin(115200);
- Serial.setTimeout(2000);
- // Wait for serial to initialize.
- while (!Serial) { }
- Serial.println("Device Started");
- Serial.println("-------------------------------------");
- Serial.println("DHT22 sketch!");
- Serial.println("-------------------------------------");
- //connect wifif fuction to connect to a wifi network
- connectwifi();
- delay(1500);
- // INitiat MQQT Server
- client.setServer(MQTT_BROKER, 1883);
- // client is now configured for use
- delay(1500);
- //Get current time for MQTT transmission for ntp server
- configTime(3600, 0, "pool.ntp.org", "time.nist.gov");
- Serial.println("\nWaiting for time");
- while (!time(nullptr)) {
- Serial.print(".");
- delay(1000);
- }
- time_t now = time(nullptr);
- Serial.println(ctime(&now));
- Serial.println("-------------------------------------");
- // Init DHT22
- dht.begin();
- }
- void loop()
- {
- float h = dht.readHumidity();
- float t = dht.readTemperature();
- // Whether or not the PubSubClient client is connected. Note that a client is considered connected if the connection has been closed but there is still unread data.
- if (!client.connected()) {
- // reconnect
- reconnect();
- }
- //loop() to allow the client to process incoming messages and maintain its connection to the server.
- if (!client.loop()) {
- Serial.print("Client disconnected...");
- // Connect with MQTT credentials
- if (client.connect(MQTT_CLIENT, MQTT_USER, MQTT_PASS)) {
- Serial.println("MQTT reconnected.");
- } else {
- Serial.println("MQTT connection failed.");
- }
- }
- if (client.loop())
- {
- Serial.println("Read Sensor data");
- // Check if any reads failed and exit early (to try again).
- //read sonsor data from SensorPin
- Serial.print("Temperatur:");
- Serial.println(String(t));
- Serial.print("Feuchtigkeit:");
- Serial.println(String(h));
- Serial.println("-------------------------------------");
- Serial.println("Publish MQTT");
- Serial.print("MQTT Client: ");
- Serial.println(MQTT_CLIENT);
- Serial.print("MQTT Broker: ");
- Serial.println(MQTT_BROKER);
- Serial.print("Topic: ");
- Serial.println(MQTT_Topic);
- Serial.println("-------------------------------------");
- Serial.print("Date: ");
- time_t now = time(nullptr);
- Serial.println(ctime(&now));
- Serial.println("-------------------------------------");
- // Create the JSON String called payload to be send via MQQT
- String payload = "{\"Date\":";
- payload += "\"";
- payload += now;
- payload += "\"";
- payload += ",\"Node\":";
- payload += "\"";
- payload += MQTT_CLIENT;
- payload += "\"";
- payload += ",\"IP\":";
- payload += "\"";
- payload += WiFi.localIP().toString();
- payload += "\"";
- payload += ",\"Temperatur\":";
- payload += "\"";
- payload += String(t);
- payload += "\"";
- payload += ",\"Humidity\":";
- payload += "\"";
- payload += String(h);
- payload += "\"";
- payload += "}";
- Serial.println("Payload: ");
- Serial.println(payload)
- / Serial.println("-------------------------------------");
- // Publish data on screen
- u8g.firstPage();
- do {
- draw(t,h);
- } while ( u8g.nextPage() );
- delay(1);
- // clinet.publish will publish the JSON string
- if (client.publish(MQTT_Topic, (char*) payload.c_str())) {
- Serial.println("Publish ok");
- delay(10*60*1000);
- }
- else {
- Serial.println("Publish failed");
- abort();
- }
- }
- }
- //publish a payload (json) string
- boolean publishmqtt(String payload)
- {
- if (!client.connected())
- {
- if (client.connect((char*) MQTT_CLIENT))
- {
- Serial.println("Connected to MQTT broker again");
- Serial.print("Topic is: ");
- Serial.println(MQTT_Topic);
- }
- else
- {
- Serial.println("MQTT connect failed");
- Serial.println("Will reset and try again...");
- abort();
- }
- }
- if (client.connected())
- {
- Serial.print("Sending payload: ");
- Serial.println(payload);
- if (client.publish(MQTT_Topic, (char*) payload.c_str()))
- {
- Serial.println("Publish ok");
- }
- }
- else
- {
- Serial.println("Publish failed");
- }
- }
- // need a funtion for int to Char* and other
- String macToStr(const uint8_t* mac)
- {
- String result;
- for (int i = 0; i < 6; ++i)
- {
- result += String(mac[i], 16);
- if (i < 5)
- result += ':';
- }
- return result;
- }
- void reconnect() {
- // Solange wiederholen bis Verbindung wiederhergestellt ist
- while (!net.connected()) {
- Serial.print("Versuch des MQTT Verbindungsaufbaus...");
- //Verbindungsversuch:
- if (client.connect(MQTT_CLIENT, MQTT_USER, MQTT_PASS)) {
- Serial.println("Erfolgreich verbunden!");
- // Nun versendet der Arduino eine Nachricht in outTopic ...
- // client.publish("outTopic","Arduino nach Hause telefonieren");
- // und meldet sich bei inTopic für eingehende Nachrichten an:
- // client.subscribe("inTopic");
- } else { // Im Fehlerfall => Fehlermeldung und neuer Versuch
- Serial.print("Fehler, rc=");
- Serial.println(client.state());
- Serial.println("-------------------------------------");
- Serial.println("Nächster Versuch in 5 Sekunden");
- // 5 Sekunden Pause vor dem nächsten Versuch
- delay(5000);
- }
- }
- }
- void connectwifi()
- {
- // Connect to Wifi.
- Serial.println();
- Serial.println();
- Serial.println("Connecting to");
- Serial.println(WIFI_SSID);
- Serial.println("-------------------------------------");
- // WiFi.begin(WIFI_SSID, WIFI_PASS);
- // WiFi fix: https://github.com/esp8266/Arduino/issues/2186
- WiFi.persistent(false);
- WiFi.mode(WIFI_OFF);
- WiFi.mode(WIFI_STA);
- WiFi.begin(WIFI_SSID, WIFI_PASS);
- unsigned long wifiConnectStart = millis();
- while (WiFi.status() != WL_CONNECTED)
- {
- // Check to see if
- if (WiFi.status() == WL_CONNECT_FAILED) {
- Serial.println("Failed to connect to WiFi. Please verify credentials: ");
- Serial.println("-------------------------------------");
- delay(10000);
- }
- delay(500);
- Serial.print(".");
- // Only try for 5 seconds.
- if (millis() - wifiConnectStart > 30000)
- {
- Serial.println("Failed to connect to WiFi");
- Serial.println("-------------------------------------");
- return;
- }
- }
- Serial.println("");
- Serial.println("WiFi connected");
- Serial.println("-------------------------------------");
- Serial.println("IP address: ");
- Serial.println(WiFi.localIP());
- Serial.println("-------------------------------------");
- clientName += "esp8266-";
- uint8_t mac[6];
- WiFi.macAddress(mac);
- clientName += macToStr(mac);
- clientName += "-";
- clientName += String(micros() & 0xff, 16);
- Serial.print("Connecting as ");
- Serial.println(clientName);
- Serial.println("-------------------------------------");
- }
- double mapDouble(double x, double in_min, double in_max, double out_min, double out_max)
- {
- double temp = (x - in_min) * (out_max - out_min) / (in_max - in_min) + out_min;
- temp = (int) (4*temp + .5);
- return (double) temp/4;
- }
- //draw t & h on the OLED display
- void draw(float temperatur, float feuchtigkeit) {
- u8g.setFont(u8g_font_fub25); //https://github.com/olikraus/u8glib/wiki/fontsize
- u8g.setPrintPos(10, 32);
- u8g.print(temperatur, 1);
- u8g.setFont(u8g_font_fub25);
- u8g.setPrintPos(10, 64);
- u8g.print(feuchtigkeit, 1);
- u8g.setFont(u8g_font_fub25);
- u8g.drawStr(95, 32, "C");
- u8g.setFont(u8g_font_ncenB12);
- u8g.drawStr(85, 10, "o");
- u8g.setFont(u8g_font_fub25);
- u8g.drawStr(85, 64, "%");
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement