IDFApp.py 9.0 KB

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