ESP8266 – Gebufferd binair SPIFFS lezen. #2

270 KB/s.

De int bufferSize = 1460 is cruciaal, dit is nl de TCP hw buffer size.


void fileSend(String fileName) {
  if ( !SPIFFS.begin() ) {
    Serial.println("Fatal error: no SPIFFS disk present!");
    analogWrite(redLED, PWMRANGE);     
    while (true) {}   //wait forever
  }
  File thisFile = SPIFFS.open(fileName, "r");
  if (!thisFile) {
    webClient.print("HTTP/1.1 404 Not found\r\n\r\n");
    webClient.print("ERROR 404 - '" + fileName + "' was not found.");
    return;
  }
  //check the file's extention and tailor the header for that
  String httpHeader = "HTTP/1.1 200 \r\nContent-Type: text/plain\r\n";
  
  if ( fileName.substring(  fileName.length() - 4 ) == ".css" ) {
    httpHeader = "HTTP/1.1 200 \r\nContent-Type: text/css\r\n";
  }

  if ( fileName.substring(  fileName.length() - 4 ) == ".htm" || 
       fileName.substring(  fileName.length() - 4 ) == ".php" ) {
    httpHeader = "HTTP/1.1 200 \r\nContent-Type: text/html\r\n";
  }
  
  httpHeader += "Content-Length: " + (String)thisFile.size() + "\r\n\r\n" ;
  webClient.print(httpHeader);

  int bufferSize = 1460;
  char rwBuffer[bufferSize];
  while ( thisFile.available() > bufferSize ) {
    thisFile.readBytes(rwBuffer,bufferSize);  
    webClient.write(rwBuffer, bufferSize);
  }
  //send last chunk
  bufferSize = thisFile.available();
  thisFile.readBytes(rwBuffer,bufferSize);  
  webClient.write(rwBuffer, bufferSize);
  thisFile.close();
}//done

ESP8266 – Gebufferd binair SPIFFS lezen.

Deze routine word gebruikt in de Aquacontroller.
Haalt ongeveer 14kB/s. Maar kan wel 1.3MB grote bestanden aan.

void fileSend(String fileName) {
 SPIFFS.begin();
 File thisFile = SPIFFS.open(fileName, "r");
 if (!thisFile) {
   webClient.println("HTTP/1.1 404 Not found\r\n");
   webClient.println("ERROR 404 - '" + fileName + "' was not found.");
   return;
 }
 //check the file's extention and tailor the header for that
 String httpHeader;
 if ( fileName.substring( fileName.length() - 4 ) == ".css" ) {
   httpHeader = "HTTP/1.1 200 \r\nContent-Type: text/css\r\n";
 } 
 else {
   httpHeader = "HTTP/1.1 200 \r\nContent-Type: text/html\r\n";
 }
 httpHeader += "Content-Length: " + (String)thisFile.size() + "\r\n" ;
 webClient.println(httpHeader);

 int bufferSize = 512;
 char rwBuffer[bufferSize];
 while ( thisFile.available() > bufferSize ) {
   for ( int bufferPos = 0; bufferPos < bufferSize; bufferPos++ ) {
     rwBuffer[bufferPos] = thisFile.read();
   }
   webClient.write(rwBuffer, bufferSize);
 }
 //send last chunk
 int leftOver = thisFile.available();
 for ( int bufferPos = 0; bufferPos < leftOver; bufferPos++ ) {
   rwBuffer[bufferPos] = thisFile.read();
 }
 webClient.write(rwBuffer, leftOver);
 thisFile.close();
}