knolleary / pubsubclient

A client library for the Arduino Ethernet Shield that provides support for MQTT.
http://pubsubclient.knolleary.net/
MIT License
3.83k stars 1.47k forks source link

conflicting declaration 'PubSubClient client' #871

Closed mvtkurd closed 3 years ago

mvtkurd commented 3 years ago

hi guys. I have a project which is sending data of sensors to a webserver( by http messaging protocol) and change the triggers of them on a MQTT server. and finally send these data to influxdb. these sketches work correctly when they are separate but when I combined them , I got this error : conflicting declaration 'PubSubClient client' would you please help me to overcome this isuue. here's my code:

TaskHandle_t Task1;
TaskHandle_t Task2;
TaskHandle_t Task3;
//#include <WiFi.h>
#include <PubSubClient.h>

//WiFiServer server(80);
String header;
//////////////define oled config

#include <Wire.h>
#include <Adafruit_GFX.h>
#include <Adafruit_SSD1306.h>
#define SCREEN_WIDTH 128 // OLED display width, in pixels
#define SCREEN_HEIGHT 64 // OLED display height, in pixels
#define OLED_RESET -1 // Reset pin # (or -1 if sharing Arduino reset pin)
Adafruit_SSD1306 display(SCREEN_WIDTH, SCREEN_HEIGHT, &Wire, OLED_RESET);
///////////////////////////////
#if defined(ESP32)
#include <WiFiMulti.h>
WiFiMulti wifiMulti;
#define DEVICE "ESP32"
#elif defined(ESP8266)
#include <ESP8266WiFiMulti.h>
ESP8266WiFiMulti wifiMulti;
#define DEVICE "ESP8266"
#endif
#include <DHT.h>
#include <InfluxDbClient.h>
#include <InfluxDbCloud.h>
#define SENSING_FREQUENCY 4.0
#define PIN_DHT 4
#define WIFI_SSID "milad"
#define WIFI_PASSWORD "pass"
// InfluxDB v2 server url, e.g. https://eu-central-1-1.aws.cloud2.influxdata.com (Use: InfluxDB UI -> Load Data -> Client Libraries)
#define INFLUXDB_URL "https://europe-west1-1.gcp.cloud2.influxdata.com"
// InfluxDB v2 server or cloud API authentication token (Use: InfluxDB UI -> Data -> Tokens -> <select token>)
#define INFLUXDB_TOKEN "GnRnKojp3knnb6VnuzuFmCVY92Snjs-Sqdd24-wVu_6rWPTYHmIXST8pZIq_s1XBJhs-QnnKuIFjN1IPuD-mLw=="
// InfluxDB v2 organization id (Use: InfluxDB UI -> User -> About -> Common Ids )
#define INFLUXDB_ORG "mvtkurd@gmail.com"
// InfluxDB v2 bucket name (Use: InfluxDB UI ->  Data -> Buckets)
#define INFLUXDB_BUCKET "IOT PROJECT"
#define TZ_INFO "CET-1CEST,M3.5.0,M10.5.0/3"
#define SensorPin 33  
DHT dht(PIN_DHT, DHT22);
// InfluxDB client instance with preconfigured InfluxCloud certificate
InfluxDBClient client(INFLUXDB_URL, INFLUXDB_ORG, INFLUXDB_BUCKET, INFLUXDB_TOKEN, InfluxDbCloud2CACert);
float SAMPLE_FREQUENCY;
float MAX_TEMP=80;
float MIN_TEMP=25;
float MAX_MOIS=70;
float MIN_MOIS=35;
float tempValue;
float humValue;
float moisValue;
const int led1 = 23; 
const int led2 = 19; 
// Data point
Point sensor("wifi_status");
Point sensor1("DHT");
Point sensor2("Mois");
Point pointDevice("env_monitor");

///////////////////////////////////////////////mqtt server and port declaration
const char* mqttServer = "130.136.2.70";
const int mqttPort = 1883;
const char* mqttUser = "-------r";
const char* mqttPassword = "------";

///////////////callback void to recieve messages
WiFiClient espClient;
PubSubClient client(espClient);
void callback(char* topic, byte* payload, unsigned int length) {

  int c;
  char p[length+1]; 
  memcpy(p,payload,length);
  p[length]=NULL;

  //String text=String(payload);
//  Serial.println(p);
    c=atoi(p);

  Serial.print("Message arrived in topic: ");
  Serial.println(topic);

  Serial.print("Message:");
  for (int i = 0; i < length; i++) {
Serial.print((char)payload[i]);

 }
 if (strcmp(topic,"esp/TEMP")==0){
     Serial.println("MAX/MIN RELATED TO TEMP UPDATED");
    Serial.println("WE ARE HERE WITH VALUE C");
    Serial.println(c);
    if (c > 50) {
    MAX_TEMP=c;
  } else {
     MIN_TEMP=c;
  }
  }

  if (strcmp(topic,"esp/MOIS")==0){
   Serial.print("MAX/MIN RELATED TO MOIS UPDATED");
      if (c > 50) {
    MAX_MOIS=c;
  } else {
     MIN_MOIS=c;
  }
  }

   if (strcmp(topic,"esp/SAMPLE")==0){
 Serial.print("SAMPLE FREQUENCY UPDATED");
  SAMPLE_FREQUENCY=c;
   }
  Serial.println();
  Serial.println("-----------------------");

}
/////////////////////////////////////////////////////////////

void setup() {
  Serial.begin(115200);
  display.begin(SSD1306_SWITCHCAPVCC, 0x3C); //initialize with the I2C addr 0x3C (128x64)
  display.clearDisplay();
  pinMode(led1, OUTPUT);
  pinMode(led2, OUTPUT);
  WiFi.mode(WIFI_STA);
  wifiMulti.addAP(WIFI_SSID, WIFI_PASSWORD);
  Serial.print("Connecting to wifi");
  while (wifiMulti.run() != WL_CONNECTED) {
    Serial.print(".");
    delay(100);
  }
Serial.println("IP address of ESP32 is : ");
Serial.println(WiFi.localIP());

  client.setServer(mqttServer, mqttPort);
  client.setCallback(callback);
  while (!client.connected()) {
    Serial.println("Connecting to MQTT...");

    if (client.connect("ESP32Client", mqttUser, mqttPassword )) {

      Serial.println("connected to the MQTT server");  

    } else {

      Serial.print("failed with state ");
      Serial.print(client.state());
      delay(2000);

    }
  }
  client.subscribe("esp/TEMP");
  client.subscribe("esp/MOIS");
  client.subscribe("esp/SAMPLE");

  Serial.println();
   dht.begin();
   server.begin();
  delay(2000);

  //add tags
  pointDevice.addTag("SMART POT ID", "oo1");
  pointDevice.addTag("GPS POSITION", "44.490235405520565, 11.348922173212442");
  timeSync(TZ_INFO, "pool.ntp.org", "time.nis.gov");

  // Check server connection
  if (client.validateConnection()) {
    Serial.print("Connected to InfluxDB: ");
    Serial.println(client.getServerUrl());
  } else {
    Serial.print("InfluxDB connection failed: ");
    Serial.println(client.getLastErrorMessage());
  }

  //create a task that will be executed in the Task1code() function, with priority 1 and executed on core 0
  xTaskCreatePinnedToCore(
                    Task1code,   /* Task function. */
                    "Task1",     /* name of task. */
                    10000,       /* Stack size of task */
                    NULL,        /* parameter of the task */
                    1,           /* priority of the task */
                    &Task1,      /* Task handle to keep track of created task */
                    0);          /* pin task to core 0 */                  
  delay(500); 

  //create a task that will be executed in the Task2code() function, with priority 1 and executed on core 1
  xTaskCreatePinnedToCore(
                    Task2code,   /* Task function. */
                    "Task2",     /* name of task. */
                    10000,       /* Stack size of task */
                    NULL,        /* parameter of the task */
                    2,           /* priority of the task */
                    &Task2,      /* Task handle to keep track of created task */
                    1);          /* pin task to core 1 */
    delay(500); 

  //create a task that will be executed in the Task2code() function, with priority 1 and executed on core 1
  xTaskCreatePinnedToCore(
                    Task3code,   /* Task function. */
                    "Task2",     /* name of task. */
                    10000,       /* Stack size of task */
                    NULL,        /* parameter of the task */
                    2,           /* priority of the task */
                    &Task3,      /* Task handle to keep track of created task */
                    1);          /* pin task to core 1 */
    delay(500); 
}

//Task1code: make webserver and html
void Task1code( void * pvParameters ){
  Serial.print("Task1 running on core ");
  Serial.println(xPortGetCoreID());

  for(;;){
    WiFiClient client = server.available();
if (client) 
{ 

Serial.println("Web Client connected ");
String request = client.readStringUntil('\r'); 
client.println("HTTP/1.1 200 OK");
client.println("Content-type:text/html");
client.println("Connection: close");
client.println("Refresh: 10");
client.println();
///////display the HTML web page
client.println("<!DOCTYPE html><html>");
client.println("<head><meta name=\"viewport\" content=\"width=device-width, initial-scale=1\">");
//client.println("<head><meta http-equiv='refresh' content='3'>");
client.println("<link rel=\"icon\" href=\"data:,\">");
client.println("<style>body {background-image: url(\"https://photos.google.com/photo/AF1QipO7OzjUR5u_RpttKi5Khq3Nr5dggyfaMyEE079R\"); text-align: center; font-family: \"Trebuchet MS\", Arial;}"); 

//////////////////////////css style
client.println("<style>body { text-align: center; font-family: \"Arial\", Arial;}");
client.println("table { border-collapse: collapse; width:40%; margin-left:auto; margin-right:auto;border-spacing: 2px;background-color: white;border: 4px solid green; }");
client.println("th { padding: 20px; background-color: #008000; color: white; }");
client.println("tr { border: 5px solid green; padding: 2px; }");
client.println("tr:hover { background-color:yellow; }");
client.println("td { border:4px; padding: 12px; }");
client.println(".sensor { color:white; font-weight: bold; background-color: #bcbcbc; padding: 1px; }");
client.println(".slider { width: 300px; }</style>");
client.println("<script src=\"https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js\"></script>");

////////////////////////////

client.println("</style></head><body><h1>ESP32 Web Server Reading sensor values</h1>");
client.println("<h2 style=color:red>UNIBO_2021</h2>");
client.println("<h2>WELCOME TO THE SMART POT STATION</h2>");

client.println("<table><tr><th>MEASUREMENT</th><th>VALUE</th></tr>");
client.println("<tr><td>Temp</td><td><span class=\"sensor\">");
client.println(tempValue);
client.println(" *C</span></td></tr>"); 
client.println("<tr><td>Moisture</td><td><span class=\"sensor\">");
client.println(moisValue);
client.println(" *%</span></td></tr>"); 
client.println("<tr><td>Humidity</td><td><span class=\"sensor\">");
client.println(humValue);
client.println(" %</span></td></tr>"); 
client.println("<tr><td>Smart Pot ID </td><td><span class=\"sensor\">");
client.println(" 001</span></td></tr>"); 

client.println("<tr><td>GPS coordination </td><td><span class=\"sensor\">");
//client.println(" 44.490243059152036, 11.348943630922456</span></td></tr>");
client.println("<a href=https://www.google.com/maps/place/44%C2%B029'24.9%22N+11%C2%B020'56.2%22E/@44.49025,11.3511331,17z/data=!3m1!4b1!4m5!3m4!1s0x0:0x0!8m2!3d44.4902431!4d11.3489436/>Google location!</a>");     
client.println("<tr><td>WIFI signal strength</td><td><span class=\"sensor\">");
client.println(WiFi.RSSI());
client.println(" dBm</span></td></tr>");
client.println("<tr><td>SHI</td><td><span class=\"sensor\">");
client.println(WiFi.RSSI());
client.println(" number</span></td></tr>");
client.println("</body></html>"); 

delay(10000);
client.stop();
client.println();
Serial.println("Client disconnected.");
Serial.println("");

}
  } 
}

//Task2code: connecting to influx
void Task2code( void * pvParameters ){
  Serial.print("Task2 running on core ");
  Serial.println(xPortGetCoreID());

  for(;;){
 sensor.clearFields();

  // Store measured value into point
  // Report RSSI of currently connected network
  sensor.addField("rssi", WiFi.RSSI());

  // If no Wifi signal, try to reconnect it
  if ((WiFi.RSSI() == 0) && (wifiMulti.run() != WL_CONNECTED)) {
    Serial.println("Wifi connection lost");
  }

  // Write point
  if (!client.writePoint(sensor)) {
    Serial.print("InfluxDB write failed: ");
    Serial.println(client.getLastErrorMessage());
  }
////////////////////////////////////////////////////////
pointDevice.clearFields();
tempValue=dht.readTemperature();

pointDevice.addField("temp", tempValue);
if ( tempValue >= MAX_TEMP || tempValue< MIN_TEMP ) {
digitalWrite(led1, HIGH);
delay(500);
digitalWrite(led1, LOW);
}

  humValue=dht.readHumidity();
  pointDevice.addField("hum", humValue);

   moisValue = analogRead(SensorPin);
   moisValue = map(moisValue, 2600, 1000, 0, 100);
  pointDevice.addField("mois", moisValue);
//////////////////write on oled
if(moisValue >=0 && moisValue <= 100)
{
  display.setCursor(45,0);  //oled display
  display.setTextSize(2);
  display.setTextColor(WHITE);
  display.println("Soil");
  display.setCursor(20,15);  
  display.setTextSize(2);
  display.setTextColor(WHITE);
  display.println("Moisture");

  display.setCursor(30,40);  //oled display
  display.setTextSize(3);
  display.setTextColor(WHITE);
  display.println(moisValue);
  display.setCursor(70,40);
  display.setTextSize(3);
  display.println(" %");
  display.display();
   delay(250);
  display.clearDisplay();
} 
///////////////////////////
if ( moisValue >= MAX_MOIS || moisValue< MIN_MOIS ) {
digitalWrite(led2, HIGH);
delay(500);
digitalWrite(led2, LOW);
}

  if ((tempValue>0) and (humValue>0)and (moisValue>0)) {
    client.writePoint(pointDevice);
    if (!client.writePoint(pointDevice)) {
      Serial.print("InfluxDB write failed: ");
      Serial.println(client.getLastErrorMessage());
    }
  }

  //Wait 2s
  Serial.println("Wait 2s");
  delay(2000);
  }
}

//Task3code: CONNECT TO MQTT
void Task3code( void * pvParameters ){
  Serial.print("Task3 running on core ");
  Serial.println(xPortGetCoreID());
   Serial.print("Task3 running TO CONNECT MQTT "); 
  Serial.println("--------------------------- ");

  for(;;){

  client.loop();
  delay(SAMPLE_FREQUENCY);
  }
}

void loop() {

}
UncleGrumpy commented 3 years ago

The problem is that you named the InfluxDBClient object and the PubSubClient object the same thing… “client” if you change the name and references for one of them to something different (like “iclient” for the influx one) it should work. This is not caused by a bug in this library, you should be able to close this issue.

mvtkurd commented 3 years ago

The problem is that you named the InfluxDBClient object and the PubSubClient object the same thing… “client” if you change the name and references for one of them to something different (like “iclient” for the influx one) it should work. This is not caused by a bug in this library, you should be able to close this issue.

oh kind of stupid mistake (= Thank you

UncleGrumpy commented 3 years ago

Not stupid, easy to overlook, I almost made that exact same mistake using MQTT and InfluxDB together last week. If it wasn’t so fresh in my head I probably would have overlooked it myself.

mvtkurd commented 3 years ago

Not stupid, easy to overlook, I almost made that exact same mistake using MQTT and InfluxDB together last week. If it wasn’t so fresh in my head I probably would have overlooked it myself.

So I'm glad you experienced it (=. And thanks for sharing and one more question(_) do you have any experience about configuration of data bridge plugin like Telegraf in influxdb?

UncleGrumpy commented 3 years ago

I am struggling with that myself, that’s the reason I opted to send directly to Influx along with MQTT. With my solar powered project it adds about 200 extra milliseconds to each run that I’d love to shave off!

mvtkurd commented 3 years ago

I am struggling with that myself, that’s the reason I opted to send directly to Influx along with MQTT. With my solar powered project it adds about 200 extra milliseconds to each run that I’d love to shave off!

so we are in common , I tried to config telegraf and other Py scripts to handle this issue but no result till now . let me know if you find something to solve it . Thanks