MQTT Arduino Mega ethernet sheld2 server

Hello Everyone I need Help for MQTT server. who help me MQTT Arduino Mega ethernet sheld2 server?

Could you give just a little bit more information please!

What help do you need, what code have you got, what is the requirment of use?

// I need to add MQTT server my project? please check

#include <SPI.h>
#include <Ethernet2.h>
#include <SD.h>
// size of buffer used to capture HTTP requests
#define REQ_BUF_SZ   60
const int buzzer = 13; //buzzer to arduino pin 13

//---------LCD 16x2 LiquidCrystal_I2C----------//
#include <Wire.h>
#include <LiquidCrystal_I2C.h>
LiquidCrystal_I2C lcd(0x27, 16, 2);
//---------LCD 16x2 LiquidCrystal_I2C--------//

// Enter a MAC address and IP address for your controller below.
// The IP address will be dependent on your local network:
byte mac[] = {
  0xDE, 0xAD, 0xBE, 0xEF, 0xFE, 0xED
};
IPAddress ip(192, 168, 0, 180);

// Initialize the Ethernet server library
// with the IP address and port you want to use
// (port 80 is default for HTTP):
EthernetServer server(80);
File webFile;                     // the web page file on the SD card
char HTTP_req[REQ_BUF_SZ] = {0};  // buffered HTTP request stored as null terminated string
char req_index = 0;               // index into HTTP_req buffer
unsigned char LED_state[3] = {0}; // stores the states of the LEDs, 1 bit per LED

byte customChar[] = {
  B00001,
  B00011,
  B00111,
  B11111,
  B11111,
  B00111,
  B00011,
  B00001
};

void setup() {
  int i;
  // disable Ethernet chip
  pinMode(buzzer, OUTPUT); // Set buzzer - pin 13 as an output
  pinMode(10, OUTPUT);
  digitalWrite(10, HIGH);
  pinMode(3, INPUT);        // switch is attached to Arduino pin 3
  lcd.setBacklight(HIGH);
  
  //---------LCD 16x2 LiquidCrystal_I2C----------------------//
  //lcd.begin(); // initialize the LCD
  lcd.init(); // initialize the lcd
  lcd.backlight(); // Turn on the blacklight and print a message.
  lcd.setCursor(4, 0); // Set the cursor on the first column and first row.
  lcd.print("NEWTECH");
  lcd.setCursor(1, 1); // Set the cursor on the first column and first row.
  lcd.print("Home Automation");
  delay(1000);
  //---------LCD 16x2 LiquidCrystal_I2C----------------------//

  // Open serial communications and wait for port to open:
  Serial.begin(9600);

  // initialize SD card
  Serial.println("Initializing SD card...");
  if (!SD.begin(4)) {
    Serial.println("ERROR - SD card initialization failed!");
    lcd.clear();
    delay(200);
    lcd.setCursor(1, 0); // Set the cursor on the first column and first row.
    lcd.print("!System Fail!");
    lcd.createChar(0, customChar);
    lcd.setCursor(14, 0); // move cursor to (2, 0)
    lcd.write((byte)0);  // print the custom char at (2, 0)
    delay(1000);
    lcd.clear();
    lcd.setCursor(0, 1); // Set the cursor on the first column and first row.
    lcd.print("Put The SD Card?");
    // delay(1000);
    tone(buzzer, 1000); // Send 1KHz sound signal...
    delay(1000);        // ...for 1 sec
    //noTone(buzzer);     // Stop sound...
    return;    // init failed
  }
  Serial.println("SUCCESS - SD card initialized.");
  lcd.clear();
  delay(200);
  lcd.setCursor(1, 0); // Set the cursor on the first column and first row.
  lcd.print("SD Initialized");
  delay(500);
  lcd.setCursor(2, 1); // Set the cursor on the first column and first row.
  lcd.print("SD Card Found");
  delay(500);

  // check for index.htm file
  if (!SD.exists("index.htm")) {
    Serial.println("ERROR - Can't find index.htm file!");
    return;  // can't find index file
  }
  Serial.println("SUCCESS - Found index.htm file.");

  // pins 26 to 49 are outputs
  for (i = 26; i <= 49; i++) {
    pinMode(i, OUTPUT);    // set pins as outputs
    digitalWrite(i, LOW);  // switch the output pins off
  }

  while (!Serial) {
    ; // wait for serial port to connect. Needed for Leonardo only
  }

  // start the Ethernet connection and the server:
  Ethernet.begin(mac, ip);
  server.begin();
  Serial.print("Newtech Server IP is at = ");
  Serial.println(Ethernet.localIP());
}


void SendOKpage(EthernetClient &client)
{
  // send a standard http response header
  client.println("HTTP/1.1 200 OK");
}


void SendAuthentificationpage(EthernetClient &client)
{
  client.println("HTTP/1.1 401 Authorization Required");
  client.println("WWW-Authenticate: Basic realm=\"Secure Area\"");
  client.println("Content-Type: text/html");
  client.println("Connnection: close");
  client.println();
  client.println("<!DOCTYPE HTML>");
  client.println("<HTML>  <HEAD>   <TITLE>Error</TITLE>");
  client.println(" </HEAD> <BODY><H1>401 Unauthorized.</H1></BODY> </HTML>");
}

char linebuf[80];
int charcount = 0;
boolean authentificated = false;
void loop() {  
 /* //lcd.clear();
  lcd.setCursor(1, 0); // Set the cursor on the first column and first row.
  lcd.print("!Ethernet Fail!");
  lcd.setCursor(2, 1); // Set the cursor on the first column and first row.
  lcd.print("00:00:00:00??");
 */ 
 /* //lcd.clear();
  lcd.setCursor(1, 0); // Set the cursor on the first column and first row.
  lcd.print("NEWTECH Teconlogy");
  lcd.setCursor(1, 1); // Set the cursor on the first column and first row.
  lcd.print("Home Automation");
 */ 
  // print your local IP address:
  // listen for incoming clients
  EthernetClient client = server.available();
  if (client) {
    Serial.println("new client");
   // lcd.clear();
    lcd.setCursor(1, 0);                   // Set the cursor on the LCD to Col 1 Row 1
    lcd.print("Lan IP Address:");          // Print on text on the LCD
    lcd.setCursor(2, 1);                   //set the cursor on the LCD to Col 0 Row 2
    lcd.print(Ethernet.localIP());         // Print the IP address on the LCD
    memset(linebuf, 0, sizeof(linebuf));
    charcount = 0;
    authentificated = false;
    // an http request ends with a blank line
    boolean currentLineIsBlank = true;
    while (client.connected()) {
      if (client.available()) {
        char c = client.read();
        if (req_index < (REQ_BUF_SZ - 1)) {
          HTTP_req[req_index] = c;          // save HTTP request character
          req_index++;
        }

        linebuf[charcount] = c;
        if (charcount < sizeof(linebuf) - 1) charcount++;
        Serial.write(c);
        // if you've gotten to the end of the line (received a newline
        // character) and the line is blank, the http request has ended,
        // so you can send a reply
        if (c == '\n' && currentLineIsBlank) {
          if (authentificated )

            SendOKpage(client);
          else
            SendAuthentificationpage(client);

          // send a standard http response header
          client.println("HTTP/1.1 200 OK");
          // remainder of header follows below, depending on if
          // web page or XML page is requested
          // Ajax request - send XML file
          if (StrContains(HTTP_req, "ajax_inputs")) {
            // send rest of HTTP header
            client.println("Content-Type: text/xml");
            client.println("Connection: keep-alive");
            client.println();
            SetLEDs();
            // send XML file containing input states
            XML_response(client);
          }
          else {  // web page request
            // send rest of HTTP header
            client.println("Content-Type: text/html");
            client.println("Connection: keep-alive");
            client.println();
            // send web page
            webFile = SD.open("index.htm");        // open web page file
            if (webFile) {
              while (webFile.available()) {
                client.write(webFile.read()); // send web page to client
              }
              webFile.close();
            }
          }
          // display received HTTP request on serial port
          //Serial.print(HTTP_req);
          // reset buffer index and all buffer elements to 0
          req_index = 0;
          StrClear(HTTP_req, REQ_BUF_SZ);
          break;
        }

        if (c == '\n') {
          // you're starting a new line
          currentLineIsBlank = true;
          if (strstr(linebuf, "Authorization: Basic") > 0 && strstr(linebuf, "Z2lhc2g6Z2lhc2g=") > 0)
            authentificated = true;
          memset(linebuf, 0, sizeof(linebuf));
          charcount = 0;
        }
        else if (c != '\r') {
          // you've gotten a character on the current line
          currentLineIsBlank = false;
        }
      }
    }
    // give the web browser time to receive the data
    delay(1);
    // close the connection:
    client.stop();
    Serial.println("client disonnected");
  }    
} 
// checks if received HTTP request is switching on/off LEDs
// also saves the state of the LEDs
void SetLEDs(void)
{   
  char str_on[12] = {0};
  char str_off[12] = {0};
  unsigned char i;
  unsigned int  j;
  int LED_num = 1;

  for (i = 0; i < 3; i++) {
    for (j = 1; j <= 0x80; j <<= 1) {
      sprintf(str_on,  "LED%d=%d", LED_num, 1);
      sprintf(str_off, "LED%d=%d", LED_num, 0);
      if (StrContains(HTTP_req, str_on)) {
        LED_state[i] |= (unsigned char)j;  // save LED state
        digitalWrite(LED_num + 25, HIGH);
        tone(buzzer, 5000); // Send 1KHz sound signal...
        delay(100);        // ...for 1 sec
        noTone(buzzer);     // Stop sound...
        lcd.clear();
        lcd.setCursor(1, 0);                   // Set the cursor on the LCD to Col 1 Row 1
        lcd.print("Data Pass HIGH");          // Print on text on the LCD
        delay (500);
        Serial.println("ON");
      }
      else if (StrContains(HTTP_req, str_off)) {
        LED_state[i] &= (unsigned char)(~j);  // save LED state
        digitalWrite(LED_num + 25, LOW);
        tone(buzzer, 5000); // Send 1KHz sound signal...
        delay(100);        // ...for 1 sec
        noTone(buzzer);     // Stop sound...
        lcd.clear();
        lcd.setCursor(1, 0);                   // Set the cursor on the LCD to Col 1 Row 1
        lcd.print("Data Pass LOW");          // Print on text on the LCD
        delay (500);
      }
      LED_num++;
    }
  }
}
//------------------------End Loop--------------------------------------------//

// send the XML file with analog values, switch status
//  and LED status
void XML_response(EthernetClient cl)
{
  unsigned char i;
  unsigned int  j;

  cl.print("<?xml version = \"1.0\" ?>");
  cl.print("<inputs>");
  for (i = 0; i < 3; i++) {
    for (j = 1; j <= 0x80; j <<= 1) {
      cl.print("<LED>");
      if ((unsigned char)LED_state[i] & j) {
        cl.print("checked");
        //Serial.println("ON");
      }
      else {
        cl.print("unchecked");
      }
      cl.println("</LED>");
    }
  }
  cl.print("</inputs>");
}

// sets every element of str to 0 (clears array)
void StrClear(char *str, char length)
{
  for (int i = 0; i < length; i++) {
    str[i] = 0;
  }
}

// searches for the string sfind in the string str
// returns 1 if string found
// returns 0 if string not found
char StrContains(char *str, char *sfind)
{
  char found = 0;
  char index = 0;
  char len;

  len = strlen(str);

  if (strlen(sfind) > len) {
    return 0;
  }
  while (index < len) {
    if (str[index] == sfind[found]) {
      found++;
      if (strlen(sfind) == found) {
        return 1;
      }
    }
    else {
      found = 0;
    }
    index++;
  }

  return 0;
}

The Mega cannot run MQTT server. You can use an online MQTT Broker (server) or you can run your own MQTT Broker on a PC of your choosing.

The Mega should be able to run PubSubClient which can connect to a MQTT server.

Here is some ESP32 MQTT client code you can use as a model.

/*
   Chappie Weather upgrade/addition
   process wind speed direction and rain fall.
*/
#include <WiFi.h>
#include <PubSubClient.h>
#include "certs.h"
#include "sdkconfig.h"
#include "esp_system.h"
#include "freertos/FreeRTOS.h"
#include "freertos/task.h"
#include "freertos/timers.h"
#include "freertos/event_groups.h"
#include "driver/pcnt.h"
#include <driver/adc.h>
#include <SimpleKalmanFilter.h>
#include <ESP32Time.h>
////
ESP32Time rtc;
WiFiClient wifiClient;
PubSubClient MQTTclient(mqtt_server, mqtt_port, wifiClient);
////
float CalculatedVoltage = 0.0f;
float kph = 0.0f;
float rain  = 0.0f;
/*
   PCNT PCNT_UNIT_0, PCNT_CHANNEL_0 GPIO_NUM_15 = pulse input pin
   PCNT PCNT_UNIT_1, PCNT_CHANNEL_0 GPIO_NUM_4 = pulse input pin
*/
pcnt_unit_t pcnt_unit00 = PCNT_UNIT_0; //pcnt unit 0 channel 0
pcnt_unit_t pcnt_unit10 = PCNT_UNIT_1; //pcnt unit 1 channel 0
//
//
hw_timer_t * timer = NULL;
//
#define evtAnemometer  ( 1 << 0 )
#define evtRainFall    ( 1 << 1 )
#define evtParseMQTT   ( 1 << 2 )
EventGroupHandle_t eg;
#define OneMinuteGroup ( evtAnemometer | evtRainFall )
////
QueueHandle_t xQ_Message; // payload and topic queue of MQTT payload and topic
const int payloadSize = 100;
struct stu_message
{
  char payload [payloadSize] = {'\0'};
  String topic ;
} x_message;
////
SemaphoreHandle_t sema_MQTT_KeepAlive;
SemaphoreHandle_t sema_mqttOK;
SemaphoreHandle_t sema_CalculatedVoltage;
////
int mqttOK = 0; // stores a count value that is used to cause an esp reset
volatile bool TimeSet = false;
////
/*
   A single subject has been subscribed to, the mqtt broker sends out "OK" messages if the client receives an OK message the mqttOK value is set back to zero.
*/
////
void IRAM_ATTR mqttCallback(char* topic, byte * payload, unsigned int length)
{
  memset( x_message.payload, '\0', payloadSize ); // clear payload char buffer
  x_message.topic = ""; //clear topic string buffer
  x_message.topic = topic; //store new topic
    int i = 0; // extract payload
    for ( i; i < length; i++)
    {
      x_message.payload[i] = ((char)payload[i]);
    }
    x_message.payload[i] = '\0';
    xQueueOverwrite( xQ_Message, (void *) &x_message );// send data to queue
} // void mqttCallback(char* topic, byte* payload, unsigned int length)
////
// interrupt service routine for WiFi events put into IRAM
void IRAM_ATTR WiFiEvent(WiFiEvent_t event)
{
  switch (event) {
    case SYSTEM_EVENT_STA_CONNECTED:
      break;
    case SYSTEM_EVENT_STA_DISCONNECTED:
      log_i("Disconnected from WiFi access point");
      break;
    case SYSTEM_EVENT_AP_STADISCONNECTED:
      log_i("WiFi client disconnected");
      break;
    default: break;
  }
} // void IRAM_ATTR WiFiEvent(WiFiEvent_t event)
////
void IRAM_ATTR onTimer()
{
  BaseType_t xHigherPriorityTaskWoken;
  xEventGroupSetBitsFromISR(eg, OneMinuteGroup, &xHigherPriorityTaskWoken);
} // void IRAM_ATTR onTimer()
////
void setup()
{
  eg = xEventGroupCreate(); // get an event group handle
  //  x_message.topic.reserve(300);
  adc1_config_width(ADC_WIDTH_12Bit);
  adc1_config_channel_atten(ADC1_CHANNEL_6, ADC_ATTEN_DB_11);// using GPIO 34 wind direction
  adc1_config_channel_atten(ADC1_CHANNEL_3, ADC_ATTEN_DB_11);// using GPIO 39 current
  adc1_config_channel_atten(ADC1_CHANNEL_0, ADC_ATTEN_DB_11);// using GPIO 36 battery volts

  // hardware timer 4 set for one minute alarm
  timer = timerBegin( 3, 80, true );
  timerAttachInterrupt( timer, &onTimer, true );
  timerAlarmWrite(timer, 60000000, true);
  timerAlarmEnable(timer);
  /* Initialize PCNT's counter */
  int PCNT_H_LIM_VAL         = 3000;
  int PCNT_L_LIM_VAL         = -10;
  // 1st PCNT counter
  pcnt_config_t pcnt_config  = {};
  pcnt_config.pulse_gpio_num = GPIO_NUM_15;// Set PCNT input signal and control GPIOs
  pcnt_config.ctrl_gpio_num  = PCNT_PIN_NOT_USED;
  pcnt_config.channel        = PCNT_CHANNEL_0;
  pcnt_config.unit           = PCNT_UNIT_0;
  // What to do on the positive / negative edge of pulse input?
  pcnt_config.pos_mode       = PCNT_COUNT_INC;   // Count up on the positive edge
  pcnt_config.neg_mode       = PCNT_COUNT_DIS;   // Count down disable
  // What to do when control input is low or high?
  pcnt_config.lctrl_mode     = PCNT_MODE_KEEP; // do not count if low reverse
  pcnt_config.hctrl_mode     = PCNT_MODE_KEEP;    // Keep the primary counter mode if high
  // Set the maximum and minimum limit values to watch
  pcnt_config.counter_h_lim  = PCNT_H_LIM_VAL;
  pcnt_config.counter_l_lim  = PCNT_L_LIM_VAL;
  pcnt_unit_config(&pcnt_config); // Initialize PCNT unit
  pcnt_set_filter_value( PCNT_UNIT_0, 1); //Configure and enable the input filter
  pcnt_filter_enable( PCNT_UNIT_0 );
  pcnt_counter_pause( PCNT_UNIT_0 );
  pcnt_counter_clear( PCNT_UNIT_0 );
  pcnt_counter_resume( PCNT_UNIT_0); // start the show
  // setup 2nd PCNT
  pcnt_config = {};
  pcnt_config.pulse_gpio_num = GPIO_NUM_4;
  pcnt_config.ctrl_gpio_num  = PCNT_PIN_NOT_USED;
  pcnt_config.channel        = PCNT_CHANNEL_0;
  pcnt_config.unit           = PCNT_UNIT_1;
  pcnt_config.pos_mode       = PCNT_COUNT_INC;
  pcnt_config.neg_mode       = PCNT_COUNT_DIS;
  pcnt_config.lctrl_mode     = PCNT_MODE_KEEP;
  pcnt_config.hctrl_mode     = PCNT_MODE_KEEP;
  pcnt_config.counter_h_lim  = PCNT_H_LIM_VAL;
  pcnt_config.counter_l_lim  = PCNT_L_LIM_VAL;
  pcnt_unit_config(&pcnt_config);
  //pcnt_set_filter_value( PCNT_UNIT_1, 1 );
  //pcnt_filter_enable  ( PCNT_UNIT_1 );
  pcnt_counter_pause  ( PCNT_UNIT_1 );
  pcnt_counter_clear  ( PCNT_UNIT_1 );
  pcnt_counter_resume ( PCNT_UNIT_1 );
  //
  xQ_Message = xQueueCreate( 1, sizeof(stu_message) );
  //
  sema_CalculatedVoltage = xSemaphoreCreateBinary();
  xSemaphoreGive( sema_CalculatedVoltage );
  sema_mqttOK = xSemaphoreCreateBinary();
  xSemaphoreGive( sema_mqttOK );
  sema_MQTT_KeepAlive = xSemaphoreCreateBinary();
  ///
  xTaskCreatePinnedToCore( MQTTkeepalive, "MQTTkeepalive", 15000, NULL, 5, NULL, 1 );
  xTaskCreatePinnedToCore( fparseMQTT, "fparseMQTT", 10000, NULL, 5, NULL, 1 ); // assign all to core 1, WiFi in use.
  xTaskCreatePinnedToCore( fReadBattery, "fReadBattery", 4000, NULL, 3, NULL, 1 );
  xTaskCreatePinnedToCore( fReadCurrent, "fReadCurrent", 4000, NULL, 3, NULL, 1 );
  xTaskCreatePinnedToCore( fWindDirection, "fWindDirection", 10000, NULL, 4, NULL, 1 );
  xTaskCreatePinnedToCore( fAnemometer, "fAnemometer", 10000, NULL, 4, NULL, 1 );
  xTaskCreatePinnedToCore( fRainFall, "fRainFall", 10000, NULL, 4, NULL, 1 );
  xTaskCreatePinnedToCore( fmqttWatchDog, "fmqttWatchDog", 3000, NULL, 3, NULL, 1 ); // assign all to core 1
} //void setup()
////


void fWindDirection( void *pvParameters )
// read the wind direction sensor, return heading in degrees
{
  float adcValue = 0.0f;
  uint64_t TimePastKalman  = esp_timer_get_time();
  SimpleKalmanFilter KF_ADC( 1.0f, 1.0f, .01f );
  float high = 0.0f;
  float low = 2000.0f;
  float ADscale = 3.3f / 4096.0f;
  TickType_t xLastWakeTime = xTaskGetTickCount();
  const TickType_t xFrequency = 100; //delay for mS
  int count = 0;
  String windDirection;
  windDirection.reserve(20);
  String MQTTinfo = "";
  MQTTinfo.reserve( 150 );
  while ( !MQTTclient.connected() )
  {
    vTaskDelay( 250 );
  }
  for (;;)
  {
    windDirection = "";
    adcValue = float( adc1_get_raw(ADC1_CHANNEL_6) ); //take a raw ADC reading
    KF_ADC.setProcessNoise( (esp_timer_get_time() - TimePastKalman) / 1000000.0f ); //get time, in microsecods, since last readings
    adcValue = KF_ADC.updateEstimate( adcValue ); // apply simple Kalman filter
    TimePastKalman = esp_timer_get_time(); // time of update complete
    adcValue = adcValue * ADscale;
    log_i( "                       adc %f", adcValue );
    if ( (adcValue >= 0.0f) & (adcValue <= .25f )  )
    {
     // log_i( " n" );
      windDirection.concat( "N" );
    }
    //
//    if ( (adcValue >= .25f) & adcValue <= .5f )
//    {
//      log_i( " nne" );
//      windDirection.concat( "NNE");
//    }
    //
    if ( (adcValue > .25f) & (adcValue <= .6f ) )
    {
    //  log_i( " e" );
      windDirection.concat( "E" );
    }
//    if ( (adcValue > 1.0f) & (adcValue < 1.75f) )
//    {
//      log_i( " sse" );
//      windDirection.concat( "S-SE");
//    }
//    //
//        if ( (adcValue >= 1.75f) & (adcValue < 2.2f) )
//    {
//      log_i( " nnw" );
//      windDirection.concat( "N-NW" );
//    }
    //
    if ( (adcValue > 2.0f) & ( adcValue < 3.3f) )
    {
   //   log_i( " s" );
      windDirection.concat( "S");
    }
    //
//    if ( (adcValue > 2.6f) & (adcValue < 3.0f ) )
//    {
//      log_i( " ssw" );
//      windDirection.concat( "S-SW" );
//    }
    if ( (adcValue >= 1.7f) & (adcValue < 2.0f ) )
    {
     // log_i( " w" );
      windDirection.concat( "W" );
    }
    if( count >= 30 )
    {
      MQTTinfo.concat( String(kph, 2) );
      MQTTinfo.concat( ",");
      MQTTinfo.concat( windDirection );
      MQTTinfo.concat( ",");
      MQTTinfo.concat( String(rain,2) );
      xSemaphoreTake( sema_MQTT_KeepAlive, portMAX_DELAY );
      MQTTclient.publish( topicWSWDRF, MQTTinfo.c_str() );
      xSemaphoreGive( sema_MQTT_KeepAlive );
      count = 0;
    }
    count++;
    MQTTinfo = "";
    xLastWakeTime = xTaskGetTickCount();
    vTaskDelayUntil( &xLastWakeTime, xFrequency );
  }
  vTaskDelete ( NULL );
}
// read rainfall
void fRainFall( void *pvParemeters )
{
  int16_t count = 0;
  pcnt_counter_pause( PCNT_UNIT_1 );
  pcnt_counter_clear( PCNT_UNIT_1 );
  pcnt_counter_resume( PCNT_UNIT_1 );
  for  (;; )
  {
    xEventGroupWaitBits (eg, evtRainFall, pdTRUE, pdTRUE, portMAX_DELAY);
    pcnt_counter_pause( PCNT_UNIT_1 );
    pcnt_get_counter_value( PCNT_UNIT_1, &count );
    pcnt_counter_clear( PCNT_UNIT_1 );
    pcnt_counter_resume( PCNT_UNIT_1 );
    if ( count != 0 )
    {
      // 0.2794mm of rain per click clear clicks at mid night
      rain = 0.2794f * (float)count;
      log_i( "count %d, rain rain = %f mm", count, rain );
    }
  }
  vTaskDelete ( NULL );
}
////
void fAnemometer( void *pvParameters )
{
  int16_t count = 0;
  pcnt_counter_clear(PCNT_UNIT_0);
  pcnt_counter_resume(PCNT_UNIT_0);
  for (;;)
  {
    xEventGroupWaitBits (eg, evtAnemometer, pdTRUE, pdTRUE, portMAX_DELAY);
    pcnt_counter_pause( PCNT_UNIT_0 );
    pcnt_get_counter_value( PCNT_UNIT_0, &count); //int16_t *count
    // A wind speed of 2.4km/h causes the switch to close once per second
    kph = 2.4 * ((float)count / 60.0f);
    //if ( count != 0 )
    //{
      log_i( "count %d, wind Kph = %f", count, kph );
    //}
    count = 0;
    pcnt_counter_clear( PCNT_UNIT_0 );
    pcnt_counter_resume( PCNT_UNIT_0 );
  }
  vTaskDelete ( NULL );
}
//////
void fmqttWatchDog( void * paramater )
{
  int UpdateImeTrigger = 86400; //seconds in a day
  int UpdateTimeInterval = 86300; // 1st time update in 100 counts
  int maxNonMQTTresponse = 60;
  for (;;)
  {
    vTaskDelay( 1000 );
    if ( mqttOK >= maxNonMQTTresponse )
    {
      ESP.restart();
    }
    xSemaphoreTake( sema_mqttOK, portMAX_DELAY );
    mqttOK++;
    xSemaphoreGive( sema_mqttOK );
    UpdateTimeInterval++; // trigger new time get
    if ( UpdateTimeInterval >= UpdateImeTrigger )
    {
      TimeSet = false; // sets doneTime to false to get an updated time after a days count of seconds
      UpdateTimeInterval = 0;
    }
  }
  vTaskDelete( NULL );
}
//////
void fparseMQTT( void *pvParameters )
{
  struct stu_message px_message;
  for (;;)
  {
    if ( xQueueReceive(xQ_Message, &px_message, portMAX_DELAY) == pdTRUE )
    {
      // parse the time from the OK message and update MCU time
      if ( String(px_message.topic) == topicOK )
      {
        if ( !TimeSet)
        {
          String temp = "";
          temp =  px_message.payload[0];
          temp += px_message.payload[1];
          temp += px_message.payload[2];
          temp += px_message.payload[3];
          int year =  temp.toInt();
          temp = "";
          temp =  px_message.payload[5];
          temp += px_message.payload[6];
          int month =  temp.toInt();
          temp =  "";
          temp =  px_message.payload[8];
          temp += px_message.payload[9];
          int day =  temp.toInt();
          temp = "";
          temp = px_message.payload[11];
          temp += px_message.payload[12];
          int hour =  temp.toInt();
          temp = "";
          temp = px_message.payload[14];
          temp += px_message.payload[15];
          int min =  temp.toInt();
          rtc.setTime( 0, min, hour, day, month, year );
          log_i( "rtc  %s ", rtc.getTime() );
          TimeSet = true;
        }
      }
      //
    } //if ( xQueueReceive(xQ_Message, &px_message, portMAX_DELAY) == pdTRUE )
    xSemaphoreTake( sema_mqttOK, portMAX_DELAY );
    mqttOK = 0;
    xSemaphoreGive( sema_mqttOK );
  }
} // void fparseMQTT( void *pvParameters )
//////
void fReadCurrent( void * parameter )
{
  float ADbits = 4096.0f;
  float ref_voltage = 3.3f;
  float offSET = .0f;
  uint64_t TimePastKalman  = esp_timer_get_time(); // used by the Kalman filter UpdateProcessNoise, time since last kalman calculation
  SimpleKalmanFilter KF_I( 1.0f, 1.0f, .01f );
  float mA = 0.0f;
  int   printCount = 0;
  const float mVperAmp = 100.0f;
  float adcValue = 0;
  float Voltage = 0;
  float Power = 0.0;
  String powerInfo = "";
  powerInfo.reserve( 150 );
  while ( !MQTTclient.connected() )
  {
    vTaskDelay( 250 );
  }
  TickType_t xLastWakeTime = xTaskGetTickCount();
  const TickType_t xFrequency = 1000; //delay for mS
  for (;;)
  {
    adc1_get_raw(ADC1_CHANNEL_3); // read once discard reading
    adcValue = ( (float)adc1_get_raw(ADC1_CHANNEL_3) );
    Voltage = ( (adcValue * ref_voltage) / ADbits ) + offSET; // Gets you mV
    mA = Voltage / mVperAmp; // get amps
    KF_I.setProcessNoise( (esp_timer_get_time() - TimePastKalman) / 1000000.0f ); //get time, in microsecods, since last readings
    mA = KF_I.updateEstimate( mA ); // apply simple Kalman filter
    TimePastKalman = esp_timer_get_time(); // time of update complete
    printCount++;
    if ( printCount == 60 )
    {
      xSemaphoreTake( sema_CalculatedVoltage, portMAX_DELAY);
      Power = CalculatedVoltage * mA;
      log_i( "Voltage=%f mA=%f Power=%f", CalculatedVoltage, mA, Power );
      printCount = 0;
      powerInfo.concat( String(CalculatedVoltage, 2) );
      xSemaphoreGive( sema_CalculatedVoltage );
      powerInfo.concat( ",");
      powerInfo.concat( String(mA, 2) );
      powerInfo.concat( ",");
      powerInfo.concat( String(Power, 4) );
      xSemaphoreTake( sema_MQTT_KeepAlive, portMAX_DELAY );
      MQTTclient.publish( topicPower, powerInfo.c_str() );
      xSemaphoreGive( sema_MQTT_KeepAlive );
      powerInfo = "";
    }
    xLastWakeTime = xTaskGetTickCount();
    vTaskDelayUntil( &xLastWakeTime, xFrequency );
  }
  vTaskDelete( NULL );
} //void fReadCurrent( void * parameter )
////
void fReadBattery( void * parameter )
{
  //float ADbits = 4096.0f;
  //float ref_voltage = 3.3f;
  float ADscale = 3.3f / 4096.0f;
  float adcValue = 0.0f;
  float offSET = 0.0f;
  const float r1 = 50500.0f; // R1 in ohm, 50K
  const float r2 = 10000.0f; // R2 in ohm, 10k potentiometer
  //float Vscale = (r1+r2)/r2;
  float Vbatt = 0.0f;
  int printCount = 0;
  float vRefScale = (3.3f / 4096.0f) * ((r1 + r2) / r2);
  uint64_t TimePastKalman  = esp_timer_get_time(); // used by the Kalman filter UpdateProcessNoise, time since last kalman calculation
  SimpleKalmanFilter KF_ADC_b( 1.0f, 1.0f, .01f );
  TickType_t xLastWakeTime = xTaskGetTickCount();
  const TickType_t xFrequency = 1000; //delay for mS
  for (;;)
  {
    adc1_get_raw(ADC1_CHANNEL_0); //read and discard
    adcValue = float( adc1_get_raw(ADC1_CHANNEL_0) ); //take a raw ADC reading
    KF_ADC_b.setProcessNoise( (esp_timer_get_time() - TimePastKalman) / 1000000.0f ); //get time, in microsecods, since last readings
    adcValue = KF_ADC_b.updateEstimate( adcValue ); // apply simple Kalman filter
    Vbatt = adcValue * vRefScale;
    xSemaphoreTake( sema_CalculatedVoltage, portMAX_DELAY );
    CalculatedVoltage = Vbatt;
    xSemaphoreGive( sema_CalculatedVoltage );
//        printCount++;
//        if ( printCount == 3 )
//        {
//        log_i( "Vbatt %f", Vbatt );
//        printCount = 0;
//        }
    TimePastKalman = esp_timer_get_time(); // time of update complete
    xLastWakeTime = xTaskGetTickCount();
    vTaskDelayUntil( &xLastWakeTime, xFrequency );
    //log_i( "fReadBattery %d",  uxTaskGetStackHighWaterMark( NULL ) );
  }
  vTaskDelete( NULL );
}
////
void MQTTkeepalive( void *pvParameters )
{
  sema_MQTT_KeepAlive   = xSemaphoreCreateBinary();
  xSemaphoreGive( sema_MQTT_KeepAlive ); // found keep alive can mess with a publish, stop keep alive during publish
  // setting must be set before a mqtt connection is made
  MQTTclient.setKeepAlive( 90 ); // setting keep alive to 90 seconds makes for a very reliable connection, must be set before the 1st connection is made.
  for (;;)
  {
    //check for a is-connected and if the WiFi 'thinks' its connected, found checking on both is more realible than just a single check
    if ( (wifiClient.connected()) && (WiFi.status() == WL_CONNECTED) )
    {
      xSemaphoreTake( sema_MQTT_KeepAlive, portMAX_DELAY ); // whiles MQTTlient.loop() is running no other mqtt operations should be in process
      MQTTclient.loop();
      xSemaphoreGive( sema_MQTT_KeepAlive );
    }
    else {
      log_i( "MQTT keep alive found MQTT status %s WiFi status %s", String(wifiClient.connected()), String(WiFi.status()) );
      if ( !(wifiClient.connected()) || !(WiFi.status() == WL_CONNECTED) )
      {
        connectToWiFi();
      }
      connectToMQTT();
    }
    vTaskDelay( 250 ); //task runs approx every 250 mS
  }
  vTaskDelete ( NULL );
}
////
void connectToWiFi()
{
  int TryCount = 0;
  //log_i( "connect to wifi" );
  while ( WiFi.status() != WL_CONNECTED )
  {
    TryCount++;
    WiFi.disconnect();
    WiFi.begin( SSID, PASSWORD );
    vTaskDelay( 4000 );
    if ( TryCount == 10 )
    {
      ESP.restart();
    }
  }
  WiFi.onEvent( WiFiEvent );
} // void connectToWiFi()
////
void connectToMQTT()
{
  MQTTclient.setKeepAlive( 90 ); // needs be made before connecting
  byte mac[5];
  WiFi.macAddress(mac);
  String clientID = String(mac[0]) + String(mac[4]) ; // use mac address to create clientID
  while ( !MQTTclient.connected() )
  {
    // boolean connect(const char* id, const char* user, const char* pass, const char* willTopic, uint8_t willQos, boolean willRetain, const char* willMessage);
    MQTTclient.connect( clientID.c_str(), mqtt_username, mqtt_password, NULL , 1, true, NULL );
    vTaskDelay( 250 );
  }
  MQTTclient.setCallback( mqttCallback );
  MQTTclient.subscribe( topicOK );
} // void connectToMQTT()
////
void loop() {}

Good luck.

Online MQTT Broker (server) or you can run your own MQTT Broker on a PC?
Please do you have any idea how to my pc build MQTT server please give me the some documents.

What were your results when you tried using the words "eclipse mqtt broker" in an internet search? When I did a internet search I found lots of documentation on how to build a MQTT Broker on a PC.

You should be able to run MQTT broker on a Raspberry Pi - plenty of online resources.

I found so many tutorial but I am don't understand, how to build my pc MQTT server so please do you have any Idea MQTT server?
I found MQTT Explore : http://mqtt-explorer.com/

I am try to later Raspberry Pi, because now our invest Original Ethernet sheld2 Italian or Mega 2560 modal hardware so I am now start our in this hardware.

So do you have any idea share me? pc build MQTT server.

Have you tried using the words "installing mqtt broker onto a pc"?

yes already I have ?

MQTT explorer is NOT a MQTT Broker.

it is really not that hard to install MQTT Broker

Please tell me details ?

Did you click clicky on the link I last posted? Did you follow those details?

OK I will try

But where I am configure my IP ?
image

At the place where you connect to the MQTT Broker using the pubsubclient library, using the connection function like so: MQTTclient.connect( clientID.c_str(), mqtt_username, mqtt_password, NULL , 1, true, NULL );

You can use the network name of the PC that is running MQTT Broker or the IP address to connect to the MQTT Broker. What is the name of the computer where you installed MQTT Broker onto?

Any Body Help me this projects MQTT server control any where ?

File here ?Newtech_Home_Automation_V_4.02_Mega_2560_Tested_OK.ino (11.1 KB)
Processing: index.htm...

<!DOCTYPE html>
<html>
    <head>	
   <head>
    <title>Newtech_Home_Automation</title>
   </head>   
   <body>      	  
	  <table width = "100%" border = "0">	  
         <tr>
            <td colspan = "2" bgcolor = "#b5dcb3"> 			
			   <img src="Home Automation_Logo.GIF" alt="Paris" style="width:100%;">
			    <h2 style='font-size:25px;color:blue;text-align:center;'>Newtech Smart Home Automation Web System</h2>
            </td>
         </tr>
         <tr>		 
	<body> 
	<table width = "100%" border = "0">
	<style>
	h1 {
  text-align: center;
}
body {
  background-color: #E6E6FA;
}
</style>
        <title>Newtech_Home_Automation</title>
        <script>
		strLED = "";

		function GetArduinoIO()
		{
			nocache = "&nocache=" + Math.random() * 1000000;
			var request = new XMLHttpRequest();
			request.onreadystatechange = function()
			{
				if (this.readyState == 4) {
					if (this.status == 200) {
						if (this.responseXML != null) {
							// XML file received - contains LED states
							var re;
							var num_LEDs;
							var i;
							var ledstr = "";
							
							re = this.responseXML.getElementsByTagName('LED');
							num_LEDs = re.length;
							
							for (i = 0; i < num_LEDs; i++) {
								ledstr = "LED" + (i + 1);
								if (re[i].childNodes[0].nodeValue === "checked") {
									document.getElementsByName(ledstr)[0].checked = true;
								}
								else {
									document.getElementsByName(ledstr)[0].checked = false;
								}
							}
						}
					}
				}
			}
			// send HTTP GET request with LEDs to switch on/off if any
			request.open("GET", "ajax_inputs" + strLED + nocache, true);
			request.send(null);
			setTimeout('GetArduinoIO()', 1000);
			strLED = "";
		}
		// service LEDs when checkbox checked/unchecked
		function GetCheck(led_num_str, cb)
		{
			if (cb.checked) {
				strLED += ("&" + led_num_str + "=1");
			}
			else {
				strLED += ("&" + led_num_str + "=0");
			}
		}
	</script>
	
	<style>
		.out_box {
			float: left;
			margin: 0 20px 20px 0;
			border: 2px solid blue;
			padding: 0 5px 0 5px;
			min-width: 280px;
		}
		input {
			margin: 10px;
		}
		input {
			vertical-align: -3px;
		}
		h1 {
			font-size: 120%;
			color: blue;
			margin: 0 0 10px 0;
		}
		h2 {
			font-size: 85%;
			color: #5734E6;
			margin: 5px 0 5px 0;
		}
		p, form, button {
			font-size: 80%;
			color: #252525;
		}
		.small_text {
			font-size: 70%;
			color: #737373;
		}
	</style>
    </head>
    <body onload="GetArduinoIO()">	
										
		<div class="out_box">
			<form class="check_LEDs" name="LED_form6">
				<h2 style='font-size:15px;color:red;text-align:center;'>Monitoring Control Panel</h2>
				<style>

				@keyframes example {
				from {color: yellow;}
				to {color: green;}
				}
				h1 {
				animation-name: example;
				animation-iteration-count: infinite;
				animation-duration: 1s;
				color: red;
				}
			</style>
				<body>
				<h1>System Is Running !!</h1>
			</body>	
				
				
				<script>
					function updateOnlineStatus() {
						document.getElementById("status").innerHTML = "System Internet Online";
					}

					function updateOfflineStatus() {
						document.getElementById("status").innerHTML = "System Internet Offline";
					}

					window.addEventListener('online', updateOnlineStatus);
					window.addEventListener('offline', updateOfflineStatus); 
					 
				</script> 
				</head>
				<meta name="viewport" content="width=device-width, initial-scale=1">
				<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.7.0/css/font-awesome.min.css">
				<body>
					 <h1 id="status">System Internet Online <i class="fa fa-wifi" style="font-size:20px;color:green"></i></h1>					
				</body>
															
				<!-- weather widget start --><a target="_blank" href="https://www.booked.net/weather/dhaka-2125"><img src="https://w.bookcdn.com/weather/picture/12_2125_1_1_2071c9_118_2071c9_ffffff_ffffff_3_2071c9_ffffff_0_6.png?scode=124&domid=w209&anc_id=84209" alt="booked.net"/> </a><!-- weather widget end -->				
				<h2 style='font-size:15px;color:red'> Syetem Temp: 0:0&#8451;</h2>
				<h2 style='font-size:10px;color:green'>Motion Sensor1 Not Dedect!!</h2>
				<h2 style='font-size:10px;color:green'>Motion Sensor2 Not Dedect!!</h2><br />
				<h2 style='font-size:10px;color:green'>Fire Sensor1 Not Dedect!!</h2>
				<h2 style='font-size:10px;color:green'>Fire Sensor2 Not Dedect!!</h2>													
			</form>
		</div>
		
		<div class="out_box">
			<form class="check_LEDs" name="LED_form1">
				<h2 style='font-size:15px;color:red;text-align:center;'>Main Power Control Panel (1)</h2>
				<input type="checkbox" name="LED1" value="0" onclick="GetCheck('LED1', this)" />Main Meter 1 (D26)
				<input type="checkbox" name="LED2" value="0" onclick="GetCheck('LED2', this)" />Sub Meter 2 (D27)<br />
				<input type="checkbox" name="LED3" value="0" onclick="GetCheck('LED3', this)" />Main Switch 3 (D28)
				<input type="checkbox" name="LED4" value="0" onclick="GetCheck('LED4', this)" />Main Gate 4 (D29)
			</form>
		</div>
		<div class="out_box">
			<form class="check_LEDs" name="LED_form2">
				<h2 style='font-size:15px;color:red;text-align:center;'>Control Panel (2)</h2>
				<input type="checkbox" name="LED5" value="0" onclick="GetCheck('LED5', this)" />LED 5 (D30)
				<input type="checkbox" name="LED6" value="0" onclick="GetCheck('LED6', this)" />LED 6 (D31)<br />
				<input type="checkbox" name="LED7" value="0" onclick="GetCheck('LED7', this)" />LED 7 (D32)
				<input type="checkbox" name="LED8" value="0" onclick="GetCheck('LED8', this)" />LED 8 (D33)
			</form>
		</div>
		<div class="out_box">
			<form class="check_LEDs" name="LED_form3">
				<h2 style='font-size:15px;color:red;text-align:center;'>Control Panel (3)</h2>
				<input type="checkbox" name="LED9" value="0" onclick="GetCheck('LED9', this)" />LED 9 (D34)
				<input type="checkbox" name="LED10" value="0" onclick="GetCheck('LED10', this)" />LED 10 (D35)<br />
				<input type="checkbox" name="LED11" value="0" onclick="GetCheck('LED11', this)" />LED 11 (D36)
				<input type="checkbox" name="LED12" value="0" onclick="GetCheck('LED12', this)" />LED 12 (D37)
			</form>
		</div>
		<div class="out_box">
			<form class="check_LEDs" name="LED_form4">
				<h2 style='font-size:15px;color:red;text-align:center;'>Control Panel (4)</h2>
				<input type="checkbox" name="LED13" value="0" onclick="GetCheck('LED13', this)" />LED 13 (D38)
				<input type="checkbox" name="LED14" value="0" onclick="GetCheck('LED14', this)" />LED 14 (D39)<br />
				<input type="checkbox" name="LED15" value="0" onclick="GetCheck('LED15', this)" />LED 15 (D40)
				<input type="checkbox" name="LED16" value="0" onclick="GetCheck('LED16', this)" />LED 16 (D41)
			</form>
		</div>
		<div class="out_box">
			<form class="check_LEDs" name="LED_form5">
				<h2 style='font-size:15px;color:red;text-align:center;'>Control Panel (5)</h2>
				<input type="checkbox" name="LED17" value="0" onclick="GetCheck('LED17', this)" />LED 17 (D42)
				<input type="checkbox" name="LED18" value="0" onclick="GetCheck('LED18', this)" />LED 18 (D43)<br />
				<input type="checkbox" name="LED19" value="0" onclick="GetCheck('LED19', this)" />LED 19 (D44)
				<input type="checkbox" name="LED20" value="0" onclick="GetCheck('LED20', this)" />LED 20 (D45)
			</form>
		</div>
		<div class="out_box">
			<form class="check_LEDs" name="LED_form6">
				<h2 style='font-size:15px;color:red;text-align:center;'>Control Panel (6)</h2>
				<input type="checkbox" name="LED21" value="0" onclick="GetCheck('LED21', this)" />LED 21 (D46)
				<input type="checkbox" name="LED22" value="0" onclick="GetCheck('LED22', this)" />LED 22 (D47)<br />
				<input type="checkbox" name="LED23" value="0" onclick="GetCheck('LED23', this)" />LED 23 (D48)
				<input type="checkbox" name="LED24" value="0" onclick="GetCheck('LED24', this)" />LED 24 (D49)
			</form>
		</div>
				
    </body>		
		
	 <tr>
            <td colspan = "2" bgcolor = "#b5dcb3">
               <center>
				<h2 style = text-align:center;color:DarkGreen;font-size:12px;> Copyright © Verson - (4.02) April - 2020</h2>
				<h2 style = text-align:center;color:DarkGreen;font-size:12px;>© Newtech Technologies | All Rights Reserved</h2>
				<h2 style = text-align:center;color:Red;font-size:15px;>Our Help Line :  +8801720037200 / +8801618884010 / +8801618884009 / Email ID : giashsmart@gmail.com</h2>
               </center>
	<tr>
	
</html>

See where I use the variable mqtt_server as the name or IP address of the MQTT Broker as part of the initialization?