MQTT how to publish Sensor value

//Including the four libraries
#include <UniversalTelegramBot.h>
#include <WiFi.h>
#include <WiFiClientSecure.h>
#include <PubSubClient.h>

//------- WiFi Settings -------
const char* ssid = "";
const char* password = "";
const char* mqtt_server = "";
const char* mqtt_username = "";
const char* mqtt_password = ""; 

// ------- Telegram config --------
#define BOT_TOKEN ""  // your Bot Token (Get from Botfather)
#define CHAT_ID "" // Chat ID of where you want the message to go (You can use MyIdBot to get the chat ID)

const int gasAnalogPin = 32;
long Bot_lasttime;


WiFiClientSecure espClient;
UniversalTelegramBot bot(BOT_TOKEN, espClient);

WiFiClient Client;
PubSubClient client(Client);

String ipAddress = "";

volatile bool telegramButton1PressedFlag = false;
volatile bool telegramButton2PressedFlag = false;
volatile bool telegramButton3PressedFlag = false;
volatile bool telegramButton4PressedFlag = false;

long lastMsg = 0;
char msg[50];

void setup_wifi() {

  delay(10);
  // We start by connecting to a WiFi network
  Serial.println();
  Serial.print("Connecting to ");
  Serial.println(ssid);

  WiFi.begin(ssid, password);

  while (WiFi.status() != WL_CONNECTED) {
    delay(500);
    Serial.print(".");
  }

  randomSeed(micros());

  Serial.println("");
  Serial.println("WiFi connected");
  Serial.println("IP address: ");
  Serial.println(WiFi.localIP());
}

void callback(char* topic, byte* payload, unsigned int length) {
  Serial.print("Message arrived [");
  Serial.print(topic);
  Serial.print("] ");
  for (int i = 0; i < length; i++) {
    Serial.print((char)payload[i]);
  }
  Serial.println();
}

void reconnect() {
  // Loop until we're reconnected
  while (!client.connected()) {
    Serial.print("Attempting MQTT connection...");
    // Create a random client ID
    String clientId = "ESP32Client-";
    clientId += String(random(0xffff), HEX);
    // Attempt to connect
    if (client.connect(clientId.c_str(), mqtt_username , mqtt_password)) {
      Serial.println("connected");
      client.publish("SmartToilet", "welcome");
      // ... and resubscribe
      client.subscribe("SmartToilet");
    } else {
      Serial.print("failed, rc=");
      Serial.print(client.state());
      Serial.println(" try again in 5 seconds");
      // Wait 5 seconds before retrying
      delay(5000);
    }
  }
}

void setup() {
Serial.begin(115200);
pinMode(gasAnalogPin, INPUT);
setup_wifi();
client.setServer(mqtt_server, 1883);
client.setCallback(callback);
}
void sendTelegramMessage1() {
  String message = "Air was good @ 27 Mandai Estate Meeting Room!";
  if(bot.sendMessage(CHAT_ID, message, "Markdown")){
    Serial.println("TELEGRAM Message 1 Successfully sent");
  }
  telegramButton1PressedFlag = false;
}

void sendTelegramMessage2() {
  String message2 = "Air was poor, please turn on the aircondition fan @ 27 Mandai Estate Meeting Room!";
  if(bot.sendMessage(CHAT_ID, message2, "Markdown")){
    Serial.println("TELEGRAM Message 2 Successfully sent");
  }
  telegramButton2PressedFlag = false;
}

void sendTelegramMessage3() {
  String message3 = "Air was bad, please leave the room @ 27 Mandai Estate Meeting Room!";
  if(bot.sendMessage(CHAT_ID, message3, "Markdown")){
    Serial.println("TELEGRAM Message 3 Successfully sent");
  }
  telegramButton3PressedFlag = false;
}

void sendTelegramMessage4() {
  String message4 = "Air was terrible, please emergency evaculation @ 27 Mandai Estate Meeting Room!";
  if(bot.sendMessage(CHAT_ID, message4, "Markdown")){
    Serial.println("TELEGRAM Message 4 Successfully sent");
  }
  telegramButton4PressedFlag = false;
}

void loop() {
  if (!client.connected()) {
    reconnect();
  }
  client.loop();
  float myfloat;
  float V0 = 750;
  float Rs = 0;
  float R0 = 0; 
  float Voltage;
  float Vout = 1183;
  float ratio = 0;
  static bool value_reach = false;
  static bool value_reach2 = false;
           R0 = ((20000*5000/V0)-40000);
           Rs = ((20000*5000/analogRead(gasAnalogPin))-40000);
  ratio = Rs/R0; //Replace R0 with the value found using the sketch above
  
    Serial.println(R0);
    Serial.println(Rs);
    Serial.println(ratio); // How to calculate PPM?
    Serial.println("ratio");
    delay(1000);
  char msg[30];
  char val[10];
  dtostrf(Ratio, 8, 0, val);
  if (ratio > 1.00) {                  //good stage 1     
       Serial.println("checking ratio (1) again");     
       delay(3000);  
       if(!value_reach)
{
                   if(ratio > 1.00){
                        snprintf (msg, 50, "Air quailty good!", val);                                                                   
                        Serial.println("Publish message: ");
                        Serial.println(msg);
                        client.publish("SmartToilet", msg);
                        Serial.println("Send notification 1 to Telegram");    
                        sendTelegramMessage1();       
                        value_reach = true;
                        Bot_lasttime = 0;
             
}  
}
} else if (ratio > 0.50 && ratio < 1.00) {        //bad   stage 2
            Serial.println("checking ratio (2) again");     
            delay(3000);
            if(value_reach)
{              
                           if(ratio > 0.50 && ratio < 1.00){
                                snprintf (msg, 50, "Air quailty bad!", val);               
                                Serial.print("Publish message: ");
                                Serial.println(msg);
                                client.publish("SmartToilet", msg);   
                                Serial.println("Send notification 2 to Telegram");
                                sendTelegramMessage2();
                                Bot_lasttime = 0;              
            value_reach = false;     
}
}
} else if (ratio > 0.10 && ratio <0.50){        //poor  stage 3
             Serial.println("checking ratio (3) again");     
             delay(3000);
             if(!value_reach2)
{
                           if (ratio > 0.10 && ratio <0.50){
                                 snprintf (msg, 50, "Air quailty poor!", val);               
                                 Serial.print("Publish message: ");
                                 Serial.println(msg);
                                 client.publish("SmartToilet", msg);         
                                 Serial.println("Send notification 3 to Telegram"); 
                                 sendTelegramMessage3();              
                                 value_reach2 = true;
                                 Bot_lasttime = 0;

}
}
} else if (ratio < 0.10){        //terrible stage 4
            Serial.println("checking ratio (4) again");     
            delay(3000);
            if(value_reach2)
{             
                         if (ratio < 0.10){
                               snprintf (msg, 50, "Air quailty terrible!", val);               
                               Serial.print("Publish message: ");
                               Serial.println(msg);
                               client.publish("SmartToilet", msg);              
                               Serial.println("Send notification 4 to Telegram");
                               sendTelegramMessage4();
                               Bot_lasttime = 0;
            value_reach2 = false;             
}
}
}
}

Full code . i wish to sending my ratio value publish to mqtt how can i do that .

problem solve .

//Thank you commuity for your help,obviously i'm a beginner and I hope this helps you but really all I did was use two awesome libraries DHT and PubSubclient 
//then combine the two great examples DHT_TEST and PubSubclient example mqtt_esp8266 and alter how I packed up for publishing
//the tricky part for me was figuring out how to convert from a float supported by DHT.h to the string supported by PubSubclient see last section of code for that
//This will publish the temperature and humidity from your DHT sensor connected to your ESP8266 to an Mqtt broker, I am using Mosquitto.  

#include <ESP8266WiFi.h>
#include <PubSubClient.h>
#include "DHT.h"


DHT dht;
WiFiClient espClient;
PubSubClient client(espClient);
long lastMsg = 0;
int value = 0;

// Configure your network here

const char* ssid = "XXXXXX"; ///UPDATE with your network 
const char* password = "XXXXX"; ///Your password
const char* mqtt_server = "XXXXXX"; ///your URL or IP address

// Variables for printing temp and humidity

String temp_str; //see last code block below use these to convert the float that you get back from DHT to a string =str
String hum_str;
char temp[50];
char hum[50];

//setting up Wifi didn't change this from the example PubSubclient example mqtt_esp8266

void setup_wifi() {

  delay(10);
  // We start by connecting to a WiFi network
  Serial.println();
  Serial.print("Connecting to ");
  Serial.println(ssid);

  WiFi.begin(ssid, password);

  while (WiFi.status() != WL_CONNECTED) {
    delay(500);
    Serial.print(".");
  }

  Serial.println("");
  Serial.println("WiFi connected");
  Serial.println("IP address: ");
  Serial.println(WiFi.localIP());
}

void callback(char* topic, byte* payload, unsigned int length) {
  Serial.print("Message arrived [");
  Serial.print(topic);
  Serial.print("] ");
  for (int i = 0; i < length; i++) {
    Serial.print((char)payload[i]);
  }
  Serial.println();

  // Switch on the LED if an 1 was received as first character
  if ((char)payload[0] == '1') {
    digitalWrite(BUILTIN_LED, LOW);   // Turn the LED on (Note that LOW is the voltage level
    // but actually the LED is on; this is because
    // it is acive low on the ESP-01)
  } else {
    digitalWrite(BUILTIN_LED, HIGH);  // Turn the LED off by making the voltage HIGH
  }

}

void reconnect() {
  // Loop until we're reconnected
  while (!client.connected()) {
    Serial.print("Attempting MQTT connection...");
    // Attempt to connect
    if (client.connect("ESP8266Client")) {
      Serial.println("connected");
      // Once connected, publish an announcement...
      client.publish("outTopic", "hello world");
      // ... and resubscribe
      client.subscribe("inTopic");
    } else {
      Serial.print("failed, rc=");
      Serial.print(client.state());
      Serial.println(" try again in 5 seconds");
      // Wait 5 seconds before retrying
      delay(5000);
    }
  }
}


void setup()   
{
pinMode(BUILTIN_LED, OUTPUT);     // Initialize the BUILTIN_LED pin as an output
  Serial.begin(115200);
  setup_wifi();
  client.setServer(mqtt_server, 1883);
  client.setCallback(callback);
  Serial.println();
  Serial.println("Status\tHumidity (%)\tTemperature (C)\t(F)");  //debug serial print

  
// Call out your data pin for your DHT sensor here

dht.setup(13); 

// 
}

//--(end setup )---


void loop()   
{
  if (!client.connected()) {
    reconnect();
  }
  client.loop();
delay(dht.getMinimumSamplingPeriod());

//this is where you get the data from the sensor

  float humidity = dht.getHumidity(); 
  float temperature = dht.getTemperature();
  float ftemp = dht.toFahrenheit(temperature);

//Using Serial print to debug

  Serial.print(dht.getStatusString());
  Serial.print("\t");
  Serial.print(humidity, 1);
  Serial.print("\t\t");
  Serial.print(temperature, 1);
  Serial.print("\t\t");
  Serial.println(dht.toFahrenheit(temperature), 1);

 
//counter for the messages, see if I am missing any on the Mqtt broker
  
  long now = millis(); 
  if (now - lastMsg > 2000) {
    lastMsg = now;
    ++value;
    
//Preparing for mqtt send

    temp_str = String(ftemp); //converting ftemp (the float variable above) to a string 
    temp_str.toCharArray(temp, temp_str.length() + 1); //packaging up the data to publish to mqtt whoa...

    hum_str = String(humidity); //converting Humidity (the float variable above) to a string
    hum_str.toCharArray(hum, hum_str.length() + 1); //packaging up the data to publish to mqtt whoa...

    Serial.print("Publish message: ");//all of these Serial prints are to help with debuging
    
    client.publish("Workshop Temperature", temp); //money shot
    client.publish("Workshop Humidity", hum);
  }

}
1 Like