Getting a Neato XV-11 Lidar Working on the Q

In several threads I posted about issues with Bridge Latency, Serial1 vs using @KurtE's Serial3, and @KurtE's PWM "analogWriteFrequency". This post brings that all together to show the results.

So in summary, I use Serial3 to collect data from the lidar and changed the PWM frequency to 4 khz which is more in line with what the original design was using. With those changes was able to get stable lidar readings to interface with streamlit to display the lidar readings:

A couple of comments and issues still remain:

BRIDGE LATENCY
To transfer the lidar data 4 arrays of 361 each I used vector tuples, i.e.,

struct {
	int angle[361];
	int flag[361];
	int quality[361];
	int range[361];
} lidar;
...
// Function returns a tuple of 4 vectors<int>
std::tuple<
    std::vector<int>, // angles
    std::vector<int>, // flags
    std::vector<int>, // qualities
    std::vector<int>  // ranges
> get_range() 
{
    // Convert arrays to vectors
    std::vector<int> angles(lidar.angle, lidar.angle + 361);
    std::vector<int> flags(lidar.flag, lidar.flag + 361);
    std::vector<int> qualities(lidar.quality, lidar.quality + 361);
    std::vector<int> ranges(lidar.range, lidar.range + 361);

    // Return as tuple
    return std::make_tuple(angles, flags, qualities, ranges);
}

Unfortunately, the latency of transfer that much data through the bridge.call... takes between 245 and 250ms.

That brings up using SPI3 to transfer data faster. This was tested using using SPIDEV and uv to build the python app. Unfortunately, do not know how to incorporate a python script using uv link to AppLab. @ptillisch / @KurtE any ideas how this can be accomplished?

Serial Output
@ptillisch - one thing I noticed when using AppLap and serial output, even though I am specifying BD as 115200 I am only seeing 9600 as the selected BD?

Other issue is if the Arduino Team would be amiable to incorporating PRs for Serial3 and analogWriteFrequency?

In case anyone is interested on how to do any of this I am attaching a zip of the whole Lidar app:
XV_11_Lidar.zip (15.6 KB)

Cool project @Merlin513. Thanks for sharing!

The situation has improved since the time of the discussion in that forum topic due to the introduction of the custom Bricks feature:

You can now easily create Bricks which use a dedicated Docker container. So you could use a dedicated Docker container that provides all the dependencies of the Spidev Python package, then do the SPI communication from that container.

There are some fairly complex things that would need to be sorted out:

  • Find or create a Docker image that meets the requirements for the container
  • Configure the container so that it has access to the SPI device hardware
  • Create an interface for the container (unless you find an existing Spidev container that already provides an interface)

There is a draft version of the custom Bricks documentation here:

https://github.com/arduino/docs-content/blob/app-lab-custom-bricks-documentation/content/software/app-lab/5.bricks/3.custom-bricks/custom-bricks.md

Note that the brick_compose.yaml file in the custom Brick is a Docker compose file, so the documentation provided by Docker will also be applicable:

If you do end up making a custom Docker image, note that (at least currently), you must develop this separately from the App project, only referencing the image from the custom Brick. You might expect to be able to put the source for the image in the custom Brick and have Arduino App Lab handle it automagically, but unfortunately this is not supported. The "gotcha" is that it will appear to do so initially, but then you will run into a confusing situation where changes you make to the image source don't have any effect on the behavior of the Brick, due to the fact that Arduino App Lab/Arduino App CLI doesn't rebuild the container as needed (arduino/arduino-app-cli#389).

Here are some examples of custom Bricks that use a dedicated container:

Thanks @ptillisch - this is going to take me a while to absorb. and ps:

easily

is relative :) :rofl:

Haha, yes that was not the best wording. What I meant is that previously there was no formal support for creating your own Bricks, and so you would essentially need to "hack" one into the system. We now have a formal framework explicitly provided to support the creation of Bricks by users.

In the case where a custom Brick only contains Python code, such as these:

It is actually quite easy. However, things can get a lot more complex when you also have a container component in the Brick. The complexity will vary depending on:

  • Is a suitable premade image available?
  • Do you need to do any special configuration of the container (e.g., giving it access to system devices)?
  • Do you already have a familiarity with images, containers, and Docker Compose?
  • The interface provided by the container.

In this example:

The Brick uses a premade image, which doesn't require any special container configuration, and provides an easy to use interface. So implementing this brick was quite simple. However, that Brick is intended only as a simple demonstration, not as a real project. I think that the demand of a real project will tend to result in more complexity.

cores: unoq: Maybe add Serial3 by KurtE ยท Pull Request #487 ยท arduino/ArduinoCore-zephyr

I marked it as ready to review. The one thing I wish is, that we could reduce how much memory is used by some of these devices. For example I believe the Arduino object for Serial objects takes somewhere around 180 bytes per. The Portenta C33 has 5...
Wondering how hard it would be to either allocate the memory for RX/TX buffers later or the whole object only if someone calls SerialX.begin() on an object the Arduino object is created...
But...

Working on the PWM frequency code, but going slow, my paws just are not working very fast,

Pushed up draft PR for the PWM
core: analog: add analogWriteFrequency by KurtE ยท Pull Request #493 ยท arduino/ArduinoCore-zephyr

@ptillisch
Went through the links and I think (big caveat until I try it) understand what has to be done but what I am getting totally confused on is what to do with with dockerfile that is necessary to pull in python-spidev, i.e., examples pull in existing image but no example on config necessary or how to setup the containers.

More specifically.

  1. the readme for creating a brick show a structure:
my-app/
โ”œโ”€โ”€ app.yaml
โ”œโ”€โ”€ python/
โ”‚   โ””โ”€โ”€ main.py
โ””โ”€โ”€ bricks/
    โ””โ”€โ”€ my_custom_brick/            # The Brick ID and Python package name
        โ”œโ”€โ”€ __init__.py             # Your Python logic
        โ”œโ”€โ”€ brick_config.yaml       # Brick metadata (ID, name, description)
        โ”œโ”€โ”€ brick_compose.yaml      # (Optional) Docker Compose configuration
        โ”œโ”€โ”€ requirements.txt        # (Optional) Python dependencies
        โ”œโ”€โ”€ docs/                   # (Optional) Brick documentation
        โ”‚   โ””โ”€โ”€ API.md
        โ””โ”€โ”€ examples/               # (Optional) Usage examples
            โ”œโ”€โ”€ 01_basic.py
            โ””โ”€โ”€ 02_advanced.py

but looking does not show how or where to setup a image that needs to be pulled in. If I look at app-brick-py there is this structure:

where apps are located in src/arduino and containers and in containers an example for:

So question is how is container structure set up for the custom app? An how much of this do I need?

# SPDX-FileCopyrightText: Copyright (C) Arduino s.r.l. and/or its affiliated companies
#
# SPDX-License-Identifier: MPL-2.0

ARG REGISTRY
ARG BASE_IMAGE_VERSION=latest
FROM ${REGISTRY}app-bricks/python-base:${BASE_IMAGE_VERSION}

# Copy the Streamlit configuration file with customized settings in home app shared directory
COPY ./streamlit/config.toml /home/app/.streamlit/config.toml

COPY ./*.sh /
COPY ./arduino*.whl /app/
RUN bash -c 'WHL_FILES=(/app/*.whl) && uv pip install --system --no-cache-dir "${WHL_FILES[@]}"[all]'; \
    rm /app/*.whl; \    
    # fix permissions for /home/app
    chown arduino:arduino -R /home/app; \
    chmod 777 -R /home/app; \
    # ensure permissions for /run.sh
    chmod 755 /*.sh; \
    # trim dependencies
    find /usr/local/lib/python3.13/site-packages -type d -name "tests" -exec rm -r {} +; \
    # precompile python files to .pyc to speed up startup time
    python -m compileall /usr/local/bin; \
    python -m compileall /usr/local/lib

USER arduino

WORKDIR /app

ENV HOME=/home/app
ENV USER=arduino

ENTRYPOINT [ "/run.sh" ]

Poking around found this: Brick Development Guide | arduino/app-bricks-py | DeepWiki which seems to indicate that the structure should look like

containers/<brick-name>/
|--- Dockerfile
|---- ci.json

my-app/
โ”œโ”€โ”€ app.yaml
โ”œโ”€โ”€ python/
โ”‚   โ””โ”€โ”€ main.py
โ””โ”€โ”€ bricks/
    โ””โ”€โ”€ my_custom_brick/            # The Brick ID and Python package name
        โ”œโ”€โ”€ __init__.py             # Your Python logic
        โ”œโ”€โ”€ brick_config.yaml       # Brick metadata (ID, name, description)
        โ”œโ”€โ”€ brick_compose.yaml      # (Optional) Docker Compose configuration
        โ”œโ”€โ”€ requirements.txt        # (Optional) Python dependencies
        โ”œโ”€โ”€ docs/                   # (Optional) Brick documentation
        โ”‚   โ””โ”€โ”€ API.md
        โ””โ”€โ”€ examples/               # (Optional) Usage examples
            โ”œโ”€โ”€ 01_basic.py
            โ””โ”€โ”€ 02_advanced.py

I think. Anyway asking AI for best docker file

# Base image: Python slim for smaller footprint
FROM python:3.11-slim

# Metadata (optional but good practice for Arduino Bricks)
LABEL maintainer="Your Name <you@example.com>"
LABEL description="Custom Arduino App Lab Brick with SPI support via spidev"

# Environment settings for Python
ENV PYTHONDONTWRITEBYTECODE=1
ENV PYTHONUNBUFFERED=1

# Install system dependencies for spidev and general builds
RUN apt-get update && apt-get install -y --no-install-recommends \
    python3-dev \
    build-essential \
    linux-headers-generic \
    && rm -rf /var/lib/apt/lists/*

# Set working directory inside container
WORKDIR /app

# Copy Brick source code into container
COPY . /app

# Install Python dependencies
# If you have a requirements.txt, include spidev there
RUN pip install --no-cache-dir spidev \
    && if [ -f requirements.txt ]; then pip install --no-cache-dir -r requirements.txt; fi

# Expose port if your Brick runs a service (optional)
EXPOSE 8080

# Default command to run the Brick
CMD ["python", "main.py"]

and ci.json

{
  "name": "my-spi-brick",
  "version": "1.0.0",
  "description": "Custom Brick with SPI support",
  "docker": {
    "context": ".",
    "dockerfile": "Dockerfile"
  }
}

Suggestions?

PS. Know this is confusing but....

EDIT: or more like this
app/
โ”œโ”€โ”€ containers/
โ”‚ โ”œโ”€โ”€ my-brick/
โ”‚ โ”‚ โ”œโ”€โ”€ Dockerfile
โ”‚ โ”‚ โ”œโ”€โ”€ ci.json
โ”‚ โ”‚ โ”œโ”€โ”€ main.py
โ”‚ โ”‚ โ”œโ”€โ”€ requirements.txt (optional)
โ”‚ โ”‚ โ”œโ”€โ”€ my_brick/
โ”‚ โ”‚ โ”‚ โ”œโ”€โ”€ init.py
โ”‚ โ”‚ โ”‚ โ”œโ”€โ”€ brick.py
โ”‚ โ”‚ โ”‚ โ”œโ”€โ”€ handlers.py (optional)
โ”‚ โ”‚ โ”‚ โ”œโ”€โ”€ utils.py (optional)
โ”‚ โ”‚ โ””โ”€โ”€ ...
โ”‚ โ””โ”€โ”€ other-bricks...
โ””โ”€โ”€ ...

Note the warning from my previous post:

The Arduino custom Brick framework doesn't have real support for managing containers from image source files. For this reason, there isn't any specific structure you must follow for the source files. You can put them wherever you like. It can be bundled with the App, or stored outside the App. You don't even need to develop or store it on the UNO Q if you publish the image it on an image registry, such as Docker Hub.

The trap is that Arduino App Lab/Arduino App CLI will build the container from the image source files the first time you start the App. So it will make you think that building the container is handled automagically, just as all the other container management for Apps. However, if you then modify the image source and then start the App again, you will find that the modifications didn't have any effect. This is because the container that was built the first time you started the App will just keep being used. I provide a demonstration of this situation here.

Keep in mind this is AI generated, likely without any human validation whatsoever. It might contain good information, but also might contain hallucinations. It seems to be based on the content of the arduino/app-bricks-py repository of the official built-in Bricks and the arduino Python package. It is worth considering the content in that repository as a reference, as it contains the source code of Bricks that use the full capabilities of the framework. However, even though official bricks do use the same general framework as custom Bricks, not everything in that repository is necessarily perfectly applicable to custom Bricks.

I would recommend using the draft of the official human written and validated documentation as your primary reference:

https://github.com/arduino/docs-content/blob/app-lab-custom-bricks-documentation/content/software/app-lab/5.bricks/3.custom-bricks/custom-bricks.md

This is an example of something that isn't very applicable outside the context of the arduino/app-bricks-py repository. The Arduino App/Bricks framework doesn't know or care anything about a file named ci.json. This is instead an arbitrary system created for the release infrastructure of the arduino/app-bricks-py repository:

If you were to set up similar infrastructure for publishing your own custom images, then the file would be used, but otherwise it is just unused confusing clutter in your project.

@ptillisch
Thanks for the quick response. Think its the muddy water is getting a little clearer. I think

PS> I always that AI stuff with a grain of salt. Sometimes it helps as a starting point :slight_smile:

Once you figure it out, I will get back to seeing if I can get a brick to be able to talk to a joystick that is connected over bluetooth...

So far they hurt when I drop them on my :foot: :laughing:

First test of trying to get a brick working.

Found that docker hub has spidev image that I tried but could it couldn't find spidev.

Step 1. install docker image
docker pull aesch1/spidev
see: aesch1/spidev - Docker Image

not sure I set it up right but here is the whole app if anyone wants to take a look
spi3dev.zip (7.5 KB)

Next up try to build my own docker image, but have some other things to do now.

@KurtE - @ptillisch

Not having much luck with getting a docker image working in a brick.

First step was working on creating a docker file for spidev which actually worked fairly well but there are a few questions on proper config for bricks.

For instance did find that I can actually run our spi3dev test setup in the other thread without using uv. For this config to work:

  1. Directory tree structure
arduino@arduinoQ4:~/spiBridge_image$ tree -L2
.
โ”œโ”€โ”€ app
โ”‚   โ””โ”€โ”€ main.py
โ””โ”€โ”€ Dockerfile
  1. Create a Dockerfile with no entry point:
# Use an official Python runtime as a parent image
FROM python:3.13-slim

# Install system dependencies needed to build spidev and other C-extensions
RUN apt-get update && apt-get install -y --no-install-recommends \
    build-essential \
    python3-dev \
    && rm -rf /var/lib/apt/lists/*

# Set the working directory in the container
WORKDIR /app

# Upgrade pip and install spidev (and any other requirements you might add)
RUN pip install --no-cache-dir --upgrade pip && \
    pip install --no-cache-dir spidev

# (Optional) Copy a generic local directory into the container
COPY app/ .

# No ENTRYPOINT or CMD specified.
# This allows you to override and run any Python script later.
  1. main.py
import spidev
import time
import sys
import struct

def bytes_to_float_array(b, byte_order='little'):
    if len(b) % 4 != 0:
        raise ValueError("Byte length must be a multiple of 4")

    fmt = ('<' if byte_order == 'little' else '>') + f'{len(b)//4}f'
    return list(struct.unpack(fmt, b))

def init_spi(bus=0, device=0, max_speed_hz=5000000, mode=0):
    """
    Initialize and return an SPI connection.
    """
    spi = spidev.SpiDev()
    try:
        spi.open_path("/dev/spidev0.0")  # Open SPI bus and device
        spi.max_speed_hz = max_speed_hz
        spi.mode = mode  # SPI mode (0, 1, 2, or 3)
        spi.bits_per_word = 8
        print(f"SPI initialized: bus={bus}, device={device}, speed={max_speed_hz}Hz, mode={mode}")
    except FileNotFoundError:
        sys.exit("Error: SPI device not found. Enable SPI in raspi-config or check /dev/spidevX.Y")
    except PermissionError:
        sys.exit("Error: Permission denied. Try running with sudo.")
    return spi

def continuous_read(spi, read_command, bytes_to_read=1024, delay=0.5):
    """
    Continuously read a fixed number of bytes from an SPI device.
    :param spi: spidev.SpiDev object
    :param read_command: list of bytes to send before reading (e.g., [0x0B, 0x00, 0x00, 0x00])
    :param bytes_to_read: number of bytes to read from the device
    :param delay: delay between reads in seconds
    """
    try:
        while True:
            # Send read command + dummy bytes to receive data
            #spi.writebytes(read_command)  # Full-duplex transfer
            #data = spi.readbytes(1024)
            data = spi.xfer2(read_command+ [0x00] * bytes_to_read)
            print(f"Read {len(data)} bytes: {data[:16]} ...")  # Show first 16 bytes for brevity
            raw_bytes = bytes(data[:720])

            count = len(raw_bytes) // 4
            fmt = '<' + str(count) + 'f'

            floats = struct.unpack(fmt, raw_bytes)
            print(", ".join(f"{v:.4f}" for v in floats))
            print("\n")
            time.sleep(delay)
    except KeyboardInterrupt:
        print("\nStopping continuous read.")
    finally:
        spi.close()

if __name__ == "__main__":
    # Example: SPI bus 0, device 0
    spi = init_spi(bus=0, device=0, max_speed_hz=2000000, mode=0)

    # Example read command for a generic SPI device
    # Replace with your device's datasheet command
    # For SPI flash: 0x0B (Fast Read) + 3-byte address + 1 dummy byte
    READ_CMD = [0x0B, 0x00, 0x00, 0x00, 0x00]  # Example: start at address 0x000000

    continuous_read(spi, READ_CMD, bytes_to_read=1024, delay=0.5)
  1. sketch.ino

#include <stdint.h>
#include <stddef.h>
#include <string.h>

#include "Arduino_RouterBridge.h"
#include "SPIPeripheral.h"


#define num_vals 180

SPIPeripheralClass<1024> spi;

void floats_to_bytes(const float* src, size_t float_count, uint8_t* dst) {
    if (!src || !dst || float_count == 0) return;
    memcpy(dst, src, float_count * sizeof(float));
}

float sensorValues[num_vals];
uint8_t buffer[12];
long randNumber ;

void get_sensor_data() {
    randomSeed(analogRead(A0));

    for(uint8_t i; i < num_vals; i++) {
      randNumber  = random(300);
      sensorValues[i] = float(randNumber) /10.0;
    }
  
}
void setup() {
  Monitor.begin();
  delay(2000);
  Monitor.println("Begin SPI3 Test....");
  spi.begin();
}

void loop() {
  uint8_t bytes[num_vals * sizeof(float)];
  
  spi.depopulate(*buffer, 12);
  for(uint8_t i = 0; i < 12; i++) {
    Monitor.print(buffer[i], HEX); Monitor.print(", ");
  } Monitor.println();

  if(buffer[0] == 0x0B) {
    // Convert float array โ†’ bytes
    get_sensor_data();
    floats_to_bytes(sensorValues, num_vals, bytes);

    spi.populate(bytes, num_vals * sizeof(float) );
    spi.ready();
  }

}
  1. and you would run it:
docker run --rm -it --device /dev/spidev0.0 spibridge python3 main.py

Screen output:

Guess I have the following questions:

  1. whats the correct COPY command do I need for the brick
  2. Not sure about the correct WORKDIR
  3. and similarly whats the ENTRYPOINT do I need for the brick. For instance in the pingpong image ( cks/docker/ping_pong/Dockerfile at master ยท ViktorUJ/cks ) the dockerfile looks like
FROM golang:alpine AS builder

RUN apk update && apk add --no-cache git
WORKDIR $GOPATH/src/mypackage/myapp/
COPY app/ .
RUN go mod tidy
RUN go build -ldflags="-w -s" -o app app.go

FROM scratch
COPY --from=builder /go/src/mypackage/myapp/app app
ENTRYPOINT ["/app"]

The main issue when using the image in the brick is that it errors out in__init__.py that it can not find module spidev

@KurtE - @ptillisch
Too much reading but think I realized the missing piece:

Docker Containers (brick_compose.yaml)
If your Custom Brick requires external services, you can define them using a Docker Compose file. The system will automatically pull and run these containers alongside your App.

services:
  my_service:
    image: custom_registry/my_service:latest
    ports:
      - "8080:8080"
Important: Docker images specified in brick_compose.yaml must be publicly accessible, as App Lab does not currently support private registries for Custom Bricks.

Now have to try and figure out how to do that.

Yep - I was trying to do something similar several days ago, with the trying to get a brick to be able to talk to a joystick device

Gets more interesting. I just pushed it up to dockerhub - mjs513:

changed compose file to:

services:
  spi3dev_service:
    # App Lab will automatically look for the Dockerfile in the same folder
    image: mjs513/spi3bridge
    
    # Map the UNO Q SPI hardware line into the container
    devices:
      - "/dev/spidev0.0:/dev/spidev0.0"
    
    # Bypass standard kernel blocks for raw hardware access
    privileged: true
    
    # Mount the local folder into the container's working directory
    volumes:
      - .:/app
      
    working_dir: /app

    ports:
      - "8080:8080"

    #command: python3 app/main.py
    restart: unless-stopped

and a init.py


from arduino.app_utils import brick
import struct
import spidev

@brick
def init_spi(bus=0, device=0, max_speed_hz=5000000, mode=0):
    spi = spidev.SpiDev()
    spi.open(bus, device)
    spi.max_speed_hz = max_speed_hz
    spi.mode = mode
    spi.bits_per_word = 8
    return spi

def read_spi(read_command, bytes_to_read=1024):
    spi = init_spi()
    try:
        data = spi.xfer2(read_command + [0x00] * bytes_to_read)
        raw_bytes = bytes(data[:720])
        count = len(raw_bytes) // 4
        fmt = '<' + str(count) + 'f'
        floats = struct.unpack(fmt, raw_bytes)
        return list(floats)
    finally:
        spi.close()

and still get can't find module spidev. Maybe something with dockerfile config.

Also checked it this way:

arduino@arduinoQ4:~/ArduinoApps$ docker inspect mjs513/spi3bridge:latest
[
    {
        "Id": "sha256:7fe9ceb122801e598b0b2dd67b1e53a7610d3bfe649ff9a0146ec74dd3a25983",
        "RepoTags": [
            "mjs513/spi3bridge:latest"
        ],
        "RepoDigests": [
            "mjs513/spi3bridge@sha256:44efd0d353654797fcfb97190fcdb8642ffa2e115c2a58fc0214288df6b73332"
        ],
        "Parent": "",
        "Comment": "buildkit.dockerfile.v0",
        "Created": "2026-05-29T20:10:14.599361461Z",
        "DockerVersion": "",
        "Author": "",
        "Config": {
            "Hostname": "",
            "Domainname": "",
            "User": "",
            "AttachStdin": false,
            "AttachStdout": false,
            "AttachStderr": false,
            "Tty": false,
            "OpenStdin": false,
            "StdinOnce": false,
            "Env": [
                "PATH=/usr/local/bin:/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin",
                "LANG=C.UTF-8",
                "GPG_KEY=A035C8C19219BA821ECEA86B64E628F8D684696D",
                "PYTHON_VERSION=3.11.15",
                "PYTHON_SHA256=272179ddd9a2e41a0fc8e42e33dfbdca0b3711aa5abf372d3f2d51543d09b625"
            ],
            "Cmd": [
                "python3"
            ],
            "Image": "",
            "Volumes": null,
            "WorkingDir": "/app",
            "Entrypoint": null,
            "OnBuild": null,
            "Labels": null
        },
        "Architecture": "arm64",
        "Variant": "v8",
        "Os": "linux",
        "Size": 558085533,
        "GraphDriver": {
            "Data": {
                "LowerDir": "/var/lib/docker/overlay2/lazxtbu6ru7ad4z4q6y351w46/diff:/var/lib/docker/overlay2/mknw9q95p04hk4a3db1diq2vq/diff:/var/lib/docker/overlay2/ggy9221w8g62q67h84fb1idlw/diff:/var/lib/docker/overlay2/4cb9ca7a3f79d0fe0dd5e0391c69326df21e7070e9ac9c8f4c01af8ac2d23729/diff:/var/lib/docker/overlay2/e10150153a513a0f5f75c3074b930344d38c8b6d5f2620d6a130ec5717e0ef8d/diff:/var/lib/docker/overlay2/cdc747610300130d6103d6c4dc4560b77b7a1d84c910e612ffd90519bb7e7634/diff:/var/lib/docker/overlay2/7a827bc03fda2016761677272e62478e54f7d2004438a8f58e2cdc1086eaa759/diff",
                "MergedDir": "/var/lib/docker/overlay2/97n205taa870istd3pidlsj5k/merged",
                "UpperDir": "/var/lib/docker/overlay2/97n205taa870istd3pidlsj5k/diff",
                "WorkDir": "/var/lib/docker/overlay2/97n205taa870istd3pidlsj5k/work"
            },
            "Name": "overlay2"
        },
        "RootFS": {
            "Type": "layers",
            "Layers": [
                "sha256:0f0c47d76d9eb2be2ad0e5d15813906c7c4d32fa5a098b4a456208142516bab4",
                "sha256:a191220d475c1210a4cca50a1323e8e20671faf211a6ccdbc6c0aafc11de41ae",
                "sha256:94aa29643a2c3be04ea6dd113bd4800e99821eabb6269cbdb4cad53d483de8c9",
                "sha256:adc5ed0e159142014f70e3b0410ef230dcf4564bf877adf4fe1ca92cd5701193",
                "sha256:632556179fa5c572c91db67962cc0262b60d0e646ccb580f316b357810a20293",
                "sha256:3b703f79a170cadc9fbba4a346ece68b8ae4b093dbbe16807951fb2bf961eff0",
                "sha256:fc4b7dd5f74fcd410d63f4420d6e9e750bab87fdae14cbc86fc5f46d28de9e48",
                "sha256:d8d3f9689d42bb8bb863a620ce4ab7f9d05b3c2547f27e29e1eaf6be1989a258"
            ]
        },
        "Metadata": {
            "LastTagTime": "2026-05-29T23:35:24.523513331Z"
        }
    }
]
arduino@arduinoQ4:~/ArduinoApps$ docker history mjs513/spi3bridge:latest
IMAGE          CREATED       CREATED BY                                      SIZE      COMMENT
7fe9ceb12280   4 hours ago   COPY . /app/ # buildkit                         800B      buildkit.dockerfile.v0
<missing>      4 hours ago   WORKDIR /app                                    0B        buildkit.dockerfile.v0
<missing>      4 hours ago   RUN /bin/sh -c pip install spidev # buildkit    12.4MB    buildkit.dockerfile.v0
<missing>      4 hours ago   RUN /bin/sh -c apt-get update && apt-get insโ€ฆ   396MB     buildkit.dockerfile.v0
<missing>      10 days ago   CMD ["python3"]                                 0B        buildkit.dockerfile.v0
<missing>      10 days ago   RUN /bin/sh -c set -eux;  for src in idle3 pโ€ฆ   36B       buildkit.dockerfile.v0
<missing>      10 days ago   RUN /bin/sh -c set -eux;   savedAptMark="$(aโ€ฆ   45.3MB    buildkit.dockerfile.v0
<missing>      10 days ago   ENV PYTHON_SHA256=272179ddd9a2e41a0fc8e42e33โ€ฆ   0B        buildkit.dockerfile.v0
<missing>      10 days ago   ENV PYTHON_VERSION=3.11.15                      0B        buildkit.dockerfile.v0
<missing>      10 days ago   ENV GPG_KEY=A035C8C19219BA821ECEA86B64E628F8โ€ฆ   0B        buildkit.dockerfile.v0
<missing>      10 days ago   RUN /bin/sh -c set -eux;  apt-get update;  aโ€ฆ   3.86MB    buildkit.dockerfile.v0
<missing>      10 days ago   ENV LANG=C.UTF-8                                0B        buildkit.dockerfile.v0
<missing>      10 days ago   ENV PATH=/usr/local/bin:/usr/local/sbin:/usrโ€ฆ   0B        buildkit.dockerfile.v0
<missing>      12 days ago   # debian.sh --arch 'arm64' out/ 'trixie' '@1โ€ฆ   100MB     debuerreotype 0.17
arduino@arduinoQ4:~/ArduinoApps$ docker run -it --rm mjs513/spi3bridge:latest /bin/bash
root@60531c9c0fd6:/app#
root@60531c9c0fd6:/app# import spidev
bash: import: command not found
root@60531c9c0fd6:/app# python3
Python 3.11.15 (main, May 19 2026, 23:56:34) [GCC 14.2.0] on linux
Type "help", "copyright", "credits" or "license" for more information.
>>> import spidev
>>> quit
Use quit() or Ctrl-D (i.e. EOF) to exit
>>>
root@60531c9c0fd6:/app#

so it does look like it has spidev in the image.

It is essential to understand that the Python package of the custom Brick is not running inside your container. It is instead running in the same container as the python/main.py script of the App.

So if you try to import spidev from the Python package of your custom Brick, it is normal and expected that it will not find that package. The reason is that the package is not installed in the container in which the Python package of your custom Brick runs.

You must instead create an application that runs inside your container, and provides an interface for communication with the App code that is running in a separate container.

Here is an App that demonstrates how such a thing can be done using the Flask web application framework:

custom-brick-with-container.zip (3.9 KB)

I choose Flask simply because it seemed like an easy way to create an interface for the container. You can use any solution you like to create the interface for your container. The demonstration project above is based on this nice tutorial:

In order to make my demonstration as simple as possible, I removed the unnecessary complexity of the database stuff that is present the container application in that tutorial.

To further simplify my demonstration, I didn't add a Python package to my custom Brick. Instead, the App's Python script simply communicates directly with the interface of the container:

print(requests.get("http://flask:5000/hello").text)

However, this could just as well have been done using a Python package in the custom Brick.

I have gone through your sample code and I have it running and think I understand what is going on at least when you are working with flask. With that said I am struggling when trying to understand it when I building an interface using spidev.

In my latest iteration I followed your example. I created a app.py that looks like

import spidev
import struct

class SPIBridge:
    def __init__(self, bus=0, device=0, max_speed_hz=5000000, mode=0, bits_per_word=8):
        self.bus = bus
        self.device = device
        self.max_speed_hz = max_speed_hz
        self.mode = mode
        self.bits_per_word = bits_per_word
        self.spi = None

    # -----------------------------
    # Initialization
    # -----------------------------
    def init_spi(self):
        spi = spidev.SpiDev()
        spi.open(self.bus, self.device)
        spi.max_speed_hz = self.max_speed_hz
        spi.mode = self.mode
        spi.bits_per_word = self.bits_per_word
        self.spi = spi
        return spi

    # -----------------------------
    # Reconfiguration
    # -----------------------------
    def set_speed(self, hz):
        self.max_speed_hz = hz
        if self.spi:
            self.spi.max_speed_hz = hz

    def set_mode(self, mode):
        self.mode = mode
        if self.spi:
            self.spi.mode = mode

    def set_bits(self, bits):
        self.bits_per_word = bits
        if self.spi:
            self.spi.bits_per_word = bits

    # -----------------------------
    # Core read functions
    # -----------------------------
    def read_bytes(self, read_command, bytes_to_read=1024):
        if self.spi is None:
            raise RuntimeError("SPI not initialized. Call init_spi() first.")

        data = self.spi.xfer2(read_command + [0x00] * bytes_to_read)
        return bytes(data)

    def read_floats(self, read_command, bytes_to_read=1024, float_count=None, byte_order='little'):
        raw = self.read_bytes(read_command, bytes_to_read)

        if float_count is None:
            if len(raw) % 4 != 0:
                raise ValueError("Raw byte length is not divisible by 4")
            float_count = len(raw) // 4

        raw_slice = raw[:float_count * 4]
        return self.bytes_to_float_array(raw_slice, byte_order)

    # -----------------------------
    # Utility
    # -----------------------------
    @staticmethod
    def bytes_to_float_array(b, byte_order='little'):
        if len(b) % 4 != 0:
            raise ValueError("Byte length must be a multiple of 4")

        fmt = ('<' if byte_order == 'little' else '>') + f'{len(b)//4}f'
        return list(struct.unpack(fmt, b))

    # -----------------------------
    # Cleanup
    # -----------------------------
    def close(self):
        if self.spi:
            self.spi.close()
            self.spi = None

with a dockerfile that looks like

FROM python:3.13-slim

RUN apt-get update && apt-get install -y python3-dev python3-pip && rm -rf /var/lib/apt/lists/*
RUN pip install spidev

WORKDIR /app
COPY . /app/

#CMD ["python3", "app.py"]

So the what I am struggling with is how to communicate with the App code. Or is it still not running in a separate container. That compose file looks like

services:
  spi3bridge:
    # App Lab will automatically look for the Dockerfile in the same folder
    build:
      context: .
    
    # Map the UNO Q SPI hardware line into the container
    devices:
      - "/dev/spidev0.0:/dev/spidev0.0"
    
    # Bypass standard kernel blocks for raw hardware access
    privileged: true
    
    # Mount the local folder into the container's working directory
    volumes:
      - .:/app
      
    working_dir: /app

    #command: python3 app/main.py
    restart: unless-stopped

so basically I am totally confused on how to do this. Please remember I am not that familar with python.

@ptillish @Merlin513 I need to go through your example as well.
I was trying to setup a brick to maybe talk to Joystick. I don't believe that the /dev/input/js* are seen within the default container. I have a version that runs outside of the default python container where I start it up and manually have an Arduino sketch running, that talks through the Bridge.

SO need something like that? except that not talk using bridge but through some other mechanism... ?

If anything in the demonstration App I provided is unclear, feel free to ask.

For code I share for the purpose of education, I would normally add some comments, and perhaps take a more "self-documenting" approach in the code. I actually created this App to supplement a bug report submitted to the Arduino App CLI developers. The developers of that project are already fluent in the subject matter, so I instead kept it very concise.