modm_data.dl.stmicro
1# Copyright 2022, Niklas Hauser 2# SPDX-License-Identifier: MPL-2.0 3 4from .document import Document, load_remote_info, load_local_info, store_remote_info, store_local_info 5from .document import load_device_info, store_device_info 6from .cubemx import download_cubemx 7from .cubeprog import download_cubeprog 8from .cubemx2 import download_cubemx2 9 10__all__ = [ 11 "Document", 12 "load_remote_info", 13 "load_local_info", 14 "store_remote_info", 15 "store_local_info", 16 "load_device_info", 17 "store_device_info", 18 "download_cubemx", 19 "download_cubeprog", 20 "download_cubemx2", 21]
15class Document: 16 """ 17 Smaller helper class to store all relevant information about a remote 18 STMicro PDF document and how to download it. 19 """ 20 21 def __init__(self, data): 22 # Primary information from JSON data 23 self._title = data["title"] 24 self._description = data["localizedDescriptions"]["en"] 25 self._url = data["localizedLinks"]["en"] 26 self._version = data["version"] 27 self._update = data["latestUpdate"] 28 self._type = data.get("resourceType", "Unknown") 29 self._md_url = data.get("localizedMdZipLinks", {}).get("en") 30 31 # Derived information 32 self._short_type = self._title[:2] 33 clean_version = self._version.replace(".0", "").replace(".", "_") 34 self.name = self._title + "-v" + clean_version 35 """The full name of the document including version.""" 36 self.filename = self.name + ".pdf" 37 """The leaf filename of the document.""" 38 self.url = "https://www.st.com" + self._url 39 """The full URL that the file was downloaded from.""" 40 self.md_url = "https://www.st.com" + self._md_url if self._md_url else None 41 """The full URL of the zipped Markdown version or `None` if there is none.""" 42 43 @property 44 def data(self) -> dict: 45 """ 46 A dictionary uniquely identifying this document version in a similar 47 format to the one used by the STMicro homepage. This can be used to 48 keep track of which documents have already been downloaded and which 49 have been updated upstream. 50 """ 51 return { 52 "title": self._title, 53 "localizedDescriptions": {"en": self._description}, 54 "localizedLinks": {"en": self._url}, 55 "version": self._version, 56 "latestUpdate": self._update, 57 "resourceType": self._type, 58 } 59 60 def store_pdf(self, path: str, overwrite: bool = False) -> bool: 61 """Download the PDF file to the path, optionally overwriting it.""" 62 return download_file(self.url, path, overwrite=overwrite) 63 64 def store_markdown(self, path: str, overwrite: bool = False) -> bool: 65 """Download the zipped Markdown version to the path, optionally overwriting it.""" 66 return download_file(self.md_url, path, overwrite=overwrite) 67 68 def __repr__(self) -> str: 69 return f"Doc({self._title} v{self._version.replace('.0', '')})" 70 71 def __eq__(self, other) -> bool: 72 if not isinstance(other, type(self)): 73 return False 74 return self.filename == other.filename 75 76 def __hash__(self) -> int: 77 return hash(self.filename)
Smaller helper class to store all relevant information about a remote STMicro PDF document and how to download it.
21 def __init__(self, data): 22 # Primary information from JSON data 23 self._title = data["title"] 24 self._description = data["localizedDescriptions"]["en"] 25 self._url = data["localizedLinks"]["en"] 26 self._version = data["version"] 27 self._update = data["latestUpdate"] 28 self._type = data.get("resourceType", "Unknown") 29 self._md_url = data.get("localizedMdZipLinks", {}).get("en") 30 31 # Derived information 32 self._short_type = self._title[:2] 33 clean_version = self._version.replace(".0", "").replace(".", "_") 34 self.name = self._title + "-v" + clean_version 35 """The full name of the document including version.""" 36 self.filename = self.name + ".pdf" 37 """The leaf filename of the document.""" 38 self.url = "https://www.st.com" + self._url 39 """The full URL that the file was downloaded from.""" 40 self.md_url = "https://www.st.com" + self._md_url if self._md_url else None 41 """The full URL of the zipped Markdown version or `None` if there is none."""
43 @property 44 def data(self) -> dict: 45 """ 46 A dictionary uniquely identifying this document version in a similar 47 format to the one used by the STMicro homepage. This can be used to 48 keep track of which documents have already been downloaded and which 49 have been updated upstream. 50 """ 51 return { 52 "title": self._title, 53 "localizedDescriptions": {"en": self._description}, 54 "localizedLinks": {"en": self._url}, 55 "version": self._version, 56 "latestUpdate": self._update, 57 "resourceType": self._type, 58 }
A dictionary uniquely identifying this document version in a similar format to the one used by the STMicro homepage. This can be used to keep track of which documents have already been downloaded and which have been updated upstream.
60 def store_pdf(self, path: str, overwrite: bool = False) -> bool: 61 """Download the PDF file to the path, optionally overwriting it.""" 62 return download_file(self.url, path, overwrite=overwrite)
Download the PDF file to the path, optionally overwriting it.
64 def store_markdown(self, path: str, overwrite: bool = False) -> bool: 65 """Download the zipped Markdown version to the path, optionally overwriting it.""" 66 return download_file(self.md_url, path, overwrite=overwrite)
Download the zipped Markdown version to the path, optionally overwriting it.
169def load_remote_info(base_dir: Path, use_cached: bool = False) -> list[dict]: 170 info = base_dir / _remote_info 171 if use_cached and info.exists(): 172 LOGGER.debug("Loading remote info from cache") 173 docs = json.loads(info.read_text()) 174 else: 175 LOGGER.info("Downloading remote info") 176 docs = [] 177 for urls in _json_urls.values(): 178 for url in urls: 179 docs.extend(_download_json(url)["rows"]) 180 # The categories overlap, so most documents are listed several times 181 docs = list({json.dumps(d, sort_keys=True): d for d in docs}.values()) 182 missing = [d for d in docs if "title" not in d or "version" not in d] 183 if missing: 184 LOGGER.warning( 185 "Some documents are missing title or version information and will be ignored: %s", 186 str(missing), 187 ) 188 return [d for d in docs if "title" in d and "version" in d]
197def load_device_info(base_dir: Path) -> dict[str, list[str]]: 198 """ 199 Downloads the documents of every STM32 part number, since the document lists 200 of the categories do not say which parts a document applies to. 201 202 :return: The sorted document names of every part number, e.g. `stm32g474re`. 203 """ 204 LOGGER.info("Downloading device info") 205 products = {} 206 # The categories miss some parts of their series and the other way around, the class has no list 207 for category in (c for c in _json_short_urls["stm32"] if not c.startswith("CL")): 208 for row in _download_json(_parts_url.format(category))["rows"]: 209 name = next(c["value"] for c in row["cells"] if c["columnId"] == "1") 210 products[name.lower()] = row["productId"] 211 212 def documents(product): 213 try: 214 rows = _download_json(_json_url_prefix + product + _json_url_suffix)["rows"] 215 except json.JSONDecodeError: 216 return None 217 return sorted({row["title"] for row in rows if "title" in row}) 218 219 # The server answers with empty responses when asked too often 220 with ThreadPool(4) as pool: 221 docs = dict(zip(products, pool.map(documents, products.values()))) 222 # A part whose documents fail to download keeps the documents of the last time 223 info = base_dir / _device_info 224 previous = json.loads(info.read_text()) if info.exists() else {} 225 if failed := [part for part, names in docs.items() if names is None]: 226 LOGGER.warning(f"No documents for {len(failed)} parts, keeping the previous ones: {failed}") 227 return {part: names if names is not None else previous.get(part, []) for part, names in docs.items()}
Downloads the documents of every STM32 part number, since the document lists of the categories do not say which parts a document applies to.
Returns
The sorted document names of every part number, e.g.
stm32g474re.
28def download_cubemx(extraction_path: Path, with_download: bool = True, with_patch: bool = True) -> bool: 29 # First check STMUpdaterDefinitions.xml from this zip 30 update_url = "https://sw-center.st.com/packs/resource/utility/updaters.zip" 31 update_url2 = "https://www.ebuc23.com/s3/stm_test/software/utility/updaters.zip" # noqa: F841 32 # Then Release="MX.6.2.0" maps to this: -win, -lin, -mac 33 cube_url = "https://sw-center.st.com/packs/resource/library/stm32cube_mx_v{}-lin.zip" 34 cube_url2 = "https://www.ebuc23.com/s3/stm_test/software/library/stm32cube_mx_v{}-lin.zip" # noqa: F841 35 36 if with_download: 37 LOGGER.info("Downloading Update Info...") 38 # try: 39 # urllib.request.urlopen(urllib.request.Request(update_url, headers=_hdr)) 40 # except: 41 # update_url = update_url2 42 # cube_url = cube_url2 43 # LOGGER.debug(update_url) 44 # time.sleep(random.randrange(0,2)) 45 46 z = zipfile.ZipFile(io.BytesIO(_dl(update_url))) 47 with io.TextIOWrapper(z.open("STMUpdaterDefinitions.xml"), encoding="utf-8") as defs: 48 version = re.search(r'Release="MX\.(.*?)"', defs.read()) 49 version = version.group(1).replace(".", "") 50 51 shutil.rmtree(extraction_path / "mcu", ignore_errors=True) 52 shutil.rmtree(extraction_path / "plugins", ignore_errors=True) 53 extraction_path.mkdir(exist_ok=True, parents=True) 54 55 LOGGER.info("Downloading Database...") 56 LOGGER.debug(cube_url.format(version)) 57 time.sleep(random.randrange(1, 6)) 58 59 z = zipfile.ZipFile(io.BytesIO(_dl(cube_url.format(version)))) 60 LOGGER.info("Extracting Database...") 61 for file in z.namelist(): 62 if any(file.startswith(prefix) for prefix in ("MX/db/mcu", "MX/db/plugins")): 63 z.extract(file, extraction_path) 64 65 LOGGER.info("Moving Database...") 66 shutil.move(extraction_path / "MX/db/mcu", extraction_path / "mcu") 67 shutil.move(extraction_path / "MX/db/plugins", extraction_path / "plugins") 68 shutil.rmtree(extraction_path / "MX", ignore_errors=True) 69 70 LOGGER.info("Normalizing file endings...") 71 for file in Path(extraction_path).glob("**/*"): 72 if str(file).endswith(".xml"): 73 with file.open("r", newline=None, encoding="utf-8", errors="replace") as rfile: 74 content = [line.rstrip() + "\n" for line in rfile.readlines()] 75 with file.open("w", encoding="utf-8") as wfile: 76 wfile.writelines(content) 77 78 if with_patch: 79 LOGGER.info("Patching Database...") 80 from . import data 81 82 return pkg_apply_patch(data, "cubemx.patch", extraction_path) 83 84 return True
19def download_cubeprog(extraction_path: Path, with_download: bool = True) -> bool: 20 # com.st.stm32cube.ide.mcu.productdb.debug contains all the SVD files 21 # com.st.stm32cube.ide.mcu.externaltools.cubeprogrammer.linux64 contains the CubeProgrammer database 22 # com.st.stm32cube.common.mx contains the CubeMX database 23 base_url = "http://sw-center.st.com/stm32cubeide/updatesite1/" 24 cubeprog_id = "com.st.stm32cube.ide.mcu.externaltools.cubeprogrammer.linux64" 25 26 if with_download: 27 LOGGER.info("Downloading Update Info...") 28 with io.TextIOWrapper( 29 io.BytesIO(_dl(f"{base_url}/compositeContent.xml")), encoding="utf-8" 30 ) as compositeContent: 31 update_version = re.findall(r"child location='(\d+\.\d+\.\d+)'", compositeContent.read()) 32 update_version = sorted(update_version, key=lambda v: tuple(map(int, v.split("."))), reverse=True)[0] 33 34 artifacts = lzma.LZMADecompressor().decompress(_dl(f"{base_url}/{update_version}/artifacts.xml.xz")) 35 version = re.search(f"id='{cubeprog_id}' version='(.*?)'", artifacts.decode("utf-8")).group(1) 36 37 download_url = f"{base_url}/{update_version}/plugins/{cubeprog_id}_{version}.jar" 38 shutil.rmtree(extraction_path / "Data_Base", ignore_errors=True) 39 extraction_path.mkdir(exist_ok=True, parents=True) 40 41 LOGGER.info("Downloading Database...") 42 LOGGER.debug(download_url) 43 time.sleep(random.randrange(1, 6)) 44 45 z = zipfile.ZipFile(io.BytesIO(_dl(download_url))) 46 LOGGER.info("Extracting Database...") 47 for file in z.namelist(): 48 if file.startswith("tools/Data_Base"): 49 z.extract(file, extraction_path) 50 51 LOGGER.info("Moving Database...") 52 shutil.move(extraction_path / "tools/Data_Base", extraction_path / "Data_Base") 53 shutil.rmtree(extraction_path / "tools", ignore_errors=True) 54 55 LOGGER.info("Normalizing file endings...") 56 for file in Path(extraction_path).glob("**/*"): 57 if str(file).endswith(".xml"): 58 with file.open("r", newline=None, encoding="utf-8", errors="replace") as rfile: 59 content = [line.rstrip() + "\n" for line in rfile.readlines()] 60 with file.open("w", encoding="utf-8") as wfile: 61 wfile.writelines(content) 62 63 return True
38def download_cubemx2(extraction_path: Path, with_download: bool = True, packs: str = DEFAULT_PACKS) -> bool: 39 """ 40 Download the matching packs into `extraction_path/{name}/`, plus the packs that matching 41 board packs require (crystal_hw-part, st-link_hw-part, ...). Packs whose version did not 42 change are skipped. Board and part packs keep only their pdsc, descriptors and license. 43 """ 44 if not with_download: 45 return True 46 extraction_path.mkdir(exist_ok=True, parents=True) 47 index = pack_index() 48 wanted = {n for _, _, n, v in index if re.fullmatch(packs, n) or re.fullmatch(packs, f"{n}.{v}")} 49 for url, vendor, name, _ in index: 50 if name in wanted and name.endswith("_hw-board"): 51 pdsc = ET.fromstring(_dl(_url(url, vendor, name, "pdsc"))) 52 wanted |= {p.get("name") for p in pdsc.iterfind("requirements/packages/package")} 53 54 for url, vendor, name, version in index: 55 if name not in wanted: 56 continue 57 dest = extraction_path / name 58 stamp = dest / ".version" 59 if stamp.exists() and stamp.read_text() == version: 60 continue 61 LOGGER.info(f"Downloading {name} v{version}...") 62 z = zipfile.ZipFile(io.BytesIO(_dl(_url(url, vendor, name, f"{version}.pack")))) 63 files = z.namelist() 64 if "_hw-" in name: 65 files = [f for f in files if f.startswith("Descriptors/") or f.endswith(".pdsc") or "LICENSE" in f] 66 shutil.rmtree(dest, ignore_errors=True) 67 z.extractall(dest, files) 68 stamp.write_text(version) 69 return True
Download the matching packs into extraction_path/{name}/, plus the packs that matching
board packs require (crystal_hw-part, st-link_hw-part, ...). Packs whose version did not
change are skipped. Board and part packs keep only their pdsc, descriptors and license.