Skip to content

Python API#

Detailed Description#

The Python API reference documentation for libpisoundmicro presents a clean interface that mirrors the C++ API while following standard Python conventions. Built as a Python layer on top of SWIG-generated C/C++ bindings, the API provides comprehensive documentation through Python docstrings, making it fully accessible within any Python IDE's autocompletion and help systems.

The only major difference from C and C++ APIs is that the libpisoundmicro is implicitly initialized when importing the pypisoundmicro library in Python, and deinitialized upon exit.

For robust applications, it is recommended to install signal handlers that would enforce cleanup, see cleanup function documentation for an example.

Quick Start#

First, install the Python library package:

sudo apt install pypisoundmicro

Then, let's create a simple program to read the GPIO value of pin B03:

#!/usr/bin/env python3

# Import the pisoundmicro module, make it available under shorthand 'psm'.
import pypisoundmicro as psm

# Set up the Gpio Input Element using pin B03 with pull-up enabled.
gpio = psm.Gpio.setup_input(psm.ElementName.randomized(),
                            psm.Pin.B03,
                            psm.PinPull.UP)

# Check if the setup was successful.
if not gpio.is_valid:
    print("GPIO setup failed")
    exit(1)

# Read the GPIO value.
if gpio.get_value():
    print("B03 is high.")
else:
    print("B03 is low.")

Save the code as example.py, make it executable:

chmod +x example.py

Then run it:

./example.py

You should see it output either "B03 is high." or "B03 is low.", depending on the B03 pin state.

Classes#

Activity #

Bases: Element

activity_type property #

Get the activity of the element.

setup_activity(name, pin, activity) classmethod #

Set up an activity element. See also: upisnd_setup_activity

ActivityType #

Bases: IntEnum

Activity type for LED indicators.

AnalogInput #

Bases: Element

get_opts() #

Retrieves the Analog Input options. See also: ::upisnd_element_analog_input_get_opts

get_value() #

This is for quick access to the value, otherwise, it's recommended to keep the

ValueFd returned by Element::openValueFd, to avoid file open and close overhead. Inspect the errno to check for errors.

set_opts(opts) #

Sets the Analog Input options. See also: ::upisnd_element_analog_input_set_opts

setup(name, pin) classmethod #

Set up an analog input element.

Element #

is_valid property #

Checks if the element is valid.

name property #

Gets the name of the element.

pin property #

Gets the pin of the element.

type property #

Gets the type of the element.

as_activity() #

Cast the element to an Activity if possible.

as_analog_input() #

Cast the element to an AnalogInput if possible.

as_encoder() #

Cast the element to an Encoder if possible.

as_gpio() #

Cast the element to a GPIO if possible.

get(name) classmethod #

Gets an Element following ::upisnd_element_get semantics.

Parameters:

Name Type Description
name :py:class:`ElementName`

The name of the element to get. Can be provided as a string constant or const char *.

open_value_fd(flags=os.O_RDWR | os.O_CLOEXEC) #

Opens the Element's value attribute as a file descriptor.

Parameters:

Name Type Description
flags int

The flags to pass to ::open. See also: upisnd_element_open_value_fd

release() #

Unreferences the underlying C #upisnd_element_ref_t handle and resets the object.

setup(name, setup) classmethod #

Sets up a new Element from a #upisnd_setup_t setup option container.

Parameters:

Name Type Description
name :py:class:`ElementName`

The name of the element to get. Can be provided as a string constant or const char *.

setup int

The setup option container. See ::upisnd_setup_set_element_type and the rest of the upisnd_setup_* APIs in api.h.

ElementName #

randomized(prefix=None) classmethod #

Returns a randomized ElementName. You may optionally specify a prefix to be prepended to the name. See also: ::upisnd_generate_random_element_name

regular(name) classmethod #

Create an ElementName from a string.

In Python, you can use f-strings for formatting element names:

Examples:

# Basic usage
ElementName.regular("encoder_1")

# With f-strings for formatting
index = 5
ElementName.regular(f"encoder_{index}")

# With f-strings and formatting options
ElementName.regular(f"ctrl_{index:02d}")  # Produces "ctrl_05"

ElementType #

Bases: IntEnum

Element type enumeration.

Encoder #

Bases: Element

get_opts() #

Retrieves the Encoder options. See also: ::upisnd_element_encoder_get_opts

get_pin_b() #

Retrieves the 2nd pin of the Encoder. See also: ::upisnd_element_encoder_get_pin_b

get_pin_b_pull() #

Retrieves the pull-up/pull-down configuration of the 2nd pin of the Encoder. See also: ::upisnd_element_encoder_get_pin_b_pull

get_pin_pull() #

Retrieves the pull-up/pull-down configuration of the 1st pin of the Encoder. See also: ::upisnd_element_gpio_get_pull

get_value() #

This is for quick access to the value, otherwise, it's recommended to keep the

ValueFd returned by Element::openValueFd, to avoid file open and close overhead. Inspect the errno to check for errors.

set_opts(opts) #

Sets the Encoder options. See also: ::upisnd_element_encoder_set_opts

setup(name, pin_a, pull_a, pin_b, pull_b) classmethod #

Set up an encoder element. See also: ::upisnd_setup_encoder

Gpio #

Bases: Element

direction property #

Get the direction of the GPIO element.

pull property #

Get the pull of the GPIO Input element.

Returns:

Type Description
int

Returns #UPISND_PIN_PULL_INVALID if the element is not an input.

get_value() #

This is for quick access to the value, otherwise, it's recommended to keep the ValueFd returned by Element::openValueFd, to avoid file open and close overhead.

Returns:

Type Description
int

Negative return value indicates an error.

set_value(high) #

Set the output value of the GPIO output element.

Returns:

Type Description
int

Negative return value indicates an error.

setup_input(name, pin, pull) classmethod #

Set up a GPIO element as input. See also: upisnd_setup_gpio_input

setup_output(name, pin, high) classmethod #

Set up a GPIO element as output. See also: upisnd_setup_gpio_output

Pin #

Bases: IntEnum

Pin numbers for the Pisound Micro.

INVALID = psm.UPISND_PIN_INVALID class-attribute instance-attribute #

Value for indicating an invalid pin.

PinDirection #

Bases: IntEnum

Pin direction (input/output).

PinPull #

Bases: IntEnum

Pin pull-up/pull-down configuration.

Range #

Range class with high and low properties for input and value ranges.

Setup #

Wrapper for upisnd_setup_t type that encapsulates Element configuration.

This class provides a Pythonic interface for working with element setup options that are passed to Element.setup() to create new elements.

activity_type property writable #

Extracts the Activity type from the setup container, applies only to Activity Elements.

element_type property writable #

Extracts the Element type from the setup container.

encoder_pin_b property writable #

Extracts the Encoder's second pin from the setup container, applies only to Encoders.

encoder_pin_b_pull property writable #

Extracts the Encoder's second pin pull from the setup container, applies only to Encoders.

gpio_direction property writable #

Extracts the GPIO direction from the setup container, applies only to GPIO Input or Output.

gpio_output property writable #

Extracts the GPIO output level from the setup container, applies only to GPIO Output.

gpio_pull property writable #

Extracts the GPIO pull from the setup container, applies to GPIO Input and the first pin of Encoder.

pin property writable #

Extracts the main pin from the setup container.

for_activity(pin, activity) staticmethod #

Initialize upisnd_setup_t with options for Activity Element.

for_analog_input(pin) staticmethod #

Initialize upisnd_setup_t with options for Analog Input.

for_encoder(pin_a, pull_a, pin_b, pull_b) staticmethod #

Initialize upisnd_setup_t with options for Encoder.

for_gpio_input(pin, pull) staticmethod #

Initialize upisnd_setup_t with options for GPIO Input.

for_gpio_output(pin, high) staticmethod #

Initialize upisnd_setup_t with options for GPIO Output.

from_int(setup_int) classmethod #

Create a Setup object from an existing integer setup value.

Args: setup_int: An integer representing a upisnd_setup_t value

Returns: A new Setup object initialized with the given setup value

to_int() #

Get the raw setup integer value.

ValueFd #

A wrapper around a file descriptor for reading/writing element values.

is_valid property #

Returns true if the object holds a valid fd.

close() #

Closes the fd and forgets about it.

get() #

Returns the fd value for your use, but keeps ownership, and will close it upon destruction.

read() #

Reads a decimal number from the fd and returns it as integer.

Returns:

Type Description
int

The read value.

Raises:

Type Description
OSError

If the file descriptor is invalid or if an error occurs during reading.

take() #

Returns the fd value, and won't close it in the destructor, transferring ownership.

write(value) #

Outputs a decimal number to the fd.

ValueMode #

Bases: IntEnum

Value mode for encoders and analog inputs.

CLAMP = psm.UPISND_VALUE_MODE_CLAMP class-attribute instance-attribute #

The value is clamped to input_min and input_max range.

WRAP = psm.UPISND_VALUE_MODE_WRAP class-attribute instance-attribute #

The value is wrapped over to the other boundary of the input range.

cleanup() #

Clean up libpisoundmicro resources.

This function ensures that all libpisoundmicro resources are properly released, including any remaining elements and the global initializer.

Note: This function is automatically registered with atexit when the module is imported, so resources will be cleaned up during normal program termination. However, for abnormal terminations (e.g., when signals are received), your main script should call this function explicitly in its signal handlers.

Thread-safe: This function is thread-safe and can be called from any thread.

Example:

# For handling abnormal termination with signals:

import signal
import pypisoundmicro as psm

def signal_handler(signum, frame):
    # Clean up pisound resources first
    psm.cleanup()

    # Then exit or perform other cleanup
    exit(1)

# Register signal handlers for common termination signals
signal.signal(signal.SIGINT, signal_handler)   # Ctrl+C
signal.signal(signal.SIGTERM, signal_handler)  # Termination signal

init() #

Initialize libpisoundmicro resources.

This function initializes the libpisoundmicro library and prepares it for use. It is automatically called when the module is imported, but you can call it explicitly if needed, in case you have used cleanup explicitly and need to reinitialize the library.

Thread-safe: This function is thread-safe and can be called from any thread.

Example: import pypisoundmicro as psm

    psm.init()