IDFApp.py 9.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254
  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. # make file offsets into integers, make paths absolute
  117. flash_files = [(int(offs, 0), os.path.join(self.binary_path, path.strip())) for (offs, path) in flash_files]
  118. return (flash_files, flash_settings)
  119. def _parse_partition_table(self):
  120. """
  121. Parse partition table contents based on app binaries
  122. Returns partition_table data
  123. (Called from constructor)
  124. """
  125. partition_tool = os.path.join(self.idf_path,
  126. "components",
  127. "partition_table",
  128. "gen_esp32part.py")
  129. assert os.path.exists(partition_tool)
  130. for (_, path) in self.flash_files:
  131. if "partition" in path:
  132. partition_file = os.path.join(self.binary_path, path)
  133. break
  134. else:
  135. raise ValueError("No partition table found for IDF binary path: {}".format(self.binary_path))
  136. process = subprocess.Popen(["python", partition_tool, partition_file],
  137. stdout=subprocess.PIPE, stderr=subprocess.PIPE)
  138. raw_data = process.stdout.read()
  139. if isinstance(raw_data, bytes):
  140. raw_data = raw_data.decode()
  141. partition_table = dict()
  142. for line in raw_data.splitlines():
  143. if line[0] != "#":
  144. try:
  145. _name, _type, _subtype, _offset, _size, _flags = line.split(",")
  146. if _size[-1] == "K":
  147. _size = int(_size[:-1]) * 1024
  148. elif _size[-1] == "M":
  149. _size = int(_size[:-1]) * 1024 * 1024
  150. else:
  151. _size = int(_size)
  152. except ValueError:
  153. continue
  154. partition_table[_name] = {
  155. "type": _type,
  156. "subtype": _subtype,
  157. "offset": _offset,
  158. "size": _size,
  159. "flags": _flags
  160. }
  161. return partition_table
  162. class Example(IDFApp):
  163. def _get_sdkconfig_paths(self):
  164. """
  165. overrides the parent method to provide exact path of sdkconfig for example tests
  166. """
  167. return [os.path.join(self.binary_path, "..", "sdkconfig")]
  168. def get_binary_path(self, app_path):
  169. # build folder of example path
  170. path = os.path.join(self.idf_path, app_path, "build")
  171. if not os.path.exists(path):
  172. # search for CI build folders
  173. app = os.path.basename(app_path)
  174. example_path = os.path.join(self.idf_path, "build_examples", "example_builds")
  175. for dirpath, dirnames, files in os.walk(example_path):
  176. if dirnames:
  177. if dirnames[0] == app:
  178. path = os.path.join(example_path, dirpath, dirnames[0], "build")
  179. break
  180. else:
  181. raise OSError("Failed to find example binary")
  182. return path
  183. class UT(IDFApp):
  184. def get_binary_path(self, app_path):
  185. """
  186. :param app_path: app path or app config
  187. :return: binary path
  188. """
  189. if not app_path:
  190. app_path = "default"
  191. path = os.path.join(self.idf_path, app_path)
  192. if not os.path.exists(path):
  193. while True:
  194. # try to get by config
  195. if app_path == "default":
  196. # it's default config, we first try to get form build folder of unit-test-app
  197. path = os.path.join(self.idf_path, "tools", "unit-test-app", "build")
  198. if os.path.exists(path):
  199. # found, use bin in build path
  200. break
  201. # ``make ut-build-all-configs`` or ``make ut-build-CONFIG`` will copy binary to output folder
  202. path = os.path.join(self.idf_path, "tools", "unit-test-app", "output", app_path)
  203. if os.path.exists(path):
  204. break
  205. raise OSError("Failed to get unit-test-app binary path")
  206. return path
  207. class SSC(IDFApp):
  208. def get_binary_path(self, app_path):
  209. # TODO: to implement SSC get binary path
  210. return app_path
  211. class AT(IDFApp):
  212. def get_binary_path(self, app_path):
  213. # TODO: to implement AT get binary path
  214. return app_path