zephyr/scripts/file2hex.py
Jukka Rissanen 0ff4c25958 build: Add rules in Makefile.gen to generate a hex file
This commit is useful if there is a need to generate a file
that can be included into the application at build time.
The file can also be compressed automatically when embedding it.

Files to be generated are listed in
     generate_inc_file
     generate_inc_gz_file
variables.

How to use this commit in your application:

1. Add this to your application Makefile

   SRC = $(ZEPHYR_BASE)/<your-app-dir>/src
   include $(ZEPHYR_BASE)/scripts/Makefile.gen

2. Add needed binary/other embedded files into src/Makefile
   to "generate_inc_file" or "generate_inc_gz_file" variables:

   # List of files that are used to generate a file that can be
   # included into .c file.
   generate_inc_file += \
           echo-apps-cert.der \
           echo-apps-key.der \
           file.bin

   generate_inc_gz_file += \
           index.html

   include $(ZEPHYR_BASE)/scripts/Makefile.gen

3. In the application, do something with the embedded file

   static const unsigned char inc_file[] = {
   #include "file.bin.inc"
   };

   static const unsigned char gz_inc_file[] = {
   #include "index.html.gz.inc"
   };

The generated files in ${SRC}/*.inc are automatically removed
when you do "make pristine"

Signed-off-by: Jukka Rissanen <jukka.rissanen@linux.intel.com>
2017-09-18 14:56:16 -04:00

50 lines
1.4 KiB
Python
Executable File

#!/usr/bin/env python3
#
# Copyright (c) 2017 Intel Corporation
#
# SPDX-License-Identifier: Apache-2.0
# This converts a file to a list of hex characters which can then
# be included to a source file.
# Optionally, the output can be compressed if needed.
import argparse
import codecs
import gzip
import io
def parse_args():
global args
parser = argparse.ArgumentParser(description = __doc__,
formatter_class = argparse.RawDescriptionHelpFormatter)
parser.add_argument("-f", "--file", required=True, help="Input file")
parser.add_argument("-g", "--gzip", action="store_true",
help="Compress the file using gzip before output")
args = parser.parse_args()
def get_nice_string(list_or_iterator):
return ", ".join( "0x" + str(x) for x in list_or_iterator)
def make_hex(chunk):
hexdata = codecs.encode(chunk, 'hex').decode("utf-8")
hexlist = map(''.join, zip(*[iter(hexdata)]*2))
print(get_nice_string(hexlist) + ',')
def main():
parse_args()
if args.gzip:
with open(args.file, 'rb') as fg:
content = io.BytesIO(gzip.compress(fg.read(), compresslevel=9))
for chunk in iter(lambda: content.read(8), b''):
make_hex(chunk)
else:
with open(args.file, "rb") as fp:
for chunk in iter(lambda: fp.read(8), b''):
make_hex(chunk)
if __name__ == "__main__":
main()