Не удалось отправить GET-запрос от nodeMCU - PullRequest
0 голосов
/ 25 октября 2019

Я пытаюсь отправить запрос GET от NodeMCU, используя следующий код, но он выдает 404 неправильных запроса. Но когда я пробую один и тот же URL в браузере и почтальоне, он работает нормально. Любые предложения нуждаются в помощи!

Это наш код Arduino:

          #include <SPI.h>
          #include <MFRC522.h>
          #include <ESP8266WiFi.h>
          #include <WiFiClient.h>
          #include <ESP8266WebServer.h>
          #include <ESP8266HTTPClient.h>

          //Profile 1 (Network Credentials)
          const char* ssid = "";
          const char* password = "";

          //Profile 2 (Network Credentials)
          //const char* ssid = "";
          //const char* password = "";

          //Web/Server address to read/write from 
          const char *host = "";          //IP address of server

          //For identifying the RFID reader's room
          String room = "AG-01";

          String content = "str";

          //ESP8266WebServer server(80);                Instantiate the server at port 80 (http port)

          constexpr uint8_t RST_PIN = 5;
          constexpr uint8_t SS_PIN = 4;

          MFRC522 rfid(SS_PIN, RST_PIN);              //Instance of the class

          MFRC522::MIFARE_Key key;

          //Stores the HTML for the Webpage
          String webpage = "<h1>My Node MCU Server</h1>";

          //Contains the scanned tag information

          //Init array that will store new NUID
          byte nuidPICC[4];

          void setup() {

            Serial.begin(115200);

            //------------For connecting to the WiFi network-------------

            WiFi.mode(WIFI_STA);                      //Hides the viewing of ESP as a WiFi Hotspot
            WiFi.begin(ssid, password);
            Serial.println("");

            Serial.print("Connecting");
            while(WiFi.status() != WL_CONNECTED) {
              delay(500);
              Serial.print(".");
            }

            //Show SSID and IP address if successfully configured
            Serial.println("");
            Serial.print("Connected to ");
            Serial.println(ssid);
            Serial.print("IP address: ");
            Serial.println(WiFi.localIP());

          //  server.on("/", []() {
          //    server.send(200, "text/html", webpage);
          //    delay(1000);
          //  });

            //------------------------WiFi module end---------------------

            //--------------------Code for reading tags-------------------

            SPI.begin();
            rfid.PCD_Init();

            //---------------------RFID tags read end---------------------
          }

          void loop() {
            sendPostReq();

            // Look for new cards
            if ( ! rfid.PICC_IsNewCardPresent())
              return;

            // Verify if the NUID has been readed
            if ( ! rfid.PICC_ReadCardSerial())
              return;

            if (rfid.uid.uidByte[0] != nuidPICC[0] || rfid.uid.uidByte[1] != nuidPICC[1] || rfid.uid.uidByte[2] != nuidPICC[2] || rfid.uid.uidByte[3] != nuidPICC[3] )
            {
              readCards();
            }

            else Serial.println(F("Card read previously."));

            // Halt PICC
            rfid.PICC_HaltA();

            // Stop encryption on PCD
            rfid.PCD_StopCrypto1();
          //  server.handleClient();
          }

          void sendPostReq()
          {
            HTTPClient http;                          //declare object of class HTTPClient

            http.begin("http://ip/myfolder/dataLogger.php");                           //Specify request destination

            int httpCode = http.GET();                                                   //Send the request
            String payload = http.getString();                                                    //Get the request payload

          //  Serial.println("{\"status\":str,\"room\":AG-01}");
            Serial.println("http Code: " + httpCode);                                             //Print HTTP return code
            Serial.println("payload: " + payload);                                                //Print request responde payload

            http.end();                                                                           //Close connection
            delay(5000);
          }

          void readCards()
          {
            content = "";
            Serial.println(F("A new card has been detected."));

            // Store NUID into nuidPICC array
            for (byte i = 0; i < 4; i++) {
              nuidPICC[i] = rfid.uid.uidByte[i];
            }

            //new code for integrating the Card Id Storing Feature!
            for (byte i = 0; i < rfid.uid.size; i++) 
            {
              content.concat(String(rfid.uid.uidByte[i] < 0x10 ? " 0" : " "));
              content.concat(String(rfid.uid.uidByte[i], HEX));
            }

            Serial.println();
            content.toUpperCase();
            Serial.println("Cart read:" + content);
            content.trim();
            Serial.println("After trim:" + content);

            if(content.equals("85 3A D6 73"))
            {
              Serial.println("Welcome Suraj");
            }
            else if(content.equals("14 51 C1 66"))
            {
              Serial.println("Welcome Bijaynanda Patnaik");
            }
            else if(content.equals("16 65 DE 73"))
            {
              Serial.println("Welcome Venkata Sridhar");
            }
          }

Это наш PHP-код для принятия запроса GET

        <?php
        //Creates new record as per request
            //Connect to database
            $servername = "";
            $username = "";
            $password = "";
            $dbname = "";

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

            //Get current date and time
            date_default_timezone_set('Asia/Kolkata');
            $d = date("Y-m-d");
            //echo " Date:".$d."<BR>";
            $t = date("H:i:s");

            if(!empty($_GET['status']) && !empty($_GET['station']))
            {
            $status = $_GET['status'];
            $station = $_GET['station'];

                // $sql = "INSERT INTO logs (station, status, Date, Time)

                // VALUES ('".$station."', '".$status."', '".$d."', '".$t."')";

            $sql = "UPDATE teacher_info SET room = '".$station."' WHERE AssignedCard = '".$status."'";
                if ($conn->query($sql) === TRUE) {
                    echo "OK";
                } else {
                    echo "Error: " . $sql . "<br>" . $conn->error;
                }
            }


            $conn->close();
        ?>
...