ESP8266 nacitanie obsahu stranky

Sekcia určená pre Arduino nadšencov

Moderátor: Moderátori

Atlass
Nový člen
Nový člen
Príspevky: 76
Dátum registrácie: 16 Mar 2019, 16:29

ESP8266 nacitanie obsahu stranky

Príspevok od používateľa Atlass » 21 Okt 2020, 15:00

Zdravím,
snažím sa rozbehnúť komunikáciu medzi ESP8266 a webom. Komunikácia by mala prebiehať tak že ESP8266 (Node MCU V3) pošle request (POST alebo GET) na stránku a tá mu odpovie jednoduchým textom. Kód mám momentálne spravený pre POST metódu ale skúšal som aj GET s rovnakým výsledkom.
- Posielanie dát aj ich spracovanie mi funguje.
- Dokonca mi funguje aj prijatie dát.
- Problém však nastáva po prijatí dát kedy sa mi ESP8266 resetuje a cyklus sa opakuje.

serialport my vypíše chybu "Exception (9)".
https://links2004.github.io/Arduino/dc/ ... auses.html

jediné čo sa mi zatiaľ podarilo zistiť je že ak sa nevykoná metóda POST na stránke tak sa modul neresetuje.

problém môže byť aj v stránke ale neviem ako ju upraviť.

používam ARDUINO IDE

Za akékoľvek postrehy Ďakujem :-)

Zdroj:
https://techtutorialsx.com/2016/07/17/e ... -requests/

Kód ESP8266

Kód: Vybrať všetko

#include <ESP8266WiFi.h>
#include <ESP8266HTTPClient.h>
#include <WiFiClient.h>

const char* ssid = "moje ssid";
const char* password = "moje heslo";
const char* address = "http://webtemp.wz.cz/test.php";
//const char* address = "http://jsonplaceholder.typicode.com/users/1"

String apiKeyValue = "mojetralalaapi";  //API 

int c = 0;
//*********** LOOP *********** 
void setup () {

  Serial.begin(115200);
  delay(10);
  WiFi.begin(ssid, password);
  delay(10);
  Serial.print("Connecting..");

  while (WiFi.status() != WL_CONNECTED) {
    delay(1000);
    Serial.print(".");
  }
  Serial.println(""); 
  Serial.println("WiFi connected"); 
  Serial.println("IP address: "); 
  Serial.println(WiFi.localIP()); 
}


//*********** SETUP *********** 
void loop() {

  Serial.println("************************ NEW LOOP ************************");
  c++;
  Serial.print("c: ");
  Serial.println(c);


  if (WiFi.status() == WL_CONNECTED) { //Check WiFi connection status
  //---------------------------------------------
  //post data
    String data =  "4321";
    String postData =   "api_key=" + apiKeyValue +
                        "&value=" + String(data) + "";
  //-------------------------------------------------
    
    HTTPClient http;  //Declare an object of class HTTPClient
    http.begin(address);  //Specify request destination
    http.addHeader("Content-Type", "application/x-www-form-urlencoded"); 
   auto httpCode = http.POST(postData); 

 //   int httpCode = http.GET();   //Send the request
   
    Serial.println(httpCode); //Print HTTP return code 
    if (httpCode > 0) { //Check the returning code
      delay(300);
      String payload = http.getString();   //Get the request response payload
      Serial.println(payload);                     //Print the response payload
    }

    http.end();   //Close connection

  }

delay(10000);    //Send a request every 30 seconds
}



Kód stránky:

Kód: Vybrať všetko

<?php

$ESP_api_key =      'mojetralalaapi';

//-----------------------------------------------------------------------------------------------
$ESP_api_key_rec = $value = "";


if ($_SERVER["REQUEST_METHOD"] == "POST") {
    $ESP_api_key_rec =  test_input($_POST["api_key"]);
    $value =            test_input($_POST["value"]);
    
    if($ESP_api_key_rec === $ESP_api_key){
        echo "API OK ";
        echo "nacitane data: " . $value; 
    
    }
    else{
         echo "Wrong API!"; 
    }
    
}
else{
    echo "no data!" ;  
}


// Osetrenie vstupnych dat 
function test_input($data) {
    $data = trim($data);
    $data = stripslashes($data);
    $data = htmlspecialchars($data);
    return $data;
}

?>

si tu

výstup serialmonitor

Kód: Vybrať všetko

WiFi connected
IP address: 
192.168.43.17
************************ NEW LOOP ************************
c: 1
200
API OK nacitane data: 4321
si tu

--------------- CUT HERE FOR EXCEPTION DECODER ---------------

Exception (9):
epc1=0x40207278 epc2=0x00000000 epc3=0x00000000 excvaddr=0x0110012e depc=0x00000000

>>>stack>>>

ctx: cont
sp: 3ffffd10 end: 3fffffc0 offset: 0190
3ffffea0:  40203c24 3ffee450 3ffe870a 40203f01  
3ffffeb0:  3fffdad0 00000020 3ffffee0 40202a38  
3ffffec0:  3ffef354 000000c8 3ffffee0 402037dc  
3ffffed0:  3fffdad0 000000c8 3ffee450 40201231  
3ffffee0:  00000000 00000000 3ffef2a4 3ffef2f4  
3ffffef0:  000d000f 00fef100 00010050 40001388  
3fffff00:  7365742f 68702e74 89fe0070 70747468  
3fffff10:  3ffe8700 84000000 3ffef5bc 0000004f  
3fffff20:  00fe870c 3ffef234 0011001f 00204196  
3fffff30:  3ffe8600 287008a9 80003c00 00000000  
3fffff40:  00000000 000000c8 00000020 40203c00  
3fffff50:  00000000 3ffe000a 3ffe8700 40203f01  
3fffff60:  80ffdad0 00000001 3ffef344 3ffef300  
3fffff70:  0020002f 80ffff00 3ffef400 000c000f  
3fffff80:  80ffdad0 3ffef26c 0021002f 002010c0  
3fffff90:  31323334 112ba800 84efeffe feefeffe  
3fffffa0:  feefeffe 00000000 3ffee48c 402053bc  
3fffffb0:  feefeffe feefeffe 3ffe84f0 40100b85  
<<<stack<<<

--------------- CUT HERE FOR EXCEPTION DECODER ---------------

 ets Jan  8 2013,rst cause:2, boot mode:(3,6)

load 0x4010f000, len 3584, room 16 
tail 0
chksum 0xb0
csum 0xb0
v2843a5ac
~ld

0

Daevid
Stály člen
Stály člen
Príspevky: 206
Dátum registrácie: 15 Nov 2007, 00:00

Re: ESP8266 nacitanie obsahu stranky

Príspevok od používateľa Daevid » 21 Okt 2020, 16:05

Skús vymazať ten 10s delay na konci loopu.
0

pocitujlasku
Ultimate člen
Ultimate člen
Príspevky: 6203
Dátum registrácie: 20 Júl 2007, 00:00
Vek: 41

Re: ESP8266 nacitanie obsahu stranky

Príspevok od používateľa pocitujlasku » 21 Okt 2020, 16:35

daj si v serial console vypisovat aj datum a cas, ci to padne na konci, alebo na zaciatku dalsieho cyklu
0
Jedním z největších projevů nedůvěry v Boha je hromosvod na kostele.

Sahasrar
Stály člen
Stály člen
Príspevky: 233
Dátum registrácie: 16 Máj 2015, 00:05
Bydlisko: TN

Re: ESP8266 nacitanie obsahu stranky

Príspevok od používateľa Sahasrar » 21 Okt 2020, 18:25

1. Ak je to možné, nepoužívať delay pri čipoch ESP... Dôvod je taký, že ak použijes dlhy delay, "watchdog timer" si myslí, že kód sa zasekol a automaticky sa iniciuje reštart. Ďalšia z vecí je, že na ESP na rozdiel od iných arduino uC bežia aj procesy v pozadí, ktoré sa delayom rušia... Najlepšie je funkciu spúšťať a kontrolovať jej stav použitím vnútorných hodín millis()...

2. V PHP kóde nemáš ošetrené, čo sa stane ak príde POST request, ale dáta nebudú vyhovovať tvojej šablóne alebo jedna z premenných odoslaná na server bude NULL...

3. Skús použiť Stack Decoder a hoď sem výstup, budeme všetci múdrejší čo sa tam deje...
0

Atlass
Nový člen
Nový člen
Príspevky: 76
Dátum registrácie: 16 Mar 2019, 16:29

Re: ESP8266 nacitanie obsahu stranky

Príspevok od používateľa Atlass » 21 Okt 2020, 21:09

- Kód som upravil a z loop som odstránil delay.
- PHP stránku som zatiaľ neošetroval ale až to bude fungovať budem riešiť aj tieto veci
- problém však pretrváva :-/

Kód ESP

Kód: Vybrať všetko

#include <ESP8266WiFi.h>
#include <ESP8266HTTPClient.h>
#include <WiFiClient.h>

const char* ssid = "xxx";
const char* password = "xxx";
const char* address = "http://webtemp.wz.cz/test.php";
//const char* address = "http://jsonplaceholder.typicode.com/users/1"

String apiKeyValue = "mojetralalaapi";  //API

int c = 0;


unsigned long lastTime = 0;
unsigned long timerDelay = 5000;


//*********** LOOP ***********
void setup () {

  Serial.begin(115200);
  WiFi.begin(ssid, password);
  Serial.print("Connecting..");

  while (WiFi.status() != WL_CONNECTED) {
    delay(1000);
    Serial.print(".");
  }
  Serial.println("");
  Serial.println("WiFi connected");
  Serial.println("IP address: ");
  Serial.println(WiFi.localIP());
}


//*********** SETUP ***********
void loop() {
if ((millis() - lastTime) > timerDelay) {
  Serial.println("************************ NEW LOOP ************************");
  c++;
  Serial.print("c: ");
  Serial.println(c);


//  if (WiFi.status() == WL_CONNECTED) { //Check WiFi connection status
  //---------------------------------------------
  //post data
    String datam =  "4321";
    String postData =   "&api_key=" + apiKeyValue +  "&value="  + datam ;
             
  //-------------------------------------------------
   
    HTTPClient http;  //Declare an object of class HTTPClient
    http.begin(address);  //Specify request destination
    http.addHeader("Content-Type", "application/x-www-form-urlencoded");
   int httpCode = http.POST(postData);

//   int httpCode = http.GET();   //Send the request
   
    Serial.println(httpCode); //Print HTTP return code
    if (httpCode > 0) { //Check the returning code
      String payload = http.getString();   //Get the request response payload
      Serial.println(payload);                     //Print the response payload
     Serial.println("--- END 1 --");
    }
     Serial.println("--- END 2 --");
  //  http.end();   //Close connection
    Serial.println("--- END 3 --");
 // }
  Serial.println("--- END 4 --");
  lastTime = millis();
  Serial.println("--- END 5 --");
}
}
Výstup serial monitor:

Kód: Vybrať všetko

.
WiFi connected
IP address: 
192.168.43.17
************************ NEW LOOP ************************
c: 1
200
API OK nacitane data: 4321
si tu
--- END 1 --
--- END 2 --
--- END 3 --
--- END 4 --
--- END 5 --

--------------- CUT HERE FOR EXCEPTION DECODER ---------------

Exception (9):
epc1=0x4020323f epc2=0x00000000 epc3=0x00000000 excvaddr=0x01cc01e6 depc=0x00000000

>>>stack>>>

ctx: cont
sp: 3ffffd30 end: 3fffffc0 offset: 0190
3ffffec0:  3ffee458 000000c8 3ffee4a4 40204060  
3ffffed0:  3ffee458 000000c8 3ffee4a4 4020125b  
3ffffee0:  00000000 00000000 3ffef8d4 3ffef924  
3ffffef0:  000d000f 00000000 00010050 3f001388  
3fffff00:  7365742f 68702e74 89fe0070 70747468  
3fffff10:  3ffe8700 84000000 3ffefbec 0000004f  
3fffff20:  00fe874e 3ffef864 0011001f 002041b2  
3fffff30:  3ffe8600 99ca9dd1 80ffff00 00000000  
3fffff40:  00000000 000000c8 00000020 40203c00  
3fffff50:  00000000 3ffe000a 3ffe8700 40203f1d  
3fffff60:  807a1200 00000001 3ffef974 3ffef900  
3fffff70:  0020002f 80ffffff 3ffefa00 000c000f  
3fffff80:  80000000 3ffef89c 0022002f 00100154  
3fffff90:  31323334 00000000 84fee4e0 40100175  
3fffffa0:  3fffdad0 00000000 3ffee4e0 402053d8  
3fffffb0:  feefeffe feefeffe 3ffe84f4 40100b85  
<<<stack<<<

--------------- CUT HERE FOR EXCEPTION DECODER ---------------

 ets Jan  8 2013,rst cause:2, boot mode:(3,6)

load 0x4010f000, len 3584, room 16 
tail 0
chksum 0xb0
csum 0xb0
v2843a5ac
~ld
výstup STACK DECODER

Kód: Vybrať všetko


Decoding stack results
0x40204060: Print::println(char const*) at C:\Users\xxx\AppData\Local\Arduino15\packages\esp8266\hardware\esp8266\2.7.4\cores\esp8266\Print.cpp line 198
0x4020125b: loop() at D:\-=xxx=-\Arduino\PROJECTS\test/test.ino line 50
0x40203c00: HardwareSerial::peek() at C:\Users\xxx\AppData\Local\Arduino15\packages\esp8266\hardware\esp8266\2.7.4\cores\esp8266/HardwareSerial.h line 133
0x40203f1d: Print::write(char const*) at C:\Users\xxx\AppData\Local\Arduino15\packages\esp8266\hardware\esp8266\2.7.4\cores\esp8266/Print.h line 62
0x40100175: esp_schedule() at C:\Users\xxx\AppData\Local\Arduino15\packages\esp8266\hardware\esp8266\2.7.4\cores\esp8266\core_esp8266_main.cpp line 125
0x402053d8: loop_wrapper() at C:\Users\xxx\AppData\Local\Arduino15\packages\esp8266\hardware\esp8266\2.7.4\cores\esp8266\core_esp8266_main.cpp line 197
0

pocitujlasku
Ultimate člen
Ultimate člen
Príspevky: 6203
Dátum registrácie: 20 Júl 2007, 00:00
Vek: 41

Re: ESP8266 nacitanie obsahu stranky

Príspevok od používateľa pocitujlasku » 21 Okt 2020, 22:00

mozno blba otazka, ale cim to napajas a ci nemas nieco pichnute na piny.
0
Jedním z největších projevů nedůvěry v Boha je hromosvod na kostele.

Atlass
Nový člen
Nový člen
Príspevky: 76
Dátum registrácie: 16 Mar 2019, 16:29

Re: ESP8266 nacitanie obsahu stranky

Príspevok od používateľa Atlass » 21 Okt 2020, 22:02

Nemám tam zapojené nič. Napájané to je priamo z USB.
0

Daevid
Stály člen
Stály člen
Príspevky: 206
Dátum registrácie: 15 Nov 2007, 00:00

Re: ESP8266 nacitanie obsahu stranky

Príspevok od používateľa Daevid » 22 Okt 2020, 13:45

Podľa chybového hlásenia sa jedná o chybu typu "LoadStoreAlignmentCause" - Load or store to an unaligned address. Takže zrejme nejaký problém s premennými, žiaľ viac poradiť neviem.
0

Daevid
Stály člen
Stály člen
Príspevky: 206
Dátum registrácie: 15 Nov 2007, 00:00

Re: ESP8266 nacitanie obsahu stranky

Príspevok od používateľa Daevid » 22 Okt 2020, 17:00

Uprav si toto:

Kód: Vybrať všetko

    HTTPClient http;  //Declare an object of class HTTPClient
    http.begin(address);  //Specify request destination
na toto:

Kód: Vybrať všetko

    WiFiClient client;
    HTTPClient http;  //Declare an object of class HTTPClient
    http.begin(client, address);  //Specify request destination
0

Atlass
Nový člen
Nový člen
Príspevky: 76
Dátum registrácie: 16 Mar 2019, 16:29

Re: ESP8266 nacitanie obsahu stranky

Príspevok od používateľa Atlass » 28 Feb 2021, 11:32

Zdravím,

vraciam sa k tomuto problému ktorý som bohužiaľ zatiaľ nevyriešil.
Problém však pravdepodobne bude s formátom načítaných dát. Rozhodol som sa preto trochu pogoogliť a nájsť iný návod.

https://randomnerdtutorials.com/esp32-h ... t-arduino/

V tomto konkrétne sa využíva JSON objekt. Nejaké skúsenosti s webom mám avšak JSON som ešte neskúšal.

Kód zatiaľ nespôsobuje reštart ESP čo je SUPER :applause: ale nenačíta dáta JSON objektu lebo tam niesu :-D


Ide o to či by mi niekto vedel pomôcť s vytvorením jednoduchej testovacej stránky. V tomto prípade by to mal byť JSON array v rozsahu 1,2,3 a v tom nejaké číslo.


Kód ESP 32

Kód: Vybrať všetko

#include <WiFi.h>
#include <HTTPClient.h>
#include <Arduino_JSON.h>

const char* ssid = "ssid";
const char* password = "veslo";

//Your Domain name with URL path or IP address with path
const char* serverName = "webtemp.wz.cz/test.php";

// the following variables are unsigned longs because the time, measured in
// milliseconds, will quickly become a bigger number than can be stored in an int.
unsigned long lastTime = 0;
// Timer set to 10 minutes (600000)
//unsigned long timerDelay = 600000;
// Set timer to 5 seconds (5000)
unsigned long timerDelay = 5000;

String sensorReadings;
float sensorReadingsArr[3];

void setup() {
  Serial.begin(115200);

  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());
 
  Serial.println("Timer set to 5 seconds (timerDelay variable), it will take 5 seconds before publishing the first reading.");
}

void loop() {
  //Send an HTTP POST request every 10 minutes
  if ((millis() - lastTime) > timerDelay) {
    //Check WiFi connection status
    if(WiFi.status()== WL_CONNECTED){
              
      sensorReadings = httpGETRequest(serverName);
      Serial.println(sensorReadings);
      JSONVar myObject = JSON.parse(sensorReadings);
  
      // JSON.typeof(jsonVar) can be used to get the type of the var
      if (JSON.typeof(myObject) == "undefined") {
        Serial.println("Parsing input failed!");
        return;
      }
    
      Serial.print("JSON object = ");
      Serial.println(myObject);
    
      // myObject.keys() can be used to get an array of all the keys in the object
      JSONVar keys = myObject.keys();
    
      for (int i = 0; i < keys.length(); i++) {
        JSONVar value = myObject[keys[i]];
        Serial.print(keys[i]);
        Serial.print(" = ");
        Serial.println(value);
        sensorReadingsArr[i] = double(value);
      }
      Serial.print("1 = ");
      Serial.println(sensorReadingsArr[0]);
      Serial.print("2 = ");
      Serial.println(sensorReadingsArr[1]);
      Serial.print("3 = ");
      Serial.println(sensorReadingsArr[2]);
    }
    else {
      Serial.println("WiFi Disconnected");
    }
    lastTime = millis();
  }
}

String httpGETRequest(const char* serverName) {
  HTTPClient http;
    
  // Your IP address with path or Domain name with URL path 
  http.begin(serverName);
  
  // Send HTTP POST request
  int httpResponseCode = http.GET();
  
  String payload = "{}"; 
  
  if (httpResponseCode>0) {
    Serial.print("HTTP Response code: ");
    Serial.println(httpResponseCode);
    payload = http.getString();
  }
  else {
    Serial.print("Error code: ");
    Serial.println(httpResponseCode);
  }
  // Free resources
  http.end();

  return payload;
}
0

maskrtnik01
Ultimate člen
Ultimate člen
Príspevky: 2564
Dátum registrácie: 20 Júl 2010, 00:00
Bydlisko: okolie KE
Vek: 27

Re: ESP8266 nacitanie obsahu stranky

Príspevok od používateľa maskrtnik01 » 28 Feb 2021, 11:36

Jednoduchá testovacia stránka....proste uložte json súbor na webserver.
0

Napísať odpoveď
  • Podobné témy
    Odpovedí
    Zobrazení
    Posledný príspevok