Stránka 1 z 1

ESP8266 ukladanie do SPIFFS obcas blbne

Napsal: 12 dub 2022, 22:04
od Sperhak
Zdravím snažím sa ukladať dáta do súboru na spiffs pamäti no občas sa dáta neuložia na nový riadok pritom by sa mali a namiesto toho mi to tam ustrihne jednu 0 a zapíše ˙˙˙ a pokračuje na tom istom riadku. Na serial to zapisuje správne. Prikladám časť kódu so zápisom údajov a výsledný zápis vyčítaný z spiffs. Vedeli by ste mi poradiť kde by mohol byť problém?

Kód: Vybrat vše

 if (currentMillis - prevTemp > DS_delay && tmpRequested) { // 750 ms after requesting the temperature
      uint32_t actualTime = timeUNIX + (currentMillis - lastNTPResponse) / 1000;
      // The actual time is the last NTP time plus the time that has elapsed since the last NTP response
      tmpRequested = false;
      float temp = random(0,80); // Get the temperature from the sensor
      temp = round(temp * 100.0) / 100.0; // round temperature to 2 digits
      float temp1 = random(0,20); // Get the temperature from the sensor
      temp1 = round(temp1 * 100.0) / 100.0; // round temperature to 2 digits
       
      Serial.printf("Appending temperature to file: %lu,", actualTime);
      Serial.print(temp);
      Serial.print(',');
      Serial.println(temp1);
  
      File tempLog = SPIFFS.open("/temp.csv", "a"); // Write the time and the temperature to the csv file
      tempLog.print(actualTime);
      tempLog.print(',');
      tempLog.print(temp);
      tempLog.print(',');
      tempLog.println(temp1);
      tempLog.close();
      Serial.println("Data zapisane do suboru");
    }
1649762305,27.00,9.0˙˙˙1649762365,70.00,13.00
1649762425,24.00,0.00
1649762485,52.00,14.00
1649762545,21.00,16.00
1649762605,29.00,9.00
1649762665,42.00,16.00
1649762725,31.00,7.0˙˙˙1649762785,63.00,2.00
1649762845,50.00,11.00
1649762905,11.00,9.0˙˙˙1649762965,18.00,9.00
1649763025,35.00,4.00
1649763085,7.00,2.00˙˙1649763145,13.00,9.00
1649763205,13.00,9.00
1649763265,25.00,11.00
1649763325,73.00,0.0˙˙˙1649763385,64.00,9.0˙˙˙1649763445,49.00,16.00
1649763505,70.00,12.00
1649763565,41.00,9.0˙˙˙1649763625,13.00,0.00
1649763685,18.00,3.00
1649763745,2.00,14.0˙˙˙1649763805,30.00,5.0˙˙˙1649763865,24.00,0.00
1649763925,49.00,7.00
1649763985,48.00,15.00

Re: ESP8266 ukladanie do SPIFFS obcas blbne

Napsal: 13 dub 2022, 14:34
od jankop
Nejsem expert přes FS na ESP8266, ale jedno vím jistě. SPIFFS se již dávno nedoporučuje používat.
https://arduino-esp8266.readthedocs.io/ ... on-warning
Ovšem chybu můžeš mít i v konfiguraci IDE nebo kdekoliv jinde. Tvůj segment programu je vcelku na nic, ten si nespustím a nezkusím, ačkoliv tady mám ESP8266 trvale připojeno k PC.

Re: ESP8266 ukladanie do SPIFFS obcas blbne

Napsal: 13 dub 2022, 18:19
od Sperhak
Myslel som že to bude stačiť pretože tam sa pracuje s tou pamäťou, pridávam teda celý program. Avšak neviem pridať ostatné súbory tak som to dal celé na uložto. https://uloz.to/file/qjOtEalbxDpZ/a-tem ... -1-333-rar Takže miesto knižnice FS.h mám používať LitleFS.h ak som to pochopil spravne.

Kód: Vybrat vše

#include <ESP8266WiFi.h>
#include <WiFiUdp.h>
#include <ESP8266WebServer.h>

#include <FS.h>

#define ONE_HOUR 3600000UL


ESP8266WebServer server(80);             // create a web server on port 80

File fsUploadFile;                                    // a File variable to temporarily store the received file

WiFiUDP UDP;                   // Create an instance of the WiFiUDP class to send and receive UDP messages

IPAddress timeServerIP;        // The time.nist.gov NTP server's IP address
const char* ntpServerName = "time.nist.gov";

const int NTP_PACKET_SIZE = 48;          // NTP time stamp is in the first 48 bytes of the message

byte packetBuffer[NTP_PACKET_SIZE];      // A buffer to hold incoming and outgoing packets

/*__________________________________________________________SETUP__________________________________________________________*/

void setup() {
  Serial.begin(115200);        // Start the Serial communication to send messages to the computer
  delay(10);
  Serial.println("\r\n");

  startWiFi();                 // Start a Wi-Fi access point, and try to connect to some given access points. Then wait for either an AP or STA connection
  startSPIFFS();               // Start the SPIFFS and list all contents
  startServer();               // Start a HTTP server with a file read handler and an upload handler
  startUDP();                  // Start listening for UDP messages to port 123

  WiFi.hostByName(ntpServerName, timeServerIP); // Get the IP address of the NTP server
  Serial.print("Time server IP:\t");
  Serial.println(timeServerIP);

  sendNTPpacket(timeServerIP);
  delay(500);
}

/*__________________________________________________________LOOP__________________________________________________________*/

const unsigned long intervalNTP = ONE_HOUR; // Update the time every hour
unsigned long prevNTP = 0;
unsigned long lastNTPResponse = millis();

const unsigned long intervalTemp = 60000;   // Do a temperature measurement every minute
unsigned long prevTemp = 0;
bool tmpRequested = false;
const unsigned long DS_delay = 750;         // Reading the temperature from the DS18x20 can take up to 750ms

uint32_t timeUNIX = 0;                      // The most recent timestamp received from the time server

void loop() {
  unsigned long currentMillis = millis();

  if (currentMillis - prevNTP > intervalNTP) { // Request the time from the time server every hour
    prevNTP = currentMillis;
    sendNTPpacket(timeServerIP);
  }

  uint32_t time = getTime();                   // Check if the time server has responded, if so, get the UNIX time
  if (time) {
    timeUNIX = time;
    Serial.print("NTP response:\t");
    Serial.println(timeUNIX);
    lastNTPResponse = millis();
  } else if ((millis() - lastNTPResponse) > 24UL * ONE_HOUR) {
    Serial.println("More than 24 hours since last NTP response. Rebooting.");
    Serial.flush();
    ESP.reset();
  }

  if (timeUNIX != 0) {
    if (currentMillis - prevTemp > intervalTemp) {  // Every minute, request the temperature
    
      tmpRequested = true;
      prevTemp = currentMillis;
      Serial.println("Temperature requested");
    }
    if (currentMillis - prevTemp > DS_delay && tmpRequested) { // 750 ms after requesting the temperature
      uint32_t actualTime = timeUNIX + (currentMillis - lastNTPResponse) / 1000;
      // The actual time is the last NTP time plus the time that has elapsed since the last NTP response
      tmpRequested = false;
      float temp = random(0,80); // Get the temperature from the sensor
      temp = round(temp * 100.0) / 100.0; // round temperature to 2 digits
      float temp1 = random(0,20); // Get the temperature from the sensor
      temp1 = round(temp1 * 100.0) / 100.0; // round temperature to 2 digits

  
      Serial.printf("Appending temperature to file: %lu,", actualTime);
      Serial.print(temp);
      Serial.print(',');
      Serial.println(temp1);
  
      File tempLog = SPIFFS.open("/temp.csv", "a"); // Write the time and the temperature to the csv file
      tempLog.print(actualTime);
      tempLog.print(',');
      tempLog.print(temp);
      tempLog.print(',');
      tempLog.println(temp1);
      tempLog.close();
      Serial.println("Data zapisane do suboru");
    }
  } else {                                    // If we didn't receive an NTP response yet, send another request
    sendNTPpacket(timeServerIP);
    Serial.println("NTP sa nepodarilo");
    delay(500);
  }

  server.handleClient();                      // run the server

}

/*__________________________________________________________SETUP_FUNCTIONS__________________________________________________________*/

void startWiFi() { // Try to connect to some given access points. Then wait for a connection
  WiFi.begin("hoj1", "");   // add Wi-Fi networks you want to connect to


  Serial.println("Connecting");
  while (WiFi.status() != WL_CONNECTED) {  // Wait for the Wi-Fi to connect
    delay(250);
    Serial.print('.');
  }
  Serial.println("\r\n");
  Serial.print("Connected to ");
  Serial.println(WiFi.SSID());             // Tell us what network we're connected to
  Serial.print("IP address:\t");
  Serial.print(WiFi.localIP());            // Send the IP address of the ESP8266 to the computer
  Serial.println("\r\n");
}

void startUDP() {
  Serial.println("Starting UDP");
  UDP.begin(123);                          // Start listening for UDP messages to port 123
  Serial.print("Local port:\t");
  Serial.println(UDP.localPort());
}



void startSPIFFS() { // Start the SPIFFS and list all contents
  SPIFFS.begin();                             // Start the SPI Flash File System (SPIFFS)
  Serial.println("SPIFFS started. Contents:");
  {
    Dir dir = SPIFFS.openDir("/");
    while (dir.next()) {                      // List the file system contents
      String fileName = dir.fileName();
      size_t fileSize = dir.fileSize();
      Serial.printf("\tFS File: %s, size: %s\r\n", fileName.c_str(), formatBytes(fileSize).c_str());
    }
    Serial.printf("\n");
  }
}



void startServer() { // Start a HTTP server with a file read handler and an upload handler
  server.on("/index.html",  HTTP_POST, []() {  // If a POST request is sent to the /edit.html address,
    server.send(200, "text/plain", "");
  });                       

  server.onNotFound(handleNotFound);          // if someone requests any other file or page, go to function 'handleNotFound'
  // and check if the file exists

  server.begin();                             // start the HTTP server
  Serial.println("HTTP server started.");
}

/*__________________________________________________________SERVER_HANDLERS__________________________________________________________*/

void handleNotFound() { // if the requested file or page doesn't exist, return a 404 not found error
  if (!handleFileRead(server.uri())) {        // check if the file exists in the flash memory (SPIFFS), if so, send it
    server.send(404, "text/plain", "404: File Not Found");
  }
}

bool handleFileRead(String path) { // send the right file to the client (if it exists)
  Serial.println("handleFileRead: " + path);
  if (path.endsWith("/")) path += "index.html";          // If a folder is requested, send the index file
  String contentType = getContentType(path);             // Get the MIME type
  String pathWithGz = path + ".gz";
  if (SPIFFS.exists(pathWithGz) || SPIFFS.exists(path)) { // If the file exists, either as a compressed archive, or normal
    if (SPIFFS.exists(pathWithGz))                         // If there's a compressed version available
      path += ".gz";                                         // Use the compressed verion
    File file = SPIFFS.open(path, "r");                    // Open the file
    size_t sent = server.streamFile(file, contentType);    // Send it to the client
    file.close();                                          // Close the file again
    Serial.println(String("\tSent file: ") + path);
    return true;
  }
  Serial.println(String("\tFile Not Found: ") + path);   // If the file doesn't exist, return false
  return false;
}


/*__________________________________________________________HELPER_FUNCTIONS__________________________________________________________*/

String formatBytes(size_t bytes) { // convert sizes in bytes to KB and MB
  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";
  }
}

String getContentType(String filename) { // determine the filetype of a given filename, based on the extension
  if (filename.endsWith(".html")) return "text/html";
  else if (filename.endsWith(".css")) return "text/css";
  else if (filename.endsWith(".js")) return "application/javascript";
  else if (filename.endsWith(".ico")) return "image/x-icon";
  else if (filename.endsWith(".gz")) return "application/x-gzip";
  return "text/plain";
}

unsigned long getTime() { // Check if the time server has responded, if so, get the UNIX time, otherwise, return 0
  if (UDP.parsePacket() == 0) { // If there's no response (yet)
    return 0;
  }
  UDP.read(packetBuffer, NTP_PACKET_SIZE); // read the packet into the buffer
  // Combine the 4 timestamp bytes into one 32-bit number
  uint32_t NTPTime = (packetBuffer[40] << 24) | (packetBuffer[41] << 16) | (packetBuffer[42] << 8) | packetBuffer[43];
  // Convert NTP time to a UNIX timestamp:
  // Unix time starts on Jan 1 1970. That's 2208988800 seconds in NTP time:
  const uint32_t seventyYears = 2208988800UL;
  // subtract seventy years:
  uint32_t UNIXTime = NTPTime - seventyYears;
  return UNIXTime;
}


void sendNTPpacket(IPAddress& address) {
  Serial.println("Sending NTP request");
  memset(packetBuffer, 0, NTP_PACKET_SIZE);  // set all bytes in the buffer to 0
  // Initialize values needed to form NTP request
  packetBuffer[0] = 0b11100011;   // LI, Version, Mode

  // send a packet requesting a timestamp:
  UDP.beginPacket(address, 123); // NTP requests are to port 123
  UDP.write(packetBuffer, NTP_PACKET_SIZE);
  UDP.endPacket();
}

Re: ESP8266 ukladanie do SPIFFS obcas blbne

Napsal: 13 dub 2022, 21:21
od jankop
Zkusil jsem si to. Vypadá to docela dobře
http.png
Použil jsem
Arduino IDE 1.8.19
ESP8266 core 3.0.2
IDE.png
A přílohou je program, upravený na LittleFS

Re: ESP8266 ukladanie do SPIFFS obcas blbne

Napsal: 14 dub 2022, 18:22
od Sperhak
Skúšal som to asi 4 hodiny a vyzerá to že už to funguje. Porovnal som si tie súbory a jediné čo si spravil je, že si zmenil knižnicu, by ma nenapadlo že to bude také jednoduché. Vďaka. Budem teda vedieť do budúcna že mám používať LittleFS.h