ESP8266 Telegram Sensor Bot


ESP8266, DHT22 (temperature & humidity), MAX4009 (luminance).


Supply Voltage: approx 3.3V – 5.4V (eg, LI-PO, USB)


Sensors close-up.


Published MQTT topics to OpenHAB.


Telegram message with Temperature, Humidity and Luminance.


Technical info and notification Thresholds.


/*
  Author:   Dejan Lauber
  Date:     9.2017
  File:     mqtt_sensor_bot.ino
  Version:  V1.5

  Description:
  sensor bot with
  dht22 temp & humidity
  max44009 ambient light

  input voltage:
  ca.3.3V - max.5.4V

  mqtt pub:
  demm_bot/updateID
  demm_bot/lux
  demm_bot/T
  demm_bot/RH
  demm_bot/vin

  telegram bot with customizable bot token.

  pinout:
  A0 voltage divider to 5V/Vin (gnd|100k|ADC|220k|A0|220k|5V/Vin)
  D0
  D5 DHT22 data (ext 10k pullup)
  D6 1/EN_deepsleep
  D7
  D8

  D1 SCL gy-49 max
  D2 SDA gy-49 max
  D3
  D4

  todo:
*/

//libraries
#include <ESP8266WiFi.h>          //https://github.com/esp8266/Arduino
#include <EEPROM.h>
//wifi manager
#include <DNSServer.h>
#include <ESP8266WebServer.h>
#include <WiFiManager.h>          //https://github.com/tzapu/WiFiManager
//max44009
#include <Wire.h>
//dht22
#include <SimpleDHT.h>
//mqtt
#include <PubSubClient.h>
//telegram
#include <UniversalTelegramBot.h>


//pin definitions
const byte DHTPIN = D5;  // Pin which is connected to the DHT sensor.
//const byte EN_deepsleep = D6;
//library variables
const int maxaddr = 0x4A;
int Bot_mtbs = 1000; //mean time between scan messages //1000
long lastBOT;   //last time messages' scan has been done

//other library stuff
WiFiClient espClient;
PubSubClient mclient(espClient);
SimpleDHT22 dht22;
WiFiClientSecure bclient;
UniversalTelegramBot *bot;

//program variables
const word MQTT_INTERVAL = 15000;
const word LTH_INTERVAL = 2500;
const byte authNumber = 10;
word lowvoltage = 3300;
byte preReq, lowvoltagesent;
long lastMQTT, lastLTH, lastMC;
word updateID = 1, vin[3] = {6000, 0, 0};
//min, current, max
float luminance[3] = {420000, -127, -127};
float temperature[3] = {420, -127, -127};
float humidity[3] = {420, -127, -127};

//user struct. "id" is loaded from eeprom
struct authObj {
  String id;
  float TT;  //temperature threshold
  byte TD; //direction of thershold; 0: off; 1: if temp<TT; 2: if temp>TT
  float RHT;
  byte RHD;
  float luxT;
  byte luxD;
  float vinT;
  byte vinD;
};
authObj auth[authNumber];  //id: 52bit (arduino max 32bit) -> string ;_; (max 16 chars) = 170 bytes

//config struct
struct confObj {
  byte en;  //the enable/valid byte
  char mqtt_server[40];
  char mqtt_port[6];  //5 chars + 1 string end char
  char BOTtoken[47];  //46 chars
};  //max 94 bytes
confObj conf = {
  42,
  "192.168.11.44",
  "1883",
  "xxxxxxxxx"
};

void setup() {

  //pinMode(EN_deepsleep, INPUT_PULLUP);

  Serial.begin(9600);

  EEPROM.begin(768);

  //reset eeprom auth. for testing puposes
  //EEPROM.write(0, 255);

  if (EEPROM.read(0) == conf.en) {
    Serial.println("reading valid EEPROM");
    EEPROM.get(0, conf);
    //total 17, 4, 1, 4, 1, 4, 1, 4, 1, +reserved = 42
    //.id
    for (byte j = 0; j < authNumber; j++) {
      for (byte i = 0; i < 17; ++i) {
        char tmp = char(EEPROM.read(100 + (42 * j) + i));

        if ((tmp == '\0') || (tmp == 255)) {
          i = 17;
        }
        else {
          auth[j].id += tmp;
        }
      }
      //Serial.println(auth[j].id);
      //.TT float 4 byte
      EEPROM.get(100 + (42 * j) + 17, auth[j].TT);
      //.TD 1 byte
      EEPROM.get(100 + (42 * j) + 21, auth[j].TD);
      //.TT float 4 byte
      EEPROM.get(100 + (42 * j) + 22, auth[j].RHT);
      //.TD 1 byte
      EEPROM.get(100 + (42 * j) + 26, auth[j].RHD);
      //.TT float 4 byte
      EEPROM.get(100 + (42 * j) + 27, auth[j].luxT);
      //.TD 1 byte
      EEPROM.get(100 + (42 * j) + 31, auth[j].luxD);
      //.TT float 4 byte
      EEPROM.get(100 + (42 * j) + 32, auth[j].vinT);
      //.TD 1 byte
      EEPROM.get(100 + (42 * j) + 36, auth[j].vinD);
    }
  } else {
    Serial.println("config not found on EEPROM, using defaults");
    for (byte j = 0; j < authNumber; j++) {
      EEPROM.write(100 + (42 * j), 255);
      EEPROM.write(100 + (42 * j) + 21, 0);
      EEPROM.write(100 + (42 * j) + 26, 0);
      EEPROM.write(100 + (42 * j) + 31, 0);
      EEPROM.write(100 + (42 * j) + 36, 0);
    }
    EEPROM.commit();
  }


  //Max44009
  Wire.begin();
  Wire.beginTransmission(maxaddr);
  Wire.write(0x02);
  Wire.write(0x40);
  Wire.endTransmission();
  delay(300);


  //WiFiManager
  WiFiManager wifiManager;
  //reset settings - for testing
  //wifiManager.resetSettings();

  //sets timeout until configuration portal gets turned off
  wifiManager.setTimeout(180);

  // id/name, placeholder/prompt, default, length
  WiFiManagerParameter custom_mqtt_server("server", "mqtt server", conf.mqtt_server, 39);
  wifiManager.addParameter(&custom_mqtt_server);
  WiFiManagerParameter custom_mqtt_port("port", "mqtt port", conf.mqtt_port, 5);
  wifiManager.addParameter(&custom_mqtt_port);
  WiFiManagerParameter custom_bot_token("token", "telegram bot token", conf.BOTtoken, 46);
  wifiManager.addParameter(&custom_bot_token);

  //fetches ssid and pass and tries to connect
  if (!wifiManager.autoConnect()) {
    Serial.println("failed to connect and hit timeout");
    delay(3000);
    //reset and try again, or maybe put it to deep sleep
    ESP.restart();
    delay(5000);
  }
  //if you get here you have connected to the WiFi
  Serial.println("wifi connected...");

  //custom parameters from wifimanager
  strcpy(conf.mqtt_server, custom_mqtt_server.getValue());
  strcpy(conf.mqtt_port, custom_mqtt_port.getValue());
  strcpy(conf.BOTtoken, custom_bot_token.getValue());
  //safe config
  EEPROM.put(0, conf);
  EEPROM.commit();

  //mqtt
  mclient.setServer(conf.mqtt_server, atoi(conf.mqtt_port));
  mclient.setCallback(callback);
  //bot
  bot = new UniversalTelegramBot(conf.BOTtoken, bclient);
}

void getlux() {
  unsigned int data[2];
  Wire.beginTransmission(maxaddr);
  Wire.write(0x03);
  Wire.endTransmission();

  // Request 2 bytes of data
  Wire.requestFrom(maxaddr, 2);

  // Read 2 bytes of data luminance msb, luminance lsb
  if (Wire.available() == 2)
  {
    data[0] = Wire.read();
    data[1] = Wire.read();
  }

  // Convert the data to lux
  int exponent = (data[0] & 0xF0) >> 4;
  int mantissa = ((data[0] & 0x0F) << 4) | (data[1] & 0x0F);
  luminance[1] = pow(2, exponent) * mantissa * 0.045;

}

void getdht() {

  temperature[1] = -127;
  humidity[1] = -127;
  int err = SimpleDHTErrSuccess;
  if ((err = dht22.read2(DHTPIN, &temperature[1], &humidity[1], NULL)) != SimpleDHTErrSuccess) {
    Serial.print("Read DHT22 failed, err="); Serial.println(err);
  }
}

byte reconnect() {
  String msg;
  Serial.print("Attempting MQTT connection... ");
  // ATttempt to connect
  if (mclient.connect("ESP_demm_bot")) {
    Serial.println("connected");
    // Once connected, publish an announcement...
    msg = String(updateID);
    mclient.publish("demm_bot/updateID", msg.c_str());
    // ... and resubscribe
    //client.subscribe("teapot/pottingphase");
    lastMQTT = millis();
  }
  return mclient.connected();
}

void callback(char* topic, byte* payload, word length) {
  //no subscribed mqtt topics
}

void handleNewMessages(int numNewMessages) {
  Serial.print("handleNewMessage: ");
  //Serial.println(String(numNewMessages));
  byte is_auth;
  String msg;

  for (int i = 0; i < numNewMessages; i++) {
    String chat_id = String(bot->messages[i].chat_id);
    String text = bot->messages[i].text;

    Serial.println(text);
    String from_name = bot->messages[i].from_name;
    if (from_name == "") from_name = "Guest";

    is_auth = 0;
    for (byte j = 0; j < authNumber; j++) {
      /*
        //debug
        Serial.println(j);
        Serial.println(chat_id);
        Serial.println(chat_id.length());
        Serial.println(int(chat_id[9]));
        Serial.println(auth[j].id);
        Serial.println(auth[j].id.length());
        Serial.println(int(auth[j].id[9]));
        Serial.println(int(auth[j].id[10]));
      */
      if (chat_id == auth[j].id) {
        is_auth = 1;
        j = authNumber;
      }
    }

    if (!is_auth) {
      Serial.println("unauthorized");

      if ((text == "/status") || (text == "/start") || (text == "/help")) {
        //msg = "ESP sensor bot\n";
        msg = "This is demm_bot.\n";
        msg += "This Chat ID is: " + chat_id + "\n\n";
        msg += "/status : Get this Message\n";
        msg += "/test : Get Test Messages";
        bot->sendMessage(chat_id, msg, "");
      }
      if (text == "/admin_xxxx") {
        //add chat_id to conf.auth_ids
        for (byte j = 0; j < authNumber; j++) {
          if (auth[j].id == "") {
            auth[j].id = chat_id;

            //Serial.println(j);
            //Serial.println(auth[j].id);
            //Serial.println(auth[j].id.length());

            for (byte i = 0; i < chat_id.length() + 1; ++i) {
              EEPROM.write(100 + (42 * j) + i, chat_id[i]);
            }
            EEPROM.commit();

            is_auth = 1;
            text = "/help";  //respond with /help
            j = authNumber;
            //bot->sendMessage(chat_id, "You have been registered!", "");
          }
        }
      }
    }
    if (is_auth) {
      Serial.println("authorized");
      if (text == "/logout") {
        for (byte j = 0; j < authNumber; j++) {
          if (chat_id == auth[j].id) {
            auth[j].id = "";
            EEPROM.write(100 + (42 * j), 255);
            EEPROM.commit();
            is_auth = 0;
            j = authNumber;
          }
        }
        bot->sendMessage(chat_id, "You have been unregistered!", "");
      }

      if (text == "/test") {
        for (byte j = 0; j < authNumber; j++) {
          if (auth[j].id != "") {
            bot->sendMessage(auth[j].id, "Test Message", "");
          }
        }
      }


      if (text == "/admin_purge") {
        for (byte j = 0; j < authNumber; j++) {
          if (auth[j].id != "") {
            bot->sendMessage(auth[j].id, "You have been unregistered!", "");
            auth[j].id = "";
            EEPROM.write(100 + (42 * j), 255);
            is_auth = 0;
          }
        }
        EEPROM.commit();
        bot->sendMessage(chat_id, "All Admins have been unregistered!", "");
      }

      if (text == "/restart") {
        bot->sendMessage(chat_id, "restarting", "");
        delay(1000);
        ESP.restart();//this only works if the esp has been restartet at least once manually (power|button)
        delay(3000);
      }

      if (text == "/tech") {
        msg = "demm_bot Statistics.\n";
        msg += String(WiFi.SSID()) + ": " + String(WiFi.RSSI()) + " dBm\n";
        msg += "IP address: " + WiFi.localIP().toString() + "\n";
        if (mclient.connected()) {
          msg += "MQTT connected to:\n" + String(conf.mqtt_server) + ":" + String(conf.mqtt_port) + "\n";
        } else {
          msg += "MQTT not connected\n";
        }
        msg += "Vin: " + String(vin[1]) + " mV\n";
        msg += "Vin min: " + String(vin[0]) + " mV\n";
        msg += "Vin max: " + String(vin[2]) + " mV\n";
        msg += "uptime : " + String(millis() / (1000 * 60 * 60)) + " h\n\n";
        msg += "Your alarm Thresholds:\n";
        for (byte j = 0; j < authNumber; j++) {
          if (chat_id == auth[j].id) {
            if (auth[j].TD) {
              msg += "T: " + String(auth[j].TT) + " °C (" + String(auth[j].TD) + ")\n";
            }
            if (auth[j].RHD) {
              msg += "RH: " + String(auth[j].RHT) + " RH% (" + String(auth[j].RHD) + ")\n";
            }
            if (auth[j].luxD) {
              msg += "lux: " + String(auth[j].luxT) + " lx (" + String(auth[j].luxD) + ")\n";
            }
            if (auth[j].vinD) {
              msg += "vin: " + String(auth[j].vinT) + " mV (" + String(auth[j].vinD) + ")\n";
            }
            j = authNumber;
          }
        }
        msg += "\nYou are Registered!\n";
        msg += "This Chat ID is: " + chat_id + "\n";
        msg += "Registered Chat IDs:\n";
        for (byte j = 0; j < authNumber; j++) {
          msg += auth[j].id + " ";
        }
        bot->sendMessage(chat_id, msg, "");

      }

      if ((text == "/status")) {
        bot->sendMessage(chat_id, SState(), ""); //send status
      }

      if ((text == "/help") || (text == "/start")) {
        //msg = "ESP sensor bot\n";
        msg = "This is demm_bot.\n";
        msg += "You are Registered!\n\n";
        msg += "/help : Get this Message\n";
        msg += "/status : Get Sensor Status\n";
        msg += "/tech : Get Statistics\n";
        msg += "/logout : Unregister\n";
        msg += "/test : Get Test Messages\n\n";
        msg += "Threshold Notifications:\n";
        msg += "/alarm_T_ : Temperature\n";
        msg += "/alarm_RH_ : Humidity\n";
        msg += "/alarm_lux_ : Luminance\n";
        msg += "/alarm_V_ : Supply Voltage\n";
        msg += "eg: /alarm_RH_40\n";
        bot->sendMessage(chat_id, msg, "");
      }

      if (text.startsWith("/alarm_T_")) {
        for (byte j = 0; j < authNumber; j++) {
          if (chat_id == auth[j].id) {
            if (text.substring(9) != "") {
              auth[j].TT = text.substring(9).toFloat();
              if (auth[j].TT > temperature[1]) {
                auth[j].TD = 2;
                msg = "I will notify you once the Temperature increases to:\n";
              } else {
                auth[j].TD = 1;
                msg = "I will notify you once the Temperature drops to:\n";
              }
              msg += String(auth[j].TT) + " °C";
              bot->sendMessage(chat_id, msg, "");
            } else {
              auth[j].TD = 0;
              msg = "Alarm deactivated";
              bot->sendMessage(chat_id, msg, "");
            }
            EEPROM.put(100 + (42 * j) + 17, auth[j].TT);
            EEPROM.put(100 + (42 * j) + 21, auth[j].TD);
            EEPROM.commit();
            j = authNumber;
          }
        }
      }
      if (text.startsWith("/alarm_RH_")) {
        for (byte j = 0; j < authNumber; j++) {
          if (chat_id == auth[j].id) {
            if (text.substring(10) != "") {
              auth[j].RHT = text.substring(10).toFloat();
              if (auth[j].RHT > humidity[1]) {
                auth[j].RHD = 2;
                msg = "I will notify you once the Humidity increases to:\n";
              } else {
                auth[j].RHD = 1;
                msg = "I will notify you once the Humidity drops to:\n";
              }
              msg += String(auth[j].RHT) + " RH%";
              bot->sendMessage(chat_id, msg, "");
            } else {
              auth[j].RHD = 0;
              msg = "Alarm deactivated";
              bot->sendMessage(chat_id, msg, "");
            }
            EEPROM.put(100 + (42 * j) + 22, auth[j].RHT);
            EEPROM.put(100 + (42 * j) + 26, auth[j].RHD);
            EEPROM.commit();
            j = authNumber;
          }
        }
      }
      if (text.startsWith("/alarm_lux_")) {
        for (byte j = 0; j < authNumber; j++) {
          if (chat_id == auth[j].id) {
            if (text.substring(11) != "") {
              auth[j].luxT = text.substring(11).toFloat();
              if (auth[j].luxT > luminance[1]) {
                auth[j].luxD = 2;
                msg = "I will notify you once the Luminance increases to:\n";
              } else {
                auth[j].luxD = 1;
                msg = "I will notify you once the Luminance drops to:\n";
              }
              msg += String(auth[j].luxT) + " lx";
              bot->sendMessage(chat_id, msg, "");
            } else {
              auth[j].luxD = 0;
              msg = "Alarm deactivated";
              bot->sendMessage(chat_id, msg, "");
            }
            EEPROM.put(100 + (42 * j) + 27, auth[j].luxT);
            EEPROM.put(100 + (42 * j) + 31, auth[j].luxD);
            EEPROM.commit();
            j = authNumber;
          }
        }
      }
      if (text.startsWith("/alarm_V_")) {
        for (byte j = 0; j < authNumber; j++) {
          if (chat_id == auth[j].id) {
            if (text.substring(9) != "") {
              auth[j].vinT = text.substring(9).toFloat();
              if (auth[j].vinT > vin[1]) {
                auth[j].vinD = 2;
                msg = "I will notify you once the Supply Voltage increases to:\n";
              } else {
                auth[j].vinD = 1;
                msg = "I will notify you once the Supply Voltage drops to:\n";
              }
              msg += String(auth[j].vinT) + " mV";
              bot->sendMessage(chat_id, msg, "");
            } else {
              auth[j].vinD = 0;
              msg = "Alarm deactivated";
              bot->sendMessage(chat_id, msg, "");
            }
            EEPROM.put(100 + (42 * j) + 32, auth[j].vinT);
            EEPROM.put(100 + (42 * j) + 36, auth[j].vinD);
            EEPROM.commit();
            j = authNumber;
          }
        }
      }
    }
    if (text == "/test") {
      for (int i = 0; i < 5; i++) {
        bot->sendMessage(chat_id, "test", "");
        delay(0);
      }
    }
  }
}

String SState() {
  //String msg = "ESP sensor bot\n";
  String msg = "This is demm_bot.\n";
  msg += "Temperature: " + String(temperature[1]) + " °C\n";
  msg += "Relative Humidity: " + String(humidity[1]) + " RH%\n";
  msg += "Light luminance: " + String(luminance[1]) + " lx\n";
  msg += "Min:\n" + String(temperature[0]) + "°C " + String(humidity[0]) + "RH% " + String(luminance[0]) + "lx\n";
  msg += "Max:\n" + String(temperature[2]) + "°C " + String(humidity[2]) + "RH% " + String(luminance[2]) + "lx\n";
  return msg;
}

void loop() {
  String msg;
  if (!mclient.connected()) {
    //throw error but continue
    if (millis() - lastMC > 15000) {
      lastMC = millis();
      // Attempt to reconnect
      if (reconnect()) {
        lastMC = 0;
      }
      else {
        Serial.print("failed, rc=");
        Serial.print(mclient.state());
        Serial.println(" trying again in 15 seconds");
      }
    }
  } else {
    // Client connected
    mclient.loop();
  }



  if ((millis() - lastLTH) > LTH_INTERVAL) {
    lastLTH = millis();
    preReq++;

    Serial.print("lt");
    getlux();
    getdht();
    vin[1] = analogRead(A0) * 5.546;
    //min max storage
    if (luminance[1] < luminance[0]) {
      luminance[0] = luminance[1];
    }
    if (luminance[1] > luminance[2]) {
      luminance[2] = luminance[1];
    }
    if (temperature[1] < temperature[0]) {
      temperature[0] = temperature[1];
    }
    if (temperature[1] > temperature[2]) {
      temperature[2] = temperature[1];
    }
    if (humidity[1] < humidity[0]) {
      humidity[0] = humidity[1];
    }
    if (humidity[1] > humidity[2]) {
      humidity[2] = humidity[1];
    }
    if (vin[1] < vin[0]) {
      vin[0] = vin[1];
    }
    if (vin[1] > vin[2]) {
      vin[2] = vin[1];
    }
    Serial.print("h ");

    //low voltage alarm
    if ((vin[1] < lowvoltage) && (!lowvoltagesent)) {
      lowvoltagesent = 1;
      for (byte j = 0; j < authNumber; j++) {
        if (auth[j].id != "") {
          msg = "Low Supply Voltage:\n";
          msg += String(vin[1]) + " mV\n";
          bot->sendMessage(auth[j].id, msg, "");
          //bot->sendMessage(auth[j].id, SState(), "");  //send status
        }
      }
    }

    //alarm notifications
    for (byte j = 0; j < authNumber; j++) {
      //user threshold alarms
      if (auth[j].TD == 2) {
        if (auth[j].TT < temperature[1]) {
          auth[j].TD = 0;
          EEPROM.write(100 + (42 * j) + 21, 0);
          EEPROM.commit();
          msg = "The Temperature reached:\n";
          msg += String(auth[j].TT) + " °C\n";
          bot->sendMessage(auth[j].id, msg, "");
          bot->sendMessage(auth[j].id, SState(), "");  //send status
        }
      }
      if (auth[j].TD == 1) {
        if (auth[j].TT > temperature[1]) {
          auth[j].TD = 0;
          EEPROM.write(100 + (42 * j) + 21, 0);
          EEPROM.commit();
          msg = "The Temperature reached:\n";
          msg += String(auth[j].TT) + " °C\n";
          bot->sendMessage(auth[j].id, msg, "");
          bot->sendMessage(auth[j].id, SState(), "");  //send status
        }
      }
      if (auth[j].RHD == 2) {
        if (auth[j].RHT < humidity[1]) {
          auth[j].RHD = 0;
          EEPROM.write(100 + (42 * j) + 26, 0);
          EEPROM.commit();
          msg = "The Humidity reached:\n";
          msg += String(auth[j].RHT) + " RH%\n";
          bot->sendMessage(auth[j].id, msg, "");
          bot->sendMessage(auth[j].id, SState(), "");  //send status
        }
      }
      if (auth[j].RHD == 1) {
        if (auth[j].RHT > humidity[1]) {
          auth[j].RHD = 0;
          EEPROM.write(100 + (42 * j) + 26, 0);
          EEPROM.commit();
          msg = "The Humidity reached:\n";
          msg += String(auth[j].RHT) + " RH%\n";
          bot->sendMessage(auth[j].id, msg, "");
          bot->sendMessage(auth[j].id, SState(), "");  //send status
        }
      }
      if (auth[j].luxD == 2) {
        if (auth[j].luxT < luminance[1]) {
          auth[j].luxD = 0;
          EEPROM.write(100 + (42 * j) + 31, 0);
          EEPROM.commit();
          msg = "The Luminance reached:\n";
          msg += String(auth[j].luxT) + " lx\n";
          bot->sendMessage(auth[j].id, msg, "");
          bot->sendMessage(auth[j].id, SState(), "");  //send status
        }
      }
      if (auth[j].luxD == 1) {
        if (auth[j].luxT > luminance[1]) {
          auth[j].luxD = 0;
          EEPROM.write(100 + (42 * j) + 31, 0);
          EEPROM.commit();
          msg = "The Luminance reached:\n";
          msg += String(auth[j].luxT) + " lx\n";
          bot->sendMessage(auth[j].id, msg, "");
          bot->sendMessage(auth[j].id, SState(), "");  //send status
        }
      }
      if (auth[j].vinD == 2) {
        if (auth[j].vinT < vin[1]) {
          auth[j].vinD = 0;
          EEPROM.write(100 + (42 * j) + 36, 0);
          EEPROM.commit();
          msg = "The Supply Voltage reached:\n";
          msg += String(auth[j].vinT) + " mV\n";
          bot->sendMessage(auth[j].id, msg, "");
          bot->sendMessage(auth[j].id, SState(), "");  //send status
        }
      }
      if (auth[j].vinD == 1) {
        if (auth[j].vinT > vin[1]) {
          auth[j].vinD = 0;
          EEPROM.write(100 + (42 * j) + 36, 0);
          EEPROM.commit();
          msg = "The Supply Voltage reached:\n";
          msg += String(auth[j].vinT) + " mV\n";
          bot->sendMessage(auth[j].id, msg, "");
          bot->sendMessage(auth[j].id, SState(), "");  //send status
        }
      }
    }
  }

  if (((millis() - lastMQTT) > MQTT_INTERVAL) && (preReq >= 2)) {  //
    lastMQTT = millis();
    preReq = 0;

    //Serial.println("Ambient Light luminance: "+String(luminance[1])+" lx");
    //Serial.print("DHT22 Values: ");
    //Serial.print((float)temperature[1]); Serial.print(" °C, ");
    //Serial.print((float)humidity[1]); Serial.println(" RH%");
    //Serial.println("Vin: "+String(vin[1])+"mV");

    if (mclient.connected()) {

      Serial.println("MQTT Publish");

      updateID++;
      msg = String(updateID);
      mclient.publish("demm_bot/updateID", msg.c_str());
      msg = String(luminance[1]);
      mclient.publish("demm_bot/lux", msg.c_str());
      msg = String(temperature[1]);
      mclient.publish("demm_bot/T", msg.c_str());
      msg = String(humidity[1]);
      mclient.publish("demm_bot/RH", msg.c_str());
      msg = String(vin[1]);
      mclient.publish("demm_bot/vin", msg.c_str());

    }
    else {
      Serial.println("MQTT not connected!");
    }
  }

  if (millis() > lastBOT + Bot_mtbs)  {
    int numNewMessages = bot->getUpdates(bot->last_message_received + 1);

    while (numNewMessages) {
      Serial.println("got response");
      handleNewMessages(numNewMessages);
      numNewMessages = bot->getUpdates(bot->last_message_received + 1);
    }

    lastBOT = millis();
  }

  //check for millis overflow
  if (millis() < lastMQTT) {
    lastMQTT = millis();
  }
  if (millis() < lastLTH) {
    lastLTH = millis();
  }
  if (millis() < lastMC) {
    lastMC = millis();
  }
  if (millis() < lastBOT) {
    lastBOT = millis();
  }
  /*
    if(!digitalRead(EN_deepsleep)){
    Serial.print("DS ");
    delay(1000);
    //delay(2000);
    ESP.deepSleep(1000000);
    delay(1000);
    }*/
}

Leave a Reply

Your email address will not be published.

*