IDFApp.py 9.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259
  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. if self.IDF_DOWNLOAD_CONFIG_FILE not in os.listdir(self.binary_path):
  33. if self.IDF_FLASH_ARGS_FILE not in os.listdir(self.binary_path):
  34. msg = ("Neither {} nor {} exists. "
  35. "Try to run 'make print_flash_cmd | tail -n 1 > {}/{}' "
  36. "or 'idf.py build' "
  37. "for resolving the issue."
  38. "").format(self.IDF_DOWNLOAD_CONFIG_FILE, self.IDF_FLASH_ARGS_FILE,
  39. self.binary_path, self.IDF_DOWNLOAD_CONFIG_FILE)
  40. raise AssertionError(msg)
  41. self.flash_files, self.flash_settings = self._parse_flash_download_config()
  42. self.partition_table = self._parse_partition_table()
  43. @classmethod
  44. def get_sdk_path(cls):
  45. idf_path = os.getenv("IDF_PATH")
  46. assert idf_path
  47. assert os.path.exists(idf_path)
  48. return idf_path
  49. def _get_sdkconfig_paths(self):
  50. """
  51. returns list of possible paths where sdkconfig could be found
  52. Note: could be overwritten by a derived class to provide other locations or order
  53. """
  54. return [os.path.join(self.binary_path, "sdkconfig"), os.path.join(self.binary_path, "..", "sdkconfig")]
  55. def get_sdkconfig(self):
  56. """
  57. reads sdkconfig and returns a dictionary with all configuredvariables
  58. :param sdkconfig_file: location of sdkconfig
  59. :raise: AssertionError: if sdkconfig file does not exist in defined paths
  60. """
  61. d = {}
  62. sdkconfig_file = None
  63. for i in self._get_sdkconfig_paths():
  64. if os.path.exists(i):
  65. sdkconfig_file = i
  66. break
  67. assert sdkconfig_file is not None
  68. with open(sdkconfig_file) as f:
  69. for line in f:
  70. configs = line.split('=')
  71. if len(configs) == 2:
  72. d[configs[0]] = configs[1].rstrip()
  73. return d
  74. def get_binary_path(self, app_path):
  75. """
  76. get binary path according to input app_path.
  77. subclass must overwrite this method.
  78. :param app_path: path of application
  79. :return: abs app binary path
  80. """
  81. pass
  82. @staticmethod
  83. def _get_elf_file_path(binary_path):
  84. ret = ""
  85. file_names = os.listdir(binary_path)
  86. for fn in file_names:
  87. if os.path.splitext(fn)[1] == ".elf":
  88. ret = os.path.join(binary_path, fn)
  89. return ret
  90. def _parse_flash_download_config(self):
  91. """
  92. Parse flash download config from build metadata files
  93. Sets self.flash_files, self.flash_settings
  94. (Called from constructor)
  95. Returns (flash_files, flash_settings)
  96. """
  97. if self.IDF_FLASH_ARGS_FILE in os.listdir(self.binary_path):
  98. # CMake version using build metadata file
  99. with open(os.path.join(self.binary_path, self.IDF_FLASH_ARGS_FILE), "r") as f:
  100. args = json.load(f)
  101. flash_files = [(offs,file) for (offs,file) in args["flash_files"].items() if offs != ""]
  102. flash_settings = args["flash_settings"]
  103. else:
  104. # GNU Make version uses download.config arguments file
  105. with open(os.path.join(self.binary_path, self.IDF_DOWNLOAD_CONFIG_FILE), "r") as f:
  106. args = f.readlines()[-1].split(" ")
  107. flash_files = []
  108. flash_settings = {}
  109. for idx in range(0, len(args), 2): # process arguments in pairs
  110. if args[idx].startswith("--"):
  111. # strip the -- from the command line argument
  112. flash_settings[args[idx][2:]] = args[idx + 1]
  113. else:
  114. # offs, filename
  115. flash_files.append((args[idx], args[idx + 1]))
  116. # The build metadata file does not currently have details, which files should be encrypted and which not.
  117. # Assume that all files should be encrypted if flash encryption is enabled in development mode.
  118. sdkconfig_dict = self.get_sdkconfig()
  119. flash_settings["encrypt"] = "CONFIG_SECURE_FLASH_ENCRYPTION_MODE_DEVELOPMENT" in sdkconfig_dict
  120. # make file offsets into integers, make paths absolute
  121. flash_files = [(int(offs, 0), os.path.join(self.binary_path, path.strip())) for (offs, path) in flash_files]
  122. return (flash_files, flash_settings)
  123. def _parse_partition_table(self):
  124. """
  125. Parse partition table contents based on app binaries
  126. Returns partition_table data
  127. (Called from constructor)
  128. """
  129. partition_tool = os.path.join(self.idf_path,
  130. "components",
  131. "partition_table",
  132. "gen_esp32part.py")
  133. assert os.path.exists(partition_tool)
  134. for (_, path) in self.flash_files:
  135. if "partition" in path:
  136. partition_file = os.path.join(self.binary_path, path)
  137. break
  138. else:
  139. raise ValueError("No partition table found for IDF binary path: {}".format(self.binary_path))
  140. process = subprocess.Popen(["python", partition_tool, partition_file],
  141. stdout=subprocess.PIPE, stderr=subprocess.PIPE)
  142. raw_data = process.stdout.read()
  143. if isinstance(raw_data, bytes):
  144. raw_data = raw_data.decode()
  145. partition_table = dict()
  146. for line in raw_data.splitlines():
  147. if line[0] != "#":
  148. try:
  149. _name, _type, _subtype, _offset, _size, _flags = line.split(",")
  150. if _size[-1] == "K":
  151. _size = int(_size[:-1]) * 1024
  152. elif _size[-1] == "M":
  153. _size = int(_size[:-1]) * 1024 * 1024
  154. else:
  155. _size = int(_size)
  156. except ValueError:
  157. continue
  158. partition_table[_name] = {
  159. "type": _type,
  160. "subtype": _subtype,
  161. "offset": _offset,
  162. "size": _size,
  163. "flags": _flags
  164. }
  165. return partition_table
  166. class Example(IDFApp):
  167. def _get_sdkconfig_paths(self):
  168. """
  169. overrides the parent method to provide exact path of sdkconfig for example tests
  170. """
  171. return [os.path.join(self.binary_path, "..", "sdkconfig")]
  172. def get_binary_path(self, app_path):
  173. # build folder of example path
  174. path = os.path.join(self.idf_path, app_path, "build")
  175. if not os.path.exists(path):
  176. # search for CI build folders
  177. app = os.path.basename(app_path)
  178. example_path = os.path.join(self.idf_path, "build_examples", "example_builds")
  179. for dirpath, dirnames, files in os.walk(example_path):
  180. if dirnames:
  181. if dirnames[0] == app:
  182. path = os.path.join(example_path, dirpath, dirnames[0], "build")
  183. break
  184. else:
  185. raise OSError("Failed to find example binary")
  186. return path
  187. class UT(IDFApp):
  188. def get_binary_path(self, app_path):
  189. """
  190. :param app_path: app path or app config
  191. :return: binary path
  192. """
  193. if not app_path:
  194. app_path = "default"
  195. path = os.path.join(self.idf_path, app_path)
  196. if not os.path.exists(path):
  197. while True:
  198. # try to get by config
  199. if app_path == "default":
  200. # it's default config, we first try to get form build folder of unit-test-app
  201. path = os.path.join(self.idf_path, "tools", "unit-test-app", "build")
  202. if os.path.exists(path):
  203. # found, use bin in build path
  204. break
  205. # ``make ut-build-all-configs`` or ``make ut-build-CONFIG`` will copy binary to output folder
  206. path = os.path.join(self.idf_path, "tools", "unit-test-app", "output", app_path)
  207. if os.path.exists(path):
  208. break
  209. raise OSError("Failed to get unit-test-app binary path")
  210. return path
  211. class SSC(IDFApp):
  212. def get_binary_path(self, app_path):
  213. # TODO: to implement SSC get binary path
  214. return app_path
  215. class AT(IDFApp):
  216. def get_binary_path(self, app_path):
  217. # TODO: to implement AT get binary path
  218. return app_path