JAndrassy / WiFiEspAT

Arduino networking library. Standard Arduino WiFi networking API over ESP8266 or ESP32 AT commands.
GNU Lesser General Public License v2.1
271 stars 44 forks source link

problem using WIFIESPAT library #42

Closed MRcode2102 closed 3 years ago

MRcode2102 commented 3 years ago

Hi Mr. JANDRASSY I want to upload a wave file, that is stored in my sd card to a web server with ESP12-F module which connected to Arduino mega 2560 with serial (UART) port, and I using of your library's (WiFiEspAt.h) but my problem is for uploading files with size Biggers than 32k to the webserver (WampServer I using), because I don't have problem with files less than 32kb for uploading I attached my sketch and php code below If you can help me thanks ...

my sketch

#include <WiFiEspAT.h>
#include <SD.h>
#include <SPI.h>
//#include <StreamLib.h>

File myFile;

String post_host = "192.168.1.103";
const int  post_port  = 80;
String  url = "/upload_file.php";
char server[] = "192.168.1.103";

// Emulate Serial1 on pins 6/7 if not present
#if defined(ARDUINO_ARCH_AVR) && !defined(HAVE_HWSERIAL1)
//#include <SoftwareSerial.h>
//SoftwareSerial Serial1(6, 7); // RX, TX
#define AT_BAUD_RATE 9600
#else
#define AT_BAUD_RATE 115200
#endif

//const char* server = "arduino.cc";

WiFiClient client;

//format bytes
String formatBytes(unsigned int bytes) {
  if (bytes < 1024) {
    return String(bytes) + "B";
  } else if (bytes < (1024 * 1024)) {
    return String(bytes / 1024.0) + "KB";
  } else if (bytes < (1024 * 1024 * 1024)) {
    return String(bytes / 1024.0 / 1024.0) + "MB";
  }
}

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

  Serial1.begin(AT_BAUD_RATE);
  WiFi.init(Serial1);

  if (WiFi.status() == WL_NO_MODULE) {
    Serial.println();
    Serial.println("Communication with WiFi module failed!");
    // don't continue
    while (true);
  }

  // waiting for connection to Wifi network set with the SetupWiFiConnection sketch
  Serial.println("Waiting for connection to WiFi");
  while (WiFi.status() != WL_CONNECTED) {
    delay(1000);
    Serial.print('.');
  }
  Serial.println();
  Serial.println("Connected to WiFi network.");

   //test connect to sd
  Serial.print("Initializing SD card...");
  if (!SD.begin(53))
  {
    Serial.println("initialization failed!");
    return;
  }
  Serial.println("initialization done.");

  //read file from SD
  //define file
  myFile = SD.open("data.wav", FILE_READ);

  String fileName = myFile.name();
  String fileSize = formatBytes(myFile.size());

  Serial.println();
  Serial.println("file exists");

  if (myFile)
  {
    Serial.println("test file:ok");
    // print content length and host
    Serial.print("contentLength : ");
    Serial.println(fileSize);
    Serial.print("connecting to ");
    Serial.println(post_host);

    // We now create a URI for the request
    Serial.println("Connected to server");
    Serial.print("Requesting URL: ");
    Serial.println(url);

    // Make a HTTP request and add HTTP headers
    //String boundary = "CustomizBoundarye----";
    //change with your content type
    String contentType = "audio/x-wav";
    String portString = String(post_port);
    String hostString = String(post_host);

    String requestHead = "--RandomNerdTutorials\r\nContent-Disposition: form-data; name=\"data\"; filename=\"data.wav\"\r\nContent-Type: audio/x-wav\r\n\r\n";

    String tail = "\r\n--RandomNerdTutorials--\r\n";

    int contentLength =  requestHead.length() + myFile.size() + tail.length();

    client.connect(server, 80);

    client.println("POST " + url + " HTTP/1.1");
    client.println("Host: " + post_host);
    client.println("Content-Length: " + String(contentLength, DEC));
    client.println("Content-Type: multipart/form-data; boundary=RandomNerdTutorials");
    client.println();
    client.print(requestHead );

    // send myFile:
    //this method is for upload data very fast
    //and only work in ESP software version after 2.3.0
    //if your version is lower than please update
    //esp software to last version or use bellow comment code
    client.write(myFile);
    // create file buffer
    const int bufSize = 2048;
    byte clientBuf[bufSize];
    int clientCount = 0;

    while (myFile.available())
    {
      clientBuf [clientCount] = myFile.read ();
      clientCount++;
      if (clientCount > (bufSize - 1))
      {
        client.write((const uint8_t *)clientBuf, bufSize);
        clientCount = 0;
      }

    }

    if (clientCount > 0)
    {
      client.write((const uint8_t *)clientBuf, clientCount);

    }

    // send tail
    //      char charBuf3[tail.length() + 1];
    //      tail.toCharArray(charBuf3, tail.length() + 1);
    client.print(tail);

    //Serial.print(charBuf3);
  }
  else
  {
    // if the file didn't open, print an error:
    Serial.println("error opening test.WAV");
    Serial.println("Post Failure");
  }

  // Read all the lines of the reply from server and print them to Serial

  Serial.println("request sent");
  String responseHeaders = "";

  while (client.connected() ) {
    //      Serial.println("while client connected");
    String line = client.readStringUntil('\n');
    Serial.println(line);
    responseHeaders += line;
    if (line == "\r") {
      Serial.println("headers received");
      break;
    }
  }

  String line = client.readStringUntil('\n');

  Serial.println("reply was:");
  Serial.println("==========");
  Serial.println(line);
  Serial.println("==========");
  Serial.println("closing connection");

  //close file
  myFile.close();

}
//}
void loop()
{}

the php code

<?PHP

    $path = "data/";
    $path = $path . basename( $_FILES['data']['name']);
    if(move_uploaded_file($_FILES['data']['tmp_name'], $path)) {
      echo "The file ".  basename( $_FILES['data']['name']).
      " has been uploaded";
    } else{
        echo "There was an error uploading the file, please try again!";

  }
?>
JAndrassy commented 3 years ago

the library has special functions to optimize writes to client including writing of a whole file. see the SDWebServer example. there the file is downloaded, but the idea is the same.

        client.write([](Print& p) { // anonymous lambda function to be called by the library
          p.println(F("HTTP/1.1 200 OK"));
          p.println(F("Connection: close"));
          p.print(F("Content-Length: "));
          p.println(file.size());
          p.print(F("Content-Type: "));
          const char* ext = strchr(file.name(), '.');
          p.println(getContentType(ext));
          p.println();
        });
        client.write(file); // send the file as body of the response
        file.close();
MRcode2102 commented 3 years ago

Hi Mr Jandrassy Thank you for your response. If possible Can you explain more about this?

For example, in this part of the code

       client.write([](Print& p) { // anonymous lambda function to be called by the library
          p.println(F("HTTP/1.1 200 OK"));
          p.println(F("Connection: close"));
          p.print(F("Content-Length: "));
          p.println(file.size());
          p.print(F("Content-Type: "));
          const char* ext = strchr(file.name(), '.');
          p.println(getContentType(ext));
          p.println();
        });
        client.write(file); // send the file as body of the response
        file.close();

why the buffer is not used? Because I am a beginner. thanks...

JAndrassy commented 3 years ago

client.write(file) sends the whole file the most efficient way using the internal buffer of the library and optimal transfer over UART and WiFi.

BTW Screenshot from 2021-04-10 15-11-38

JAndrassy commented 3 years ago

client.write(file) sends the whole file the most efficient way using the internal buffer of the library and optimal transfer over UART and WiFi.

MRcode2102 commented 3 years ago

Thank you again for your answer Mr Jandrassy. I had another question, sir, do you think I can send a 200 KB file to a server with your library and with Arduino mega 2560 and a esp 12F module which connected together with UART port? Thank you very much again sir for taking the time to answer me

JAndrassy commented 3 years ago

I had another question, sir, do you think I can send a 200 KB file to a server with your library and with Arduino mega 2560 and a esp 12F module which connected together with UART port? Thank you very much again sir for taking the time to answer me

yes. but set 250000 baud on Serial to esp8266 and in AT firmware

MRcode2102 commented 3 years ago

Thank you sir for answering my questions Excuse me, is it possible to give me the contact number from WhatsApp or if you have another social network? Because I had a few small questions for your service if there is no problem Thanks

JAndrassy commented 3 years ago

Thank you sir for answering my questions Excuse me, is it possible to give me the contact number from WhatsApp or if you have another social network? Because I had a few small questions for your service if there is no problem Thanks

you can ask here

MRcode2102 commented 3 years ago

Now can i ask a question mr?