Skip to content
Closed
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
115 changes: 96 additions & 19 deletions NeewerLite/NeewerLite/AppDelegate.swift
Original file line number Diff line number Diff line change
Expand Up @@ -96,6 +96,12 @@ class AppDelegate: NSObject, NSApplicationDelegate, NSWindowDelegate, NSMenuDele
}
}
var scanningTimer: Timer?
/// How long a scan for saved lights runs before it stops by itself.
private let backgroundScanDuration: TimeInterval = 60
/// Minimum gap between background scans while a saved light is still missing.
private let backgroundScanRetryInterval: TimeInterval = 300
private var scanStopWorkItem: DispatchWorkItem?
private var lastScanStartedAt: Date?
var server: NeewerLiteServer?
var launching: Bool = true
var commonJobTimer: Timer?
Expand Down Expand Up @@ -134,6 +140,7 @@ class AppDelegate: NSObject, NSApplicationDelegate, NSWindowDelegate, NSMenuDele
self.viewsButton.selectSegment(withTag: idx ?? 0)

localizeXIBStrings()
addRescanMenuItem()

appMenu.delegate = self
self.statusItem.menu = appMenu
Expand Down Expand Up @@ -431,9 +438,72 @@ class AppDelegate: NSObject, NSApplicationDelegate, NSWindowDelegate, NSMenuDele
viewObject.view?.grayOut()
}
}
self.scanForMissingLightsIfNeeded()
}
}

// MARK: - Scan Lifecycle

/// Starts a BLE scan. With a `duration` the scan stops by itself (or earlier, once
/// every saved light is connected); without one it runs until `stopScanning()`.
/// Scanning never runs indefinitely in the background: an endless scan makes
/// CoreBluetooth accumulate every nearby device, and memory grows for as long
/// as the app stays open.
func startScanning(duration: TimeInterval?) {
guard let central = cbCentralManager, central.state == .poweredOn else { return }
central.stopScan()
central.scanForPeripherals(withServices: nil, options: nil)
scanning = true
lastScanStartedAt = Date()
Logger.debug(LogTag.bluetooth, "scanForPeripherals, duration: \(String(describing: duration))")

scanStopWorkItem?.cancel()
scanStopWorkItem = nil
if let duration {
let item = DispatchWorkItem { [weak self] in
guard let self, !self.scanningNewLightMode else { return }
self.stopScanning()
}
scanStopWorkItem = item
DispatchQueue.main.asyncAfter(deadline: .now() + duration, execute: item)
}
}

func stopScanning() {
scanStopWorkItem?.cancel()
scanStopWorkItem = nil
if cbCentralManager?.state == .poweredOn {
cbCentralManager?.stopScan()
}
scanning = false
// Non-Neewer devices only need to be remembered while a scan is running.
peripheralInvalidCache.removeAll()
Logger.debug(LogTag.bluetooth, "scan stopped")
}

private var hasMissingSavedLights: Bool {
if debugFakeLights {
return false
}
return viewObjects.contains { $0.device.peripheral == nil }
}

private func stopScanningIfAllLightsFound() {
if scanning && !scanningNewLightMode && !hasMissingSavedLights {
stopScanning()
}
}

/// Saved lights that are already known reconnect through `connect()` without a scan.
/// A scan is only needed for a saved light the app has not found since launch.
private func scanForMissingLightsIfNeeded() {
guard !scanning, hasMissingSavedLights else { return }
if let last = lastScanStartedAt, Date().timeIntervalSince(last) < backgroundScanRetryInterval {
return
}
startScanning(duration: backgroundScanDuration)
}

// MARK: - XIB String Localization

/// Overrides hardcoded English strings from MainMenu.xib with localized versions.
Expand Down Expand Up @@ -885,6 +955,25 @@ class AppDelegate: NSObject, NSApplicationDelegate, NSWindowDelegate, NSMenuDele
}
}

/// Adds "Rescan for Lights" to the status-bar menu, just above Quit.
/// Background scanning is time-boxed, so this lets the user force a fresh scan
/// when a saved light isn't reconnecting.
private func addRescanMenuItem() {
let item = NSMenuItem(
title: "Rescan for Lights".localized,
action: #selector(rescanLightsAction(_:)),
keyEquivalent: "")
item.target = self
let quitIndex = appMenu.items.firstIndex { $0.action == #selector(NSApplication.terminate(_:)) }
appMenu.insertItem(item, at: quitIndex ?? appMenu.items.count)
}

@objc func rescanLightsAction(_ sender: Any) {
Logger.info(LogTag.click, "Rescan for Lights")
// Not new-light mode, so scanAction runs a time-boxed scan for saved lights.
scanAction(self)
}

@IBAction func syncDatabaseAction(_ sender: NSMenuItem) {
ContentManager.shared.downloadDatabase(force: true)
}
Expand Down Expand Up @@ -1535,6 +1624,7 @@ class AppDelegate: NSObject, NSApplicationDelegate, NSWindowDelegate, NSMenuDele
Logger.info(LogTag.click, "Scan")
} else {
scanningNewLightMode = false
stopScanning()
scanningStatus?.stringValue = ""
sender.title = "Scan".localized
Logger.info(LogTag.click, "Stop")
Expand All @@ -1543,18 +1633,6 @@ class AppDelegate: NSObject, NSApplicationDelegate, NSWindowDelegate, NSMenuDele

@IBAction func scanAction(_ sender: AnyObject) {

if scanning {
// stop scanning
cbCentralManager?.stopScan()
scanning = false
} else {
// start scanning
cbCentralManager?.scanForPeripherals(withServices: nil, options: nil)
// scanAction(self)
scanning = true
Logger.debug("scanForPeripherals...")
}

Logger.debug("\(peripheralCache)")
peripheralCache.removeAll()
peripheralInvalidCache.removeAll()
Expand Down Expand Up @@ -1582,8 +1660,9 @@ class AppDelegate: NSObject, NSApplicationDelegate, NSWindowDelegate, NSMenuDele

self.statusItemIcon = .off
updateUI()
cbCentralManager?.scanForPeripherals(
withServices: nil, options: [CBCentralManagerScanOptionAllowDuplicatesKey: true])
// A new-light scan runs until the user presses Stop; any other scan is time-boxed.
// No AllowDuplicates: it delivers every advertisement packet of every nearby device.
startScanning(duration: scanningNewLightMode ? nil : backgroundScanDuration)
}

@objc func scanningTimerFired() {
Expand Down Expand Up @@ -1727,6 +1806,7 @@ class AppDelegate: NSObject, NSApplicationDelegate, NSWindowDelegate, NSMenuDele
peripheral, characteristic1, characteristic2)
targetViewObject.device.startLightOnNotify()
forcePowerOffAfterLaunchIfNeeded(targetViewObject)
stopScanningIfAllLightsFound()
}

if !found {
Expand Down Expand Up @@ -1826,13 +1906,10 @@ extension AppDelegate: CBCentralManagerDelegate {
case .unsupported: break
case .poweredOn:
Logger.debug(LogTag.bluetooth, "powered on")
central.scanForPeripherals(withServices: nil, options: nil)
// scanAction(self)
self.scanning = true
startScanning(duration: scanningNewLightMode ? nil : backgroundScanDuration)
case .poweredOff:
central.stopScan()
stopScanning()
Logger.debug(LogTag.bluetooth, "powered off")
self.scanning = false
case .resetting:
Logger.debug(LogTag.bluetooth, "resetting")
@unknown default: break
Expand Down
40 changes: 40 additions & 0 deletions NeewerLite/NeewerLite/Resources/Localizable.xcstrings
Original file line number Diff line number Diff line change
Expand Up @@ -8035,6 +8035,46 @@
}
}
},
"Rescan for Lights" : {
"localizations" : {
"de" : {
"stringUnit" : {
"state" : "translated",
"value" : "Lichter erneut suchen"
}
},
"es" : {
"stringUnit" : {
"state" : "translated",
"value" : "Volver a buscar luces"
}
},
"fr" : {
"stringUnit" : {
"state" : "translated",
"value" : "Rechercher à nouveau les lumières"
}
},
"ja" : {
"stringUnit" : {
"state" : "translated",
"value" : "ライトを再スキャン"
}
},
"ko" : {
"stringUnit" : {
"state" : "translated",
"value" : "조명 다시 검색"
}
},
"zh-Hans" : {
"stringUnit" : {
"state" : "translated",
"value" : "重新扫描灯"
}
}
}
},
"Restart Now" : {
"extractionState" : "stale",
"localizations" : {
Expand Down
28 changes: 26 additions & 2 deletions NeewerLite/NeewerLite/Server.swift
Original file line number Diff line number Diff line change
Expand Up @@ -102,6 +102,10 @@ private actor SessionManager {
}

func bindSessionID(_ sessionID: String, to context: MCPSessionContext) {
// A re-initialized context gets a new session ID; forget the old one.
if let previous = context.sessionID, previous != sessionID {
clientKeyBySessionID.removeValue(forKey: previous)
}
context.sessionID = sessionID
context.lastSeen = Date()
clientKeyBySessionID[sessionID] = context.clientKey
Expand Down Expand Up @@ -306,10 +310,25 @@ final class NeewerLiteServer {
let endpointEvent = "event: endpoint\ndata: /messages?sessionId=\(sessionId)\n\n"
try? await writer.writeBuffer(ByteBuffer(string: endpointEvent))

// Stream outbound SSE events until the session ends
// A periodic SSE comment makes a dropped client show up as a write error
// even when no MCP traffic is flowing; otherwise the session lives forever.
let heartbeat = Task {
while !Task.isCancelled {
try? await Task.sleep(nanoseconds: 30_000_000_000)
session.pushSSE(": keepalive\n\n")
}
}

// Stream outbound SSE events until the session ends or the client goes away
for await chunk in session.outbound {
try? await writer.writeBuffer(ByteBuffer(string: chunk))
do {
try await writer.writeBuffer(ByteBuffer(string: chunk))
} catch {
break
}
}
heartbeat.cancel()
session.finish()
try? await writer.write(.end)

// Clean up after client disconnects
Expand Down Expand Up @@ -396,6 +415,11 @@ final class NeewerLiteServer {
}
}
}

// The SSE connection is gone; release its MCP session context.
if let context = await sessionManager.context(forClientKey: clientKey) {
await sessionManager.removeContext(context)
}
}

// MARK: - MCP Route (Vapor ↔ MCP SDK)
Expand Down
7 changes: 7 additions & 0 deletions NeewerLite/NeewerLite/Spectrogram/AudioSpectrogram.swift
Original file line number Diff line number Diff line change
Expand Up @@ -221,6 +221,9 @@ public class AudioSpectrogram: NSObject {

deinit {
removeVolumeListener()
// Manually allocated buffers are not freed by ARC.
filterBank.deallocate()
sgemmResult.deallocate()
}

// A reusable array that contains the current frame of time domain audio data as single-precision
Expand Down Expand Up @@ -515,6 +518,10 @@ extension AudioSpectrogram: AVCaptureAudioDataOutputSampleBufferDelegate {
}

private func startVolumeListener() {
// startRunning() is called every time the Music view is shown; drop the
// previous listener so repeated starts don't stack listeners.
removeVolumeListener()

var defaultOutputDeviceID = AudioDeviceID(0)
var defaultOutputDeviceIDSize = UInt32(MemoryLayout.size(ofValue: defaultOutputDeviceID))

Expand Down
Loading