• Welcome to ASR. There are many reviews of audio hardware and expert members to help answer your questions. Click here to have your audio equipment measured for free!

Low Budget 8ch DSP/Streamer/Player/Preamp using Camilla DSP and Volumio

PeteSahat

Member
Joined
Dec 28, 2023
Messages
34
Likes
25
Hi!

Volumio OS is probably one of the most convenient pieces of software for playing music, and even the free version offers quite a few features through its plugins.
However, for my preamp/streamer project, I naturally need the ability to play other audio sources.

So I've "downgraded" Volumio OS to being one of several sources. An analog source can now be selected in addition to the usual sources via the I2S ADC. In the same way, it should also be possible to implement an S/PDIF or Bluetooth input. In theory, Bluetooth output should also be possible this way.

The prerequisite for this is CamillaDSP as the "control center," where source selection and routing are handled via presets.
An important point: I'm not using Volumio's built-in Fusion DSP plugin, but rather a "real" CamillaDSP installation running in parallel on the Pi.
Volumio no longer sends the audio stream directly to the physical playback hardware. Instead, it writes the stream to the ALSA loopback device.

CamillaDSP reads this stream from the loopback capture device and then takes care of the further signal processing and output to the playback hardware.

1789778035998.png


For the D/A converter, I'm using the new WONDOM 8-channel USB DAC (https://store.sure-electronics.com/product/854).
There's nothing comparable available at this price. Multichannel DACs are pretty rare to begin with, and they're usually expensive.

1789778077123.png


For the ADC, I'm also using the PCM1822 from WONDOM (https://store.sure-electronics.com/product/813).
The ADC even offers balanced inputs, and since it operates as a slave, it doesn't require a master clock either, which simplifies the wiring.

1789781026035.png


With a selector switch, you can connect as many analog sources to the Pi as you like.
And with an I2S selector, the whole setup can also be cascaded, for example to accommodate additional digital sources. The possibilities are endless!
This makes it very easy to build a fully-fledged preamp/streamer/receiver with DSP for crossover management, room correction, and EQ.


Here is the installation guide:

Volumio + CamillaDSP Installation

This guide describes how to install CamillaDSP and CamillaGUI on Volumio and route the Volumio audio signal through ALSA Loopback.
Audio output is handled by the aforementioned USB DAC.

Prerequisite: The Linux username is volumio. If you use a different username, every occurrence of

/home/volumio

must be adjusted accordingly.

### 1. Flash Volumio

Flash Volumio onto the SD card.

### 2. Resize the Volumio partition

Use GParted or another partitioning tool to enlarge the volumio_data partition:

1. Select the partition:volumio_data
2. Expand the partition to use all available storage space.

### 3. Set up Volumio

1. Start Volumio and connect to the Volumio hotspot via Wi-Fi. The setup page should then open automatically in your browser.
2. Enter your network details and complete the setup. The Pi will then reboot.
3. Wait for the Pi to reconnect to the network.
4. Open: http://your-pi-ip/dev and enable SSH.
5. Connect to the Pi via SSH, either using PowerShell or, more conveniently, an SSH client. I use MUON on Linux.

ssh volumio@YOUR-PI-IP The password is volumio

### 4. Install CamillaDSP and its services, and create the Loopback device

1. Copy the following script and save it as setup.sh


Code:
#!/bin/bash

set -e

EFFECTIVE_USER="volumio"

INSTALL_ROOT="/home/$EFFECTIVE_USER"
CAMILLADSP_DIR="$INSTALL_ROOT/camilladsp"
CAMILLADSP_BINARY="$CAMILLADSP_DIR/camilladsp"
CAMILLAGUI_DIR="$INSTALL_ROOT/camillagui_backend"

CAMILLADSP_API="https://api.github.com/repos/HEnquist/camilladsp/releases/latest"
CAMILLAGUI_API="https://api.github.com/repos/HEnquist/camillagui-backend/releases/latest"

CAMILLADSP_ASSET="camilladsp-linux-armv7.tar.gz"
CAMILLAGUI_ASSET="bundle_linux_armv7.tar.gz"


log() {
echo "$(date '+%Y-%m-%d %H:%M:%S') - $1"
}


mark_done() {
echo "$1 completed"
}


install_dependencies() {

log "Installing dependencies..."

sudo apt update

sudo apt install -y \
alsa-utils \
libasound2 \
curl \
wget \
ca-certificates

}


prepare_directories() {

log "Preparing installation directories..."

sudo mkdir -p \
"$CAMILLADSP_DIR" \
"$CAMILLADSP_DIR/coeffs" \
"$CAMILLADSP_DIR/configs"

sudo chown -R \
"$EFFECTIVE_USER:$EFFECTIVE_USER" \
"$CAMILLADSP_DIR"

}


install_loopback() {

log "Preparing ALSA loopback..."

echo "snd-aloop" | sudo tee \
/etc/modules-load.d/snd-aloop.conf >/dev/null

sudo modprobe snd-aloop || true

}


get_latest_asset_url() {

local api_url="$1"
local asset_name="$2"

curl -fsSL \
-H "Accept: application/vnd.github+json" \
"$api_url" |
grep '"browser_download_url":' |
grep "$asset_name" |
head -n 1 |
cut -d '"' -f 4

}


get_latest_version() {

local api_url="$1"

curl -fsSL \
-H "Accept: application/vnd.github+json" \
"$api_url" |
grep '"tag_name":' |
head -n 1 |
cut -d '"' -f 4

}


install_camilladsp() {

log "Installing latest CamillaDSP ARMv7 binary..."

local version
local download_url
local tmp_dir

version=$(get_latest_version "$CAMILLADSP_API")
download_url=$(get_latest_asset_url \
"$CAMILLADSP_API" \
"$CAMILLADSP_ASSET"
)

if [ -z "$download_url" ]; then
echo "ERROR: Could not find CamillaDSP ARMv7 release."
exit 1
fi

log "Latest CamillaDSP version: $version"

tmp_dir=$(mktemp -d)

log "Downloading CamillaDSP..."

sudo wget \
-q \
--show-progress \
"$download_url" \
-O "$tmp_dir/$CAMILLADSP_ASSET"

log "Installing CamillaDSP binary..."

sudo tar \
-xzf "$tmp_dir/$CAMILLADSP_ASSET" \
-C "$tmp_dir"

if [ ! -f "$tmp_dir/camilladsp" ]; then
echo "ERROR: CamillaDSP binary not found after extraction."
rm -rf "$tmp_dir"
exit 1
fi

sudo install \
-m 0755 \
"$tmp_dir/camilladsp" \
"$CAMILLADSP_BINARY"

sudo chown \
"$EFFECTIVE_USER:$EFFECTIVE_USER" \
"$CAMILLADSP_BINARY"

rm -rf "$tmp_dir"

log "CamillaDSP installed at:"
log "$CAMILLADSP_BINARY"

}


install_camilladsp_service() {

log "Installing CamillaDSP systemd service..."

cat <<EOF | sudo tee /etc/systemd/system/camilladsp.service >/dev/null

[Unit]
Description=CamillaDSP
After=network.target sound.target

[Service]
Type=simple

User=$EFFECTIVE_USER

WorkingDirectory=$CAMILLADSP_DIR

ExecStart=$CAMILLADSP_BINARY \
-s $CAMILLADSP_DIR/statefile.yml \
-w \
-g-40 \
-o $CAMILLADSP_DIR/camilladsp.log \
-p 1234

Restart=always
RestartSec=1

StandardOutput=journal
StandardError=journal

SyslogIdentifier=camilladsp

[Install]
WantedBy=multi-user.target

EOF

}


install_camillagui() {

log "Installing latest CamillaGUI backend..."

local version
local download_url
local tmp_dir

version=$(get_latest_version "$CAMILLAGUI_API")
download_url=$(get_latest_asset_url \
"$CAMILLAGUI_API" \
"$CAMILLAGUI_ASSET"
)

if [ -z "$download_url" ]; then
echo "ERROR: Could not find CamillaGUI ARMv7 release."
exit 1
fi

log "Latest CamillaGUI version: $version"

tmp_dir=$(mktemp -d)

log "Downloading CamillaGUI..."

sudo wget \
-q \
--show-progress \
"$download_url" \
-O "$tmp_dir/$CAMILLAGUI_ASSET"

log "Removing previous CamillaGUI installation..."

sudo rm -rf "$CAMILLAGUI_DIR"

log "Extracting CamillaGUI..."

sudo tar \
-xzf "$tmp_dir/$CAMILLAGUI_ASSET" \
-C "$INSTALL_ROOT"

rm -rf "$tmp_dir"

if [ ! -x "$CAMILLAGUI_DIR/camillagui_backend" ]; then
echo "ERROR: CamillaGUI backend not found after extraction."
exit 1
fi

sudo chown -R \
"$EFFECTIVE_USER:$EFFECTIVE_USER" \
"$CAMILLAGUI_DIR"

log "CamillaGUI installed at:"
log "$CAMILLAGUI_DIR"

log "Using CamillaGUI default configuration paths."

}


install_camillagui_service() {

log "Installing CamillaGUI systemd service..."

cat <<EOF | sudo tee /etc/systemd/system/camillagui.service >/dev/null

[Unit]
Description=CamillaDSP Backend and GUI
After=network.target camilladsp.service
Requires=camilladsp.service

[Service]
Type=simple

User=$EFFECTIVE_USER

WorkingDirectory=$CAMILLAGUI_DIR

ExecStart=$CAMILLAGUI_DIR/camillagui_backend

Restart=always
RestartSec=2

StandardOutput=journal
StandardError=journal

SyslogIdentifier=camillagui

[Install]
WantedBy=multi-user.target

EOF

}


enable_services() {

log "Enabling and starting services..."

sudo systemctl daemon-reload

sudo systemctl enable camilladsp.service
sudo systemctl enable camillagui.service

sudo systemctl restart camilladsp.service
sudo systemctl restart camillagui.service

}


show_status() {

log "Installation status:"

echo
sudo systemctl --no-pager --full status camilladsp.service || true

echo
sudo systemctl --no-pager --full status camillagui.service || true

echo
log "Listening ports:"

sudo ss -ltnp | grep -E ':1234|:5005' || true

echo
log "ALSA devices:"

aplay -l || true

}


###################################
# MAIN
###################################

log "Starting CamillaDSP installation on Volumio..."

install_dependencies

prepare_directories

install_loopback

install_camilladsp

install_camilladsp_service

install_camillagui

install_camillagui_service

enable_services

show_status

log "Installation complete."


2. Then copy the file to the Pi's home directory:
Code:
/home/volumio/

3. Make the file executable:
Code:
chmod +x setup.sh
4. Then run it:
Code:
sudo ./setup.sh

5. In the Volumio GUI, under Playback Options, select "Loopback" as the output device. Further down, set Mixer Type to "None". Volume control will be handled by CamillaDSP.
6. The CamillaGUI can now also be accessed in your browser at:
Code:
http://YOUR-PI-IP:5005/gui/index.html

7. In CamillaGUI, open the Devices section and enter the following settings exactly as shown. CamillaDSP will only work correctly with these settings:
Code:
Capture device: hw:CARD=Loopback,DEV=1
Playback device: hw:CARD=UCM,DEV=0
Sample rate: 48000
Capture channels: 2
Playback channels: 8

8. In the Mixer tab, create a mixer and configure it for 2 input channels and 8 output channels.

1787272814057.png


9. In the Pipeline tab, add the newly created mixer to the processing chain.

1787272844563.png


10. In the Files tab, give the configuration a name and save it. Then click the star (⭐) to mark the configuration as active. This ensures that this configuration will be used as the default configuration when the system starts.

1787272863535.png


NOTE: You can choose whatever sample rate you want in CamillaDSP. However, the DAC manual states: "The USB sound card only supports 48-kHz/16-bit or 48-kHz/24-bit." It's best to leave the sample rate at 48 kHz to minimize sample-rate conversion.

From this point onward, you can adapt CamillaDSP to your own requirements. But the basic setup is now complete.




Next, we'll install the PCM1822 as the capture device:

### 1. Copy the following script and save it as install_pcm1822.sh


Code:
#!/bin/bash

# PCM1822 ADC Installation Script for Volumio/Raspberry Pi
# This script installs the PCM1822 device tree overlay and systemd service
# to enable the PCM1822 ADC alongside the Wondom USB DAC

set -e

echo "=========================================="
echo "PCM1822 ADC Installation Script"
echo "=========================================="

# Check if running as root
if [ "$EUID" -ne 0 ]; then
echo "Please run as root (sudo)"
exit 1
fi

# 1. Create device tree overlay source file
echo "Creating device tree overlay source..."
cat > /tmp/pcm1822-i2s.dts << 'EOF'
/dts-v1/;
/plugin/;

/ {
compatible = "brcm,bcm2835";

fragment@0 {
target = <&i2s>;
__overlay__ {
status = "okay";
};
};

fragment@1 {
target = <&sound>;
sound_overlay: __overlay__ {
compatible = "simple-audio-card";
simple-audio-card,name = "pcm1822";
simple-audio-card,format = "i2s";

simple-audio-card,bitclock-master = <&dailink0_cpu>;
simple-audio-card,frame-master = <&dailink0_cpu>;

status = "okay";

dailink0_cpu: simple-audio-card,cpu {
sound-dai = <&i2s>;
dai-tdm-slot-num = <2>;
dai-tdm-slot-width = <32>;
};

simple-audio-card,codec {
sound-dai = <&i2s>;
system-clock-frequency = <12288000>;
};
};
};

__overrides__ {
card-name = <&sound_overlay>,"simple-audio-card,name";
};
};
EOF

# 2. Compile device tree overlay
echo "Compiling device tree overlay..."
dtc -@ -I dts -O dtb -o /boot/overlays/pcm1822-i2s.dtbo /tmp/pcm1822-i2s.dts

# 3. Remove overlay from config.txt if present
echo "Checking config.txt..."
if grep -q "dtoverlay=pcm1822-i2s" /boot/config.txt; then
echo "Removing existing overlay from config.txt..."
sed -i '/dtoverlay=pcm1822-i2s/d' /boot/config.txt
fi

# Ensure I2S is enabled
if ! grep -q "dtparam=i2s=on" /boot/config.txt; then
echo "Enabling I2S in config.txt..."
echo "dtparam=i2s=on" >> /boot/config.txt
fi

# 4. Create systemd service
echo "Creating systemd service..."
cat > /etc/systemd/system/load-pcm1822-overlay.service << 'EOF'
[Unit]
Description=Load PCM1822 overlay after USB initialization
After=multi-user.target
Wants=multi-user.target

[Service]
Type=oneshot
ExecStart=/usr/bin/dtoverlay pcm1822-i2s
RemainAfterExit=yes

[Install]
WantedBy=multi-user.target
EOF

# 5. Enable and start systemd service
echo "Enabling systemd service..."
systemctl daemon-reload
systemctl enable load-pcm1822-overlay.service
systemctl start load-pcm1822-overlay.service

# 6. Verify installation
echo "Verifying installation..."
sleep 2
if systemctl is-active --quiet load-pcm1822-overlay.service; then
echo "✓ Systemd service is running"
else
echo "✗ Systemd service failed to start"
systemctl status load-pcm1822-overlay.service
fi

# 7. Check audio devices
echo ""
echo "Checking audio devices..."
echo "Playback devices:"
aplay -l
echo ""
echo "Capture devices:"
arecord -l

echo ""
echo "=========================================="
echo "Installation Complete!"
echo "=========================================="
echo ""
echo "Expected devices:"
echo "  - Card 5: UCM [WONDOM UCM] (USB DAC - Playback)"
echo "  - Card 6: pcm1822 [pcm1822] (ADC - Capture)"
echo ""
echo "CamillaDSP configuration:"
echo "  capture:"
echo "    device: \"hw:CARD=pcm1822,DEV=0\""
echo "  playback:"
echo "    device: \"hw:CARD=UCM,DEV=0\""
echo ""
echo "PCM1822 Hardware Configuration:"
echo "  - All switches set to LOW (UP position)"
echo ""
echo "Reboot recommended to ensure all services start correctly."
echo "Run: sudo reboot"

### 2. Then copy the file to the Pi's home directory:
Code:
/home/volumio/
### 3. Make it executable

Code:
chmod +x install_pcm1822.sh

### 4. Run the script and reboot

Code:
sudo ./install_pcm1822.sh

Then reboot the Pi.

### 5. Set the ADC switches

Make sure all switches on the ADC are set to LOW (switches in the up position).

1787272936245.png



### 7. Connect the ADC to the Pi

Connect the ADC to the Raspberry Pi according to the pinout shown at pinout.xyz:

Code:
GND → physical pin 9
DATA → physical pin 38
BCLK → physical pin 12
LRCLK → physical pin 35

### 8. Configure CamillaGUI

In CamillaGUI, create a new configuration and give it a unique name.
The only change you need to make is to change the Capture Device to:

Code:
hw:CARD=pcm1822,DEV=0

Voilà — you now have analog input via I2S!

Congratulations! You have now installed Volumio and an analog source on a Pi and can output 8 channels simultaneously. Camilla can be used as a crossover, EQ, and mixer, and—to a certain extent—for room correction.
This allows you to build an ultra-compact streamer/preamp/DSP—all for just under €100!
 
Last edited:
Once fully assembled, the whole thing looks like this.
The Douk Mall/Nobsound cases are really exceptionally good for the price.
I replaced the 10 mm aluminum front panel with a black acrylic panel. This means I don’t need an external Wi‑Fi antenna for the Pi.
Instead of the supplied IEC power inlet, I’m using a PowerCON socket and printed a suitable adapter for it.

I've implemented a volume control knob and a remote control - the setup is described in the next post.

1789779467952.png
1789779504090.png
1789779530127.png
 
Here’s another script for integrating a remote control.
I’m simply using an inexpensive 2.4 GHz air mouse from AliExpress that cost €5.
It lets you control the volume, play/pause, skip to the next or previous song, shut down the Pi, and select the sources or cycle through the presets (be careful!).

1789780100019.png


1. Save this script as install_remote_control.sh

Code:
#!/bin/bash
set -e

echo "=========================================="
echo "2.4 GHz Remote Control Installation"
echo "=========================================="
echo ""

echo "Installing dependencies..."
sudo apt update
sudo apt install -y python3-evdev python3-websocket

echo ""
echo "Creating remote control script..."

sudo tee /home/volumio/remote_control.py > /dev/null <<'PYTHON'
#!/usr/bin/env python3

import evdev
from evdev import ecodes
import websocket
import json
import time
import threading
import os
import urllib.request
import subprocess


# ----------------------------------------------------------------------
# Configuration
# ----------------------------------------------------------------------

CAMILLA_WS = "ws://127.0.0.1:1234"
VOLUMIO_URL = "http://127.0.0.1:3000"

REMOTE_VENDOR = 0x1915
REMOTE_PRODUCT = 0x1025

MIN_VOLUME = -80.0
MAX_VOLUME = 0.0
VOLUME_STEP = 1.0

HOLD_DELAY = 0.5
HOLD_INTERVAL = 0.1

CONFIG_DIR = "/home/volumio/camilladsp/configs"


# ----------------------------------------------------------------------
# General helpers
# ----------------------------------------------------------------------

def log(message):
    print(message, flush=True)


# ----------------------------------------------------------------------
# Volumio control
# ----------------------------------------------------------------------

def volumio_command(command):
    url = (
        VOLUMIO_URL
        + "/api/v1/commands/?cmd="
        + command
    )

    try:
        with urllib.request.urlopen(url, timeout=3) as response:
            response.read()

        log(f"Volumio command: {command}")

    except Exception as e:
        log(f"Volumio command '{command}' failed: {e}")


# ----------------------------------------------------------------------
# Raspberry Pi power control
# ----------------------------------------------------------------------

def shutdown_pi():
    log("POWER BUTTON PRESSED")
    log("Shutting down Raspberry Pi...")

    try:
        subprocess.Popen(
            [
                "/usr/bin/sudo",
                "/usr/bin/systemctl",
                "poweroff"
            ],
            stdout=subprocess.DEVNULL,
            stderr=subprocess.DEVNULL
        )

    except Exception as e:
        log(f"Shutdown failed: {e}")


# ----------------------------------------------------------------------
# CamillaDSP
# ----------------------------------------------------------------------

def connect_camilla():
    while True:
        try:
            log(f"Connecting to CamillaDSP {CAMILLA_WS}...")

            ws = websocket.create_connection(
                CAMILLA_WS,
                timeout=5
            )

            log("CamillaDSP WebSocket connected.")
            return ws

        except Exception as e:
            log(f"CamillaDSP connection failed: {e}")
            time.sleep(2)


def camilla_command(ws, command):
    ws.send(json.dumps(command))

    try:
        response = ws.recv()
        return json.loads(response)

    except Exception:
        return None


def camilla_volume(ws, amount):
    response = camilla_command(
        ws,
        {
            "AdjustVolume": [
                amount,
                MIN_VOLUME,
                MAX_VOLUME
            ]
        }
    )

    if response:
        try:
            volume = response["AdjustVolume"]["value"]
            log(f"CamillaDSP volume: {volume:.1f} dB")

        except Exception:
            pass


def camilla_mute(ws):
    response = camilla_command(
        ws,
        {
            "ToggleMute": None
        }
    )

    if response:
        try:
            mute = response["ToggleMute"]["value"]
            log(f"CamillaDSP mute: {mute}")

        except Exception:
            log(f"CamillaDSP response: {response}")


def get_config_path(ws):
    response = camilla_command(
        ws,
        "GetConfigFilePath"
    )

    if response:
        try:
            return response["GetConfigFilePath"]["value"]

        except Exception:
            pass

    return None


def get_configs():
    configs = []

    try:
        for filename in os.listdir(CONFIG_DIR):

            if not filename.lower().endswith((".yml", ".yaml")):
                continue

            path = os.path.join(CONFIG_DIR, filename)

            if os.path.isfile(path):
                configs.append(os.path.realpath(path))

    except Exception as e:
        log(f"Could not read config directory: {e}")

    configs.sort()
    return configs


def cycle_config(ws):
    configs = get_configs()

    if not configs:
        log("No CamillaDSP configs found.")
        return

    current = get_config_path(ws)

    if current:
        current = os.path.realpath(current)

    if current in configs:
        current_index = configs.index(current)
        next_index = (current_index + 1) % len(configs)

    else:
        next_index = 0

    next_config = configs[next_index]

    log(f"Switching config: {os.path.basename(next_config)}")

    response = camilla_command(
        ws,
        {
            "SetConfigFilePath": next_config
        }
    )

    if response is None:
        log("SetConfigFilePath failed.")
        return

    response = camilla_command(
        ws,
        "Reload"
    )

    if response is None:
        log("CamillaDSP reload failed.")
        return

    log(f"Active config: {os.path.basename(next_config)}")


# ----------------------------------------------------------------------
# Device discovery
# ----------------------------------------------------------------------

def find_device(name_fragment):
    log(
        f"Looking for {name_fragment} device "
        f"{REMOTE_VENDOR:04x}:{REMOTE_PRODUCT:04x}..."
    )

    while True:

        for path in evdev.list_devices():

            try:
                device = evdev.InputDevice(path)

                if (
                    device.info.vendor == REMOTE_VENDOR
                    and
                    device.info.product == REMOTE_PRODUCT
                    and
                    name_fragment in device.name
                ):
                    log(f"Found {name_fragment}: {path}")
                    log(f"Device name: {device.name}")
                    return device

                device.close()

            except Exception:
                pass

        time.sleep(2)


# ----------------------------------------------------------------------
# Volume hold
# ----------------------------------------------------------------------

def volume_hold(ws, amount, stop_event):
    if stop_event.wait(HOLD_DELAY):
        return

    while not stop_event.is_set():

        try:
            camilla_volume(ws, amount)

        except websocket.WebSocketException:
            break

        if stop_event.wait(HOLD_INTERVAL):
            break


# ----------------------------------------------------------------------
# Consumer Control interface
# ----------------------------------------------------------------------

def consumer_loop(camilla_state):
    """
    Handles the Consumer Control interface:

        KEY_PLAYPAUSE
        KEY_VOLUMEUP
        KEY_VOLUMEDOWN
        KEY_MUTE
    """

    while True:

        device = find_device("Consumer Control")

        try:
            device.grab()
            log("Consumer Control device grabbed exclusively.")

        except Exception as e:
            log(f"Could not grab Consumer Control device: {e}")

        hold_stop = None
        held_key = None

        try:

            for event in device.read_loop():

                if event.type != ecodes.EV_KEY:
                    continue

                code = event.code
                value = event.value

                # Play/pause.
                if code == ecodes.KEY_PLAYPAUSE:

                    if value == 1:
                        log("PLAY/PAUSE")
                        volumio_command("toggle")

                    continue

                # Volume up.
                if code == ecodes.KEY_VOLUMEUP:

                    if value == 1:
                        log("VOLUME UP")

                        try:
                            camilla_volume(
                                camilla_state["ws"],
                                VOLUME_STEP
                            )

                        except websocket.WebSocketException:
                            camilla_state["reconnect"].set()

                        if hold_stop is not None:
                            hold_stop.set()

                        hold_stop = threading.Event()

                        threading.Thread(
                            target=volume_hold,
                            args=(
                                camilla_state["ws"],
                                VOLUME_STEP,
                                hold_stop
                            ),
                            daemon=True
                        ).start()

                        held_key = code

                    elif value == 0 and held_key == code:

                        if hold_stop is not None:
                            hold_stop.set()

                        hold_stop = None
                        held_key = None

                    continue

                # Volume down.
                if code == ecodes.KEY_VOLUMEDOWN:

                    if value == 1:
                        log("VOLUME DOWN")

                        try:
                            camilla_volume(
                                camilla_state["ws"],
                                -VOLUME_STEP
                            )

                        except websocket.WebSocketException:
                            camilla_state["reconnect"].set()

                        if hold_stop is not None:
                            hold_stop.set()

                        hold_stop = threading.Event()

                        threading.Thread(
                            target=volume_hold,
                            args=(
                                camilla_state["ws"],
                                -VOLUME_STEP,
                                hold_stop
                            ),
                            daemon=True
                        ).start()

                        held_key = code

                    elif value == 0 and held_key == code:

                        if hold_stop is not None:
                            hold_stop.set()

                        hold_stop = None
                        held_key = None

                    continue

                # Mute.
                if code == ecodes.KEY_MUTE and value == 1:
                    log("MUTE")

                    try:
                        camilla_mute(camilla_state["ws"])

                    except websocket.WebSocketException:
                        camilla_state["reconnect"].set()

                    continue

        except OSError:
            log("Consumer Control device disconnected.")

        except Exception as e:
            log(f"Consumer Control error: {e}")

        finally:

            if hold_stop is not None:
                hold_stop.set()

            try:
                device.ungrab()

            except Exception:
                pass

            try:
                device.close()

            except Exception:
                pass

            time.sleep(2)


# ----------------------------------------------------------------------
# Keyboard interface
# ----------------------------------------------------------------------

def keyboard_loop(camilla_state):
    """
    Handles the Keyboard interface.

    Based on your evtest output:

        KEY_LEFT    = 105 -> previous song
        KEY_RIGHT   = 106 -> next song
        KEY_COMPOSE = 127 -> preset
        KEY_POWER   = 116 -> shut down Raspberry Pi
    """

    while True:

        device = find_device("Keyboard")

        try:
            device.grab()
            log("Keyboard device grabbed exclusively.")

        except Exception as e:
            log(f"Could not grab Keyboard device: {e}")

        try:

            for event in device.read_loop():

                if event.type != ecodes.EV_KEY:
                    continue

                # Ignore key release and autorepeat events.
                if event.value != 1:
                    continue

                code = event.code

                # Power button.
                if code == ecodes.KEY_POWER:
                    log("POWER BUTTON")
                    shutdown_pi()
                    continue

                # Right button: next song.
                if code == ecodes.KEY_RIGHT:
                    log("NEXT SONG")
                    volumio_command("next")
                    continue

                # Left button: previous song.
                if code == ecodes.KEY_LEFT:
                    log("PREVIOUS SONG")
                    volumio_command("prev")
                    continue

                # Preset button.
                if code == ecodes.KEY_COMPOSE:
                    log("PRESET")

                    try:
                        cycle_config(camilla_state["ws"])

                    except websocket.WebSocketException:
                        camilla_state["reconnect"].set()

        except OSError:
            log("Keyboard device disconnected.")

        except Exception as e:
            log(f"Keyboard error: {e}")

        finally:

            try:
                device.ungrab()

            except Exception:
                pass

            try:
                device.close()

            except Exception:
                pass

            time.sleep(2)


# ----------------------------------------------------------------------
# CamillaDSP reconnection
# ----------------------------------------------------------------------

def camilla_reconnect_loop(camilla_state):
    while True:

        camilla_state["reconnect"].wait()
        camilla_state["reconnect"].clear()

        try:
            camilla_state["ws"].close()

        except Exception:
            pass

        camilla_state["ws"] = connect_camilla()


# ----------------------------------------------------------------------
# Main
# ----------------------------------------------------------------------

def main():
    log("2.4 GHz Remote Control")
    log("Single process, two evdev interfaces")
    log("Consumer Control: play/pause, volume, mute")
    log("Keyboard: left/right, preset, power")

    camilla_state = {
        "ws": connect_camilla(),
        "reconnect": threading.Event()
    }

    threading.Thread(
        target=camilla_reconnect_loop,
        args=(camilla_state,),
        daemon=True
    ).start()

    threading.Thread(
        target=consumer_loop,
        args=(camilla_state,),
        daemon=True
    ).start()

    threading.Thread(
        target=keyboard_loop,
        args=(camilla_state,),
        daemon=True
    ).start()

    log("Remote control is running.")

    try:

        while True:
            time.sleep(1)

    except KeyboardInterrupt:
        log("Stopping remote control.")

    finally:

        try:
            camilla_state["ws"].close()

        except Exception:
            pass


if __name__ == "__main__":
    main()
PYTHON

echo "Making script executable..."
sudo chmod +x /home/volumio/remote_control.py

echo ""
echo "Creating systemd service..."

sudo tee /etc/systemd/system/remote-control.service > /dev/null <<'SERVICE'
[Unit]
Description=2.4 GHz Remote Control - CamillaDSP and Volumio
After=camilladsp.service volumio.service
Wants=camilladsp.service volumio.service

[Service]
Type=simple
User=volumio
ExecStart=/usr/bin/python3 /home/volumio/remote_control.py
Restart=always
RestartSec=2

[Install]
WantedBy=multi-user.target
SERVICE

echo "Reloading systemd..."
sudo systemctl daemon-reload

echo "Enabling remote control service..."
sudo systemctl enable remote-control.service

echo "Starting remote control service..."
sudo systemctl restart remote-control.service

echo ""
echo "=========================================="
echo "Installation complete"
echo "=========================================="
echo ""
echo "Python script:"
echo "  /home/volumio/remote_control.py"
echo ""
echo "Systemd service:"
echo "  /etc/systemd/system/remote-control.service"
echo ""
echo "Service status:"
echo ""

sudo systemctl --no-pager status remote-control.service

2. Copy it to your Pi home folder and make it executable

Code:
chmod +x install_remote_control.sh

3. Execute

Code:
sudo ./install_remote_control.sh

Now you have a remote control for the basic tasks.
 
For the Volume control knob on the pre-amp I dismantled this USB Volume Control, shortened the cable
and put the board in the enclosure.

1789781169236.png


Here's the install script:

1. Save the following script as install_volume_knob.sh

Code:
#!/bin/bash

set -euo pipefail

# ============================================================
# CamillaDSP USB HID Volume Knob Installer
#
# Hardware:
#   USB VID: 0x413d
#   USB PID: 0x553a
#
# Functions:
#   Volume Up   -> +1 dB
#   Volume Down -> -1 dB
#   Mute        -> toggle mute
#
# Safety:
#   Volume is forced to -40 dB whenever the service starts.
# ============================================================

USER_NAME="volumio"
USER_HOME="/home/$USER_NAME"

SCRIPT_NAME="volume_knob.py"
SERVICE_NAME="volume_knob.service"

SCRIPT_PATH="$USER_HOME/$SCRIPT_NAME"
SERVICE_PATH="/etc/systemd/system/$SERVICE_NAME"

USB_VENDOR="0x413d"
USB_PRODUCT="0x553a"

echo
echo "============================================================"
echo " CamillaDSP USB HID Volume Knob Installer"
echo "============================================================"
echo
echo "User:        $USER_NAME"
echo "Script:      $SCRIPT_PATH"
echo "Service:     $SERVICE_NAME"
echo "USB device:  413d:553a"
echo
echo "Startup volume: -40.0 dB"
echo


# ------------------------------------------------------------
# 1. Check that we are running as root
# ------------------------------------------------------------

if [[ "$EUID" -ne 0 ]]; then
    echo "ERROR: This installer must be run with sudo."
    echo
    echo "Run:"
    echo "  sudo ./install_volume_knob.sh"
    exit 1
fi


# ------------------------------------------------------------
# 2. Check that the volumio user exists
# ------------------------------------------------------------

if ! id "$USER_NAME" >/dev/null 2>&1; then
    echo "ERROR: User '$USER_NAME' does not exist."
    exit 1
fi


# ------------------------------------------------------------
# 3. Install required Debian/Raspbian packages
# ------------------------------------------------------------

echo "=== Installing required packages ==="

apt update

apt install -y \
    python3 \
    python3-evdev \
    python3-websocket


# ------------------------------------------------------------
# 4. Verify Python modules
# ------------------------------------------------------------

echo
echo "=== Verifying Python modules ==="

if ! /usr/bin/python3 -c "import evdev" >/dev/null 2>&1; then
    echo "ERROR: Python module 'evdev' is not available."
    exit 1
fi

if ! /usr/bin/python3 -c "import websocket" >/dev/null 2>&1; then
    echo "ERROR: Python module 'websocket' is not available."
    exit 1
fi

echo "evdev:    OK"
echo "websocket: OK"


# ------------------------------------------------------------
# 5. Verify the volumio user has input-device access
# ------------------------------------------------------------

echo
echo "=== Checking input group membership ==="

if id -nG "$USER_NAME" | grep -qw input; then
    echo "User '$USER_NAME' is a member of the input group."
else
    echo "Adding '$USER_NAME' to the input group..."
    usermod -aG input "$USER_NAME"
    echo
    echo "NOTE: The input-group membership will take effect for"
    echo "new sessions. The systemd service will start correctly"
    echo "because it runs with the user's configured groups."
fi


# ------------------------------------------------------------
# 6. Create Python program
# ------------------------------------------------------------

echo
echo "=== Creating Python program ==="

cat > "$SCRIPT_PATH" << 'PYTHON'
#!/usr/bin/env python3

import evdev
from evdev import InputDevice, ecodes
import websocket
import json
import time


# ============================================================
# Configuration
# ============================================================

HOST = "127.0.0.1"
PORT = 1234

# USB HID volume knob
USB_VENDOR = 0x413d
USB_PRODUCT = 0x553a

# Volume settings
STEP_DB = 1.0
MIN_VOLUME = -50.0
MAX_VOLUME = 0.0

# Safety startup volume
START_VOLUME = -40.0


# ============================================================
# Find USB volume knob
# ============================================================

def find_volume_knob():

    print(
        f"Looking for HID volume knob "
        f"{USB_VENDOR:04x}:{USB_PRODUCT:04x}...",
        flush=True
    )

    while True:

        for path in evdev.list_devices():

            try:
                device = InputDevice(path)

                vendor = device.info.vendor
                product = device.info.product

                if vendor == USB_VENDOR and product == USB_PRODUCT:

                    print(
                        f"Found volume knob: {path}",
                        flush=True
                    )

                    print(
                        f"Device name: {device.name}",
                        flush=True
                    )

                    print(
                        f"USB ID: "
                        f"{vendor:04x}:{product:04x}",
                        flush=True
                    )

                    return device

                device.close()

            except Exception as e:

                print(
                    f"Could not inspect {path}: {e}",
                    flush=True
                )

        print(
            "Volume knob not found. "
            "Retrying in 2 seconds...",
            flush=True
        )

        time.sleep(2)


# ============================================================
# Connect to CamillaDSP WebSocket
# ============================================================

def connect_ws():

    while True:

        try:

            print(
                f"Connecting to CamillaDSP "
                f"ws://{HOST}:{PORT}...",
                flush=True
            )

            ws = websocket.create_connection(
                f"ws://{HOST}:{PORT}",
                timeout=5
            )

            print(
                "CamillaDSP WebSocket connected.",
                flush=True
            )

            return ws

        except Exception as e:

            print(
                f"WebSocket connection failed: {e}",
                flush=True
            )

            print(
                "Retrying in 2 seconds...",
                flush=True
            )

            time.sleep(2)


# ============================================================
# Global state
# ============================================================

ws = None

current_volume = START_VOLUME
mute_state = False


# ============================================================
# Set volume
# ============================================================

def set_volume(volume):

    global current_volume
    global ws

    volume = max(
        MIN_VOLUME,
        min(MAX_VOLUME, volume)
    )

    current_volume = volume

    message = json.dumps({
        "SetVolume": volume
    })

    while True:

        try:

            ws.send(message)

            print(
                f"Volume set to {volume:.1f} dB",
                flush=True
            )

            return

        except Exception as e:

            print(
                f"WebSocket send failed: {e}",
                flush=True
            )

            try:
                ws.close()
            except Exception:
                pass

            ws = connect_ws()


# ============================================================
# Toggle mute
# ============================================================

def toggle_mute():

    global mute_state
    global ws

    mute_state = not mute_state

    message = json.dumps({
        "SetMute": mute_state
    })

    while True:

        try:

            ws.send(message)

            print(
                f"Mute {'ON' if mute_state else 'OFF'}",
                flush=True
            )

            return

        except Exception as e:

            print(
                f"WebSocket send failed: {e}",
                flush=True
            )

            try:
                ws.close()
            except Exception:
                pass

            ws = connect_ws()


# ============================================================
# Main
# ============================================================

def main():

    global ws

    print(
        "============================================================",
        flush=True
    )

    print(
        "CamillaDSP USB HID Volume Knob",
        flush=True
    )

    print(
        "============================================================",
        flush=True
    )

    # --------------------------------------------------------
    # Connect to CamillaDSP first.
    #
    # This is deliberately before looking for the USB knob.
    # The safety volume must be applied whenever the service
    # starts, even if the USB knob isn't connected.
    # --------------------------------------------------------

    ws = connect_ws()

    # --------------------------------------------------------
    # SAFETY STARTUP VOLUME
    # --------------------------------------------------------

    print(
        f"Forcing safe startup volume: "
        f"{START_VOLUME:.1f} dB",
        flush=True
    )

    set_volume(START_VOLUME)

    # --------------------------------------------------------
    # Find USB volume knob
    # --------------------------------------------------------

    device = find_volume_knob()

    print(
        "Waiting for volume knob events...",
        flush=True
    )

    # --------------------------------------------------------
    # Process input events
    # --------------------------------------------------------

    try:

        for event in device.read_loop():

            # We only care about keyboard-style events
            if event.type != ecodes.EV_KEY:
                continue

            # value:
            #   0 = key release
            #   1 = key press
            #   2 = key repeat
            #
            # Only react to initial press.
            if event.value != 1:
                continue

            if event.code == ecodes.KEY_VOLUMEUP:

                set_volume(
                    current_volume + STEP_DB
                )

            elif event.code == ecodes.KEY_VOLUMEDOWN:

                set_volume(
                    current_volume - STEP_DB
                )

            elif event.code == ecodes.KEY_MUTE:

                toggle_mute()

    finally:

        try:
            device.close()
        except Exception:
            pass


# ============================================================
# Entry point
# ============================================================

if __name__ == "__main__":

    try:

        main()

    except KeyboardInterrupt:

        print(
            "Volume knob service stopped.",
            flush=True
        )

    except Exception as e:

        print(
            f"Fatal error: {e}",
            flush=True
        )

        raise
PYTHON


# ------------------------------------------------------------
# 7. Set ownership and permissions
# ------------------------------------------------------------

chown "$USER_NAME:$USER_NAME" "$SCRIPT_PATH"
chmod 755 "$SCRIPT_PATH"


# ------------------------------------------------------------
# 8. Create systemd service
# ------------------------------------------------------------

echo
echo "=== Creating systemd service ==="

cat > "$SERVICE_PATH" << EOF
[Unit]
Description=CamillaDSP USB HID Volume Knob
After=network.target sound.target

[Service]
Type=simple

User=$USER_NAME
Group=$USER_NAME

WorkingDirectory=$USER_HOME

ExecStart=/usr/bin/python3 $SCRIPT_PATH

Restart=always
RestartSec=3

# Give the service access to the input group.
SupplementaryGroups=input

# Send Python output directly to journald.
Environment=PYTHONUNBUFFERED=1

[Install]
WantedBy=multi-user.target
EOF


# ------------------------------------------------------------
# 9. Reload systemd
# ------------------------------------------------------------

echo
echo "=== Reloading systemd ==="

systemctl daemon-reload


# ------------------------------------------------------------
# 10. Enable service
# ------------------------------------------------------------

echo
echo "=== Enabling service ==="

systemctl enable "$SERVICE_NAME"


# ------------------------------------------------------------
# 11. Restart service
# ------------------------------------------------------------

echo
echo "=== Starting service ==="

systemctl restart "$SERVICE_NAME"


# ------------------------------------------------------------
# 12. Give it a moment to start
# ------------------------------------------------------------

sleep 2


# ------------------------------------------------------------
# 13. Check service status
# ------------------------------------------------------------

echo
echo "=== Service status ==="

if systemctl is-active --quiet "$SERVICE_NAME"; then

    echo
    echo "============================================================"
    echo " INSTALLATION SUCCESSFUL"
    echo "============================================================"
    echo
    echo "Service:       $SERVICE_NAME"
    echo "USB device:    HID 413d:553a"
    echo "Startup volume: -40.0 dB"
    echo
    echo "Check status with:"
    echo
    echo "  sudo systemctl status $SERVICE_NAME"
    echo
    echo "View live logs with:"
    echo
    echo "  sudo journalctl -u $SERVICE_NAME -f"
    echo

else

    echo
    echo "============================================================"
    echo " ERROR: SERVICE FAILED TO START"
    echo "============================================================"
    echo
    echo "Run:"
    echo
    echo "  sudo systemctl status $SERVICE_NAME"
    echo
    echo "and:"
    echo
    echo "  sudo journalctl -u $SERVICE_NAME -n 100 --no-pager"
    echo

    exit 1

fi

2. Copy it to your Pi home folder and make it executable

Code:
chmod +x install_volume_knob.sh

3. Execute

Code:
sudo ./install_volume_knob.sh

DONE!
 
Back
Top Bottom