ESP32 probleme de connection avec MySQL

Bonjour,
J'essaye de configurer un ESP32 pour transmettre les valeurs relevees par des capteurs (DHT22 et BMP) a une base de donnee sur un raspberry pi en local.
J'ai suivi ce tuto: ESP32/ESP8266 Insert Data into MySQL Database | Random Nerd Tutorials

Et ben... ca marche pas.....

Voila ce que j'obtient dans le serial Moniteur d"Arduino IDE :

Connected to WiFi network with IP Address: 192.168.8.136

Pressure = 1008.00 mb
Altitude = 42.21 meters
Humidity = 40.80 %	
BMP Temperature = 33.50 *C 
DHT Temperature = 32.40 *C 
DHT + BMP Average Temp = 32.95 *C 

httpRequestData: api_key= tPmAT5Ab3j7F9&sensor=GY68&location=Living room&value1=32.40&value2=40.80&value3=1008.21
Error code: -1

J'ai bien LAMP installe sur le raspi, la DB existe, etc.....

Mais j'obtient cette erreur meme lorsque le raspi est eteint.... Je pense donc qu'il y a un bug dans le code sur l'ESP32.....

Voila le code en question:

/*
  Rui Santos
  Complete project details at https://RandomNerdTutorials.com/esp32-esp8266-mysql-database-php/
  
  Permission is hereby granted, free of charge, to any person obtaining a copy
  of this software and associated documentation files.
  
  The above copyright notice and this permission notice shall be included in all
  copies or substantial portions of the Software.

*/

#include <WiFi.h>
#include <WiFiClientSecure.h>
#include <HTTPClient.h>
#include "DHT.h"
#include <Wire.h>
#include <Adafruit_Sensor.h>
#include <Adafruit_BMP085.h>

// Replace with your network credentials
const char* ssid     = "Yann";
const char* password = "16421642";

// REPLACE with your Domain name and URL path or IP address with path
const char* serverName = "HTTP://192.168.8.140";

// Keep this API Key value to be compatible with the PHP code provided in the project page. 
// If you change the apiKeyValue value, the PHP file /post-esp-data.php also needs to have the same key 
String apiKeyValue = "tPmAT5Ab3j7F9";

String sensorName = "GY68";
String sensorLocation = "Living room";

// Humidity qnd Temperature
#define DHTPIN 13     
#define DHTTYPE DHT22  
DHT dht(DHTPIN, DHTTYPE);

#define SEALEVELPRESSURE_HPA (1013.25)

//Pressure and Altitude
Adafruit_BMP085 bmp;

//WiFi.mode(WIFI_STA);
//WiFiServer server(80);
//WiFiClient client = server.available();

void setup() {
  Serial.begin(115200);
  delay(1000);
  dht.begin();
   if (!bmp.begin()) {
 Serial.println("Could not find a valid BMP085 sensor, check wiring!");
  while (1) {}
  }
  
  WiFi.begin(ssid, password);
  Serial.println("Connecting");
  while(WiFi.status() != WL_CONNECTED) { 
    delay(500);
    Serial.print(".");
  }
  Serial.println("");
  Serial.print("Connected to WiFi network with IP Address: ");
  Serial.println(WiFi.localIP());
}

void loop() {
  //Check WiFi connection status
  if(WiFi.status()== WL_CONNECTED){
    WiFiClientSecure *client = new WiFiClientSecure;
    client->setInsecure(); //don't use SSL certificate
    HTTPClient https;
  Serial.println("");
  Serial.print("Connected to WiFi network with IP Address: ");
  Serial.println(WiFi.localIP());
  Serial.println("");
 float h = dht.readHumidity();
  // Read temperature as Celsius (the default)
  float t = dht.readTemperature();
  //Read temperature as Fahrenheit (isFahrenheit = true)
  float f = dht.readTemperature(true);
  // Check if any reads failed and exit early (to try again).
  if (isnan(h) || isnan(t) || isnan(f)) {
    Serial.println("Failed to read from DHT sensor!");
    return;
  }
 float p = bmp.readPressure()/100;
   Serial.print("Pressure = ");
   Serial.print(p);
   Serial.println(" mb");
  // Calculate altitude assuming 'standard' barometric
  // pressure of 1013.25 millibar = 101325 Pascal
  float a = bmp.readAltitude();
  float bt = bmp.readTemperature();
  Serial.print("Altitude = ");
  Serial.print(a);
  Serial.println(" meters");
  Serial.print("Humidity = ");
  Serial.print(h);
  Serial.println(" %\t");
  Serial.print("BMP Temperature = ");
  Serial.print(bmp.readTemperature());
  Serial.println(" *C ");
  Serial.print("DHT Temperature = ");
  Serial.print(t);
  Serial.println(" *C ");
  Serial.print("DHT + BMP Average Temp = ");
  Serial.print((bt + t) /2);
  Serial.println(" *C ");
  Serial.println();
  delay(1000);

    // Your Domain name with URL path or IP address with path
    https.begin(serverName);
    
    // Specify content-type header
    https.addHeader("Content-Type", "application/x-www-form-urlencoded");
    
    // Prepare your HTTP POST request data
    String httpRequestData = "api_key=" + apiKeyValue + "&sensor=" + sensorName
                          + "&location=" + sensorLocation + "&value1=" + String(dht.readTemperature())
                          + "&value2=" + String(dht.readHumidity()) + "&value3=" + String(bmp.readPressure()/100.0F) + "";

  
  Serial.print("httpRequestData: ");
  Serial.println(httpRequestData);
    
    // You can comment the httpRequestData variable above
    // then, use the httpRequestData variable below (for testing purposes without the BME280 sensor)
    //String httpRequestData = "api_key=tPmAT5Ab3j7F9&sensor=BME280&location=Office&value1=24.75&value2=49.54&value3=1005.14";

    // Send HTTP POST request
    int httpResponseCode = https.POST(httpRequestData);
     
    // If you need an HTTP request with a content type: text/plain
    //https.addHeader("Content-Type", "text/plain");
    //int httpResponseCode = https.POST("Hello, World!");
    
    // If you need an HTTP request with a content type: application/json, use the following:
    //https.addHeader("Content-Type", "application/json");
    //int httpResponseCode = https.POST("{\"value1\":\"19\",\"value2\":\"67\",\"value3\":\"78\"}");
    
    if (httpResponseCode>0) {
      Serial.print("HTTP Response code: ");
      Serial.println(httpResponseCode);
    }
    else {
      Serial.print("Error code: ");
      Serial.println(httpResponseCode);
    }
    // Free resources
    https.end();
   }
  else {
    Serial.println("WiFi Disconnected");
  }
  //Send an HTTP POST request every 30 seconds
  delay(5000);  
}

l'adresse IP du serveur apache sur le raspi est correcte (j'y accede depuis n'importe quel autre ordi sans probleme.....)

Une idee ? une suggestion?

Merci de votre aide

dans le tuto ils utilisent

// REPLACE with your Domain name and URL path or IP address with path
const char* serverName = "https://example.com/post-esp-data.php";

je suppose que vous avez bien créé le script post-esp-data.php et votre URL (si votre RPi est sur cette IP) devrait être

const char* serverName = "https://192.168.8.140/post-esp-data.php";

Oui, j'ai bien cree le script "post-esp-data.php" sur le raspi... j'y accede sans probleme, et ca m'affiche:

No data posted with HTTP POST.

pour la ligne

const char* serverName = "https://example.com/post-esp-data.php";

j'ai bien moodifie pour avoir;

const char* serverName = "https://192.168.8.140/post-esp-data.php";

l'adresse du raspi et correcte, mais le moniteur serie affiche toujours:

Connected to WiFi network with IP Address: 192.168.8.136

Pressure = 1005.00 mb
Altitude = 63.55 meters
Humidity = 39.60 %	
BMP Temperature = 33.30 *C 
DHT Temperature = 32.10 *C 
DHT + BMP Average Temp = 32.70 *C 

httpRequestData: api_key=tPmAT5Ab3j7F9&sensor=GY68&location=Living room&value1=32.10&value2=39.60&value3=1005.66
Error code: -1

:sleepy:

postez le nouveau code

normalement une URL n'a pas le droit de contenir d'espace je ne sais pas si le framework remplace cela par un %20

essayez de modifier

String sensorLocation = "Living room";

en

String sensorLocation = "LivingRoom";

Bien vu pour l'espace vide!
J'ai modifie ce probleme, mais toujours le meme resultat...

Voila le code a jour:

/*
  Rui Santos
  Complete project details at https://RandomNerdTutorials.com/esp32-esp8266-mysql-database-php/
  
  Permission is hereby granted, free of charge, to any person obtaining a copy
  of this software and associated documentation files.
  
  The above copyright notice and this permission notice shall be included in all
  copies or substantial portions of the Software.

*/

#include <WiFi.h>
#include <WiFiClientSecure.h>
#include <HTTPClient.h>
#include "DHT.h"
#include <Wire.h>
#include <Adafruit_Sensor.h>
#include <Adafruit_BMP085.h>

// Replace with your network credentials
const char* ssid     = "Yann";
const char* password = "16421642";

// REPLACE with your Domain name and URL path or IP address with path
const char* serverName = "HTTP://192.168.8.140/post-esp-data.php";

// Keep this API Key value to be compatible with the PHP code provided in the project page. 
// If you change the apiKeyValue value, the PHP file /post-esp-data.php also needs to have the same key 
String apiKeyValue = "tPmAT5Ab3j7F9";

String sensorName = "GY68";
String sensorLocation = "Living room";

// Humidity qnd Temperature
#define DHTPIN 13     
#define DHTTYPE DHT22  
DHT dht(DHTPIN, DHTTYPE);

#define SEALEVELPRESSURE_HPA (1013.25)

//Pressure and Altitude
Adafruit_BMP085 bmp;

//WiFi.mode(WIFI_STA);
//WiFiServer server(80);
//WiFiClient client = server.available();

void setup() {
  Serial.begin(115200);
  delay(1000);
  dht.begin();
   if (!bmp.begin()) {
 Serial.println("Could not find a valid BMP085 sensor, check wiring!");
  while (1) {}
  }
  
  WiFi.begin(ssid, password);
  Serial.println("Connecting");
  while(WiFi.status() != WL_CONNECTED) { 
    delay(500);
    Serial.print(".");
  }
  Serial.println("");
  Serial.print("Connected to WiFi network with IP Address: ");
  Serial.println(WiFi.localIP());
}

void loop() {
  //Check WiFi connection status
  if(WiFi.status()== WL_CONNECTED){
    WiFiClientSecure *client = new WiFiClientSecure;
    client->setInsecure(); //don't use SSL certificate
    HTTPClient https;
  Serial.println("");
  Serial.print("Connected to WiFi network with IP Address: ");
  Serial.println(WiFi.localIP());
  Serial.println("");
 float h = dht.readHumidity();
  // Read temperature as Celsius (the default)
  float t = dht.readTemperature();
  //Read temperature as Fahrenheit (isFahrenheit = true)
  float f = dht.readTemperature(true);
  // Check if any reads failed and exit early (to try again).
  if (isnan(h) || isnan(t) || isnan(f)) {
    Serial.println("Failed to read from DHT sensor!");
    return;
  }
 float p = bmp.readPressure()/100;
   Serial.print("Pressure = ");
   Serial.print(p);
   Serial.println(" mb");
  // Calculate altitude assuming 'standard' barometric
  // pressure of 1013.25 millibar = 101325 Pascal
  float a = bmp.readAltitude();
  float bt = bmp.readTemperature();
  Serial.print("Altitude = ");
  Serial.print(a);
  Serial.println(" meters");
  Serial.print("Humidity = ");
  Serial.print(h);
  Serial.println(" %\t");
  Serial.print("BMP Temperature = ");
  Serial.print(bmp.readTemperature());
  Serial.println(" *C ");
  Serial.print("DHT Temperature = ");
  Serial.print(t);
  Serial.println(" *C ");
  Serial.print("DHT + BMP Average Temp = ");
  Serial.print((bt + t) /2);
  Serial.println(" *C ");
  Serial.println();
  delay(1000);

    // Your Domain name with URL path or IP address with path
    https.begin(serverName);
    
    // Specify content-type header
    https.addHeader("Content-Type", "application/x-www-form-urlencoded");
    
    // Prepare your HTTP POST request data
    String httpRequestData = "api_key=" + apiKeyValue + "&sensor=" + sensorName
                          + "&location=" + sensorLocation + "&value1=" + String(dht.readTemperature())
                          + "&value2=" + String(dht.readHumidity()) + "&value3=" + String(bmp.readPressure()/100.0F) + "";

  
  Serial.print("httpRequestData: ");
  Serial.println(httpRequestData);
    
    // You can comment the httpRequestData variable above
    // then, use the httpRequestData variable below (for testing purposes without the BME280 sensor)
    //String httpRequestData = "api_key=tPmAT5Ab3j7F9&sensor=BME280&location=Office&value1=24.75&value2=49.54&value3=1005.14";

    // Send HTTP POST request
    int httpResponseCode = https.POST(httpRequestData);
     
    // If you need an HTTP request with a content type: text/plain
    //https.addHeader("Content-Type", "text/plain");
    //int httpResponseCode = https.POST("Hello, World!");
    
    // If you need an HTTP request with a content type: application/json, use the following:
    //https.addHeader("Content-Type", "application/json");
    //int httpResponseCode = https.POST("{\"value1\":\"19\",\"value2\":\"67\",\"value3\":\"78\"}");
    
    if (httpResponseCode>0) {
      Serial.print("HTTP Response code: ");
      Serial.println(httpResponseCode);
    }
    else {
      Serial.print("Error code: ");
      Serial.println(httpResponseCode);
    }
    // Free resources
    https.end();
   }
  else {
    Serial.println("WiFi Disconnected");
  }
  //Send an HTTP POST request every 30 seconds
  delay(5000);  
}

vous utilisez juste http, pas https donc sans doute pas besoin de faire

    WiFiClientSecure *client = new WiFiClientSecure;
    client->setInsecure(); //don't use SSL certificate
    HTTPClient https;
...

regardez ESP32 HTTP GET and HTTP POST with Arduino IDE | Random Nerd Tutorials pour faire une simple requête POST en HTTP (pas HTTPS)

1 Like

Merci!
J'ai viré toutes les references a https, et maintenant, je m'approche du but!

Voila ce que je recupere dans le terminal! il y a du mieux!

Pressure = 1005.00 mb
Altitude = 65.98 meters
Humidity = 38.50 %	
BMP Temperature = 33.50 *C 
DHT Temperature = 32.40 *C 
DHT + BMP Average Temp = 32.95 *C 

httpRequestData: api_key=tPmAT5Ab3j7F9&sensor=GY68&location=Livingroom&value1=32.40&value2=38.50&value3=1005.40
HTTP Response code: 200

Reste a verifier que tout part dans la base de donnees, et ensuite je posterais le code complet et fonctionnel!

Encore 1000 Mercis pour ton aide!

Et bien sur, un probleme solutionne endecouvre d'autres...

Tout va bien au niveau de l'ESP32, mais nada/rien/que'dalle du cote base de donnees..pfff...

Voila mes pages php...

post-esp-data.php                                                         
<?php

/*
  Rui Santos
  Complete project details at https://RandomNerdTutorials.com/esp32-esp8266-mysql-database-php/

  Permission is hereby granted, free of charge, to any person obtaining a copy
  of this software and associated documentation filesyo
  The above copyright notice and this permission notice shall be included in all
  copies or substantial portions of the Software.
*/

$servername = "192.168.8.140";
$dbname = "esp_data";
$username = "yoda";
$password = "ola";

// Keep this API Key value to be compatible with the ESP32 code provided in the project page.
// If you change this value, the ESP32 sketch needs to match
$api_key_value = "tPmAT5Ab3j7F9";

$api_key= $sensor = $location = $value1 = $value2 = $value3 = "";

if ($_SERVER["REQUEST_METHOD"] == "POST") {
    $api_key = test_input($_POST["api_key"]);
    if($api_key == $api_key_value) {
        $sensor = test_input($_POST["sensor"]);
        $location = test_input($_POST["location"]);
        $value1 = test_input($_POST["value1"]);
        $value2 = test_input($_POST["value2"]);
        $value3 = test_input($_POST["value3"]);

  GNU nano 5.4                                                  esp-data.php                                                            
<!DOCTYPE html>
<html><body>
<?php
/*
  Rui Santos
  Complete project details at https://RandomNerdTutorials.com/esp32-esp8266-mysql-database-php/
  
  Permission is hereby granted, free of charge, to any person obtaining a copy
  of this software and associated documentation files.
  
  The above copyright notice and this permission notice shall be included in all
  copies or substantial portions of the Software.
*/

$servername = "localhost";

// REPLACE with your Database name
$dbname = "esp_data";
// REPLACE with Database user
$username = "yoda";
// REPLACE with Database user password
$password = "ola";

// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
    die("Connection failed: " . $conn->connect_error);
} 

$sql = "SELECT id, sensor, location, value1, value2, value3, reading_time FROM SensorData ORDER BY id DESC";
echo '<table cellspacing="5" cellpadding="5">
      <tr> 
        <td>ID</td> 
        <td>Sensor</td> 
        <td>Location</td> 
        <td>Value 1</td> 
        <td>Value 2</td>
        <td>Value 3</td> 
        <td>Timestamp</td> 
      </tr>';
 
if ($result = $conn->query($sql)) {
    while ($row = $result->fetch_assoc()) {
        $row_id = $row["id"];
        $row_sensor = $row["sensor"];
        $row_location = $row["location"];
        $row_value1 = $row["value1"];
        $row_value2 = $row["value2"]; 
        $row_value3 = $row["value3"]; 
        $row_reading_time = $row["reading_time"];
        // Uncomment to set timezone to - 1 hour (you can change 1 to any number)
        //$row_reading_time = date("Y-m-d H:i:s", strtotime("$row_reading_time - 1 hours"));

        // Uncomment to set timezone to + 4 hours (you can change 4 to any number)
        //$row_reading_time = date("Y-m-d H:i:s", strtotime("$row_reading_time + 4 hours"));

        echo '<tr> 
                <td>' . $row_id . '</td> 
                <td>' . $row_sensor . '</td> 
                <td>' . $row_location . '</td> 
                <td>' . $row_value1 . '</td> 

  GNU nano 5.4                                                  esp-data.php                                                      M     
        $row_id = $row["id"];
        $row_sensor = $row["sensor"];
        $row_location = $row["location"];
                <td>' . $row_value1 . '</td> 
                <td>' . $row_value2 . '</td>
                <td>' . $row_value3 . '</td> 
                <td>' . $row_reading_time . '</td> 
              </tr>';
    }
    $result->free();
}

$conn->close();
?> 
</table>
</body>
</html>


Parmis les trucs que je ne comprends pas, pourquoi je ne me prends pas un message d'erreur si problee de connexion avec MySQL...?

Vous avez copié n’importe quoi dans le script d’origine?

Prenez la version raw

https://raw.githubusercontent.com/RuiSantosdotme/ESP32-ESP8266-PHP-MySQL/master/code/post-esp-data.php

Effectivement...quand je ne fais pas n'importe quoi... Ben ca marche!
Un ENORME Merci!

Super

Bonne continuation

This topic was automatically closed 180 days after the last reply. New replies are no longer allowed.