Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
3 changes: 3 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,9 @@ and this project adheres to [Semantic Versioning](http://semver.org/spec/v2.0.0.

## [Unreleased]
### Fixed
- Long titles scrolled slightly past their last pixel before bouncing back; the scroll window now matches the drawn text area exactly
- Bluetooth: nearby devices switched off mid-scan no longer linger as unresponsive "ghost" rows; they leave the list when their last advertisement goes stale
- Bluetooth: a known device that is off or out of range now shows just its name, like a saved wifi network, instead of the non-applicable "press its button" hint
- The parameter dialog on the LCD sometimes did not change values due to a race condition with respect to MOD-UI's `last.json`. pi-Stomp then did not send parameter changes to MOD-UI until you selected a different pedalboard. Parameters on a knob or an encoder continued to work, because they send MIDI CC.
- The LCD showed a bypass that MOD-UI did not receive, if you tapped it while a pedalboard loaded. The LCD now keeps the last value that MOD-UI confirmed.
- A parameter change from a plugin menu could be lost if the connection to MOD-UI was busy. pi-Stomp now sends the value again on the next cycle.
Expand Down
127 changes: 127 additions & 0 deletions common/command_queue.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,127 @@
# This file is part of pi-stomp.
#
# pi-stomp is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# pi-stomp is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with pi-stomp. If not, see <https://www.gnu.org/licenses/>.

"""Serialized background executor shared by the wifi and bluetooth managers.

Commands run one at a time on a worker thread; results are delivered on the
main thread via poll(). The manager it runs against is duck-typed to
CommandContext, so neither subsystem has to know about the other."""

import logging
import queue
import threading
from abc import ABC, abstractmethod
from typing import Any, Callable, Generic, Protocol, TypeVar

from common.util import TEARDOWN_JOIN_S

T = TypeVar("T")


class CommandContext(Protocol):
"""What CommandQueue needs of the manager it executes against."""

def request_refresh(self) -> None: ...


class Command(ABC, Generic[T]):
"""A unit of serialized work. Deduped by key() — if a command with the
same key is pending or in-flight, a fresh submission is dropped."""

# Positional-only so subclasses are free to name (and narrow) the manager.
@abstractmethod
def run(self, ctx: Any, /) -> T: ...

@abstractmethod
def key(self) -> str: ...


_SHUTDOWN_SENTINEL = object()


class CommandQueue:
"""Serialized executor over a manager. Worker thread runs Commands;
results are delivered on the main thread via poll(). Dedupes by key()."""

def __init__(self, ctx: CommandContext) -> None:
self._ctx = ctx
self._cmd_queue: queue.Queue = queue.Queue()
self._result_queue: queue.Queue = queue.Queue()
self._lock = threading.Lock()
self._pending_op_count = 0
self._pending_keys: set[str] = set()
self._worker = threading.Thread(target=self._drain, daemon=True)
self._worker.start()

def submit(self, cmd: "Command[T]", on_done: Callable[[T], None]) -> bool:
return self._enqueue(cmd, on_done, bumps_pending=True)

def submit_scan(self, cmd: "Command[T]", on_done: Callable[[T], None]) -> bool:
return self._enqueue(cmd, on_done, bumps_pending=False)

def _enqueue(self, cmd: Command, on_done: Callable, bumps_pending: bool) -> bool:
key = cmd.key()
with self._lock:
if key in self._pending_keys:
return False
self._pending_keys.add(key)
if bumps_pending:
self._pending_op_count += 1
self._cmd_queue.put((cmd, on_done, bumps_pending))
return True

def _drain(self) -> None:
while True:
item = self._cmd_queue.get()
if item is _SHUTDOWN_SENTINEL:
return
cmd, on_done, bumps_pending = item
try:
result = cmd.run(self._ctx)
except Exception as e:
logging.exception("Command failed: %s", cmd)
result = e
with self._lock:
self._pending_keys.discard(cmd.key())
if bumps_pending:
self._pending_op_count -= 1
if bumps_pending:
# Nudge the poller for fresh status — don't wait out the tick.
try:
self._ctx.request_refresh()
except Exception:
logging.exception("Status refresh request failed")
self._result_queue.put((on_done, result))

def poll(self) -> None:
assert threading.current_thread() is threading.main_thread(), "CommandQueue.poll() must run on the main thread"
while True:
try:
on_done, result = self._result_queue.get_nowait()
except queue.Empty:
return
try:
on_done(result)
except Exception:
logging.exception("Command result callback failed")

def pending_op_count(self) -> int:
with self._lock:
return self._pending_op_count

def shutdown(self, join: bool = True) -> None:
self._cmd_queue.put(_SHUTDOWN_SENTINEL)
if join:
self._worker.join(timeout=TEARDOWN_JOIN_S)
11 changes: 10 additions & 1 deletion emulator/modhandler.py
Original file line number Diff line number Diff line change
Expand Up @@ -33,7 +33,13 @@
from modalapi.pedalboard_monitor import FileChangeMonitor
from modalapi.websocket_bridge import AsyncWebSocketBridge
import pistomp.settings as Settings
from emulator.stubs import StubEthernetManager, StubJackMute, StubWifiManager, VirtualAudiocard
from emulator.stubs import (
StubBluetoothManager,
StubEthernetManager,
StubJackMute,
StubWifiManager,
VirtualAudiocard,
)


class EmulatorModhandler(Modhandler):
Expand All @@ -57,6 +63,9 @@ def __init__(self, homedir):
self.root_uri = "http://127.0.0.1:18181/"
self.wifi_manager = StubWifiManager(on_status_change=self._on_wifi_status_change)
self.wifi_manager.poll()
self.bluetooth_manager.shutdown()
self.bluetooth_manager = StubBluetoothManager(on_status_change=self._on_bluetooth_status_change)
self.bluetooth_manager.poll()

# Replace the real EthernetManager (and its sysfs/systemctl polling
# thread) created by super().__init__() with the always-up stub.
Expand Down
192 changes: 191 additions & 1 deletion emulator/stubs.py
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,7 @@

VirtualAudiocard — in-memory audiocard; no ALSA/hardware access.
StubWifiManager — in-memory wifi; satisfies Mod/Modhandler's wifi_manager.
StubBluetoothManager — in-memory bluetooth; no D-Bus, no bluez, no threads.
StubEthernetManager — pinned-up ethernet stub; no sysfs / systemctl / threads.
StubRelay — no-op relay; satisfies the Relay interface without GPIO.
"""
Expand All @@ -27,10 +28,12 @@
import time
from typing import Callable, Optional

from modalapi.bluetooth import BtDevice, BtStatus, DeviceKind, KnownDevice
from modalapi.bluetooth.manager import BluetoothManager
from modalapi.ethernet import EthernetManager
from modalapi.jack_mute import JackMute
from modalapi.wifi import SavedConnection, ScannedNetwork, WifiStatus
from modalapi.wifi.commands import CommandQueue
from common.command_queue import CommandQueue
from modalapi.wifi.manager import WifiManager
from pistomp.audiocard import Audiocard
import pistomp.relay
Expand Down Expand Up @@ -255,6 +258,193 @@ def delete_connection(self, name: str) -> Optional[bytes]:
return None


class StubBluetoothManager(BluetoothManager):
"""In-memory bluetooth manager; no D-Bus connection and no bluez.

Devices only become visible once discovery is running, mirroring the real
thing: bluez publishes unpaired LE objects during a scan and purges them
the moment it stops. 'Stubborn Speaker' is a tripwire — pairing it always
fails, so the menu's error path is reachable in the emulator."""

FAILING_NAME = "Stubborn Speaker"

_NEARBY: list[BtDevice] = [
BtDevice(
path="/org/bluez/hci0/dev_D4_06_0F_EE_16_83",
address="D4:06:0F:EE:16:83",
name="EV-1-WL",
kind=DeviceKind.MIDI,
paired=False,
connected=False,
trusted=False,
rssi=-52,
),
BtDevice(
path="/org/bluez/hci0/dev_C8_3B_44_10_02_9A",
address="C8:3B:44:10:02:9A",
name="R400 Presenter",
kind=DeviceKind.INPUT,
paired=False,
connected=False,
trusted=False,
rssi=-71,
),
BtDevice(
path="/org/bluez/hci0/dev_11_22_33_44_55_66",
address="11:22:33:44:55:66",
name=FAILING_NAME,
kind=DeviceKind.MIDI,
paired=False,
connected=False,
trusted=False,
rssi=-88,
),
]

def __init__(self, on_status_change: Optional[Callable[[BtStatus], None]] = None) -> None:
self.lock = threading.Lock()
self.settings = None
self.on_status_change = on_status_change
self.last_status: BtStatus = {}
self._last_sig: tuple = ()
self._enabled: bool = True
self._capable: bool = True
self._discovering: bool = False
self._known: list[KnownDevice] = []
self._devices: dict[str, BtDevice] = {}
self._off: set[str] = set() # addresses whose device stopped advertising
self._off_at: float = 0.0 # monotonic time it went dark
self.queue: CommandQueue = CommandQueue(self)

STALE_AFTER_S = 15.0 # mirrors BluezClient._STALE_AFTER_S

def power_cycle(self, address: Optional[str] = None) -> None:
"""Simulate switching a device off mid-scan: it stops advertising, so
it must vanish from the nearby list even though discovery keeps
running (exactly what a real bluez never signals)."""
live = [a for a, d in self._devices.items() if not d["paired"]]
if address is None:
address = live[0] if live else None
if address is not None:
self._off.add(address)
self._off_at = time.monotonic()
self.request_refresh()

def _revive(self, address: Optional[str] = None) -> None:
"""Device powered back on: advertise again."""
if address is None:
self._off.clear()
else:
self._off.discard(address)
self.request_refresh()

# ----- overrides of the real manager's bluez-backed surface -----

@property
def supported(self) -> bool:
return True

@property
def capable(self) -> bool:
return self._capable

def status(self) -> BtStatus:
return BtStatus(
supported=True,
capable=self._capable,
enabled=self._enabled,
powered=self._enabled,
discovering=self._discovering,
connected=[d["name"] for d in self._devices.values() if d["connected"]],
)

def request_refresh(self) -> None:
"""Inherited poll() recomputes unconditionally; nothing to arm."""
return

def shutdown(self) -> None:
try:
self.queue.shutdown()
except Exception:
pass

def devices(self) -> list[BtDevice]:
now = time.monotonic()
if self._off and now - self._off_at > self.STALE_AFTER_S:
# Evict the ghosts, but keep the off set itself: the device is
# still powered off, so a later scan must not resurrect it.
self._devices = {a: d for a, d in self._devices.items() if a not in self._off}
self._off_at = now
return list(self._devices.values())

def known_devices(self) -> list[KnownDevice]:
return list(self._known)

def remember(self, device: BtDevice) -> None:
self._known = [k for k in self._known if k["address"] != device["address"]]
self._known.append(
KnownDevice(
address=device["address"],
name=device["name"],
kind=device["kind"].value,
last_connected=int(time.time()),
)
)

def forget(self, address: str, name: str) -> None:
self._known = [k for k in self._known if k["address"] != address]

def set_enabled(self, enabled: bool) -> Optional[str]:
self._enabled = enabled
if not enabled:
self._devices.clear()
self._discovering = False
self.request_refresh()
return None

def start_discovery(self) -> None:
self._discovering = True
for device in self._NEARBY:
if device["address"] in self._off:
continue # powered off: nothing advertises, bluez has no object
self._devices.setdefault(device["address"], device.copy())
self.request_refresh()

def stop_discovery(self) -> None:
self._discovering = False
# Unpaired objects do not survive the end of a scan.
self._devices = {a: d for a, d in self._devices.items() if d["paired"]}
self.request_refresh()

def pair(self, device: BtDevice) -> None:
if device["name"] == self.FAILING_NAME:
raise RuntimeError("org.bluez.Error.AuthenticationFailed: stub refuses to pair")
live = self._devices.setdefault(device["address"], device.copy())
live["paired"] = True
live["trusted"] = True
live["connected"] = True
self.remember(live)
self.request_refresh()

def connect(self, device: BtDevice) -> None:
live = self._devices.setdefault(device["address"], device.copy())
live["connected"] = True
self.remember(live)
self.request_refresh()

def disconnect(self, device: BtDevice) -> None:
live = self._devices.get(device["address"])
if live is not None:
live["connected"] = False
live["paired"] = False # the EV-1-WL's non-bonding behaviour
self.request_refresh()

def remove(self, device: BtDevice) -> None:
self._devices.pop(device["address"], None)
self.forget(device["address"], device["name"])
self.request_refresh()


class StubEthernetManager(EthernetManager):
"""Pinned-up ethernet stub for the emulator.

Expand Down
Loading
Loading