modm_data.cubemx
STMicro STM32CubeMX Database
1# Copyright 2022, Niklas Hauser 2# SPDX-License-Identifier: MPL-2.0 3 4""" 5# STMicro STM32CubeMX Database 6""" 7 8from .clock_tree import clock_tree_from_partname, evaluate as evaluate_clock_tree 9from .device_data import ( 10 devices_from_family, 11 devices_from_prefix, 12 devices_from_partname, 13 cubemx_device_list, 14 temperature_codes, 15 header_from_partname, 16) 17 18__all__ = [ 19 "clock_tree_from_partname", 20 "evaluate_clock_tree", 21 "header_from_partname", 22 "devices_from_family", 23 "devices_from_prefix", 24 "devices_from_partname", 25 "cubemx_device_list", 26 "temperature_codes", 27]
418def clock_tree_from_partname(partname: str) -> dict: 419 """ 420 The clock tree of one device as a solver friendly graph. 421 422 :param partname: A full STM32 device name. 423 :return: The nodes of the tree with the peripherals attached to them, or 424 None if the device has no clock tree in the database. 425 """ 426 if _hal2().is_hal2_device(partname): 427 from ..hal2.clock_tree import clock_tree_from_partname as hal2_clock_tree 428 429 return hal2_clock_tree(partname) 430 device_file = _device_file(partname) 431 drawing = device_file.tree.get("ClockTree") 432 rcc = next((ip.get("Version") for ip in device_file.query('//IP[@Name="RCC"]')), None) 433 if not drawing or not rcc: 434 LOGGER.error(f"No clock tree found for {partname}") 435 return None 436 if not (_CLOCK_PATH / f"{drawing}.xml").exists() or not (_MCU_PATH / "IP" / f"RCC-{rcc}_Modes.xml").exists(): 437 LOGGER.error(f"Clock tree files missing for {partname}: {drawing}, RCC-{rcc}") 438 return None 439 440 parameters = read_parameters(rcc) 441 context = conditions.context_of(device_file) 442 nodes, dropped = read_tree(drawing, context) 443 resolve(nodes, parameters, context, read_signals(drawing)) 444 buses = bus_peripherals(parameters, nodes) 445 446 instances = peripherals_of(device_file) 447 header = header_from_partname(partname) 448 attached = attach_peripherals( 449 nodes, buses, header_buses(header) if header else {}, instances, base_buses(header) if header else {} 450 ) 451 452 semaphores = _semaphores(parameters) 453 add_scale_limits(nodes, scale_limits(parameters, context)) 454 latencies = manual_flash_latency(partname, parameters) or flash_latency(parameters, context) 455 options = _options(nodes, parameters, semaphores, latencies) 456 options |= _enables(nodes, parameters, options, semaphores, context) 457 constraints = correct(nodes, options, partname) 458 # A limit an output of a fixed source always meets says nothing, the STM32G4 IWDG runs at LSI, not up to 170 MHz 459 for node in nodes.values(): 460 sources = [nodes.get(i["from"], {}) for i in node["inputs"]] 461 if node["kind"] == "output" and len(sources) == 1 and sources[0].get("kind") == "fixed": 462 value = sources[0].get("value", 0) 463 if node.get("min", 0) <= value <= node.get("max", value) and "limits" not in node: 464 node.pop("min", None) 465 node.pop("max", None) 466 return { 467 "device": partname, 468 "tree": drawing, 469 "rcc": rcc, 470 "nodes": nodes, 471 "dropped": dropped, 472 "busIP": buses, 473 "semaphores": semaphores, 474 "options": options, 475 "derived": _derived(options, parameters, context), 476 # The values an option can take, for example, PWREXT_OverDrive_ACTIVATED 477 "choices": { 478 name: sorted({v["macro"] for d in parameters[name] for v in d.get("values", ())}) 479 for name in options 480 if any(d.get("values") for d in parameters[name]) 481 }, 482 "modes": read_modes(rcc, context), 483 "flash": latencies, 484 "constraints": constraints, 485 "clocks": attached, 486 "unattached": sorted(instances - set(attached)), 487 }
The clock tree of one device as a solver friendly graph.
Parameters
- partname: A full STM32 device name.
Returns
The nodes of the tree with the peripherals attached to them, or None if the device has no clock tree in the database.
338def evaluate(tree: dict, config: dict[str, str] | None = None, use: set[str] | None = None) -> dict[str, dict]: 339 """ 340 The frequency of every node for one configuration, with everything that the 341 configuration does not set at its default. 342 343 :param tree: The clock tree, see `clock_tree_from_partname`. What depends on the 344 tree alone is cached per tree, so a tree must not change in place. 345 :param config: The settings by node or parameter name, see `_setting`, for 346 example, `{"PLLN": "20", "SysClkSource": "PLLR"}`. Options 347 that no node stands for take the macro as given, for 348 example, `{"PWR_Regulator_Voltage_Scale": "SCALE2"}`, and so 349 do the flags that rules test, for example, `{"USBUsed_ForRCC": "1"}`, 350 and the oscillator modes, for example, `{"HSE": "ByPass"}`. 351 :param use: The peripherals and features in use, for example, `{"USART1", "USB_OTG_FS", "MCO"}`. 352 It sets their usage flags, which some limits test, and only they, 353 the bus clocks and the outputs that need no enable or one that the 354 configuration sets count as used, the STM32U5 notInLPBAM by default. 355 By default everything counts as used and no flag is set. 356 :return: The `freq`uency in Hz of every node, None if it has none, its 357 `setting`, whether it is `used` by an output through the chosen 358 mux inputs, the limits it violates as `errors` and the limits that 359 apply as `bounds` (`""` of the node, `"out_"` of its output signal), and under 360 `FLatency` the fewest flash wait states as `setting`. 361 """ 362 nodes, semaphores = tree["nodes"], tree["semaphores"] 363 static = _static(tree) 364 by_param, compiled = static["by_param"], static["compiled"] 365 366 def _test(gate: list, values: dict, semaphores: dict) -> bool: 367 if (function := compiled.get(id(gate))) is None: 368 function = compiled[id(gate)] = _compile(gate, semaphores) 369 return function(values) 370 371 chosen, settings, invalid = {}, dict(tree["options"]), {} 372 for key, value in (config or {}).items(): 373 if key in nodes or key in by_param: 374 name = key if key in nodes else by_param[key] 375 try: 376 chosen[name] = _setting(name, nodes[name], value) 377 except _OutOfRange as error: 378 # Evaluated anyway, the violation is an error of the node like any other 379 chosen[name], invalid[name] = error.value, str(error) 380 elif key in tree.get("modes", {}): 381 # An oscillator mode, for example, HSE=ByPass, sets its semaphore and clears the others 382 modes = tree["modes"][key] 383 flag = next((f for m, f in modes.items() if str(value).strip().lower() in (m.lower(), f.lower())), None) 384 if flag is None: 385 raise ValueError(f"{key} has no mode '{value}', choose from {', '.join(modes)}") 386 settings |= {f: "1" if f == flag else "0" for f in modes.values()} 387 elif key in tree["options"] or key in static["identifiers"]: 388 # An option or a flag like USB_OTG_FSUsed_ForRCC=1 that a rule tests, 389 # options also by the end of their macro, for example, SCALE2 390 settings[key] = option_value(tree, key, value) 391 else: 392 raise ValueError(f"unknown node or parameter '{key}'") 393 use = frozenset(u.strip().upper() for u in use) if use is not None else None 394 if use: 395 for flag in _flags_in_use(static, use): 396 if flag not in settings: 397 settings[flag] = "1" 398 399 explicit = set(settings) - set(tree["options"]) | {k for k in (config or {}) if k in tree["options"]} 400 401 def derive(values: dict): 402 """Settles the derived options that the configuration does not set, twice for chains.""" 403 for _ in range(2): 404 for name, declarations in tree.get("derived", {}).items(): 405 if name not in explicit: 406 merged = values | settings 407 settings[name] = next( 408 (d["value"] for d in declarations if "when" not in d or _test(d["when"], merged, semaphores)), 409 settings.get(name), 410 ) 411 412 def setting(name: str, node: dict): 413 if name in chosen: 414 return chosen[name] 415 return node.get("value", node.get("default")) 416 417 # The macro every parameter stands at, which the derivation rules test 418 for name, node in nodes.items(): 419 if "param" not in node or (value := setting(name, node)) is None: 420 continue 421 if node["kind"] == "mux": 422 settings[node["param"]] = value 423 else: 424 found = [d["macro"] for d in node.get("domain", ()) if d.get("factor", d.get("value")) == value] 425 settings[node["param"]] = found[0] if found else f"{value:g}" 426 427 derive(settings) 428 429 def factor(name: str, node: dict) -> float: 430 for rule in node.get("rules", ()): 431 if "when" in rule and _test(rule["when"], settings, semaphores): 432 return rule["factor"] 433 defaults = [rule["factor"] for rule in node.get("rules", ()) if "when" not in rule] 434 return defaults[0] if defaults and name not in chosen else setting(name, node) 435 436 result = {} 437 438 def freq_of(name: str) -> float: 439 if name in result: 440 return result[name]["freq"] 441 node = nodes[name] 442 result[name] = {"freq": None} # breaks cycles 443 kind, sources = node["kind"], [i["from"] for i in node["inputs"] if i["from"] in nodes] 444 value, freq = setting(name, node), None 445 if kind in ("fixed", "varied", "choice"): 446 freq = value 447 elif kind == "mux": 448 picked = [i["from"] for i in node["inputs"] if value in (i.get("macro"), i["from"])] 449 freq = freq_of(picked[0]) if picked and picked[0] in nodes else None 450 elif kind == "mulfrac": 451 inputs = [s for s in sources if nodes[s]["kind"] != "frac"] 452 fraction = sum(setting(s, nodes[s]) or 0 for s in sources if nodes[s]["kind"] == "frac") 453 if inputs and (f := freq_of(inputs[0])) is not None and value is not None: 454 freq = f * (value + fraction / 8192) 455 elif kind in ("div", "mul"): 456 if sources and (f := freq_of(sources[0])) is not None and (k := factor(name, node)): 457 freq = f / k if kind == "div" else f * k 458 elif kind in ("output", "peripheral") and sources: 459 freq = freq_of(sources[0]) 460 result[name] = {"freq": freq, "setting": value, "used": False, "errors": []} 461 return freq 462 463 for name in nodes: 464 freq_of(name) 465 466 # What an output or peripheral draws from through the chosen mux inputs 467 # The PLL outputs that clock nothing are only for show, PLLQoutput 468 if use is None: 469 stack = list(static["roots"]) 470 else: 471 472 def enabled(node): 473 return any(settings.get(e, "").lower() in ("1", "true") for e in node.get("enable", "").split(",") if e) 474 475 stack = static["always"] + [n for n in static["gated"] if enabled(nodes[n])] 476 stack += [static["peripherals"][u] for u in use if u in static["peripherals"]] 477 while stack: 478 name = stack.pop() 479 if result[name]["used"]: 480 continue 481 result[name]["used"] = True 482 node = nodes[name] 483 if "bus" in node: 484 stack.append(node["bus"]) 485 for input in node["inputs"]: 486 if input["from"] in nodes and ( 487 node["kind"] != "mux" or result[name]["setting"] in (input.get("macro"), input["from"]) 488 ): 489 stack.append(input["from"]) 490 491 # The derived options that test the clocks, for example, the over-drive above 168 MHz 492 # or the STM32H5 PLL input range, and the frequencies of the signals they test 493 clocks = {clock: result[name]["freq"] for clock, name in static["scaled"]} 494 # The STM32WB0 and STM32WL3 have no HCLK of their own, it is SysCLKFreq_VALUE 495 clocks.setdefault("HCLKFreq_Value", clocks.get("SYSCLKFreq_VALUE")) 496 clocks["HCLK3Freq_Value"] = clocks.get("HCLKFreq_Value") 497 for param, name in static["signals"]: 498 clocks.setdefault(param, result[name]["freq"]) 499 clocks = {k: v for k, v in clocks.items() if v is not None} 500 # A PLL in use is in use, CubeMX sets PLLUsed on the STM32F446 only for the MCO 501 for flag, pll in static["pll_flags"]: 502 if flag in explicit: 503 continue 504 candidates = [pll, *_PLL_NODES.get(pll, ())] 505 if any(result.get(by_param.get(c), {}).get("used") for c in candidates): 506 settings[flag] = "1" 507 explicit.add(flag) 508 derive(clocks) 509 510 def check(name: str, freq: float, static: dict, variants: list, prefix: str): 511 bounds, usage = static, False 512 for variant in variants: 513 if "when" not in variant or _test(variant["when"], settings, semaphores): 514 if any(key in variant for key in (f"{prefix}min", f"{prefix}max")): 515 bounds = variant 516 # The fallback without limits stands for an element not in use, but this one 517 # is, for example, PLLP feeding the ADC on the STM32G0 without the ADCUsed_ForRCC 518 # flag, so the static limits apply. A condition on the configuration alone is 519 # decided though: the F7 RTC needs 1 MHz from the HSE, from the LSE it has no limit. 520 elif "when" not in variant and variants[:-1] and not usage: 521 bounds = {} 522 break 523 usage = usage or _tests_usage(variant["when"]) 524 low, high = bounds.get(f"{prefix}min"), bounds.get(f"{prefix}max") 525 # The limits that apply in this configuration 526 result[name].setdefault("bounds", {})[prefix] = (low, high) 527 if low is not None and freq < low * (1 - 1e-9): 528 result[name]["errors"].append(f"{freq:g} < {low:g}") 529 if high is not None and freq > high * (1 + 1e-9): 530 result[name]["errors"].append(f"{freq:g} > {high:g}") 531 532 for name, node in nodes.items(): 533 if (freq := result[name]["freq"]) is None or not result[name]["used"]: 534 continue 535 if node["kind"] in ("fixed", "varied", "output"): 536 check(name, freq, node, node.get("limits", ()), "") 537 check(name, freq, node, node.get("out_limits", ()), "out_") 538 539 for name in static["inputs"]: 540 if not result[name]["used"] or not nodes[name]["inputs"]: 541 continue 542 option = next((d for d in nodes[name]["domain"] if d["factor"] == result[name]["setting"]), {}) 543 freq = result[nodes[name]["inputs"][0]["from"]]["freq"] 544 if "input" in option and (freq is None or abs(freq - option["input"]) > 1e-3): 545 error = f"{option['macro']} needs an input of {option['input']:g}, not {freq or 0:g}" 546 result[name]["errors"].append(error) 547 548 # The ratios a mux input needs, for example, PLLQ an integer multiple of PCLK for the U0 TIM1 549 for constraint in tree.get("constraints", ()): 550 mux = constraint["mux"] 551 selected = [i["from"] for i in nodes[mux]["inputs"] if result[mux]["setting"] in (i.get("macro"), i["from"])] 552 if not result[mux]["used"] or constraint["input"] not in selected: 553 continue 554 if "erratum" in constraint: 555 result[mux]["errors"].append(constraint["erratum"]) 556 continue 557 base = constraint["base"] 558 freq, reference = result[mux]["freq"], result[base]["freq"] 559 if freq and reference: 560 ratio = freq / reference 561 if ratio < constraint["ratio"] - 1e-9 or abs(ratio - round(ratio)) > 1e-6: 562 result[mux]["errors"].append( 563 f"{freq:g} is not an integer multiple of {constraint['ratio']} or more of {reference:g}" 564 ) 565 566 # The fewest flash wait states for the core clocks, as the first declaration that holds 567 if latencies := tree.get("flash"): 568 values = settings | clocks 569 found = next((latency["latency"] for latency in latencies if _test(latency["when"], values, semaphores)), None) 570 result["FLatency"] = { 571 "freq": None, 572 "setting": found, 573 "used": True, 574 "errors": [] if found else [f"no flash wait states for {clocks.get('HCLKFreq_Value') or 0:g}"], 575 } 576 for name, message in invalid.items(): 577 result[name]["errors"].append(message) 578 579 # A derived voltage scale follows SYSCLK only, so take the slowest scale 580 # under which every clock in use meets its limits, like the board would need 581 scale = "PWR_Regulator_Voltage_Scale" 582 583 def errors(r): 584 return sum(len(v["errors"]) for n, v in r.items() if n in nodes and v["used"]) 585 586 if scale in tree.get("derived", {}) and scale not in explicit and errors(result): 587 current = _scale_rank(settings.get(scale, "")) 588 for faster in sorted(tree.get("choices", {}).get(scale, ()), key=_scale_rank, reverse=True): 589 if _scale_rank(faster) < current: 590 trial = evaluate(tree, {**(config or {}), scale: faster}, use) 591 if errors(trial) < errors(result): 592 result, current = trial, _scale_rank(faster) 593 if not errors(trial): 594 break 595 if result is not None and "options" in result: 596 return result 597 598 # The options as evaluated, derived ones included 599 result["options"] = { 600 "freq": None, 601 "setting": {k: settings[k] for k in tree["options"] if k in settings}, 602 "used": True, 603 "errors": [], 604 } 605 return result
The frequency of every node for one configuration, with everything that the configuration does not set at its default.
Parameters
- tree: The clock tree, see
clock_tree_from_partname. What depends on the tree alone is cached per tree, so a tree must not change in place. - config: The settings by node or parameter name, see
_setting, for example,{"PLLN": "20", "SysClkSource": "PLLR"}. Options that no node stands for take the macro as given, for example,{"PWR_Regulator_Voltage_Scale": "SCALE2"}, and so do the flags that rules test, for example,{"USBUsed_ForRCC": "1"}, and the oscillator modes, for example,{"HSE": "ByPass"}. - use: The peripherals and features in use, for example,
{"USART1", "USB_OTG_FS", "MCO"}. It sets their usage flags, which some limits test, and only they, the bus clocks and the outputs that need no enable or one that the configuration sets count as used, the STM32U5 notInLPBAM by default. By default everything counts as used and no flag is set.
Returns
The
frequency in Hz of every node, None if it has none, itssetting, whether it isusedby an output through the chosen mux inputs, the limits it violates aserrorsand the limits that apply asbounds(""of the node,"out_"of its output signal), and underFLatencythe fewest flash wait states assetting.
187@cache 188def header_from_partname(partname: str) -> Header: 189 """ 190 :param partname: A full STM32 device name. 191 :return: The CMSIS device header of the device, or None if there is none. 192 """ 193 did = did_from_string(partname.lower()) 194 # The pack does not list every order code, for example, the 32kB STM32G071C6, 195 # however, the header only depends on the name, the size and the pin count 196 define = "" 197 if node := _dfp_node(partname, did): 198 define = _dfp_findall(node[0], "compile")[0].get("define") 199 family = _dfp_folder(did)[:-4].lower() 200 if not (Header._HEADER_PATH / (family if "xx" in family else family + "x")).exists(): 201 # The STM32MP1 and STM32MP2 have no CMSIS device header 202 return None 203 header = Header(did, family, define) 204 if not header.is_valid: 205 LOGGER.error("CMSIS Header invalid for %s", did.string) 206 return None 207 return header
Parameters
- partname: A full STM32 device name.
Returns
The CMSIS device header of the device, or None if there is none.
55def devices_from_family(family: str) -> list[str]: 56 """ 57 :param family: A STM32 family name, for example, F0, H7, G4. 58 :return: A list of device names belonging to a STM32 family. 59 """ 60 devices = _family_file().query(f'//Family[@Name="{family.upper()}"]/SubFamily/Mcu/@RefName') 61 devices = _format_raw_devices(devices) + _hal2().devices_from_prefix(f"STM32{family}") 62 LOGGER.info("Found devices of family '{}': {}".format(family, ", ".join(devices))) 63 return devices
Parameters
- family: A STM32 family name, for example, F0, H7, G4.
Returns
A list of device names belonging to a STM32 family.
66def devices_from_prefix(prefix: str) -> list[str]: 67 """ 68 :param prefix: A STM32 device prefix, for example, STM32, STM32H7, STM32G432. 69 :return: A list of device names starting with the prefix. 70 """ 71 devices = _family_file().query(f'//Family/SubFamily/Mcu[starts-with(@RefName,"{prefix.upper()}")]') 72 devices = _format_raw_devices(devices) 73 devices = [d for d in devices if not stm32_data.ignoreDevice(d)] + _hal2().devices_from_prefix(prefix) 74 LOGGER.info("Found devices for prefix '{}': {}".format(prefix, ", ".join(devices))) 75 return list(sorted(devices))
Parameters
- prefix: A STM32 device prefix, for example, STM32, STM32H7, STM32G432.
Returns
A list of device names starting with the prefix.
210def devices_from_partname(partname: str) -> list[dict[str]]: 211 """ 212 Find the STM32 device name in the STM32CubeMX database and convert the data 213 into a device specific key-value mapping describing the hardware. 214 215 .. note:: 216 One partname may contain multiple devices, for example, multiple 217 asymmetric CPU cores like in the STM32H745 device. 218 219 :param partname: A full STM32 device name. 220 :return: a list of dictionaries containing a device specific data structure. 221 """ 222 if _hal2().is_hal2_device(partname): 223 return _hal2().devices_from_partname(partname) 224 device_file = _device_file(partname) 225 comboDeviceName = Path(device_file.filename).stem 226 did = did_from_string(partname.lower()) 227 LOGGER.info(f"Parsing '{did.string}'") 228 229 # information about the core and architecture 230 cores = [c.text.lower().replace("arm ", "").replace("+", "plus") for c in device_file.query("//Core")] 231 if len(cores) > 1: 232 did.naming_schema += "@{core}" 233 devices = [_properties_from_id(partname, comboDeviceName, device_file, did.copy(), c) for c in cores] 234 return [d for d in devices if d is not None]
Find the STM32 device name in the STM32CubeMX database and convert the data into a device specific key-value mapping describing the hardware.
One partname may contain multiple devices, for example, multiple asymmetric CPU cores like in the STM32H745 device.
Parameters
- partname: A full STM32 device name.
Returns
a list of dictionaries containing a device specific data structure.
101def cubemx_device_list() -> list[DeviceIdentifier]: 102 """ 103 :return: A list of all STM32 device identifiers. 104 """ 105 return [did_from_string(d) for d in devices_from_prefix("STM32")]
Returns
A list of all STM32 device identifiers.
81def temperature_codes(partname: str) -> list[str]: 82 """ 83 CubeMX uses `x` as placeholder for the temperature range in the device name. 84 This function computes the temperature codes from the maximum operating 85 temperature, since every higher range also supports all the lower ranges. 86 87 :param partname: A STM32 device name with temperature placeholder. 88 :return: A sorted list of temperature codes, for example, `["3", "6", "7"]`. 89 """ 90 if _hal2().is_hal2_device(partname): 91 return _hal2().temperature_codes(partname) 92 codes = set() 93 for device in _family_file().query(f'//Family/SubFamily/Mcu[@RefName="{partname}"]'): 94 temp_max = device.find("Temperature") 95 temp_max = "" if temp_max is None else temp_max.get("Max") 96 temp_max = int(float(temp_max)) if len(temp_max) else min(_TEMPERATURE_CODES) 97 codes.update(code for temp, code in _TEMPERATURE_CODES.items() if temp_max >= temp) 98 return sorted(codes)
CubeMX uses x as placeholder for the temperature range in the device name.
This function computes the temperature codes from the maximum operating
temperature, since every higher range also supports all the lower ranges.
Parameters
- partname: A STM32 device name with temperature placeholder.
Returns
A sorted list of temperature codes, for example,
["3", "6", "7"].