Skocz do zawartości

ESP8266 + PHP + MYsql


merinum

Pomocna odpowiedź

witam Państwa

jestem w trakcie pewnych testów związanych z łączeniem się i zapisem wysłanych danych z ESP8266 poprzez skrypt PHP do MYsql i mam pewien dylemat, z którym nie bardzo jak sobie potrafię poradzić: problem jest w tym, że wysłany przez skrypt PHP komunikat z echo ("MYsql") po wyświetleniu w Serial monitorze strasznie mi sie wyhacza (owy skrypt wysyła komunikat po podłączeniu się przez niego do bazy i rozłączeniu sie z niej), jeśli chodzi o połączenie z serwerem gdzie jest skrypt oraz baza danych to jest to stabilne, łącze internetowe też jest ok, więc nie mam pojęcia gdzie by szukac przyczyn takiego problemu, bardzo dziękuje z góry za pomoc.

poniżej kod programu:

#ifdef ESP32
#include <WiFi.h>
#include <HTTPClient.h>
#else
#include <ESP8266WiFi.h>
#include <ESP8266HTTPClient.h>
#include <WiFiClient.h>
#endif
const char *ssid = "merinum24";
const char *password = "**********";
const char *host1 = "http://serwer2276319.home.pl/logowanie_test.php";
String posting;   //treść zapytania dla POST
int zresetowanie = 0;
int limit = 20;
int mysql_d = 10; //czas pomiędzy logowaniem (sekundy)
unsigned long mysql_t = 0;
void setup() {
  Serial.begin(112500);
  WiFi.mode(WIFI_STA);
  WiFi.begin(ssid, password);
  Serial.print("Connecting to WiFi ..");
  while (WiFi.status() != WL_CONNECTED) {
    Serial.print(".");
    delay(250);
    zresetowanie++;
    if (zresetowanie >= limit) {
      ESP.restart();
    }
  }
  Serial.println("");
  Serial.print("IP address: ");
  Serial.print(WiFi.localIP());
  Serial.print(", ");
  Serial.println(ssid);
  Serial.print("RRSI: ");
  Serial.print(WiFi.RSSI());
  Serial.println(" dBm");
}
void loop() {
  if (millis() - mysql_t > mysql_d * 1000UL) {
    WiFiClient client;
    HTTPClient http;
    http.begin(client, host1);
    http.addHeader("Content-Type", "application/x-www-form-urlencoded");
    int httpCode = http.POST("posting");    //Sending the request
    if (httpCode == 200) {                  //Print HTTP return code(200) - status OK
      String payload = http.getString();    //Get the response payload
      Serial.println(payload);              //printing the respose from the submitted data
      http.end();                           //Close connection
      mysql_t = millis();
    }
  }
}

1156852266_serialmonitor.thumb.JPG.e250e7a9489c7d5c20b41b363951350f.JPG

Link do komentarza
Share on other sites

Nie wiem czy Ci to pomoże ale mogę Ci wysłac mój kod do zapisywania w bazie danych danych z pogody,  robię to przez GET, a sktypt PHP przechwyuje i insertuje do bazy, myślę że to najprostsze rozwiązanie, i jeśli baza jest w sieci lokalnej to nie ma się o co martwić.

cpp:
 

#include <Wire.h>
#include <WiFi.h>
#include "DHT.h"
#include <HTTPClient.h>

#define DHTPIN 32     
#define DHTTYPE DHT22

DHT dht(DHTPIN, DHTTYPE);

int pushDataSecondsDelay = 28;
int currentValue = 0;

const char WIFI_SSID[] = "Internety";
const char WIFI_PASSWORD[] = "***";

String HOST_NAME = "http://192.168.0.100"; 
String PATH_NAME   = "/InsertValues.php";
String key = "?key=797494D2611F955F61986218A8D3C";
String temperatureString = "&temperature=";
String humidityString = "&humidity=";
String pressureString = "&pressure=";
String raindrop_Values = "&raindrop_value=";
String luxString = "&lux=";

void setup() {
  Serial.begin(9600);
  WiFi.begin(WIFI_SSID, WIFI_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());
 
  dht.begin();
  
}

void loop()
{
  delay(10000);
  
  if(pushDataSecondsDelay < currentValue)
  {
    float t = dht.readTemperature();
    float h = dht.readHumidity();
    
    HTTPClient http;
    http.begin(HOST_NAME + PATH_NAME + key + temperatureString + String(t) + humidityString + String(h) + pressureString + String(1000) + raindrop_Values + String(0) + luxString + String(100)); 
    int httpCode = http.GET();
    http.end();
    currentValue = 0;
  }else
  {
    currentValue ++;
  }
  
}

php:

<?php
$private_key = "797494D2611F955F61986218A8D3C";

$servername = "localhost";
$username = "root";
$password = "xxx";
$database_name = "weather_station";

if(isset($_GET["key"]) && $_GET["key"] == $private_key) 
{
   if(
        isset($_GET["temperature"]) && $_GET["temperature"] != null &&
        isset($_GET["humidity"]) && $_GET["humidity"] != null &&
        isset($_GET["pressure"]) && $_GET["pressure"] != null &&
        isset($_GET["raindrop_value"]) && $_GET["raindrop_value"] != null &&
        isset($_GET["lux"]) && $_GET["lux"] != null )
   {
        $date = date('Y-m-d H:i:s');
        $temperature = $_GET["temperature"];
        $humidity = $_GET["humidity"];
        $pressure = $_GET["pressure"];
        $raindrop_value = $_GET["raindrop_value"];
        $lux = $_GET["lux"];

        $connection = new mysqli($servername, $username, $password, $database_name);
        if ($connection->connect_error) {
            die("MySQL connection failed: " . $connection->connect_error);
        }

        $sql = "INSERT INTO `weather_data`(`id`, `date`, `temperature`, `humidity`, `pressure`, `raindrop_value`, `lux`) VALUES (null, '$date', $temperature, $humidity, $pressure, $raindrop_value, $lux)";

        if ($connection->query($sql) === TRUE) {
            echo "New record created successfully";
        } 
        else 
        {
            echo "Error: " . $sql . " => " . $connection->error;
        }
        $connection->close();
    } 
}
?>

 

Link do komentarza
Share on other sites

Dołącz do dyskusji, napisz odpowiedź!

Jeśli masz już konto to zaloguj się teraz, aby opublikować wiadomość jako Ty. Możesz też napisać teraz i zarejestrować się później.
Uwaga: wgrywanie zdjęć i załączników dostępne jest po zalogowaniu!

Anonim
Dołącz do dyskusji! Kliknij i zacznij pisać...

×   Wklejony jako tekst z formatowaniem.   Przywróć formatowanie

  Dozwolonych jest tylko 75 emoji.

×   Twój link będzie automatycznie osadzony.   Wyświetlać jako link

×   Twoja poprzednia zawartość została przywrócona.   Wyczyść edytor

×   Nie możesz wkleić zdjęć bezpośrednio. Prześlij lub wstaw obrazy z adresu URL.

×
×
  • Utwórz nowe...

Ważne informacje

Ta strona używa ciasteczek (cookies), dzięki którym może działać lepiej. Więcej na ten temat znajdziesz w Polityce Prywatności.