Python Devicetree Library

0.0.2 · active · verified Fri Apr 17

The `devicetree` library provides Python tools for parsing and manipulating devicetree files, commonly used in embedded systems. It supports both binary (.dtb) and source (.dts) formats. The current version is 0.0.2, indicating early development, and releases are not on a fixed cadence.

Common errors

Warnings

Install

Imports

Quickstart

This quickstart demonstrates how to load a device tree from a temporary .dts file, access its root node, retrieve properties, and find specific child nodes by path or compatible string. It includes cleanup of the temporary file.

import os
import devicetree

# Create a dummy DTS file for demonstration
dts_content = """
/dts-v1/;

/ {
    compatible = "acme,board-v1";
    cpus {
        cpu@0 {
            compatible = "arm,cortex-m4";
            reg = <0>;
        };
    };
    gpio@10000 {
        compatible = "gpio-controller";
        reg = <0x10000 0x100>;
        #gpio-cells = <2>;
    };
};
"""
dts_path = "example.dts"
with open(dts_path, "w") as f:
    f.write(dts_content)

try:
    # Load the device tree from the DTS file
    dt = devicetree.dtlib.DT(dts_path)
    print(f"\n--- Device Tree Content ---")
    print(f"Root node name: {dt.name}")
    
    # Accessing properties of the root node
    compatible_prop = dt.get_prop('compatible')
    if compatible_prop: # get_prop returns DTProperty or None
        print(f"Root compatible: {compatible_prop.value}")
    
    # Finding a specific node by path
    cpu_node = dt.get_node("/cpus/cpu@0")
    if cpu_node:
        print(f"CPU Node path: {cpu_node.path}")
        cpu_compatible = cpu_node.get_prop('compatible')
        if cpu_compatible:
            print(f"CPU Node compatible: {cpu_compatible.value}")
    
    # Finding a node by compatible string
    gpio_node = dt.get_node_by_compatible("gpio-controller")
    if gpio_node:
        print(f"GPIO Controller found at: {gpio_node.path}")

except Exception as e:
    print(f"An error occurred during device tree processing: {e}")
finally:
    # Clean up the dummy file
    if os.path.exists(dts_path):
        os.remove(dts_path)
    print(f"\nCleaned up {dts_path}")

view raw JSON →