Skip to content

Instantly share code, notes, and snippets.

@pfeerick
Last active January 5, 2024 09:15
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save pfeerick/9607fba1bfae45726187ab53add40027 to your computer and use it in GitHub Desktop.
Save pfeerick/9607fba1bfae45726187ab53add40027 to your computer and use it in GitHub Desktop.
Extra script to make PlatformIO do compressed OTA updates for the ESP8266
import gzip
import shutil
import os
Import("env")
def compressFirmware(source, target, env):
""" Compress ESP8266 firmware using gzip for 'compressed OTA upload' """
SOURCE_FILE = env.subst("$BUILD_DIR") + os.sep + env.subst("$PROGNAME") + ".bin"
if not os.path.exists(SOURCE_FILE+'.bak'):
print("Compressing firmware for upload...")
shutil.move(SOURCE_FILE, SOURCE_FILE + '.bak')
with open(SOURCE_FILE + '.bak', 'rb') as f_in:
with gzip.open(SOURCE_FILE, 'wb') as f_out:
shutil.copyfileobj(f_in, f_out)
if os.path.exists(SOURCE_FILE+'.bak'):
ORG_FIRMWARE_SIZE = os.stat(SOURCE_FILE + '.bak').st_size
GZ_FIRMWARE_SIZE = os.stat(SOURCE_FILE).st_size
print("Compression reduced firmware size to {:.0f}% of original (was {} bytes, now {} bytes)".format((GZ_FIRMWARE_SIZE / ORG_FIRMWARE_SIZE) * 100, ORG_FIRMWARE_SIZE, GZ_FIRMWARE_SIZE))
env.AddPreAction("upload", compressFirmware)
@petter-b
Copy link

petter-b commented Jan 5, 2024

Thx for this script.

One suggested improvement:
SOURCE_FILE = source[0].get_abspath()

Then I prefer to use this as part of the build rather than upload. This is achieved by replacing last row with:
env.AddPostAction("buildprog", compressFirmware)

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment