ESP8266 OTA not Uploading at all

Good day to all in this forum,
I am capable of loading my sketches OTA using the examples on the esp32 But I do have exit 1 error when I try to load the ESP8266 using the equivalent technique. I did try all the suggestion found on the net but no succes at all.. Any help please or any sample code for me ? Thanks, regards

You will have to be more specific about the error message.

In my experience, when using IDE 1.8.19 all works the same, but in IDE 2 the esp8266 ports don't show up. (they may have fixed that by now, i don't keep track and find that IDE 2 is no real improvement)

Again some more specifics please.

One of the things that gets missed quite often is that after a wired upload, the esp8266 requires a 'hard-reset' with non of the boot-strap pins pulled LOW before it will accept an OTA upload.

thanks Deva,
I did try IDE1.8.x and IDE 2.3.2 and I got the same message:
Lo sketch usa 313676 byte (32%) dello spazio disponibile per i programmi. Il massimo è 958448 byte.
Le variabili globali usano 28808 byte (35%) di memoria dinamica, lasciando altri 53112 byte liberi per le variabili locali. Il massimo è 81920 byte.
Uploading.........................................................................................................................................................................
17:04:43 [ERROR]: Error Uploading
Caricamento non riuscito: errore durante il caricamento: exit status 1
I did try an Hard reset ( by pressing the button) and a power _on reset too: no success.
The network port IP is shown correctly on the right bottom of the IDE's.
The strange thing is that everything is working when loading the esp32 using the same procedure ( I did change the includes only since there is a difference between esp32 and 8266). Thanks again for your prompt reply. Regards.

Okay, what are the board settings you have for the ESP8266 board you have (and what board) ?

That is strange, because on IDE 2.3.2 i only have the ESP32 IP addresses showing up.

Yes i also have differences there. I tend to use some compiler directives to deal with this.
Anyway, just post the esp8266 code.

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

#include <ArduinoOTA.h>

const char* ssid = "RIT";
const char* password = "1950@";

//variabls for blinking an LED with Millis
const int led = 2; // ESP8266 Pin to which onboard LED is connected
unsigned long previousMillis = 0; // will store last time LED was updated
const long interval = 100; // interval at which to blink (milliseconds)
int ledState = LOW; // ledState used to set the LED

void setup() {
pinMode(led, OUTPUT);

Serial.begin(115200);
delay(500);
Serial.println("Booting");
WiFi.mode(WIFI_STA);
WiFi.begin(ssid, password);
while (WiFi.waitForConnectResult() != WL_CONNECTED) {
Serial.println("Connection Failed! Rebooting...");
delay(5000);
ESP.restart();
}
ArduinoOTA.begin();
Serial.println("Ready");
Serial.print("IP address: ");
Serial.println(WiFi.localIP());

}

void loop() {
// ArduinoOTA.handle();

//loop to blink without delay
unsigned long currentMillis = millis();
if (currentMillis - previousMillis >= interval) {
// save the last time you blinked the LED
previousMillis = currentMillis;
// if the LED is off turn it on and vice-versa:
ledState = not(ledState);
// set the LED with the ledState of the variable:
digitalWrite(led, ledState);
}

}

You do need to un-comment that.

I use the following code for both boards

#if defined(ARDUINO_ARCH_ESP32)
  #include <WiFi.h>
  #include <ESPmDNS.h>
  #include <WebServer.h>
  #include "FS.h"
  #include "SPIFFS.h"
  #include <WiFiUdp.h>
#else
  #include <ESP8266WiFi.h>
  #include <WiFiClient.h>
  #include <ESP8266WebServer.h>
  #include <ESP8266mDNS.h>
  #include <FS.h>
  #include <WiFiUdp.h>
#endif

#include <PatchDNSServer.h>
#include <ArduinoOTA.h>
#include <StreamString.h>


#if defined(ARDUINO_ARCH_ESP32)
  WebServer server(80);
#else
  ESP8266WebServer server(80);
#endif

const char *ssid  = "XXX";
const char *password = "xxxxxxxx";
const char *apname = "esp8266";
const char *appass = "password"; // minimum length 8 characters
const char *accessIP  = "http://192.168.4.1";

#if defined(ARDUINO_ARCH_ESP32)
  const int ledpin = 12;
#else
  const int ledpin = 2;  // I'm running this on an ESP-01
  // i have a led connected to this active LOW
  // i can't use the internal (pin 1) for the use of Serial
#endif

uint8_t ledstatus = 3; // this is keeping track of the state (of our statemachine)

bool spiffsmounted = false;

const char* update_path = "/firmware";

static const char pageheader[] PROGMEM = "<!DOCTYPE html PUBLIC \"-//W3C//DTD XHTML 1.0 Transitional//EN\"\"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd\">";
static const char htmlhead[] PROGMEM  = "<html><head><title>AP OTA Update Example</title><meta http-equiv=\"Content-Type\" content=\"text/html;charset=utf-8\" ></head>";
static const char bodystyle[] PROGMEM  = "<body style=\"color: dimgray; background-color: palegoldenrod; font-size: 12pt; font-family: sans-serif;\">";
static const char htmlclose[] PROGMEM  = "</body></html>";

String webIP;

void setup() {
  webIP.reserve(30);  // prevent fragments
  pinMode(ledpin, OUTPUT);
  digitalWrite(ledpin, LOW);
  Serial.begin(115200);

  WiFi.softAP(apname, appass); // start AP mode
  webIP = accessIP;
  Serial.print("Started Access Point \"");
  Serial.print(apname);
  Serial.println("\"");
  Serial.print("With password \"");
  Serial.print(appass);
  Serial.println("\"");
  WiFi.begin(ssid, password);  // attempt starting STA mode
  Serial.println("Attempting to start Station mode");

  uint32_t moment = millis();
  while ((WiFi.status() != WL_CONNECTED) && (millis() < moment + 8000)) {
    delay(500);
    Serial.print(".");
  }
  Serial.println("");
  if (WiFi.status() == WL_CONNECTED) {
    Serial.print("Connected to ");
    Serial.println(ssid);
    Serial.print("IP address: ");
    Serial.println(WiFi.localIP());

    if (MDNS.begin("esp8266")) {  // type esp8266.local/ in your browser
      Serial.println("MDNS responder started, type esp8266.local/ in your browser");
    }
    webIP = StationIP();
  }
  else if (WiFi.status() == WL_CONNECT_FAILED) {
    Serial.print("Connecting to ");
    Serial.print(ssid);
    Serial.println(" Unsuccessful.");
  }
  else if (WiFi.status() == WL_NO_SSID_AVAIL) {
    Serial.print("Network ");
    Serial.print(ssid);
    Serial.println(" not available.");
  }
  WiFi.reconnect();   // reconnect AP after attempting to connect STA


  OTAUpdateSetup();
  spiffsmounted = SPIFFS.begin();
  server.on("/", handleRoot);
  server.on(update_path, HTTP_GET, handleUpdate);
  server.on(update_path, HTTP_POST, handlePostUpdate, handleFileUpload);

  server.begin();
}

void loop() {
  ArduinoOTA.handle();
  yield();
  server.handleClient();
  yield();
  checkLedStatus();
}

void checkLedStatus() {  // our statemachine
  switch (ledstatus) {
    case 0: {
        digitalWrite(ledpin, HIGH);
        return;
      }
    case 1: {
        digitalWrite(ledpin, LOW);
        return;
      }
    case 2: {
        if (ledBlink(500)) ; // here the return value (of ledBlink() ) gets discarded
        return;
      }
    case 3: {
        modulateLed();
        return;
      }
  }
}

void modulateLed() {
  static uint16_t ms = 100;
  static bool increase = true;

  if (!ledBlink(ms)) return;
  if (ms > 250) increase = false;
  if (ms < 20) increase = true;
  if (increase) ms = (ms * 10) / 9;
  else ms = (ms * 9) / 10;
}

bool ledBlink(uint32_t wait) {
  static bool pinstate = false;
  static uint32_t moment = millis();
  if (millis() > moment + wait) {
    pinstate = !pinstate;
    moment = millis();
    if (pinstate) digitalWrite(ledpin, LOW);
    else digitalWrite(ledpin, HIGH);
    return pinstate;  // if pinstate is true and the pinstate has changed, the modulator will change speed
  }
  return false;
}

void handleRoot() {
  String ledstatusupdate;
  if (server.hasArg("led")) {
    if (server.arg("led") == "off") {
      ledstatus = 0;
      ledstatusupdate = "The LED has been turned Off<br>";
    }
    else if (server.arg("led") == "on") {
      ledstatus = 1;
      ledstatusupdate = "The LED has been turned On<br>";
    }
    else if (server.arg("led") == "blink") {
      ledstatus = 2;
      ledstatusupdate = "The LED has been set to Blink<br>";
    }
    else if (server.arg("led") == "modulate") {
      ledstatus = 3;
      ledstatusupdate = "The LED has been set to Modulate<br>";
    }
  }

  String s = "";
  s += FPSTR(pageheader);
  s += FPSTR(htmlhead);
  s += FPSTR(bodystyle);

  s += "<h1>Welcome to ESP webserver</h1><p>From here you can control your LED making it blink or just turn on or off. ";
  s += "</p>";

  s += ledstatusupdate;
  s += "<br>";

  s += "<form action='";
  s += webIP;
  s += "' method='get' name='button'>";
  s += "<input type='hidden' name='led' value='on'>"; // the hidden parameter gets included
  s += "<input type='submit' value=' LED ON '></form><br>"; // the button simply submits the form

  s += "<form action='";
  s += webIP;
  s += "' method='get' name='button'>";
  s += "<input type='hidden' name='led' value='off'>";
  s += "<input type='submit' value=' LED OFF'></form><br>";

  s += "<form action='";
  s += webIP;
  s += "' method='get' name='button'>";
  s += "<input type='hidden' name='led' value='blink'>";
  s += "<input type='submit' value='  BLINK  '></form><br>";

  s += "<form action='";
  s += webIP;
  s += "' method='get' name='button'>";
  s += "<input type='hidden' name='led' value='modulate'>";
  s += "<input type='submit' value='MODULATE'></form><br>";

  s += "<form action='";
  s += webIP;
  s += "/firmware' method='get' name='firmware'>";
  s += "<input type='submit' value='FIRMWARE'></form><br>";

  s += FPSTR(htmlclose);
  yield();  // not stricktly neccesary, though the String class can be slow
  server.send(200, "text/html", s); //Send web page
}




String StationIP() {
  String stationIP = "http://";
  stationIP += WiFi.localIP().toString();
  return stationIP;
}

void handleUpdate() {
  String s = "";
  s += FPSTR(pageheader);
  s += FPSTR(htmlhead);
  s += FPSTR(bodystyle);
  s += "<h1>OTA Firmware Update</h1>";

  s += "<pre><form method='post' action='' enctype='multipart/form-data'>";
  s += "<input type='file' name='update'>";
  s += "           <input type='submit' value='  Update  '></form></pre>";
  s += FPSTR(htmlclose);
  server.send(200, "text/html", s);
}


void handlePostUpdate() {

  if (Update.hasError()) {
    StreamString str;
    Update.printError(str);
    str;
    String s = "";
    s += FPSTR(pageheader);
    s += FPSTR(htmlhead);
    s += FPSTR(bodystyle);
    s += "<h1>Update Error </h1>";
    s += str;
    s += FPSTR(htmlclose);
    server.send(200, "text / html", s);
  }
  else {
    String s = "";
    s += FPSTR(pageheader);
    s += FPSTR(htmlhead);
    s += FPSTR(bodystyle);
    s += "<META http-equiv='refresh' content='20;URL=/'>Update Success ! Rebooting...\n";
    s += FPSTR(htmlclose);
    server.client().setNoDelay(true);
    server.send(200, "text / html", s);
    delay(100);
    server.client().stop();
    ESP.restart();
  }
}

void handleFileUpload() {

  HTTPUpload& upload = server.upload();
  String updateerror = "";
  if (upload.status == UPLOAD_FILE_START) {
#if defined(ARDUINO_ARCH_ESP32)

#else
    WiFiUDP::stopAll();
#endif


    uint32_t maxSketchSpace = (ESP.getFreeSketchSpace() - 0x1000) & 0xFFFFF000;
    if (!Update.begin(maxSketchSpace)) { //start with max available size
      StreamString str;
      Update.printError(str);
      updateerror = str;
    }
  }
  else if (upload.status == UPLOAD_FILE_WRITE) {
    if (Update.write(upload.buf, upload.currentSize) != upload.currentSize) {
      StreamString str;
      Update.printError(str);
      updateerror = str;
    }
  }
  else if (upload.status == UPLOAD_FILE_END) {
    if (Update.end(true)) { //true to set the size to the current progress
      StreamString str;
      Update.printError(str);
      updateerror = str;
    }
    else if (upload.status == UPLOAD_FILE_ABORTED) {
      Update.end();
    }
    yield();
  }
}


void OTAUpdateSetup() {

  const char* hostName = "ThisAp";

  ArduinoOTA.setHostname(hostName);

  ArduinoOTA.onStart([]() {
    String type;

    if (ArduinoOTA.getCommand() == U_FLASH) {

    }
    else { // U_SPIFFS
      type = "filesystem";
      if (spiffsmounted) {
        SPIFFS.end();
        spiffsmounted = false;
      }
    }

    // NOTE: if updating SPIFFS this would be the place to unmount SPIFFS using SPIFFS.end()
    //  Serial.println("Start updating " + type);
  });
  ArduinoOTA.onEnd([]() {
    if (!spiffsmounted) spiffsmounted = SPIFFS.begin();
    delay(1000);
    // Serial.println("\nEnd");
  });
  ArduinoOTA.onProgress([](unsigned int progress, unsigned int total) {
    //  Serial.printf("Progress: % u % % \r", (progress / (total / 100)));
  });
  ArduinoOTA.onError([](ota_error_t error) {
    //Serial.printf("Error[ % u]: ", error);
    if (error == OTA_AUTH_ERROR) {
      //  Serial.println("Auth Failed");
    }
    else if (error == OTA_BEGIN_ERROR) {
      //Serial.println("Begin Failed");
    }
    else if (error == OTA_CONNECT_ERROR) {
      //Serial.println("Connect Failed");
    }
    else if (error == OTA_RECEIVE_ERROR) {
      //Serial.println("Receive Failed");
    } else if (error == OTA_END_ERROR) {
      //Serial.println("End Failed");
    }
  });
  ArduinoOTA.begin();
}

#if defined(ARDUINO_ARCH_ESP32)
uint32_t ChipId() {
  uint32_t chipid;
  for (int i = 0; i < 17; i = i + 8) {
    chipid |= ((ESP.getEfuseMac() >> (40 - i)) & 0xff) << i;
  }
  return chipid;
}
#endif

It is a bit more complex and also includes the http upload through a webserver

I am sorry: it was uncomment before .

my sketch works well if loaded using USB port !

But thereafter you need to give it a hard reset, and change the port to the IP-address it has been assigned.

Anyway i know my sketch works, be it only with IDE 1.8.19 using OTA

You did not answer my question regarding the board type and board settings. It is important since the amount of flash and the partition scheme define if OTA is available at all.

I am here again.
Of course I did change the port from COM_5 to xxx 192.168.1.27 an then I did a Reset.
The board is : Lolin ver 0.1 and the board info are: BN: unknown board, VID: 0x1A86, PID: 0x7523, SN: (null).

What board have you selected in the IDE ? what core are you using ?

can you show me a link to where you got the board from ?

One of the reasons i added the whole wenserver thing to my sketch is that in that way you can demonstrate to yourself that the wifi connection is actually working properly. Mind you, if the port shows up in the IDE, i guess it is working.

The selected board is relevant in regards to the amount of flash & partition scheme should match that.

I did select a "general esp8266" board.
I do not remember where I bought the board: it a long time ago.

1MB (FS:64K OTA:470KB) is selected

Dear Deva:
I am able to upload your program using the AP 192.168.4.1 very well
It is working well.
What is the reason for which my sketch does not load through network port 192.168.1.27 ?

Don't know really. It may have something to do with your network or even more likely router settings.
Clearly it works when connecting to the ESP as an Access Point, but not when connecting thru the network.
What OS are you using ? can you access the network settings ?

A generic 8266 ok.

is that the actual flash size ? 1MB.

Depending on the core you are using, you will find that it may end up being quite a tight fit for larger sketches if you want to maintain an FS. (i use core 2.4.2 on my ESP-01's particularly for that reason, but there are some things that are not supported like https and the SD library doesn't really work properly, but an ESP-01 doesn't have the SPI pins exposed so ithat doesn't matter much.

Thanks;
I am using windows_10.
Yes, I can access to my router.
I do not know the real size of the lolin 8266 but my sketch is small wrt your sketch that loads well.
I really suspect it could be a router setting: any suggestion please ?
regards

In that case i think the network & firewall settings are available and may be at fault. Make sure that your network is defined as 'private'

Thank to be so patient,
the network is set to private.....

for what reason it works well using esp32 ?

I also used an esp07 board but the same message....
Now i do not think it is a network problem since it is the same network used for the esp32 loading.... I am nearly giving_up !

Have you given permission for/to the esptool to breach the firewall ?

An esp07 is an esp8266 with the option of an external antenna. Anyway it's gotta be something like this. Anti-Virus software or firewall settings on w10

thanks,
I will try hard today.