versions.py 6.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207
  1. #! /usr/bin/env python3
  2. from dotenv import load_dotenv
  3. load_dotenv()
  4. import os
  5. import struct
  6. import zipfile
  7. import oss2
  8. import json
  9. import requests
  10. from requests.exceptions import RequestException
  11. # 切换到项目根目录
  12. os.chdir(os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
  13. def get_chip_id_string(chip_id):
  14. return {
  15. 0x0000: "esp32",
  16. 0x0002: "esp32s2",
  17. 0x0005: "esp32c3",
  18. 0x0009: "esp32s3",
  19. 0x000C: "esp32c2",
  20. 0x000D: "esp32c6",
  21. 0x0010: "esp32h2",
  22. 0x0011: "esp32c5",
  23. 0x0012: "esp32p4",
  24. 0x0017: "esp32c5",
  25. }[chip_id]
  26. def get_flash_size(flash_size):
  27. MB = 1024 * 1024
  28. return {
  29. 0x00: 1 * MB,
  30. 0x01: 2 * MB,
  31. 0x02: 4 * MB,
  32. 0x03: 8 * MB,
  33. 0x04: 16 * MB,
  34. 0x05: 32 * MB,
  35. 0x06: 64 * MB,
  36. 0x07: 128 * MB,
  37. }[flash_size]
  38. def get_app_desc(data):
  39. magic = struct.unpack("<I", data[0x00:0x04])[0]
  40. if magic != 0xabcd5432:
  41. raise Exception("Invalid app desc magic")
  42. version = data[0x10:0x30].decode("utf-8").strip('\0')
  43. project_name = data[0x30:0x50].decode("utf-8").strip('\0')
  44. time = data[0x50:0x60].decode("utf-8").strip('\0')
  45. date = data[0x60:0x70].decode("utf-8").strip('\0')
  46. idf_ver = data[0x70:0x90].decode("utf-8").strip('\0')
  47. elf_sha256 = data[0x90:0xb0].hex()
  48. return {
  49. "name": project_name,
  50. "version": version,
  51. "compile_time": date + "T" + time,
  52. "idf_version": idf_ver,
  53. "elf_sha256": elf_sha256,
  54. }
  55. def get_board_name(folder):
  56. basename = os.path.basename(folder)
  57. if basename.startswith("v0.2"):
  58. return "bread-simple"
  59. if basename.startswith("v0.3") or basename.startswith("v0.4") or basename.startswith("v0.5") or basename.startswith("v0.6"):
  60. if "ML307" in basename:
  61. return "bread-compact-ml307"
  62. elif "WiFi" in basename:
  63. return "bread-compact-wifi"
  64. elif "KevinBox1" in basename:
  65. return "kevin-box-1"
  66. if basename.startswith("v0.7") or basename.startswith("v0.8") or basename.startswith("v0.9") or basename.startswith("v1.") or basename.startswith("v2."):
  67. return basename.split("_")[1]
  68. raise Exception(f"Unknown board name: {basename}")
  69. def read_binary(dir_path):
  70. merged_bin_path = os.path.join(dir_path, "merged-binary.bin")
  71. merged_bin_data = open(merged_bin_path, "rb").read()
  72. # find app partition
  73. if merged_bin_data[0x100000] == 0xE9:
  74. data = merged_bin_data[0x100000:]
  75. elif merged_bin_data[0x200000] == 0xE9:
  76. data = merged_bin_data[0x200000:]
  77. elif merged_bin_data[0xe0000] == 0xE9:
  78. data = merged_bin_data[0xe0000:]
  79. else:
  80. print(dir_path, "is not a valid image")
  81. return
  82. # get flash size
  83. flash_size = get_flash_size(data[0x3] >> 4)
  84. chip_id = get_chip_id_string(data[0xC])
  85. # get segments
  86. segment_count = data[0x1]
  87. segments = []
  88. offset = 0x18
  89. for i in range(segment_count):
  90. segment_size = struct.unpack("<I", data[offset + 4:offset + 8])[0]
  91. offset += 8
  92. segment_data = data[offset:offset + segment_size]
  93. offset += segment_size
  94. segments.append(segment_data)
  95. assert offset < len(data), "offset is out of bounds"
  96. # extract bin file
  97. bin_path = os.path.join(dir_path, "xiaozhi.bin")
  98. if not os.path.exists(bin_path):
  99. print("extract bin file to", bin_path)
  100. open(bin_path, "wb").write(data)
  101. # The app desc is in the first segment
  102. desc = get_app_desc(segments[0])
  103. return {
  104. "chip_id": chip_id,
  105. "flash_size": flash_size,
  106. "board": get_board_name(dir_path),
  107. "application": desc,
  108. "firmware_size": len(data),
  109. }
  110. def extract_zip(zip_path, extract_path):
  111. if not os.path.exists(extract_path):
  112. os.makedirs(extract_path)
  113. print(f"Extracting {zip_path} to {extract_path}")
  114. with zipfile.ZipFile(zip_path, 'r') as zip_ref:
  115. zip_ref.extractall(extract_path)
  116. def upload_dir_to_oss(source_dir, target_dir):
  117. auth = oss2.Auth(os.environ['OSS_ACCESS_KEY_ID'], os.environ['OSS_ACCESS_KEY_SECRET'])
  118. bucket = oss2.Bucket(auth, os.environ['OSS_ENDPOINT'], os.environ['OSS_BUCKET_NAME'])
  119. for filename in os.listdir(source_dir):
  120. oss_key = os.path.join(target_dir, filename)
  121. print('uploading', oss_key)
  122. bucket.put_object(oss_key, open(os.path.join(source_dir, filename), 'rb'))
  123. def post_info_to_server(info):
  124. """
  125. 将固件信息发送到服务器
  126. Args:
  127. info: 包含固件信息的字典
  128. """
  129. try:
  130. # 从环境变量获取服务器URL和token
  131. server_url = os.environ.get('VERSIONS_SERVER_URL')
  132. server_token = os.environ.get('VERSIONS_TOKEN')
  133. if not server_url or not server_token:
  134. raise Exception("Missing SERVER_URL or TOKEN in environment variables")
  135. # 准备请求头和数据
  136. headers = {
  137. 'Authorization': f'Bearer {server_token}',
  138. 'Content-Type': 'application/json'
  139. }
  140. # 发送POST请求
  141. response = requests.post(
  142. server_url,
  143. headers=headers,
  144. json={'jsonData': json.dumps(info)}
  145. )
  146. # 检查响应状态
  147. response.raise_for_status()
  148. print(f"Successfully uploaded version info for tag: {info['tag']}")
  149. except RequestException as e:
  150. if hasattr(e.response, 'json'):
  151. error_msg = e.response.json().get('error', str(e))
  152. else:
  153. error_msg = str(e)
  154. print(f"Failed to upload version info: {error_msg}")
  155. raise
  156. except Exception as e:
  157. print(f"Error uploading version info: {str(e)}")
  158. raise
  159. def main():
  160. release_dir = "releases"
  161. # look for zip files startswith "v"
  162. for name in os.listdir(release_dir):
  163. if name.startswith("v") and name.endswith(".zip"):
  164. tag = name[:-4]
  165. folder = os.path.join(release_dir, tag)
  166. info_path = os.path.join(folder, "info.json")
  167. if not os.path.exists(info_path):
  168. if not os.path.exists(folder):
  169. os.makedirs(folder)
  170. extract_zip(os.path.join(release_dir, name), folder)
  171. info = read_binary(folder)
  172. target_dir = os.path.join("firmwares", tag)
  173. info["tag"] = tag
  174. info["url"] = os.path.join(os.environ['OSS_BUCKET_URL'], target_dir, "xiaozhi.bin")
  175. open(info_path, "w").write(json.dumps(info, indent=4))
  176. # upload all file to oss
  177. upload_dir_to_oss(folder, target_dir)
  178. # read info.json
  179. info = json.load(open(info_path))
  180. # post info.json to server
  181. post_info_to_server(info)
  182. if __name__ == "__main__":
  183. main()