Skip to main content
Linux Systems · BlueZ · PipeWire6 min read
BR/EDR D-Bus · PipeWire · Lid-Close FD

Bypassing BlueZ LE Audio Contention & systemd-logind Sleep Races for Galaxy Buds on Ubuntu

How I solved Samsung Galaxy Buds multipoint takeover on Ubuntu 24.04+ using explicit BlueZ D-Bus ConnectProfile UUIDs, dynamic PipeWire wpctl profile routing, and pre-sleep systemd-logind inhibitor FDs.

By Pulkit Mundra · Senior Software Developer (SDE-3)Markdown (llms.txt)
Ubuntu LinuxBlueZ D-BusPipeWireGNOME Shellsystemd-logindGalaxy Buds
View Full Project Case Study

TL;DR · Production Summary

  • Samsung locks Seamless Earbud Connection to One UI devices, and calling generic org.bluez.Device1.Connect() on Ubuntu 24.04+ often stalls negotiating LE Audio (BAP) while Android still holds the ACL link - calling ConnectProfile() explicitly for Classic BR/EDR UUIDs (A2DP 110b, AVRCP 110e, HFP 111e) takes over reliably in one click.
  • Switching between Hi-Fi music (A2DP) and microphone calls (HFP) without brittle PulseAudio indices works cleanly by parsing PipeWire's live pw-dump JSON graph, matching the Bluetooth MAC, and applying wpctl set-profile + wpctl set-default.
  • To hand earbuds back to Android when closing a laptop lid before NetworkManager drops Wi-Fi, v1.3.0 dynamically acquires a systemd-logind handle-lid-switch inhibitor FD strictly while Buds are connected, confirms BlueZ Connected == false, waits a 600ms radio settle window, fires an HTTP/1.1 MacroDroid webhook, and closes the FD under a hard 10s fail-safe.
BENCHMARK & ARCHITECTURE MATRIX
Scroll

Samsung Galaxy Buds on Ubuntu 24.04+: Default GNOME Bluetooth vs Explicit BlueZ D-Bus & logind Handoff

Samsung Galaxy Buds on Ubuntu 24.04+: Default GNOME Bluetooth vs Explicit BlueZ D-Bus & logind Handoff
Failure Mode / StepDefault GNOME Settings (Connect())Galaxy Buds Switcher (GNOME Ext)Root Systems Mechanism
Takeover While Paired to AndroidOften hangs or binds no audio sink1-click reliable Classic BR/EDR connectExplicit ConnectProfile (A2DP 110b, AVRCP 110e, HFP 111e)
Music (A2DP) <-> Mic (HFP) Switch4+ clicks in Sound Settings dialog1 click in Quick Settings or buds profile [a2dp|hfp]Live pw-dump device match + wpctl set-profile + set-default
Closing Laptop Lid Mid-PlaybackWi-Fi drops -> Buds stranded on laptopClean Android handoff before S3 suspendDynamic login1.Inhibit('handle-lid-switch') FD + 600ms settle
Idle Lock Screen + Lid CloseExtension paused / webhook skippedActive on unlock-dialog, settings hiddensession-modes: ['user', 'unlock-dialog'] + allowSettings guard
Offline Wi-Fi During Lid CloseN/AHard 10.0s fail-safe -> native sleepTimeout closes inhibitor FD via GLib.close(fd)

Interactive Benchmark Playground

Loading interactive benchmark playground...

1. Why Standard Bluetooth Connect Fails on Galaxy Buds (LE Audio vs. BR/EDR)

Unlike Bose or Sony headsets that implement standard Bluetooth Multipoint, Samsung restricts automatic multi-device switching (Seamless Earbud Connection) to Galaxy phones, tablets, and Galaxy Books signed into the same Samsung account. On Ubuntu 24.04 LTS, pulling Samsung Galaxy Buds3 Pro or Buds2 Pro away from an active Android phone through GNOME's default Bluetooth menu frequently stalls or connects without routing an active audio sink.

The root cause sits inside BlueZ 5.72+ dual-mode negotiation. Modern Galaxy Buds advertise both Classic Bluetooth (BR/EDR) and LE Audio (BAP) services simultaneously while maintaining an active link to Android. Generic org.bluez.Device1.Connect() (and bluetoothctl connect) attempts to bring up every advertised profile at once, colliding with LE Audio states on the headset.

Instead of calling Connect() first, our GNOME Shell Quick Settings extension (EGO #11611) and Bash CLI (buds-switch) talk directly to org.bluez over the system D-Bus and invoke org.bluez.Device1.ConnectProfile(uuid) explicitly for the three Classic BR/EDR audio UUIDs in order: A2DP Sink (0000110b), AVRCP (0000110e), and HFP (0000111e), falling back to generic Connect() only if A2DP fails.

Explicit Classic BR/EDR profile takeover over system D-Bus (budsQuickToggle.js)
const A2DP_UUID  = '0000110b-0000-1000-8000-00805f9b34fb';
const AVRCP_UUID = '0000110e-0000-1000-8000-00805f9b34fb';
const HFP_UUID   = '0000111e-0000-1000-8000-00805f9b34fb';

// Bypass LE Audio (BAP) negotiation stalls by connecting Classic BR/EDR profiles explicitly.
let connectedA2dp = false;
for (const uuid of [A2DP_UUID, AVRCP_UUID, HFP_UUID]) {
    try {
        await dbusCallAsync(
            Gio.DBus.system, 'org.bluez', info.objectPath,
            'org.bluez.Device1', 'ConnectProfile',
            new GLib.Variant('(s)', [uuid]), cancellable, 5000
        );
        if (uuid === A2DP_UUID) connectedA2dp = true;
    } catch (_e) {
        if (cancellable.is_cancelled()) return;
    }
}
if (!connectedA2dp) {
    await dbusCallAsync(Gio.DBus.system, 'org.bluez', info.objectPath,
        'org.bluez.Device1', 'Connect', null, cancellable, 6000);
}

2. Zero-Hardcoding PipeWire A2DP / HFP Profile Switching via pw-dump & wpctl

Even after BlueZ brings up Classic Bluetooth, Ubuntu users hit two daily friction points: GNOME occasionally leaves the laptop speakers as the default output sink, and jumping into a Zoom or Meet call requires digging 4 clicks deep into Sound Settings to switch from stereo A2DP to wideband HFP microphone mode (and back again afterward).

Rather than scraping locale-dependent pactl text or hardcoding numeric card IDs that shift after every reconnect, we query PipeWire's structured JSON state with pw-dump, match the PipeWire:Interface:Device node whose device.name contains the earbud MAC address, pick the highest-priority available a2dp-sink or headset-head-unit profile index from EnumProfile, apply wpctl set-profile, and immediately bind wpctl set-default on the matching bluez_output sink.

Resolving PipeWire Bluetooth device & profile indices dynamically (buds-switch)
data = json.loads(subprocess.check_output(["pw-dump"], text=True))
prefix = "a2dp-sink" if mode in ("a2dp", "music") else "headset-head-unit"

for obj in data:
    if obj.get("type") != "PipeWire:Interface:Device":
        continue
    dev_name = str(obj.get("info", {}).get("props", {}).get("device.name", "")).upper()
    if mac_underscore not in dev_name:
        continue

    enum_profiles = obj.get("info", {}).get("params", {}).get("EnumProfile", [])
    candidates = [
        p for p in enum_profiles
        if str(p.get("name", "")).startswith(prefix) and p.get("available") != "no"
    ]
    chosen = next((c for c in candidates if c.get("name") in ("a2dp-sink", "headset-head-unit")), candidates[0])
    subprocess.check_call(["wpctl", "set-profile", str(obj["id"]), str(chosen["index"])])

3. Winning the Laptop Lid-Close Race: systemd-logind vs. NetworkManager & BlueZ

Returning earbuds from Ubuntu back to Android manually is straightforward: disconnect BlueZ, then fire a lightweight HTTP webhook to MacroDroid on Android so the phone actively reconnects. The real systems bug appeared when building v1.3.0's automatic lid-close handoff.

The instant you shut a laptop lid, three Linux daemons race each other: systemd-logind initiates S3/s2idle suspend, NetworkManager drops Wi-Fi, and BlueZ still holds an active ACL radio link. Without coordination, the webhook fails on a dead socket and the earbuds stay stranded on a sleeping laptop.

Our solution uses a dynamic handle-lid-switch block inhibitor via org.freedesktop.login1.Manager.Inhibit (receiving a Unix file descriptor via Gio.UnixFDList) that is armed strictly while Galaxy Buds are connected (zero inhibitors held when disconnected). When UPower/logind reports LidClosed, the extension runs a deterministic state machine before releasing the FD via GLib.close():

  • Clamshell & reopen safety: Skips handoff if docked to an external monitor with lid-close-suspend-with-external-monitor disabled, and immediately aborts the webhook if the lid reopens mid-disconnect.
  • Confirmed BlueZ release + 600ms radio settle window: Calls org.bluez.Device1.Disconnect(), actively polls org.bluez.Device1.Connected until false (4.5s budget), then waits 600ms so the earbuds' baseband controller fully drops Ubuntu's ACL before Android pages them.
  • HTTP/1.1 webhook + wake cleanup: Forces HTTP/1.1 on Soup.Message (set_force_http1(true)) with a transient retry, purges stale keep-alive sockets on PrepareForSleep(false), and enforces a hard 10.0s fail-safe timer so offline Wi-Fi can never block laptop sleep.
  • Lock-screen resilience: Declaring session-modes: ['user', 'unlock-dialog'] in metadata.json keeps lid-close handoff active after GNOME's 5-minute idle screen lock while hiding preferences whenever Main.sessionMode.allowSettings is false.
Deterministic pre-sleep lid-close handoff with 10s fail-safe FD release (budsQuickToggle.js)
// Armed via org.freedesktop.login1.Manager.Inhibit('handle-lid-switch', ..., 'block')
// strictly while Buds are connected. Hard 10s fail-safe guarantees sleep is never blocked.
const failSafeId = GLib.timeout_add(GLib.PRIORITY_DEFAULT, 10000, () => {
    this._lidHandoffInFlight = false;
    this._releaseLidInhibitor(); // GLib.close(this._lidInhibitFd)
    return GLib.SOURCE_REMOVE;
});

try {
    await this._disconnectBluezDevice(info, 4500);       // Poll Device1.Connected == false
    if (this._lidIsClosed && !this._isClamshellExternalMonitorMode()) {
        await this._waitMs(600);                         // Bluetooth ACL radio settle window
        if (this._lidIsClosed) {
            await this._sendWebhookWithRetry(4000, () => !this._lidIsClosed);
        }
    }
} finally {
    this._clearLidFailSafeTimer();
    this._lidHandoffInFlight = false;
    if (this._lidIsClosed) this._releaseLidInhibitor();  // Hand control back to systemd-logind
}

4. Passing Official GNOME Extensions Store (EGO) Review & GSettings Sync

Shipping on extensions.gnome.org (EGO #11611 across GNOME Shell 45-48) enforces strict memory and lifecycle hygiene because extensions execute directly inside the compositor process. Any leaked D-Bus callback or stray GLib timeout surviving disable() or screen lock is an immediate rejection.

We eliminated ad-hoc _destroyed flags in favor of a single Gio.Cancellable threaded through every async Gio.DBus, Soup.Session, and Gio.Subprocess invocation, migrated GObject subclasses to ES6 constructor() syntax, and backed all settings (bud-mac, macrodroid-webhook, lid-close-handoff) with a compiled GSettings schema bidirectionally synced to ~/.config/buds-switch.env (0600 permissions, parsed safely without shell source) so the GNOME Quick Settings pill, GTK4/Libadwaita preferences app, and buds CLI always stay in sync.

Technical Q&A

Frequently Asked Architecture Questions

Modern Galaxy Buds advertise both Classic BR/EDR and LE Audio (BAP) while holding an active ACL connection to an Android phone. Calling generic org.bluez.Device1.Connect() tells BlueZ to negotiate all profiles including LE Audio, which frequently stalls or leaves PipeWire without an active a2dp-sink. Explicitly invoking org.bluez.Device1.ConnectProfile for Classic A2DP (0000110b), AVRCP (0000110e), and HFP (0000111e) bypasses LE Audio contention cleanly.

Related Consulting Services

Share this engineering breakdown:
Open to Senior / Staff Roles & High-Impact Consulting

Need Linux systems engineering, D-Bus/daemon tooling, or Python automation?

I design production MCP & ADK toolkits, high-throughput Python/Django APIs, and reliable fintech & Linux software. Reach out directly and I typically reply within 24 hours.