OTA Updates¶

Introduction¶

OTA (Over the Air) update is the procedure of uploading firmware to an ESP module using a Wi-Fi connexion rather than a serial port. Such functionality becomes extremely useful in instance of express or no physical access to the module.

OTA may be done using:

  • Arduino IDE

  • Web Browser

  • HTTP Server

The Arduino IDE pick is intended primarily for the software development phase. The other two options would be more than useful after deployment, to provide the module with application updates either manually with a web browser, or automatically using an HTTP server.

In any case, the offset firmware upload has to exist done over a series port. If the OTA routines are correctly implemented in the sketch, then all subsequent uploads may be washed over the air.

By default, there is no imposed security for the OTA process. Information technology is up to the developer to ensure that updates are allowed only from legitimate / trusted sources. In one case the update is complete, the module restarts, and the new lawmaking is executed. The programmer should ensure that the application running on the module is close down and restarted in a prophylactic manner. Chapters below provide additional information regarding security and safety of OTA updates.

Security Disclaimer¶

No guarantees as to the level of security provided for your application by the following methods is implied. Please refer to the GNU LGPL license associated for this projection for total disclaimers. If you do find security weaknesses, please don't hesitate to contact the maintainers or supply pull requests with fixes. The MD5 verification and password protection schemes are already known to supply a very weak level of security.

Basic Security¶

The module has to be exposed wirelessly to get it updated with a new sketch. That poses a risk of the module being violently hacked and programmed with another code. To reduce the likelihood of being hacked, consider protecting your uploads with a password, selecting certain OTA port, etc.

Bank check functionality provided with the ArduinoOTA library that may improve security:

                                        void                                                            setPort                    (                    uint16_t                                                            port                    );                                        void                                                            setHostname                    (                    const                                                            char                    *                                                            hostname                    );                                        void                                                            setPassword                    (                    const                                                            char                    *                                                            password                    );                                      

Sure bones protection is already congenital in and does non crave any additional coding past the developer. ArduinoOTA and espota.py utilize Digest-MD5 to authenticate uploads. Integrity of transferred data is verified on the ESP side using MD5 checksum.

Brand your ain risk assay and, depending on the application, decide what library functions to implement. If required, consider implementation of other means of protection from being hacked, like exposing modules for uploads only according to a specific schedule, triggering OTA only when the user presses a dedicated "Update" button wired to the ESP, etc.

Advanced Security - Signed Updates¶

While the above password-based security will dissuade casual hacking attempts, it is non highly secure. For applications where a higher level of security is needed, cryptographically signed OTA updates tin can exist required. This uses SHA256 hashing in place of MD5 (which is known to exist cryptographically broken) and RSA-2048 bit level public-key encryption to guarantee that but the holder of a cryptographic individual key can produce signed updates accepted by the OTA update mechanisms.

Signed updates are updates whose compiled binaries are signed with a individual key (held by the developer) and verified with a public primal (stored in the application and available for all to see). The signing procedure computes a hash of the binary lawmaking, encrypts the hash with the developer's private key, and appends this encrypted hash (also called a signature) to the binary that is uploaded (via OTA, web, or HTTP server). If the code is modified or replaced in any way past anyone except the holder of the developer'southward private key, the signature will not friction match and the ESP8266 will reject the upload.

Cryptographic signing only protects against tampering with binaries delivered via OTA. If someone has physical admission, they will always be able to flash the device over the serial port. Signing also does non encrypt anything but the hash (so that information technology tin't be modified), then this does not protect code inside the device: if a user has physical access they can read out your program.

Securing your private key is paramount. The same private/public primal pair that was used with the original upload must likewise be used to sign later binaries. Loss of the private primal associated with a binary ways that you volition non be able to OTA-update any of your devices in the field. Alternatively, if someone else copies the private key, then they volition be able to use it to sign binaries which will be accepted by the ESP.

Signed Binary Format¶

The format of a signed binary is uniform with the standard binary format, and can exist uploaded to a non-signed ESP8266 via serial or OTA without whatsoever conditions. Annotation, however, that once an unsigned OTA app is overwritten past this signed version, further updates will crave signing.

Every bit shown beneath, the signed hash is appended to the unsigned binary, followed by the total length of the signed hash (i.e., if the signed hash was 64 bytes, then this uint32 data segment will contain 64). This format allows for extensibility (such as adding a CA-based validation scheme allowing multiple signing keys all based on a trust ballast). Pull requests are always welcome. (currently it uses SHA256 with RSASSA-PKCS1-V1_5-SIGN signature scheme from RSA PKCS #1 v1.5)

                      NORMAL-BINARY <SIGNATURE> <uint32 LENGTH-OF-SIGNATURE>                    

Signed Binary Prerequisites¶

OpenSSL is required to run the standard signing steps, and should exist available on any UNIX-like or Windows system. As usual, the latest stable version of OpenSSL is recommended.

Signing requires the generation of an RSA-2048 key (other bit lengths are supported as well, but 2048 is a good selection today) using any appropriate tool. The following shell commands will generate a new public/private key pair. Run them in the sketch directory:

                      openssl genrsa -out private.key                      2048                      openssl rsa -in private.key -outform PEM -pubout -out public.key                    

Automatic Signing – Only bachelor on Linux and Mac¶

The simplest manner of implementing signing is to use the automated mode, which shortly is but possible on Linux and Mac due to some of the tools not beingness available for Windows. This mode uses the IDE to configure the source code to enable sigining verification with a given public key, and signs binaries as role of the standard build process using a given public key.

To enable this mode, only include private.key and public.primal in the sketch .ino directory. The IDE will call a helper script (tools/signing.py) before the build begins to create a header to enable key validation using the given public key, and to really do the signing after the build process, generating a sketch.bin.signed file. When OTA is enabled (ArduinoOTA, Web, or HTTP), the binary will automatically only accept signed updates.

When the signing process starts, the message:

will appear in the IDE window before a compile is launched. At the completion of the build, the signed binary file well exist displayed in the IDE build window as:

                      Signed binary: /full/path/to/sketch.bin.signed                    

If you receive either of the following messages in the IDE window, the signing was non completed and y'all will need to verify the public.primal and individual.key:

                      Not enabling binary signing ... or ... Not signing the generated binary                    

Manual Signing of Binaries¶

Users may besides manually sign executables and require the OTA process to verify their signature. In the main code, before enabling any update methods, add the post-obit declarations and function telephone call:

                                            <                      in                                                                  globals                      >                                            BearSSL                      ::                      PublicKey                                                                  signPubKey                      (                                                                  ...                                                                  primal                                                                  contents                                                                  ...                                                                  );                                            BearSSL                      ::                      HashSHA256                                                                  hash                      ;                                            BearSSL                      ::                      SigningVerifier                                                                  sign                      (                                                                  &                      signPubKey                                                                  );                                            ...                                            <                      in                                                                  setup                      ()                      >                                            Update                      .                      installSignature                      (                                                                  &                      hash                      ,                                                                  &                      sign                                                                  );                                          

The above snippet creates a BearSSL public key and a SHA256 hash verifier, and tells the Update object to utilise them to validate any updates it receives from whatever method.

Compile the sketch normally and, once a .bin file is available, sign information technology using the signer script:

                      <ESP8266ArduinoPath>/tools/signing.py --fashion sign --privatekey <path-to-private.key> --bin <path-to-unsigned-bin> --out <path-to-signed-binary>                    

Onetime And New Signature Formats¶

Up to version ii.v.two of the core, the format of signatures was a trivial different. An additional signed binary with the extension legacy_sig is created. This file contains a signature in the old format and tin be uploaded OTA to a device that checks for the old signature format.

To create a legacy signature, call the signing script with –legacy:

                      <ESP8266ArduinoPath>/tools/signing.py --style sign --privatekey <path-to-individual.primal> --bin <path-to-unsigned-bin> --out <path-to-signed-binary> --legacy <path-to-legacy-file>                    

Compression¶

The eboot bootloader incorporates a GZIP decompressor, built for very low code requirements. For applications, this optional decompression is completely transparent. For uploading compressed filesystems, the application must be built with ATOMIC_FS_UPDATE defined because, otherwise, eboot will not be involved in writing the filesystem.

No changes to the application are required. The Updater form and eboot bootloader (which performs actual application overwriting on update) automatically search for the gzip header in the uploaded binary, and if plant, handle it.

Compress an application .bin file or filesystem package using whatsoever gzip available, at whatever desired compression level (gzip -9 is recommended because information technology provides the maximum compression and uncompresses as fast as any other compressino level). For example:

                  gzip -ix sketch.bin                  # Maximum compression, output sketch.bin.gz                  <Upload the resultant sketch.bin.gz>                

If signing is desired, sign the gzip compressed file after pinch.

                  gzip -9 sketch.bin <ESP8266ArduinoPath>/tools/signing.py --fashion sign --privatekey <path-to-private.key> --bin sketch.bin.gz --out sketch.bin.gz.signed                

Updating apps in the field to support compression¶

If you lot take applications deployed in the field and wish to update them to support compressed OTA uploads, you will demand to first recompile the application, then _upload the uncompressed .bin file once. Attempting to upload a gzip compressed binary to a legacy app will result in the Updater rejecting the upload as it does not understand the gzip format. Subsequently this initial upload, which will include the new bootloader and Updater form with compression back up, compressed updates tin then be used.

Safety¶

The OTA process consumes some of the ESP's resources and bandwidth during upload. Then, the module is restarted and a new sketch executed. Analyse and test how this affects the functionality of the existing and new sketches.

If the ESP is in a remote location and controlling some equipment, y'all should devote additional attending to what happens if operation of this equipment is of a sudden interrupted by the update process. Therefore, decide how to put this equipment into a safe land earlier starting the update. For instance, your module may be decision-making a garden watering system in a sequence. If this sequence is not properly shut downwards and a water valve is left open, the garden may be flooded.

The following functions are provided with the ArduinoOTA library and intended to handle functionality of your awarding during specific stages of OTA, or on an OTA error:

                                        void                                                            onStart                    (                    OTA_CALLBACK                    (                    fn                    ));                                        void                                                            onEnd                    (                    OTA_CALLBACK                    (                    fn                    ));                                        void                                                            onProgress                    (                    OTA_CALLBACK_PROGRESS                    (                    fn                    ));                                        void                                                            onError                    (                    OTA_CALLBACK_ERROR                                                            (                    fn                    ));                                      

OTA Basic Requirements¶

The flash chip size should be large enough to hold the one-time sketch (currently running) and the new sketch (OTA) at the aforementioned fourth dimension.

Keep in mind that the file organisation and EEPROM, for example, need space as well; see Flash layout.

                                        ESP                    .                    getFreeSketchSpace                    ();                                      

can be used for checking the gratuitous infinite available for the new sketch.

For an overview of memory layout, where the new sketch is stored and how it is copied during the OTA process, see Update procedure - memory view.

The following chapters provide more details and specific methods for OTA updates.

Arduino IDE¶

Uploading modules wirelessly from Arduino IDE is intended for the post-obit typical scenarios:

  • during firmware development as a quicker alternative to loading over a serial port,

  • for updating a small number of modules,

  • simply if modules are accessible on the same network every bit the computer with the Arduino IDE.

Requirements¶

  • The ESP and the estimator must be connected to the same network.

Application Example¶

Instructions below testify configuration of OTA on a NodeMCU 1.0 (ESP-12E Module) board. You can use any other board that meets the requirements described above. This pedagogy is valid for all operating systems supported by the Arduino IDE. Screen captures have been made on Windows 7 and you may see small differences (like name of the serial port), if you are using Linux or MacOS.

  1. Before you lot begin, please make sure that you accept the following software installed:

    • Arduino IDE i.6.7 or newer - https://www.arduino.cc/en/Main/Software

    • esp8266/Arduino platform package ii.0.0 or newer - for instructions follow https://github.com/esp8266/Arduino#installing-with-boards-manager

  2. Now fix the sketch and configuration for upload via a serial port.

    • Start Arduino IDE and upload the sketch BasicOTA.ino, available under File > Examples > ArduinoOTA ota sketch selection

    • Update the SSID and password in the sketch, so that the module can join your Wi-Fi network ota ssid pass entry

    • Configure upload parameters every bit below (yous may need to conform configuration if you are using a unlike module): ota serial upload config

      Note: Depending on version of platform package and lath y'all have, you may see Upload Using: in the menu higher up. This pick is inactive and it does not matter what you select. Information technology has been left for compatibility with older implementation of OTA and finally removed in platform package version two.ii.0.

  3. Upload the sketch (Ctrl+U). In one case done, open Serial Monitor (Ctrl+Shift+Thousand) and bank check if module has joined your Wi-Fi network:

    Check if module joined network

Note: The ESP module should be reset later serial upload. Otherwise, subsequent steps will not work. Reset may be done for you automatically after opening series monitor, every bit visible on the screenshot in a higher place. It depends on how you have DTR and RTS wired from the USB-Series converter to the ESP. If reset is not washed automatically, then trigger it by pressing reset button or manually cycling the ability. For more details why this should exist done please refer to FAQ regarding ESP.restart() .

  1. Merely if the module is continued to network, after a couple of seconds, the esp8266-ota port volition show up in Arduino IDE. Select port with IP address shown in the Serial Monitor window in previous stride:

    Selection of OTA port

    Annotation: If the OTA port does not testify upwardly, exit Arduino IDE, open it again and cheque if the port is at that place. If it is non, check your firewall and router settings. The OTA port is advertised using mDNS service. To check if the port is visible by your PC, you tin can utilise an application like Bonjour Browser.

  2. Now get ready for your commencement OTA upload by selecting the OTA port:

    Configuration of OTA upload

    Note: The menu entry Upload Speed: does non matter at this point every bit it concerns the serial port. But left information technology unchanged.

  3. If yous have successfully completed all the above steps, y'all can upload (Ctrl+U) the aforementioned (or any other) sketch over OTA:

    OTA upload complete

Annotation: To exist able to upload your sketch over and again using OTA, you need to embed OTA routines inside. Please apply BasicOTA.ino every bit an instance.

Countersign Protection¶

Protecting your OTA uploads with password is really straightforward. All yous need to practice, is to include the post-obit statement in your lawmaking:

                                            ArduinoOTA                      .                      setPassword                      ((                      const                                                                  char                                                                  *                      )                      "123"                      );                                          

Where 123 is a sample password that you should supervene upon with your own.

Before implementing it in your sketch, it is a proficient thought to check how it works using BasicOTA.ino sketch bachelor under File > Examples > ArduinoOTA. Go ahead, open BasicOTA.ino, uncomment the higher up argument that is already at that place, and upload the sketch. To make troubleshooting easier, exercise not modify example sketch likewise what is absolutely required. This is including original uncomplicated 123 OTA password. So attempt to upload sketch again (using OTA). Afterwards compilation is complete, one time upload is about to brainstorm, you should meet prompt for password every bit follows:

Password prompt for OTA upload

Enter the countersign and upload should be initiated as usual with the only divergence being Authenticating...OK bulletin visible in upload log.

Authenticating...OK during OTA upload

You lot volition non be prompted for a reentering the aforementioned password next fourth dimension. Arduino IDE will think it for you. You volition come across prompt for password but later on reopening IDE, or if you lot modify it in your sketch, upload the sketch then attempt to upload it again.

Delight note, it is possible to reveal password entered previously in Arduino IDE, if IDE has non been closed since last upload. This can be done by enabling Show verbose output during: upload in File > Preferences and attempting to upload the module.

Verbose upload output with password passing in plain text

The picture above shows that the password is visible in log, as it is passed to espota.py upload script.

Another instance below shows situation when countersign is changed betwixt uploads.

Verbose output when OTA password has been changed between uploads

When uploading, Arduino IDE used previously entered password, so the upload failed and that has been clearly reported by IDE. But then IDE prompted for a new password. That was entered correctly and second attempt to upload has been successful.

Troubleshooting¶

If OTA update fails, first pace is to check for fault messages that may be shown in upload window of Arduino IDE. If this is not providing any useful hints, try to upload again while checking what is shown by ESP on serial port. Serial Monitor from IDE will not exist useful in that case. When attempting to open up information technology, you will likely see the following:

Arduino IDE network terminal window

This window is for Arduino Yún and non nevertheless implemented for esp8266/Arduino. It shows up because IDE is attempting to open up Serial Monitor using network port yous take selected for OTA upload.

Instead yous need an external series monitor. If y'all are a Windows user check out Termite. This is handy, slick and uncomplicated RS232 concluding that does not impose RTS or DTR flow command. Such menstruation control may cause issues if yous are using corresponding lines to toggle GPIO0 and RESET pins on ESP for upload.

Select COM port and baud rate on external terminal program every bit if y'all were using Arduino Serial Monitor. Please run across typical settings for Termite below:

Termite settings

Then run OTA from IDE and look what is displayed on terminal. Successful ArduinoOTA process using BasicOTA.ino sketch looks similar below (IP address depends on your network configuration):

OTA upload successful - output on an external serial terminal

If upload fails you lot will likely see errors caught past the uploader, exception and the stack trace, or both.

Instead of the log as on the above screen you may see the following:

OTA upload failed - output on an external serial terminal

If this is the instance, then almost likely ESP module has non been reset after initial upload using series port.

The about common causes of OTA failure are as follows:

  • non enough physical memory on the chip (e.1000. ESP01 with 512K flash retentivity is not enough for OTA).

  • too much memory alleged for the filesystem so new sketch will non fit between existing sketch and the filesystem – see Update process - retentivity view.

  • also piddling retentiveness declared in Arduino IDE for your selected board (i.east. less than physical size).

  • not resetting the ESP module subsequently initial upload using series port.

For more details regarding flash memory layout please cheque File organization. For overview where new sketch is stored, how it is copied and how memory is organized for the purpose of OTA run across Update process - memory view.

Web Browser¶

Updates described in this affiliate are done with a web browser that can be useful in the following typical scenarios:

  • afterward awarding deployment if loading directly from Arduino IDE is inconvenient or not possible,

  • later deployment if user is unable to expose module for OTA from external update server,

  • to provide updates after deployment to pocket-size quantity of modules when setting an update server is non practicable.

Requirements¶

  • The ESP and the computer must be connected to the same network.

Implementation Overview¶

Updates with a spider web browser are implemented using ESP8266HTTPUpdateServer class together with ESP8266WebServer and ESP8266mDNS classes. The following code is required to become it work:

setup()

                                        MDNS                    .                    begin                    (                    host                    );                                        httpUpdater                    .                    setup                    (                    &                    httpServer                    );                                        httpServer                    .                    begin                    ();                                        MDNS                    .                    addService                    (                    "http"                    ,                                                            "tcp"                    ,                                                            80                    );                                      

loop()

                                        httpServer                    .                    handleClient                    ();                                      

Application Example¶

The sample implementation provided below has been done using:

  • case sketch WebUpdater.ino available in ESP8266HTTPUpdateServer library,

  • NodeMCU ane.0 (ESP-12E Module).

You tin use another module if it meets previously described requirements.

  1. Before you begin, please make sure that you have the following software installed:

    • Arduino IDE and 2.0.0-rc1 (of Nov 17, 2015) version of platform package as described under https://github.com/esp8266/Arduino#installing-with-boards-manager

    • Host software depending on O/Due south y'all utilise:

      1. Avahi https://avahi.org/ for Linux

      2. Bonjour https://www.apple.com/support/bonjour/ for Windows

      3. Mac OSX and iOS - support is already built in / no any extra s/due west is required

  2. Prepare the sketch and configuration for initial upload with a serial port.

    • Offset Arduino IDE and load sketch WebUpdater.ino available under File > Examples > ESP8266HTTPUpdateServer.

    • Update SSID and password in the sketch, and so the module can join your Wi-Fi network.

    • Open File > Preferences, look for "Evidence verbose output during:" and cheque out "compilation" option.

      Preferences - enabling verbose output during compilation

      Annotation: This setting volition be required in step 5 below. You can uncheck this setting afterwards.

  3. Upload sketch (Ctrl+U). Once done, open Serial Monitor (Ctrl+Shift+M) and check if you lot see the following bulletin displayed, that contains url for OTA update.

    Serial Monitor - after first load using serial

    Note: Such bulletin will be shown only after module successfully joins network and is set up for an OTA upload. Please call back about resetting the module once subsequently serial upload as discussed in chapter Arduino IDE, pace iii.

  4. Now open web browser and enter the url provided on Serial Monitor, i.east. http://esp8266-webupdate.local/update . In one case entered, browser should brandish a course like beneath that has been served by your module. The form invites you to cull a file for update.

    OTA update form in web browser

    Note: If entering http://esp8266-webupdate.local/update does non work, endeavor replacing esp8266-webupdate with module'due south IP address. For example, if your module IP is 192.168.ane.100 and so url should be http://192.168.one.100/update . This workaround is useful in case the host software installed in step ane does not work. If even so nothing works and there are no clues on the Serial Monitor, endeavor to diagnose issue past opening provided url in Google Chrome, pressing F12 and checking contents of "Panel" and "Network" tabs. Chrome provides some avant-garde logging on these tabs.

  5. To obtain the file, navigate to directory used past Arduino IDE to shop results of compilation. Y'all can cheque the path to this file in compilation log shown in IDE debug window as marked beneath.

    Compilation complete - path to binary file

  6. Now press "Choose File" in spider web browser, become to directory identified in pace 5 above, find the file "WebUpdater.cpp.bin" and upload it. If upload is successful, you volition see "OK" on web browser like beneath.

    OTA update complete

    Module will reboot that should be visible on Serial Monitor:

    Serial Monitor - after OTA update

    Just after reboot you should run into exactly the same message HTTPUpdateServer ready! Open up http://esp8266-webupdate.local/update in your browser like in step three. This is because module has been loaded once more with the same code – first using serial port, and so using OTA.

Once you lot are comfortable with this process, go ahead and modify WebUpdater.ino sketch to print some additional messages, compile it, locate new binary file and upload information technology using spider web browser to see entered changes on a Series Monitor.

You can also add OTA routines to your own sketch following guidelines in Implementation Overview above. If this is done correctly, you lot should be e'er able to upload new sketch over the previous ane using a web browser.

In case OTA update fails dead later on entering modifications in your sketch, y'all can ever recover module by loading it over a serial port. So diagnose the issue with sketch using Serial Monitor. One time the issue is fixed try OTA over again.

HTTP Server¶

ESPhttpUpdate form can cheque for updates and download a binary file from HTTP spider web server. It is possible to download updates from every IP or domain address on the network or Cyberspace.

Notation that past default this form closes all other connections except the 1 used by the update, this is because the update method blocks. This means that if there'due south some other application receiving information and so TCP packets volition build up in the buffer leading to out of retentiveness errors causing the OTA update to neglect. There'southward also a express number of receive buffers bachelor and all may be used up past other applications.

In that location are some cases where you know that you won't be receiving whatsoever data merely would still similar to send progress updates. It'south possible to disable the default behaviour (and keep connections open) by calling closeConnectionsOnUpdate(false).

Arduino code¶

Simple updater¶

Unproblematic updater downloads the file every time the office is called.

                                            WiFiClient                                                                  client                      ;                                            ESPhttpUpdate                      .                      update                      (                      client                      ,                                                                  "192.168.0.ii"                      ,                                                                  80                      ,                                                                  "/arduino.bin"                      );                                          

Advanced updater¶

Its possible to signal the update role to a script on the server. If a version string argument is given, it will be sent to the server. The server side script can apply this cord to check whether an update should be performed.

The server-side script can respond as follows: - response lawmaking 200, and send the firmware image, - or response code 304 to notify ESP that no update is required.

                                            WiFiClient                                                                  client                      ;                                            t_httpUpdate_return                                                                  ret                                                                  =                                                                  ESPhttpUpdate                      .                      update                      (                      customer                      ,                                                                  "192.168.0.2"                      ,                                                                  80                      ,                                                                  "/esp/update/arduino.php"                      ,                                                                  "optional current version string here"                      );                                            switch                      (                      ret                      )                                                                  {                                                                                        case                                                                  HTTP_UPDATE_FAILED                      :                                                                                        Series                      .                      println                      (                      "[update] Update failed."                      );                                                                                        interruption                      ;                                                                                        example                                                                  HTTP_UPDATE_NO_UPDATES                      :                                                                                        Series                      .                      println                      (                      "[update] Update no Update."                      );                                                                                        interruption                      ;                                                                                        example                                                                  HTTP_UPDATE_OK                      :                                                                                        Serial                      .                      println                      (                      "[update] Update ok."                      );                                                                  // may not be called since nosotros reboot the ESP                                                                  suspension                      ;                                            }                                          

TLS updater¶

Please read and try the examples provided with the library.

Server request handling¶

Uncomplicated updater¶

For the elementary updater the server only needs to deliver the binary file for update.

Advanced updater¶

For advanced update direction a script (such as a PHP script) needs to run on the server side. On every update request, the ESP sends some information in HTTP headers to the server.

Example header information:

                                            [                      User                      -                      Agent                      ]                      =>                      ESP8266                      -                      http                      -                      Update                      [                      x                      -                      ESP8266                      -                      STA                      -                      MAC                      ]                      =>                      18                      :                      Atomic number 26                      :                      AA                      :                      AA                      :                      AA                      :                      AA                      [                      x                      -                      ESP8266                      -                      AP                      -                      MAC                      ]                      =>                      one                      A                      :                      FE                      :                      AA                      :                      AA                      :                      AA                      :                      AA                      [                      ten                      -                      ESP8266                      -                      free                      -                      space                      ]                      =>                      671744                      [                      10                      -                      ESP8266                      -                      sketch                      -                      size                      ]                      =>                      373940                      [                      x                      -                      ESP8266                      -                      sketch                      -                      md5                      ]                      =>                      a56f8ef78a0bebd812f62067daf1408a                      [                      x                      -                      ESP8266                      -                      chip                      -                      size                      ]                      =>                      4194304                      [                      x                      -                      ESP8266                      -                      sdk                      -                      version                      ]                      =>                      1.3.0                      [                      x                      -                      ESP8266                      -                      version                      ]                      =>                      DOOR                      -                      7                      -                      g14f53a19                      [                      x                      -                      ESP8266                      -                      manner                      ]                      =>                      sketch                    

With this data the script at present can check if an update is needed. It is as well possible to deliver different binaries based on the MAC accost, as in the following example:

                                            <?PHP                      header                      (                      'Content-type: text/obviously; charset=utf8'                      ,                      true                      );                      function                      check_header                      (                      $name                      ,                      $value                      =                      faux                      )                      {                      if                      (                      !                      isset                      (                      $_SERVER                      [                      $proper name                      ]))                      {                      return                      false                      ;                      }                      if                      (                      $value                      &&                      $_SERVER                      [                      $name                      ]                      !=                      $value                      )                      {                      render                      fake                      ;                      }                      return                      truthful                      ;                      }                      office                      sendFile                      (                      $path                      )                      {                      header                      (                      $_SERVER                      [                      "SERVER_PROTOCOL"                      ]                      .                      ' 200 OK'                      ,                      true                      ,                      200                      );                      header                      (                      'Content-Blazon: application/octet-stream'                      ,                      true                      );                      header                      (                      'Content-Disposition: attachment; filename='                      .                      basename                      (                      $path                      ));                      header                      (                      'Content-Length: '                      .                      filesize                      (                      $path                      ),                      true                      );                      header                      (                      'x-MD5: '                      .                      md5_file                      (                      $path                      ),                      true                      );                      readfile                      (                      $path                      );                      }                      if                      (                      !                      check_header                      (                      'User-Agent'                      ,                      'ESP8266-http-Update'                      ))                      {                      header                      (                      $_SERVER                      [                      "SERVER_PROTOCOL"                      ]                      .                      ' 403 Forbidden'                      ,                      true                      ,                      403                      );                      echo                      "only for ESP8266 updater!                      \north                      "                      ;                      get out                      ();                      }                      if                      (                      !                      check_header                      (                      '10-ESP8266-STA-MAC'                      )                      ||                      !                      check_header                      (                      'x-ESP8266-AP-MAC'                      )                      ||                      !                      check_header                      (                      'x-ESP8266-free-space'                      )                      ||                      !                      check_header                      (                      '10-ESP8266-sketch-size'                      )                      ||                      !                      check_header                      (                      'ten-ESP8266-sketch-md5'                      )                      ||                      !                      check_header                      (                      'ten-ESP8266-chip-size'                      )                      ||                      !                      check_header                      (                      '10-ESP8266-sdk-version'                      )                      )                      {                      header                      (                      $_SERVER                      [                      "SERVER_PROTOCOL"                      ]                      .                      ' 403 Forbidden'                      ,                      true                      ,                      403                      );                      echo                      "but for ESP8266 updater! (header)                      \n                      "                      ;                      leave                      ();                      }                      $db                      =                      assortment                      (                      "18:FE:AA:AA:AA:AA"                      =>                      "DOOR-seven-g14f53a19"                      ,                      "18:FE:AA:AA:AA:BB"                      =>                      "TEMP-1.0.0"                      );                      if                      (                      !                      isset                      (                      $db                      [                      $_SERVER                      [                      'x-ESP8266-STA-MAC'                      ]]))                      {                      header                      (                      $_SERVER                      [                      "SERVER_PROTOCOL"                      ]                      .                      ' 500 ESP MAC not configured for updates'                      ,                      truthful                      ,                      500                      );                      }                      $localBinary                      =                      "./bin/"                      .                      $db                      [                      $_SERVER                      [                      'x-ESP8266-STA-MAC'                      ]]                      .                      ".bin"                      ;                      // Bank check if version has been set and does not friction match, if not, bank check if                      // MD5 hash between local binary and ESP8266 binary do not match if not.                      // then no update has been establish.                      if                      ((                      !                      check_header                      (                      'x-ESP8266-sdk-version'                      )                      &&                      $db                      [                      $_SERVER                      [                      'x-ESP8266-STA-MAC'                      ]]                      !=                      $_SERVER                      [                      'x-ESP8266-version'                      ])                      ||                      $_SERVER                      [                      "x-ESP8266-sketch-md5"                      ]                      !=                      md5_file                      (                      $localBinary                      ))                      {                      sendFile                      (                      $localBinary                      );                      }                      else                      {                      header                      (                      $_SERVER                      [                      "SERVER_PROTOCOL"                      ]                      .                      ' 304 Non Modified'                      ,                      truthful                      ,                      304                      );                      }                      header                      (                      $_SERVER                      [                      "SERVER_PROTOCOL"                      ]                      .                      ' 500 no version for ESP MAC'                      ,                      truthful                      ,                      500                      );                    

Stream Interface¶

The Stream Interface is the base of operations for all other update modes like OTA, HTTP Server / client. Given a Stream-course variable streamVar providing byteCount bytes of firmware, it can store the firmware every bit follows:

                                    Update                  .                  begin                  (                  firmwareLengthInBytes                  );                                    Update                  .                  writeStream                  (                  streamVar                  );                                    Update                  .                  end                  ();                                  

Updater form¶

Updater is in the Core and deals with writing the firmware to the flash, checking its integrity and telling the bootloader (eboot) to load the new firmware on the next boot.

Annotation: The bootloader command will be stored into the beginning 128 bytes of user RTC memory, then it will exist retrieved by eboot on boot. That means that user data present at that place will be lost (per discussion in #5330).

Note: For uncompressed firmware images, the Updater will change the flash fashion $.25 if they differ from the flash mode the device is currently running at. This ensures that the flash fashion is not changed to an incompatible mode when the device is in a remote or hard to access surface area. Compressed images are non modified, thus changing the flash mode in this instance could event in damage to the ESP8266 and/or wink retention flake or your device no longer be accessible via OTA, and requiring re-flashing via a serial connection (per discussion in #7307).

Update procedure - memory view¶

  • The new sketch will be stored in the space between the old sketch and the spiff.

  • on the next reboot, the "eboot" bootloader checks for commands.

  • the new sketch is now copied "over" the former 1.

  • the new sketch is started.

By default, OTA filesystem updates overwrite the target flash directly. This tin can lead to the file organisation existence corrupted if there is a power outage during the update process. In order to utilize the same ii stride procedure that is used for OTA application firmware updates, fix the ATOMIC_FS_UPDATE flag. Notation that you volition need to accept enough unused space for the new filesystem prototype to be stored, hence is why this is not the default behaviour.

Memory layout for OTA updates