Tasmota/pio-tools/gzip-firmware.py

70 lines
2.3 KiB
Python
Raw Normal View History

2021-08-16 11:37:38 +01:00
Import("env")
2020-08-17 18:45:59 +01:00
import os
import shutil
2021-08-16 11:37:38 +01:00
import pathlib
import tasmotapiolib
2022-11-12 16:12:15 +00:00
import gzip
2021-08-06 19:34:14 +01:00
def map_gzip(source, target, env):
# create string with location and file names based on variant
2021-08-16 11:37:38 +01:00
map_file = tasmotapiolib.get_final_map_path(env)
2021-08-06 19:34:14 +01:00
2021-08-16 11:37:38 +01:00
if map_file.is_file():
gzip_file = map_file.with_suffix(".map.gz")
2021-08-06 19:34:14 +01:00
# check if new target map files exist and remove if necessary
2021-08-16 11:37:38 +01:00
if gzip_file.is_file():
gzip_file.unlink()
2021-08-06 19:34:14 +01:00
# write gzip map file
2021-08-16 11:37:38 +01:00
with map_file.open("rb") as fp:
with gzip.open(gzip_file, "wb", compresslevel=9) as f:
shutil.copyfileobj(fp, f)
# remove map file
2021-08-16 11:37:38 +01:00
if map_file.is_file():
map_file.unlink()
2021-08-06 19:34:14 +01:00
if not tasmotapiolib.is_env_set(tasmotapiolib.DISABLE_MAP_GZ, env):
env.AddPostAction("$BUILD_DIR/${PROGNAME}.bin", [map_gzip])
2021-08-06 19:34:14 +01:00
2021-01-18 18:21:51 +00:00
# gzip only for ESP8266
if env["PIOPLATFORM"] != "espressif32":
2022-11-13 15:46:26 +00:00
from zopfli.gzip import compress
2021-01-18 18:21:51 +00:00
def bin_gzip(source, target, env):
# create string with location and file names based on variant
2021-08-16 11:37:38 +01:00
bin_file = tasmotapiolib.get_final_bin_path(env)
gzip_file = bin_file.with_suffix(".bin.gz")
2020-11-12 12:26:14 +00:00
2021-01-18 18:21:51 +00:00
# check if new target files exist and remove if necessary
2021-08-16 11:37:38 +01:00
if os.path.isfile(gzip_file):
os.remove(gzip_file)
2020-08-17 18:45:59 +01:00
2021-01-18 18:21:51 +00:00
# write gzip firmware file
2021-08-16 11:37:38 +01:00
with open(bin_file, "rb") as fp:
2022-11-12 16:12:15 +00:00
with open(gzip_file, "wb") as f:
zopfli_gz = compress(fp.read())
f.write(zopfli_gz)
2021-01-18 18:21:51 +00:00
2021-08-16 11:37:38 +01:00
ORG_FIRMWARE_SIZE = bin_file.stat().st_size
GZ_FIRMWARE_SIZE = gzip_file.stat().st_size
2021-01-18 18:21:51 +00:00
2021-02-10 12:51:53 +00:00
if ORG_FIRMWARE_SIZE > 995326:
2021-08-16 11:37:38 +01:00
print(
"\u001b[31;1m!!! Tasmota firmware size is too big with {} bytes. Max size is 995326 bytes !!! \u001b[0m".format(
ORG_FIRMWARE_SIZE
)
)
2021-02-10 12:51:53 +00:00
else:
2021-08-16 11:37:38 +01:00
print(
"Compression reduced firmware size by {:.0f}% (was {} bytes, now {} bytes)".format(
(GZ_FIRMWARE_SIZE / ORG_FIRMWARE_SIZE) * 100,
ORG_FIRMWARE_SIZE,
GZ_FIRMWARE_SIZE,
)
)
2021-08-06 19:34:14 +01:00
if not tasmotapiolib.is_env_set(tasmotapiolib.DISABLE_BIN_GZ, env):
env.AddPostAction("$BUILD_DIR/${PROGNAME}.bin", [bin_gzip])