0.38.0 (72): Bluetooth LE MIDI controllers in Settings (Android and iOS)

- Android: BleMidi scans for the BLE MIDI service, connects through
  MidiManager.openBluetoothDevice, remembers and reconnects controllers;
  Settings › MIDI inputs › Bluetooth MIDI (Scan / Connect / Disconnect / Forget)
- iOS: the system Bluetooth MIDI panel from Setup › MIDI Sync, connected
  controllers remembered and reconnected at launch via CoreBluetooth

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
Reactorcoremeltdown
2026-11-16 14:57:53 +01:00
co-authored by Claude Opus 5.5
parent 2bc5cb1cbb
commit 4d9e2328cb
18 changed files with 574 additions and 7 deletions
+1
View File
@@ -25,6 +25,7 @@ enum AppBoot {
midi.onNote = { on, ch, note, vel in input.midiNote(on: on, channel: ch, note: note, velocity: vel) }
midi.onControl = { cc, value in input.midiControl(cc, value) }
midi.start(withDisabledKeys: settings.midiSourcesOff)
BluetoothMidi.shared.reconnectRemembered()
}
/// Leaving the foreground: save, and unless Sizzle stays on as a sound module
+16 -1
View File
@@ -29,6 +29,10 @@ final class AppSettings: ObservableObject {
@Published var soundModule: Bool { didSet { d.set(soundModule, forKey: "soundModule") } }
/// MIDI sources the user switched off (MidiSourceKey).
@Published var midiSourcesOff: Set<String> { didSet { d.set(Array(midiSourcesOff).sorted(), forKey: "midiSourcesOff") } }
/// Bluetooth LE MIDI controllers to connect at launch: peripheral id -> name.
@Published var bleMidiDevices: [String: String] {
didSet { d.set(bleMidiDevices.map { "\($0.key)|\($0.value)" }.sorted(), forKey: "bleMidiDevices") }
}
/// Input bindings, one `code=actionId` line each (gamepad: `modifier:code=actionId`);
/// nil until the user changes them (the defaults apply).
@Published var keyboardBindings: String? { didSet { d.set(keyboardBindings, forKey: "bindKeyboard") } }
@@ -45,6 +49,10 @@ final class AppSettings: ObservableObject {
receiveMidiClock = d.bool(forKey: "midiClockRecv")
soundModule = d.bool(forKey: "soundModule")
midiSourcesOff = Set(d.stringArray(forKey: "midiSourcesOff") ?? [])
bleMidiDevices = Dictionary((d.stringArray(forKey: "bleMidiDevices") ?? []).map { e -> (String, String) in
let parts = e.split(separator: "|", maxSplits: 1).map(String.init)
return (parts[0], parts.count > 1 ? parts[1] : parts[0])
}, uniquingKeysWith: { a, _ in a })
keyboardBindings = d.string(forKey: "bindKeyboard")
gamepadBindings = d.string(forKey: "bindGamepad")
midiBindings = d.string(forKey: "bindMidi")
@@ -53,7 +61,8 @@ final class AppSettings: ObservableObject {
// MARK: Backup text
private static let keys = ["palette", "recordTailBars", "kbdChannel", "kbdOctave", "vuMeters", "midiClockSend",
"midiClockRecv", "soundModule", "midiSourcesOff", "bindKeyboard", "bindGamepad", "bindMidi"]
"midiClockRecv", "soundModule", "midiSourcesOff", "bleMidiDevices", "bindKeyboard",
"bindGamepad", "bindMidi"]
/// Every setting as `key=value` lines; multi-line values (bindings, the source
/// list) are escaped (`\n` → `\\n`).
@@ -92,6 +101,12 @@ final class AppSettings: ObservableObject {
if let v = map["midiClockRecv"] { receiveMidiClock = v == "true" }
if let v = map["soundModule"] { soundModule = v == "true" }
if let v = map["midiSourcesOff"] { midiSourcesOff = Set(v.split(separator: "\n").map(String.init)) }
if let v = map["bleMidiDevices"] {
bleMidiDevices = Dictionary(v.split(separator: "\n").map { e -> (String, String) in
let parts = e.split(separator: "|", maxSplits: 1).map(String.init)
return (parts[0], parts.count > 1 ? parts[1] : parts[0])
}, uniquingKeysWith: { a, _ in a })
}
if let v = map["bindKeyboard"] { keyboardBindings = v }
if let v = map["bindGamepad"] { gamepadBindings = v }
if let v = map["bindMidi"] { midiBindings = v }
+96
View File
@@ -0,0 +1,96 @@
// SPDX-FileCopyrightText: 2026 Reactorcoremeltdown
// SPDX-License-Identifier: GPL-3.0-or-later
import Foundation
#if os(iOS)
import CoreBluetooth
#endif
/// Bluetooth LE MIDI controllers (the Android app's BleMidi). Discovery and
/// connecting go through the system's Bluetooth MIDI panel (CABTMIDICentralViewController,
/// Setup › MIDI Sync › Find controllers); once connected a controller is an
/// ordinary CoreMIDI source, listed and played like the others.
///
/// When the panel closes, the connected BLE MIDI peripherals are remembered
/// (identifier and name, in AppSettings); at the next launch Sizzle connects them
/// again through CoreBluetooth, so they come back without opening the panel.
/// Bluetooth is only touched once something is remembered or the panel is used,
/// so the permission prompt doesn't appear for people without BLE controllers.
@MainActor
final class BluetoothMidi: ObservableObject {
static let shared = BluetoothMidi()
/// Peripheral identifier -> name.
@Published private(set) var remembered: [String: String]
private init() {
remembered = AppSettings.shared.bleMidiDevices
}
func forget(_ id: String) {
remembered[id] = nil
AppSettings.shared.bleMidiDevices = remembered
#if os(iOS)
if let uuid = UUID(uuidString: id), let p = central?.retrievePeripherals(withIdentifiers: [uuid]).first {
central?.cancelPeripheralConnection(p)
}
#endif
}
#if os(iOS)
static let midiService = CBUUID(string: "03B80E5A-EDE8-4B33-A751-6CE34EC4C700")
private var central: CBCentralManager?
private var pending: [() -> Void] = []
private lazy var delegate = CentralDelegate { [weak self] in self?.poweredOn() }
/// Run [action] once Bluetooth is on (creating the central manager on first use).
private func whenPoweredOn(_ action: @escaping () -> Void) {
if let c = central, c.state == .poweredOn { action(); return }
pending.append(action)
if central == nil { central = CBCentralManager(delegate: delegate, queue: .main) }
}
/// At launch: connect every remembered controller.
func reconnectRemembered() {
guard !remembered.isEmpty else { return }
whenPoweredOn { [self] in
let ids = remembered.keys.compactMap(UUID.init(uuidString:))
for p in central?.retrievePeripherals(withIdentifiers: ids) ?? [] where p.state == .disconnected {
central?.connect(p, options: nil)
}
}
}
/// The Bluetooth MIDI panel closed: remember what is connected now.
func panelClosed() {
whenPoweredOn { [self] in
for p in central?.retrieveConnectedPeripherals(withServices: [Self.midiService]) ?? [] {
remembered[p.identifier.uuidString] = p.name ?? "Bluetooth MIDI"
}
AppSettings.shared.bleMidiDevices = remembered
}
}
private func poweredOn() {
let actions = pending
pending.removeAll()
actions.forEach { $0() }
}
#else
func reconnectRemembered() {}
func panelClosed() {}
#endif
}
#if os(iOS)
/// The central manager's delegate, kept out of the Objective-C header (which
/// doesn't import CoreBluetooth).
private final class CentralDelegate: NSObject, CBCentralManagerDelegate {
private let onPoweredOn: @MainActor () -> Void
init(_ onPoweredOn: @escaping @MainActor () -> Void) { self.onPoweredOn = onPoweredOn }
func centralManagerDidUpdateState(_ central: CBCentralManager) {
guard central.state == .poweredOn else { return }
Task { @MainActor in self.onPoweredOn() }
}
}
#endif
+2
View File
@@ -20,6 +20,8 @@
<string>1</string>
<key>LSSupportsOpeningDocumentsInPlace</key>
<true/>
<key>NSBluetoothAlwaysUsageDescription</key>
<string>Sizzle connects Bluetooth MIDI controllers and reconnects them when it starts.</string>
<key>NSMicrophoneUsageDescription</key>
<string>Sizzle records the microphone or an audio interface's input into samples.</string>
<key>UIBackgroundModes</key>
@@ -148,6 +148,8 @@ struct MidiSyncCard: View {
SizzleMidi.shared.setSourceKey(src.key, enabled: on)
}
}
SetupDivider()
BluetoothMidiSection()
}
}
}
@@ -195,3 +197,35 @@ struct BackupCard: View {
}
}
}
/// Bluetooth LE MIDI controllers (the Android app's Bluetooth MIDI list): the
/// system panel finds and connects them; connected ones join the MIDI inputs
/// above and are remembered, to reconnect at every launch until forgotten.
struct BluetoothMidiSection: View {
@ObservedObject var ble = BluetoothMidi.shared
var body: some View {
HStack {
VStack(alignment: .leading, spacing: 2) {
Text("Bluetooth MIDI").font(.system(size: 15, weight: .medium)).foregroundColor(Theme.text)
Text("Find Bluetooth LE MIDI controllers and connect them. Connected ones are listed with the " +
"MIDI inputs and reconnect at every launch.")
.font(.system(size: 12)).foregroundColor(Theme.dim).fixedSize(horizontal: false, vertical: true)
}
Spacer()
SetupButton(title: "Find controllers", icon: "antenna.radiowaves.left.and.right") {
BluetoothMidiPanel.present { ble.panelClosed() }
}
}
ForEach(ble.remembered.sorted { $0.value < $1.value }, id: \.key) { id, name in
HStack {
VStack(alignment: .leading, spacing: 2) {
Text(name).font(.system(size: 15)).foregroundColor(Theme.text)
Text("Remembered — reconnects at launch").font(.system(size: 12)).foregroundColor(Theme.dim)
}
Spacer()
SetupButton(title: "Forget") { ble.forget(id) }
}
}
}
}
@@ -9,6 +9,7 @@ import SwiftUI
#if canImport(UIKit)
import AVKit
import CoreAudioKit
import UIKit
enum ShareSheet {
@@ -119,8 +120,42 @@ struct AudioRouteView: View {
}
}
/// The system's Bluetooth MIDI panel (find, connect, disconnect BLE MIDI
/// controllers) in a sheet with Done; [done] runs however it closes.
enum BluetoothMidiPanel {
@MainActor static func present(done: @escaping () -> Void) {
let scenes = UIApplication.shared.connectedScenes.compactMap { $0 as? UIWindowScene }
let scene = scenes.first { $0.activationState == .foregroundActive } ?? scenes.first
var top = scene?.windows.first { $0.isKeyWindow }?.rootViewController
while let p = top?.presentedViewController { top = p }
guard let host = top else { return }
let panel = CABTMIDICentralViewController()
let nav = UINavigationController(rootViewController: panel)
let closer = Closer(done)
panel.navigationItem.rightBarButtonItem = UIBarButtonItem(systemItem: .done, primaryAction: UIAction { [weak nav] _ in
nav?.dismiss(animated: true) { closer.fire() }
})
nav.modalPresentationStyle = .formSheet
nav.presentationController?.delegate = closer
objc_setAssociatedObject(nav, &Closer.key, closer, .OBJC_ASSOCIATION_RETAIN_NONATOMIC)
host.present(nav, animated: true)
}
private final class Closer: NSObject, UIAdaptivePresentationControllerDelegate {
static var key = 0
private var done: (() -> Void)?
init(_ done: @escaping () -> Void) { self.done = done }
func fire() { done?(); done = nil }
func presentationControllerDidDismiss(_ presentationController: UIPresentationController) { fire() }
}
}
#else
enum BluetoothMidiPanel {
@MainActor static func present(done: @escaping () -> Void) { done() }
}
struct AudioRouteView: View {
var body: some View {
Text("Output: Speaker\nInput: Microphone").font(.system(size: 14)).foregroundColor(Theme.text)
+2
View File
@@ -53,6 +53,7 @@ targets:
properties:
UIBackgroundModes: [audio]
NSMicrophoneUsageDescription: Sizzle records the microphone or an audio interface's input into samples.
NSBluetoothAlwaysUsageDescription: Sizzle connects Bluetooth MIDI controllers and reconnects them when it starts.
# Documents (songs, samples, recordings, backups) shows in the Files app.
UIFileSharingEnabled: true
LSSupportsOpeningDocumentsInPlace: true
@@ -77,6 +78,7 @@ targets:
- sdk: CoreAudioKit.framework
- sdk: CoreMIDI.framework
- sdk: GameController.framework
- sdk: CoreBluetooth.framework
settings:
base:
PRODUCT_BUNDLE_IDENTIFIER: cc.tiredsysadmin.ios.sizzle