IDFApp.py 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264
  1. # Copyright 2015-2017 Espressif Systems (Shanghai) PTE LTD
  2. #
  3. # Licensed under the Apache License, Version 2.0 (the "License");
  4. # you may not use this file except in compliance with the License.
  5. # You may obtain a copy of the License at
  6. #
  7. # http:#www.apache.org/licenses/LICENSE-2.0
  8. #
  9. # Unless required by applicable law or agreed to in writing, software
  10. # distributed under the License is distributed on an "AS IS" BASIS,
  11. # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  12. # See the License for the specific language governing permissions and
  13. # limitations under the License.
  14. """ IDF Test Applications """
  15. import subprocess
  16. import os
  17. import json
  18. import App
  19. class IDFApp(App.BaseApp):
  20. """
  21. Implements common esp-idf application behavior.
  22. idf applications should inherent from this class and overwrite method get_binary_path.
  23. """
  24. IDF_DOWNLOAD_CONFIG_FILE = "download.config"
  25. IDF_FLASH_ARGS_FILE = "flasher_args.json"
  26. def __init__(self, app_path):
  27. super(IDFApp, self).__init__(app_path)
  28. self.idf_path = self.get_sdk_path()
  29. self.binary_path = self.get_binary_path(app_path)
  30. self.elf_file = self._get_elf_file_path(self.binary_path)
  31. assert os.path.exists(self.binary_path)
  32. sdkconfig_dict = self.get_sdkconfig()
  33. if "CONFIG_APP_BUILD_GENERATE_BINARIES" in sdkconfig_dict:
  34. # There are no flashing targets available when no binaries where generated.
  35. if self.IDF_DOWNLOAD_CONFIG_FILE not in os.listdir(self.binary_path):
  36. if self.IDF_FLASH_ARGS_FILE not in os.listdir(self.binary_path):
  37. msg = ("Neither {} nor {} exists. "
  38. "Try to run 'make print_flash_cmd | tail -n 1 > {}/{}' "
  39. "or 'idf.py build' "
  40. "for resolving the issue."
  41. "").format(self.IDF_DOWNLOAD_CONFIG_FILE, self.IDF_FLASH_ARGS_FILE,
  42. self.binary_path, self.IDF_DOWNLOAD_CONFIG_FILE)
  43. raise AssertionError(msg)
  44. self.flash_files, self.flash_settings = self._parse_flash_download_config()
  45. self.partition_table = self._parse_partition_table()
  46. @classmethod
  47. def get_sdk_path(cls):
  48. idf_path = os.getenv("IDF_PATH")
  49. assert idf_path
  50. assert os.path.exists(idf_path)
  51. return idf_path
  52. def _get_sdkconfig_paths(self):
  53. """
  54. returns list of possible paths where sdkconfig could be found
  55. Note: could be overwritten by a derived class to provide other locations or order
  56. """
  57. return [os.path.join(self.binary_path, "sdkconfig"), os.path.join(self.binary_path, "..", "sdkconfig")]
  58. def get_sdkconfig(self):
  59. """
  60. reads sdkconfig and returns a dictionary with all configuredvariables
  61. :param sdkconfig_file: location of sdkconfig
  62. :raise: AssertionError: if sdkconfig file does not exist in defined paths
  63. """
  64. d = {}
  65. sdkconfig_file = None
  66. for i in self._get_sdkconfig_paths():
  67. if os.path.exists(i):
  68. sdkconfig_file = i
  69. break
  70. assert sdkconfig_file is not None
  71. with open(sdkconfig_file) as f:
  72. for line in f:
  73. configs = line.split('=')
  74. if len(configs) == 2:
  75. d[configs[0]] = configs[1].rstrip()
  76. return d
  77. def get_binary_path(self, app_path):
  78. """
  79. get binary path according to input app_path.
  80. subclass must overwrite this method.
  81. :param app_path: path of application
  82. :return: abs app binary path
  83. """
  84. pass
  85. @staticmethod
  86. def _get_elf_file_path(binary_path):
  87. ret = ""
  88. file_names = os.listdir(binary_path)
  89. for fn in file_names:
  90. if os.path.splitext(fn)[1] == ".elf":
  91. ret = os.path.join(binary_path, fn)
  92. return ret
  93. def _parse_flash_download_config(self):
  94. """
  95. Parse flash download config from build metadata files
  96. Sets self.flash_files, self.flash_settings
  97. (Called from constructor)
  98. Returns (flash_files, flash_settings)
  99. """
  100. if self.IDF_FLASH_ARGS_FILE in os.listdir(self.binary_path):
  101. # CMake version using build metadata file
  102. with open(os.path.join(self.binary_path, self.IDF_FLASH_ARGS_FILE), "r") as f:
  103. args = json.load(f)
  104. flash_files = [(offs,file) for (offs,file) in args["flash_files"].items() if offs != ""]
  105. flash_settings = args["flash_settings"]
  106. else:
  107. # GNU Make version uses download.config arguments file
  108. with open(os.path.join(self.binary_path, self.IDF_DOWNLOAD_CONFIG_FILE), "r") as f:
  109. args = f.readlines()[-1].split(" ")
  110. flash_files = []
  111. flash_settings = {}
  112. for idx in range(0, len(args), 2): # process arguments in pairs
  113. if args[idx].startswith("--"):
  114. # strip the -- from the command line argument
  115. flash_settings[args[idx][2:]] = args[idx + 1]
  116. else:
  117. # offs, filename
  118. flash_files.append((args[idx], args[idx + 1]))
  119. # The build metadata file does not currently have details, which files should be encrypted and which not.
  120. # Assume that all files should be encrypted if flash encryption is enabled in development mode.
  121. sdkconfig_dict = self.get_sdkconfig()
  122. flash_settings["encrypt"] = "CONFIG_SECURE_FLASH_ENCRYPTION_MODE_DEVELOPMENT" in sdkconfig_dict
  123. # make file offsets into integers, make paths absolute
  124. flash_files = [(int(offs, 0), os.path.join(self.binary_path, path.strip())) for (offs, path) in flash_files]
  125. return (flash_files, flash_settings)
  126. def _parse_partition_table(self):
  127. """
  128. Parse partition table contents based on app binaries
  129. Returns partition_table data
  130. (Called from constructor)
  131. """
  132. partition_tool = os.path.join(self.idf_path,
  133. "components",
  134. "partition_table",
  135. "gen_esp32part.py")
  136. assert os.path.exists(partition_tool)
  137. for (_, path) in self.flash_files:
  138. if "partition" in path:
  139. partition_file = os.path.join(self.binary_path, path)
  140. break
  141. else:
  142. raise ValueError("No partition table found for IDF binary path: {}".format(self.binary_path))
  143. process = subprocess.Popen(["python", partition_tool, partition_file],
  144. stdout=subprocess.PIPE, stderr=subprocess.PIPE)
  145. raw_data = process.stdout.read()
  146. if isinstance(raw_data, bytes):
  147. raw_data = raw_data.decode()
  148. partition_table = dict()
  149. for line in raw_data.splitlines():
  150. if line[0] != "#":
  151. try:
  152. _name, _type, _subtype, _offset, _size, _flags = line.split(",")
  153. if _size[-1] == "K":
  154. _size = int(_size[:-1]) * 1024
  155. elif _size[-1] == "M":
  156. _size = int(_size[:-1]) * 1024 * 1024
  157. else:
  158. _size = int(_size)
  159. except ValueError:
  160. continue
  161. partition_table[_name] = {
  162. "type": _type,
  163. "subtype": _subtype,
  164. "offset": _offset,
  165. "size": _size,
  166. "flags": _flags
  167. }
  168. return partition_table
  169. class Example(IDFApp):
  170. def _get_sdkconfig_paths(self):
  171. """
  172. overrides the parent method to provide exact path of sdkconfig for example tests
  173. """
  174. return [os.path.join(self.binary_path, "..", "sdkconfig")]
  175. def get_binary_path(self, app_path):
  176. # build folder of example path
  177. path = os.path.join(self.idf_path, app_path, "build")
  178. if not os.path.exists(path):
  179. # search for CI build folders
  180. app = os.path.basename(app_path)
  181. example_path = os.path.join(self.idf_path, "build_examples", "example_builds")
  182. # example_path has subdirectories named after targets. So we need to look into only the right
  183. # subdirectory. Currently, the target is not known at this moment.
  184. for dirpath, dirnames, files in os.walk(example_path):
  185. if dirnames:
  186. if dirnames[0] == app:
  187. path = os.path.join(example_path, dirpath, dirnames[0], "build")
  188. break
  189. else:
  190. raise OSError("Failed to find example binary")
  191. return path
  192. class UT(IDFApp):
  193. def get_binary_path(self, app_path):
  194. """
  195. :param app_path: app path or app config
  196. :return: binary path
  197. """
  198. if not app_path:
  199. app_path = "default"
  200. path = os.path.join(self.idf_path, app_path)
  201. if not os.path.exists(path):
  202. while True:
  203. # try to get by config
  204. if app_path == "default":
  205. # it's default config, we first try to get form build folder of unit-test-app
  206. path = os.path.join(self.idf_path, "tools", "unit-test-app", "build")
  207. if os.path.exists(path):
  208. # found, use bin in build path
  209. break
  210. # ``make ut-build-all-configs`` or ``make ut-build-CONFIG`` will copy binary to output folder
  211. path = os.path.join(self.idf_path, "tools", "unit-test-app", "output", app_path)
  212. if os.path.exists(path):
  213. break
  214. raise OSError("Failed to get unit-test-app binary path")
  215. return path
  216. class SSC(IDFApp):
  217. def get_binary_path(self, app_path):
  218. # TODO: to implement SSC get binary path
  219. return app_path
  220. class AT(IDFApp):
  221. def get_binary_path(self, app_path):
  222. # TODO: to implement AT get binary path
  223. return app_path