Compare commits
6 Commits
| Author | SHA1 | Date | |
|---|---|---|---|
| e09983223c | |||
| f4b55dbf62 | |||
| 5e13ff069d | |||
| 7a34c719e8 | |||
| 5e0cc74aaf | |||
| 0ecf2c7940 |
@@ -16,6 +16,9 @@
|
|||||||
A100000D229E3D0000000007 /* Assets.xcassets in Resources */ = {isa = PBXBuildFile; fileRef = A100000E229E3D0000000007 /* Assets.xcassets */; };
|
A100000D229E3D0000000007 /* Assets.xcassets in Resources */ = {isa = PBXBuildFile; fileRef = A100000E229E3D0000000007 /* Assets.xcassets */; };
|
||||||
A1000020229E3D0000000019 /* SerialManager.swift in Sources */ = {isa = PBXBuildFile; fileRef = A1000021229E3D000000001A /* SerialManager.swift */; };
|
A1000020229E3D0000000019 /* SerialManager.swift in Sources */ = {isa = PBXBuildFile; fileRef = A1000021229E3D000000001A /* SerialManager.swift */; };
|
||||||
A1000022229E3D000000001B /* HardwareView.swift in Sources */ = {isa = PBXBuildFile; fileRef = A1000023229E3D000000001C /* HardwareView.swift */; };
|
A1000022229E3D000000001B /* HardwareView.swift in Sources */ = {isa = PBXBuildFile; fileRef = A1000023229E3D000000001C /* HardwareView.swift */; };
|
||||||
|
A1000024229E3D000000001D /* VUServer.swift in Sources */ = {isa = PBXBuildFile; fileRef = A1000025229E3D000000001E /* VUServer.swift */; };
|
||||||
|
A1000026229E3D000000001F /* ServerView.swift in Sources */ = {isa = PBXBuildFile; fileRef = A1000027229E3D0000000020 /* ServerView.swift */; };
|
||||||
|
A1000028229E3D0000000021 /* SplashView.swift in Sources */ = {isa = PBXBuildFile; fileRef = A1000029229E3D0000000022 /* SplashView.swift */; };
|
||||||
/* End PBXBuildFile section */
|
/* End PBXBuildFile section */
|
||||||
|
|
||||||
/* Begin PBXFileReference section */
|
/* Begin PBXFileReference section */
|
||||||
@@ -31,6 +34,9 @@
|
|||||||
A1000011229E3D000000000A /* AudioVUMeter.app */ = {isa = PBXFileReference; explicitFileType = wrapper.application; includeInIndex = 0; path = AudioVUMeter.app; sourceTree = BUILT_PRODUCTS_DIR; };
|
A1000011229E3D000000000A /* AudioVUMeter.app */ = {isa = PBXFileReference; explicitFileType = wrapper.application; includeInIndex = 0; path = AudioVUMeter.app; sourceTree = BUILT_PRODUCTS_DIR; };
|
||||||
A1000021229E3D000000001A /* SerialManager.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = SerialManager.swift; sourceTree = "<group>"; };
|
A1000021229E3D000000001A /* SerialManager.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = SerialManager.swift; sourceTree = "<group>"; };
|
||||||
A1000023229E3D000000001C /* HardwareView.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = HardwareView.swift; sourceTree = "<group>"; };
|
A1000023229E3D000000001C /* HardwareView.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = HardwareView.swift; sourceTree = "<group>"; };
|
||||||
|
A1000025229E3D000000001E /* VUServer.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = VUServer.swift; sourceTree = "<group>"; };
|
||||||
|
A1000027229E3D0000000020 /* ServerView.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = ServerView.swift; sourceTree = "<group>"; };
|
||||||
|
A1000029229E3D0000000022 /* SplashView.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = SplashView.swift; sourceTree = "<group>"; };
|
||||||
/* End PBXFileReference section */
|
/* End PBXFileReference section */
|
||||||
|
|
||||||
/* Begin PBXFrameworksBuildPhase section */
|
/* Begin PBXFrameworksBuildPhase section */
|
||||||
@@ -63,6 +69,9 @@
|
|||||||
A100000C229E3D0000000006 /* SettingsView.swift */,
|
A100000C229E3D0000000006 /* SettingsView.swift */,
|
||||||
A1000021229E3D000000001A /* SerialManager.swift */,
|
A1000021229E3D000000001A /* SerialManager.swift */,
|
||||||
A1000023229E3D000000001C /* HardwareView.swift */,
|
A1000023229E3D000000001C /* HardwareView.swift */,
|
||||||
|
A1000025229E3D000000001E /* VUServer.swift */,
|
||||||
|
A1000027229E3D0000000020 /* ServerView.swift */,
|
||||||
|
A1000029229E3D0000000022 /* SplashView.swift */,
|
||||||
A100000E229E3D0000000007 /* Assets.xcassets */,
|
A100000E229E3D0000000007 /* Assets.xcassets */,
|
||||||
A100000F229E3D0000000008 /* AudioVUMeter.entitlements */,
|
A100000F229E3D0000000008 /* AudioVUMeter.entitlements */,
|
||||||
A1000010229E3D0000000009 /* Info.plist */,
|
A1000010229E3D0000000009 /* Info.plist */,
|
||||||
@@ -155,6 +164,9 @@
|
|||||||
A100000B229E3D0000000006 /* SettingsView.swift in Sources */,
|
A100000B229E3D0000000006 /* SettingsView.swift in Sources */,
|
||||||
A1000020229E3D0000000019 /* SerialManager.swift in Sources */,
|
A1000020229E3D0000000019 /* SerialManager.swift in Sources */,
|
||||||
A1000022229E3D000000001B /* HardwareView.swift in Sources */,
|
A1000022229E3D000000001B /* HardwareView.swift in Sources */,
|
||||||
|
A1000024229E3D000000001D /* VUServer.swift in Sources */,
|
||||||
|
A1000026229E3D000000001F /* ServerView.swift in Sources */,
|
||||||
|
A1000028229E3D0000000021 /* SplashView.swift in Sources */,
|
||||||
);
|
);
|
||||||
runOnlyForDeploymentPostprocessing = 0;
|
runOnlyForDeploymentPostprocessing = 0;
|
||||||
};
|
};
|
||||||
@@ -298,7 +310,7 @@
|
|||||||
"$(inherited)",
|
"$(inherited)",
|
||||||
"@executable_path/../Frameworks",
|
"@executable_path/../Frameworks",
|
||||||
);
|
);
|
||||||
MARKETING_VERSION = 1.1;
|
MARKETING_VERSION = 1.3;
|
||||||
PRODUCT_BUNDLE_IDENTIFIER = com.audiotools.AudioVUMeter;
|
PRODUCT_BUNDLE_IDENTIFIER = com.audiotools.AudioVUMeter;
|
||||||
PRODUCT_NAME = "$(TARGET_NAME)";
|
PRODUCT_NAME = "$(TARGET_NAME)";
|
||||||
SWIFT_EMIT_LOC_STRINGS = YES;
|
SWIFT_EMIT_LOC_STRINGS = YES;
|
||||||
@@ -327,7 +339,7 @@
|
|||||||
"$(inherited)",
|
"$(inherited)",
|
||||||
"@executable_path/../Frameworks",
|
"@executable_path/../Frameworks",
|
||||||
);
|
);
|
||||||
MARKETING_VERSION = 1.1;
|
MARKETING_VERSION = 1.3;
|
||||||
PRODUCT_BUNDLE_IDENTIFIER = com.audiotools.AudioVUMeter;
|
PRODUCT_BUNDLE_IDENTIFIER = com.audiotools.AudioVUMeter;
|
||||||
PRODUCT_NAME = "$(TARGET_NAME)";
|
PRODUCT_NAME = "$(TARGET_NAME)";
|
||||||
SWIFT_EMIT_LOC_STRINGS = YES;
|
SWIFT_EMIT_LOC_STRINGS = YES;
|
||||||
|
|||||||
@@ -6,7 +6,13 @@
|
|||||||
<true/>
|
<true/>
|
||||||
<key>com.apple.security.device.audio-input</key>
|
<key>com.apple.security.device.audio-input</key>
|
||||||
<true/>
|
<true/>
|
||||||
|
<key>com.apple.security.device.serial</key>
|
||||||
|
<true/>
|
||||||
<key>com.apple.security.files.user-selected.read-only</key>
|
<key>com.apple.security.files.user-selected.read-only</key>
|
||||||
<true/>
|
<true/>
|
||||||
|
<key>com.apple.security.network.server</key>
|
||||||
|
<true/>
|
||||||
|
<key>com.apple.security.network.client</key>
|
||||||
|
<true/>
|
||||||
</dict>
|
</dict>
|
||||||
</plist>
|
</plist>
|
||||||
|
|||||||
@@ -5,6 +5,7 @@
|
|||||||
// macOS Audio VU Meter with System Monitoring
|
// macOS Audio VU Meter with System Monitoring
|
||||||
// Captures audio from BlackHole virtual audio device
|
// Captures audio from BlackHole virtual audio device
|
||||||
// Outputs to physical VU meter hardware via Serial/USB
|
// Outputs to physical VU meter hardware via Serial/USB
|
||||||
|
// Includes VU Server for external app connections
|
||||||
//
|
//
|
||||||
|
|
||||||
import SwiftUI
|
import SwiftUI
|
||||||
@@ -14,21 +15,40 @@ struct AudioVUMeterApp: App {
|
|||||||
@StateObject private var audioEngine = AudioEngine()
|
@StateObject private var audioEngine = AudioEngine()
|
||||||
@StateObject private var systemMonitor = SystemMonitor()
|
@StateObject private var systemMonitor = SystemMonitor()
|
||||||
@StateObject private var serialManager = SerialManager()
|
@StateObject private var serialManager = SerialManager()
|
||||||
|
@StateObject private var vuServer = VUServer()
|
||||||
|
|
||||||
// Timer for updating hardware values
|
// Timer for updating hardware values
|
||||||
@State private var updateTimer: Timer?
|
@State private var updateTimer: Timer?
|
||||||
|
|
||||||
|
// Splash screen state
|
||||||
|
@State private var showSplash = true
|
||||||
|
|
||||||
var body: some Scene {
|
var body: some Scene {
|
||||||
WindowGroup {
|
WindowGroup {
|
||||||
|
ZStack {
|
||||||
ContentView()
|
ContentView()
|
||||||
.environmentObject(audioEngine)
|
.environmentObject(audioEngine)
|
||||||
.environmentObject(systemMonitor)
|
.environmentObject(systemMonitor)
|
||||||
.environmentObject(serialManager)
|
.environmentObject(serialManager)
|
||||||
|
.environmentObject(vuServer)
|
||||||
.onAppear {
|
.onAppear {
|
||||||
|
setupServer()
|
||||||
startHardwareUpdateTimer()
|
startHardwareUpdateTimer()
|
||||||
}
|
}
|
||||||
.onDisappear {
|
.onDisappear {
|
||||||
stopHardwareUpdateTimer()
|
stopHardwareUpdateTimer()
|
||||||
|
vuServer.stop()
|
||||||
|
}
|
||||||
|
|
||||||
|
// Splash screen overlay
|
||||||
|
if showSplash {
|
||||||
|
SplashView {
|
||||||
|
withAnimation(.easeOut(duration: 0.5)) {
|
||||||
|
showSplash = false
|
||||||
|
}
|
||||||
|
}
|
||||||
|
.transition(.opacity)
|
||||||
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
.windowStyle(.hiddenTitleBar)
|
.windowStyle(.hiddenTitleBar)
|
||||||
@@ -38,14 +58,32 @@ struct AudioVUMeterApp: App {
|
|||||||
SettingsView()
|
SettingsView()
|
||||||
.environmentObject(audioEngine)
|
.environmentObject(audioEngine)
|
||||||
.environmentObject(serialManager)
|
.environmentObject(serialManager)
|
||||||
|
.environmentObject(vuServer)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private func setupServer() {
|
||||||
|
// Link server to serial manager for broadcasting
|
||||||
|
vuServer.serialManager = serialManager
|
||||||
|
|
||||||
|
// Auto-start server if it was enabled
|
||||||
|
if vuServer.options.enabled {
|
||||||
|
vuServer.start()
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
private func startHardwareUpdateTimer() {
|
private func startHardwareUpdateTimer() {
|
||||||
updateTimer = Timer.scheduledTimer(withTimeInterval: 1.0/30.0, repeats: true) { _ in
|
updateTimer = Timer.scheduledTimer(withTimeInterval: 1.0/30.0, repeats: true) { _ in
|
||||||
|
// Check if external control is active from VU Server
|
||||||
|
if vuServer.externalControlActive, let externalValues = vuServer.receivedDialValues {
|
||||||
|
// Use values from external app
|
||||||
|
serialManager.dialValues = externalValues
|
||||||
|
} else {
|
||||||
|
// Use local audio/system values
|
||||||
serialManager.updateValues(audioEngine: audioEngine, systemMonitor: systemMonitor)
|
serialManager.updateValues(audioEngine: audioEngine, systemMonitor: systemMonitor)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
}
|
||||||
|
|
||||||
private func stopHardwareUpdateTimer() {
|
private func stopHardwareUpdateTimer() {
|
||||||
updateTimer?.invalidate()
|
updateTimer?.invalidate()
|
||||||
|
|||||||
@@ -11,9 +11,11 @@ struct ContentView: View {
|
|||||||
@EnvironmentObject var audioEngine: AudioEngine
|
@EnvironmentObject var audioEngine: AudioEngine
|
||||||
@EnvironmentObject var systemMonitor: SystemMonitor
|
@EnvironmentObject var systemMonitor: SystemMonitor
|
||||||
@EnvironmentObject var serialManager: SerialManager
|
@EnvironmentObject var serialManager: SerialManager
|
||||||
|
@EnvironmentObject var vuServer: VUServer
|
||||||
|
|
||||||
@State private var showSettings = false
|
@State private var showSettings = false
|
||||||
@State private var showHardwareSettings = false
|
@State private var showHardwareSettings = false
|
||||||
|
@State private var showServerSettings = false
|
||||||
|
|
||||||
var body: some View {
|
var body: some View {
|
||||||
ZStack {
|
ZStack {
|
||||||
@@ -38,6 +40,15 @@ struct ContentView: View {
|
|||||||
|
|
||||||
Spacer()
|
Spacer()
|
||||||
|
|
||||||
|
// Server settings button
|
||||||
|
Button(action: { showServerSettings.toggle() }) {
|
||||||
|
Image(systemName: "server.rack")
|
||||||
|
.font(.system(size: 14))
|
||||||
|
.foregroundColor(vuServer.isRunning ? .cyan : .gray)
|
||||||
|
}
|
||||||
|
.buttonStyle(.plain)
|
||||||
|
.help("VU Server Settings")
|
||||||
|
|
||||||
// Hardware settings button
|
// Hardware settings button
|
||||||
Button(action: { showHardwareSettings.toggle() }) {
|
Button(action: { showHardwareSettings.toggle() }) {
|
||||||
Image(systemName: "cable.connector")
|
Image(systemName: "cable.connector")
|
||||||
@@ -192,6 +203,10 @@ struct ContentView: View {
|
|||||||
HardwarePanelView()
|
HardwarePanelView()
|
||||||
.environmentObject(serialManager)
|
.environmentObject(serialManager)
|
||||||
|
|
||||||
|
// VU Server Panel
|
||||||
|
ServerPanelView()
|
||||||
|
.environmentObject(vuServer)
|
||||||
|
|
||||||
// Control buttons
|
// Control buttons
|
||||||
HStack(spacing: 15) {
|
HStack(spacing: 15) {
|
||||||
Button(action: {
|
Button(action: {
|
||||||
@@ -224,11 +239,15 @@ struct ContentView: View {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
.frame(width: 400, height: 750)
|
.frame(width: 400, height: 880)
|
||||||
.sheet(isPresented: $showHardwareSettings) {
|
.sheet(isPresented: $showHardwareSettings) {
|
||||||
HardwareSettingsSheet()
|
HardwareSettingsSheet()
|
||||||
.environmentObject(serialManager)
|
.environmentObject(serialManager)
|
||||||
}
|
}
|
||||||
|
.sheet(isPresented: $showServerSettings) {
|
||||||
|
ServerSettingsSheet()
|
||||||
|
.environmentObject(vuServer)
|
||||||
|
}
|
||||||
.onAppear {
|
.onAppear {
|
||||||
audioEngine.start()
|
audioEngine.start()
|
||||||
systemMonitor.startMonitoring()
|
systemMonitor.startMonitoring()
|
||||||
@@ -340,4 +359,5 @@ struct ControlButtonStyle: ButtonStyle {
|
|||||||
.environmentObject(AudioEngine())
|
.environmentObject(AudioEngine())
|
||||||
.environmentObject(SystemMonitor())
|
.environmentObject(SystemMonitor())
|
||||||
.environmentObject(SerialManager())
|
.environmentObject(SerialManager())
|
||||||
|
.environmentObject(VUServer())
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -91,18 +91,54 @@ struct HardwarePanelView: View {
|
|||||||
.disabled(serialManager.isProbing)
|
.disabled(serialManager.isProbing)
|
||||||
}
|
}
|
||||||
|
|
||||||
// Stats / Device info
|
// Stats / Device info / Errors
|
||||||
if serialManager.isConnected {
|
if serialManager.isConnected {
|
||||||
|
VStack(spacing: 4) {
|
||||||
HStack {
|
HStack {
|
||||||
Text("TX: \(formatBytes(serialManager.bytesSent))")
|
Text("TX: \(formatBytes(serialManager.bytesSent))")
|
||||||
.font(.system(size: 9, design: .monospaced))
|
.font(.system(size: 9, design: .monospaced))
|
||||||
.foregroundColor(.gray)
|
.foregroundColor(.gray)
|
||||||
|
|
||||||
|
Text("RX: \(formatBytes(serialManager.bytesReceived))")
|
||||||
|
.font(.system(size: 9, design: .monospaced))
|
||||||
|
.foregroundColor(.gray)
|
||||||
|
|
||||||
Spacer()
|
Spacer()
|
||||||
|
|
||||||
Text(serialManager.selectedPortPath.components(separatedBy: "/").last ?? "")
|
Text(serialManager.selectedPortPath.components(separatedBy: "/").last ?? "")
|
||||||
.font(.system(size: 9, design: .monospaced))
|
.font(.system(size: 9, design: .monospaced))
|
||||||
.foregroundColor(.gray)
|
.foregroundColor(.green)
|
||||||
|
}
|
||||||
|
|
||||||
|
// VU-Server hardware info
|
||||||
|
if serialManager.selectedProtocol == .vuServer {
|
||||||
|
HStack {
|
||||||
|
if let fw = serialManager.firmwareVersion {
|
||||||
|
Text("FW: \(fw)")
|
||||||
|
.font(.system(size: 8, design: .monospaced))
|
||||||
|
.foregroundColor(.cyan)
|
||||||
|
}
|
||||||
|
if let hw = serialManager.hardwareVersion {
|
||||||
|
Text("HW: \(hw)")
|
||||||
|
.font(.system(size: 8, design: .monospaced))
|
||||||
|
.foregroundColor(.cyan)
|
||||||
|
}
|
||||||
|
Spacer()
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
} else if let error = serialManager.lastError {
|
||||||
|
HStack {
|
||||||
|
Image(systemName: "exclamationmark.triangle.fill")
|
||||||
|
.foregroundColor(.red)
|
||||||
|
.font(.system(size: 10))
|
||||||
|
|
||||||
|
Text(error)
|
||||||
|
.font(.system(size: 9, design: .monospaced))
|
||||||
|
.foregroundColor(.red)
|
||||||
|
.lineLimit(2)
|
||||||
|
|
||||||
|
Spacer()
|
||||||
}
|
}
|
||||||
} else if let detected = serialManager.detectedDevice {
|
} else if let detected = serialManager.detectedDevice {
|
||||||
HStack {
|
HStack {
|
||||||
@@ -122,6 +158,18 @@ struct HardwarePanelView: View {
|
|||||||
.foregroundColor(.gray)
|
.foregroundColor(.gray)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
} else if serialManager.availablePorts.isEmpty {
|
||||||
|
HStack {
|
||||||
|
Image(systemName: "usb")
|
||||||
|
.foregroundColor(.orange)
|
||||||
|
.font(.system(size: 10))
|
||||||
|
|
||||||
|
Text("No USB serial devices detected")
|
||||||
|
.font(.system(size: 9, design: .monospaced))
|
||||||
|
.foregroundColor(.orange)
|
||||||
|
|
||||||
|
Spacer()
|
||||||
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
.padding()
|
.padding()
|
||||||
@@ -183,29 +231,35 @@ struct DialIndicatorView: View {
|
|||||||
|
|
||||||
var body: some View {
|
var body: some View {
|
||||||
VStack(spacing: 4) {
|
VStack(spacing: 4) {
|
||||||
// Dial number
|
// Dial number with connection indicator
|
||||||
|
HStack(spacing: 2) {
|
||||||
|
Circle()
|
||||||
|
.fill(isConnected ? Color.green : Color.red)
|
||||||
|
.frame(width: 5, height: 5)
|
||||||
Text("D\(dialNumber)")
|
Text("D\(dialNumber)")
|
||||||
.font(.system(size: 10, weight: .bold, design: .monospaced))
|
.font(.system(size: 10, weight: .bold, design: .monospaced))
|
||||||
.foregroundColor(.white.opacity(0.7))
|
.foregroundColor(.white.opacity(0.7))
|
||||||
|
}
|
||||||
|
|
||||||
// Value arc
|
// Value arc
|
||||||
ZStack {
|
ZStack {
|
||||||
// Background arc
|
// Background arc
|
||||||
Circle()
|
Circle()
|
||||||
.trim(from: 0.25, to: 0.75)
|
.trim(from: 0.25, to: 0.75)
|
||||||
.stroke(Color.gray.opacity(0.2), lineWidth: 4)
|
.stroke(Color.gray.opacity(0.3), lineWidth: 4)
|
||||||
.frame(width: 50, height: 50)
|
.frame(width: 50, height: 50)
|
||||||
.rotationEffect(.degrees(180))
|
.rotationEffect(.degrees(180))
|
||||||
|
|
||||||
// Value arc
|
// Value arc - always show with minimum visibility
|
||||||
Circle()
|
Circle()
|
||||||
.trim(from: 0.25, to: 0.25 + (Double(value) / 255.0) * 0.5)
|
.trim(from: 0.25, to: 0.25 + max(0.02, (Double(value) / 255.0) * 0.5))
|
||||||
.stroke(
|
.stroke(
|
||||||
isConnected ? dialColor(for: value) : Color.gray,
|
dialColor(for: value, connected: isConnected),
|
||||||
style: StrokeStyle(lineWidth: 4, lineCap: .round)
|
style: StrokeStyle(lineWidth: 4, lineCap: .round)
|
||||||
)
|
)
|
||||||
.frame(width: 50, height: 50)
|
.frame(width: 50, height: 50)
|
||||||
.rotationEffect(.degrees(180))
|
.rotationEffect(.degrees(180))
|
||||||
|
.animation(.easeOut(duration: 0.1), value: value)
|
||||||
|
|
||||||
// Value text
|
// Value text
|
||||||
VStack(spacing: 0) {
|
VStack(spacing: 0) {
|
||||||
@@ -222,7 +276,10 @@ struct DialIndicatorView: View {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
private func dialColor(for value: Int) -> Color {
|
private func dialColor(for value: Int, connected: Bool) -> Color {
|
||||||
|
if !connected {
|
||||||
|
return Color.gray.opacity(0.5)
|
||||||
|
}
|
||||||
let ratio = Double(value) / 255.0
|
let ratio = Double(value) / 255.0
|
||||||
if ratio > 0.9 { return .red }
|
if ratio > 0.9 { return .red }
|
||||||
if ratio > 0.75 { return .orange }
|
if ratio > 0.75 { return .orange }
|
||||||
@@ -456,7 +513,8 @@ struct HardwareSettingsView: View {
|
|||||||
Text("Format: {\"dials\":[d1,d2,d3,d4]}\\n")
|
Text("Format: {\"dials\":[d1,d2,d3,d4]}\\n")
|
||||||
Text("Values: 0-255 array")
|
Text("Values: 0-255 array")
|
||||||
case .vuServer:
|
case .vuServer:
|
||||||
Text("Format: #0:val\\n#1:val\\n#2:val\\n#3:val\\n")
|
Text("Binary Protocol: '>' + 9-byte header + payload")
|
||||||
|
Text("Commands: 0x03 (single %), 0x04 (all %)")
|
||||||
Text("Values: 0-100 percentage per dial")
|
Text("Values: 0-100 percentage per dial")
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -17,7 +17,7 @@ enum SerialProtocol: String, CaseIterable, Identifiable {
|
|||||||
case rawBytes = "Raw Bytes (0-255)"
|
case rawBytes = "Raw Bytes (0-255)"
|
||||||
case textCommand = "Text Commands"
|
case textCommand = "Text Commands"
|
||||||
case json = "JSON Format"
|
case json = "JSON Format"
|
||||||
case vuServer = "VU-Server Compatible"
|
case vuServer = "VU-Server Binary"
|
||||||
|
|
||||||
var id: String { rawValue }
|
var id: String { rawValue }
|
||||||
|
|
||||||
@@ -32,11 +32,148 @@ enum SerialProtocol: String, CaseIterable, Identifiable {
|
|||||||
case .json:
|
case .json:
|
||||||
return "{\"cmd\":\"ping\"}\n".data(using: .utf8)!
|
return "{\"cmd\":\"ping\"}\n".data(using: .utf8)!
|
||||||
case .vuServer:
|
case .vuServer:
|
||||||
return "?\n".data(using: .utf8)! // Query command
|
// Binary probe: get firmware version command
|
||||||
|
return VUServerProtocol.buildCommand(.getFirmwareVersion, payload: [])
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// MARK: - VU-Server Binary Protocol
|
||||||
|
|
||||||
|
/// VU-Server hardware binary protocol implementation
|
||||||
|
/// Based on https://github.com/SasaKaranovic/VU-Server
|
||||||
|
struct VUServerProtocol {
|
||||||
|
|
||||||
|
// Protocol constants
|
||||||
|
static let startByte: UInt8 = 0x3E // '>'
|
||||||
|
static let responseStartByte: UInt8 = 0x3C // '<'
|
||||||
|
static let headerSize = 9
|
||||||
|
static let maxPayloadSize = 1000
|
||||||
|
|
||||||
|
// Command codes (from Comms_Hub_Gauge.py)
|
||||||
|
enum Command: UInt8 {
|
||||||
|
// Dial control commands
|
||||||
|
case setDialRawSingle = 0x01 // Set single dial raw value (0-65535)
|
||||||
|
case setDialRawAll = 0x02 // Set all dials raw
|
||||||
|
case setDialPercentSingle = 0x03 // Set single dial percentage (0-100)
|
||||||
|
case setDialPercentAll = 0x04 // Set all dials percentage
|
||||||
|
case setDialDAC = 0x05 // Set DAC directly
|
||||||
|
|
||||||
|
// Backlight commands
|
||||||
|
case setBacklightRGB = 0x12 // Set RGB backlight
|
||||||
|
case setBacklightRGBW = 0x13 // Set RGBW backlight
|
||||||
|
|
||||||
|
// Calibration
|
||||||
|
case calibrateMin = 0x20 // Calibrate minimum
|
||||||
|
case calibrateMax = 0x21 // Calibrate maximum
|
||||||
|
case calibrateMid = 0x22 // Calibrate midpoint
|
||||||
|
|
||||||
|
// Info commands
|
||||||
|
case getUID = 0x30 // Get device UID
|
||||||
|
case getFirmwareVersion = 0x31 // Get firmware version
|
||||||
|
case getHardwareVersion = 0x32 // Get hardware version
|
||||||
|
case getProtocolVersion = 0x33 // Get protocol version
|
||||||
|
|
||||||
|
// Easing commands
|
||||||
|
case setEasingDialStep = 0x40
|
||||||
|
case setEasingDialPeriod = 0x41
|
||||||
|
case setEasingBacklightStep = 0x42
|
||||||
|
case setEasingBacklightPeriod = 0x43
|
||||||
|
case getEasingConfig = 0x44
|
||||||
|
|
||||||
|
// Display commands
|
||||||
|
case clearDisplay = 0x50
|
||||||
|
case updateDisplay = 0x51
|
||||||
|
|
||||||
|
// Power
|
||||||
|
case setPower = 0x60
|
||||||
|
}
|
||||||
|
|
||||||
|
// Data type identifiers
|
||||||
|
enum DataType: UInt8 {
|
||||||
|
case none = 0x00
|
||||||
|
case uint8 = 0x01
|
||||||
|
case uint16 = 0x02
|
||||||
|
case uint32 = 0x03
|
||||||
|
case string = 0x04
|
||||||
|
case binary = 0x05
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Build a command frame for VU-Server hardware
|
||||||
|
/// Frame format: [START] [CMD] [RESERVED] [DATA_TYPE] [RESERVED] [LEN_H] [LEN_L] [RESERVED] [LEN_L] [PAYLOAD...]
|
||||||
|
static func buildCommand(_ command: Command, payload: [UInt8], dataType: DataType = .uint8) -> Data {
|
||||||
|
var frame = [UInt8]()
|
||||||
|
|
||||||
|
// Header (9 bytes)
|
||||||
|
frame.append(startByte) // Byte 0: Start '>'
|
||||||
|
frame.append(command.rawValue) // Byte 1: Command
|
||||||
|
frame.append(0x00) // Byte 2: Reserved
|
||||||
|
frame.append(dataType.rawValue) // Byte 3: Data type
|
||||||
|
frame.append(0x00) // Byte 4: Reserved
|
||||||
|
|
||||||
|
let payloadLen = UInt16(payload.count)
|
||||||
|
frame.append(UInt8(payloadLen >> 8)) // Byte 5: Length high
|
||||||
|
frame.append(UInt8(payloadLen & 0xFF)) // Byte 6: Length low
|
||||||
|
frame.append(0x00) // Byte 7: Reserved
|
||||||
|
frame.append(UInt8(payloadLen & 0xFF)) // Byte 8: Length low (repeated)
|
||||||
|
|
||||||
|
// Payload
|
||||||
|
frame.append(contentsOf: payload)
|
||||||
|
|
||||||
|
return Data(frame)
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Build command to set a single dial to a percentage value
|
||||||
|
static func setDialPercent(dialIndex: UInt8, percent: UInt8) -> Data {
|
||||||
|
let clampedPercent = min(percent, 100)
|
||||||
|
return buildCommand(.setDialPercentSingle, payload: [dialIndex, clampedPercent])
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Build command to set all dials at once (percentage values)
|
||||||
|
static func setAllDialsPercent(values: [UInt8]) -> Data {
|
||||||
|
let payload = values.map { min($0, 100) }
|
||||||
|
return buildCommand(.setDialPercentAll, payload: payload)
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Build command to set a single dial to a raw 16-bit value
|
||||||
|
static func setDialRaw(dialIndex: UInt8, value: UInt16) -> Data {
|
||||||
|
return buildCommand(.setDialRawSingle, payload: [
|
||||||
|
dialIndex,
|
||||||
|
UInt8(value >> 8), // High byte
|
||||||
|
UInt8(value & 0xFF) // Low byte
|
||||||
|
], dataType: .uint16)
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Build command to set backlight RGB color
|
||||||
|
static func setBacklightRGB(dialIndex: UInt8, red: UInt8, green: UInt8, blue: UInt8) -> Data {
|
||||||
|
return buildCommand(.setBacklightRGB, payload: [dialIndex, red, green, blue])
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Build command to set backlight RGBW color
|
||||||
|
static func setBacklightRGBW(dialIndex: UInt8, red: UInt8, green: UInt8, blue: UInt8, white: UInt8) -> Data {
|
||||||
|
return buildCommand(.setBacklightRGBW, payload: [dialIndex, red, green, blue, white])
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Parse response from hardware
|
||||||
|
static func parseResponse(_ data: Data) -> (success: Bool, command: UInt8, payload: Data)? {
|
||||||
|
guard data.count >= headerSize else { return nil }
|
||||||
|
|
||||||
|
let bytes = [UInt8](data)
|
||||||
|
|
||||||
|
// Check start byte
|
||||||
|
guard bytes[0] == responseStartByte else { return nil }
|
||||||
|
|
||||||
|
let command = bytes[1]
|
||||||
|
let payloadLength = Int(bytes[5]) << 8 | Int(bytes[6])
|
||||||
|
|
||||||
|
guard data.count >= headerSize + payloadLength else { return nil }
|
||||||
|
|
||||||
|
let payload = Data(bytes[headerSize..<(headerSize + payloadLength)])
|
||||||
|
|
||||||
|
return (success: true, command: command, payload: payload)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
/// Represents a serial port device with extended info
|
/// Represents a serial port device with extended info
|
||||||
struct SerialPort: Identifiable, Hashable {
|
struct SerialPort: Identifiable, Hashable {
|
||||||
let id: String
|
let id: String
|
||||||
@@ -111,6 +248,12 @@ class SerialManager: ObservableObject {
|
|||||||
@Published var dialConfigs: [DialConfig] = []
|
@Published var dialConfigs: [DialConfig] = []
|
||||||
@Published var lastError: String?
|
@Published var lastError: String?
|
||||||
@Published var bytesSent: UInt64 = 0
|
@Published var bytesSent: UInt64 = 0
|
||||||
|
@Published var bytesReceived: UInt64 = 0
|
||||||
|
|
||||||
|
// Hardware info (VU-Server)
|
||||||
|
@Published var firmwareVersion: String?
|
||||||
|
@Published var hardwareVersion: String?
|
||||||
|
@Published var deviceUID: String?
|
||||||
|
|
||||||
// Auto-probe state
|
// Auto-probe state
|
||||||
@Published var isProbing = false
|
@Published var isProbing = false
|
||||||
@@ -316,19 +459,60 @@ class SerialManager: ObservableObject {
|
|||||||
/// Perform the actual auto-probe
|
/// Perform the actual auto-probe
|
||||||
private func performAutoProbe() {
|
private func performAutoProbe() {
|
||||||
let ports = availablePorts
|
let ports = availablePorts
|
||||||
let baudRates = [115200, 9600, 57600, 38400, 19200] // Most common first
|
|
||||||
let protocols = SerialProtocol.allCases
|
|
||||||
|
|
||||||
let totalSteps = Double(ports.count * baudRates.count * protocols.count)
|
// First pass: quick check which ports can be opened
|
||||||
|
let baudRates = [115200, 9600] // Most common baud rates only
|
||||||
|
let protocols: [SerialProtocol] = [.vuServer, .rawBytes] // Most likely protocols
|
||||||
|
|
||||||
|
let totalSteps = Double(ports.count * baudRates.count * protocols.count + ports.count)
|
||||||
var currentStep = 0
|
var currentStep = 0
|
||||||
|
|
||||||
var bestResult: ProbeResult?
|
var workingPorts: [(port: SerialPort, baudRate: Int)] = []
|
||||||
|
|
||||||
|
// Phase 1: Find all ports that can be opened
|
||||||
|
DispatchQueue.main.async {
|
||||||
|
self.probeStatus = "Scanning USB ports..."
|
||||||
|
}
|
||||||
|
|
||||||
for port in ports {
|
for port in ports {
|
||||||
guard isProbing else { break }
|
guard isProbing else { break }
|
||||||
|
|
||||||
|
currentStep += 1
|
||||||
DispatchQueue.main.async {
|
DispatchQueue.main.async {
|
||||||
self.probeStatus = "Probing: \(port.name)"
|
self.probeProgress = Double(currentStep) / totalSteps
|
||||||
|
self.probeStatus = "Checking: \(port.name)"
|
||||||
|
}
|
||||||
|
|
||||||
|
// Quick check if port can be opened
|
||||||
|
let fd = open(port.path, O_RDWR | O_NOCTTY | O_NONBLOCK)
|
||||||
|
if fd != -1 {
|
||||||
|
close(fd)
|
||||||
|
// Port can be opened - it's a candidate
|
||||||
|
// Default to 115200 baud for serial USB devices
|
||||||
|
workingPorts.append((port: port, baudRate: 115200))
|
||||||
|
|
||||||
|
DispatchQueue.main.async {
|
||||||
|
let result = ProbeResult(
|
||||||
|
port: port,
|
||||||
|
protocol_: .vuServer,
|
||||||
|
baudRate: 115200,
|
||||||
|
success: true,
|
||||||
|
response: "Port accessible",
|
||||||
|
responseTime: 0.01
|
||||||
|
)
|
||||||
|
self.probeResults.append(result)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// Phase 2: If we have working ports, try to communicate
|
||||||
|
var bestResult: ProbeResult?
|
||||||
|
|
||||||
|
for (port, defaultBaud) in workingPorts {
|
||||||
|
guard isProbing else { break }
|
||||||
|
|
||||||
|
DispatchQueue.main.async {
|
||||||
|
self.probeStatus = "Testing: \(port.name)"
|
||||||
}
|
}
|
||||||
|
|
||||||
for baud in baudRates {
|
for baud in baudRates {
|
||||||
@@ -355,7 +539,7 @@ class SerialManager: ObservableObject {
|
|||||||
}
|
}
|
||||||
|
|
||||||
// If we got a response, this is very likely the device
|
// If we got a response, this is very likely the device
|
||||||
if result.response != nil {
|
if result.response != nil && !result.response!.isEmpty {
|
||||||
DispatchQueue.main.async {
|
DispatchQueue.main.async {
|
||||||
self.detectedDevice = port
|
self.detectedDevice = port
|
||||||
self.selectedPortPath = port.path
|
self.selectedPortPath = port.path
|
||||||
@@ -382,9 +566,20 @@ class SerialManager: ObservableObject {
|
|||||||
self.selectedPortPath = best.port.path
|
self.selectedPortPath = best.port.path
|
||||||
self.selectedProtocol = best.protocol_
|
self.selectedProtocol = best.protocol_
|
||||||
self.baudRate = best.baudRate
|
self.baudRate = best.baudRate
|
||||||
self.probeStatus = "Found: \(best.port.name) (\(best.protocol_.rawValue))"
|
self.probeStatus = "Found: \(best.port.name)"
|
||||||
|
// Auto-connect after successful probe
|
||||||
|
self.connect()
|
||||||
|
} else if let firstWorking = workingPorts.first {
|
||||||
|
// No response but port works - use it anyway
|
||||||
|
self.detectedDevice = firstWorking.port
|
||||||
|
self.selectedPortPath = firstWorking.port.path
|
||||||
|
self.selectedProtocol = .vuServer
|
||||||
|
self.baudRate = firstWorking.baudRate
|
||||||
|
self.probeStatus = "Using: \(firstWorking.port.name)"
|
||||||
|
// Auto-connect
|
||||||
|
self.connect()
|
||||||
} else {
|
} else {
|
||||||
self.probeStatus = "No VU meter found"
|
self.probeStatus = "No serial devices found"
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -409,9 +604,11 @@ class SerialManager: ObservableObject {
|
|||||||
options.c_lflag &= ~UInt(ICANON | ECHO | ECHOE | ISIG)
|
options.c_lflag &= ~UInt(ICANON | ECHO | ECHOE | ISIG)
|
||||||
options.c_oflag &= ~UInt(OPOST)
|
options.c_oflag &= ~UInt(OPOST)
|
||||||
|
|
||||||
// Set read timeout
|
// Set read timeout using withUnsafeMutableBytes for c_cc tuple
|
||||||
options.c_cc.16 = 0 // VMIN
|
withUnsafeMutableBytes(of: &options.c_cc) { ptr in
|
||||||
options.c_cc.17 = 5 // VTIME (0.5 seconds)
|
ptr[Int(VMIN)] = 0 // VMIN
|
||||||
|
ptr[Int(VTIME)] = 5 // VTIME (0.5 seconds)
|
||||||
|
}
|
||||||
|
|
||||||
tcsetattr(fd, TCSANOW, &options)
|
tcsetattr(fd, TCSANOW, &options)
|
||||||
tcflush(fd, TCIOFLUSH)
|
tcflush(fd, TCIOFLUSH)
|
||||||
@@ -482,19 +679,42 @@ class SerialManager: ObservableObject {
|
|||||||
|
|
||||||
/// Connect to selected serial port
|
/// Connect to selected serial port
|
||||||
func connect() {
|
func connect() {
|
||||||
|
print("[DEBUG] connect() called")
|
||||||
|
print("[DEBUG] selectedPortPath: \(selectedPortPath)")
|
||||||
|
print("[DEBUG] selectedProtocol: \(selectedProtocol)")
|
||||||
|
print("[DEBUG] baudRate: \(baudRate)")
|
||||||
|
|
||||||
guard !selectedPortPath.isEmpty else {
|
guard !selectedPortPath.isEmpty else {
|
||||||
lastError = "No port selected"
|
print("[DEBUG] ERROR: No port selected")
|
||||||
|
DispatchQueue.main.async {
|
||||||
|
self.lastError = "No port selected"
|
||||||
|
}
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// Ensure we disconnect first if already connected
|
||||||
|
if fileDescriptor != -1 {
|
||||||
|
print("[DEBUG] Already connected, disconnecting first...")
|
||||||
|
disconnect()
|
||||||
|
}
|
||||||
|
|
||||||
// Open serial port
|
// Open serial port
|
||||||
fileDescriptor = open(selectedPortPath, O_RDWR | O_NOCTTY | O_NONBLOCK)
|
print("[DEBUG] Opening port: \(selectedPortPath)")
|
||||||
|
let fd = open(selectedPortPath, O_RDWR | O_NOCTTY | O_NONBLOCK)
|
||||||
|
|
||||||
guard fileDescriptor != -1 else {
|
guard fd != -1 else {
|
||||||
lastError = "Failed to open port: \(String(cString: strerror(errno)))"
|
let errorMsg = String(cString: strerror(errno))
|
||||||
|
print("[DEBUG] ERROR: Failed to open port: \(errorMsg)")
|
||||||
|
DispatchQueue.main.async {
|
||||||
|
self.lastError = "Failed to open port: \(errorMsg)"
|
||||||
|
self.isConnected = false
|
||||||
|
}
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
|
|
||||||
|
print("[DEBUG] Port opened successfully, fd=\(fd)")
|
||||||
|
fileDescriptor = fd
|
||||||
|
|
||||||
// Configure serial port
|
// Configure serial port
|
||||||
var options = termios()
|
var options = termios()
|
||||||
tcgetattr(fileDescriptor, &options)
|
tcgetattr(fileDescriptor, &options)
|
||||||
@@ -525,13 +745,58 @@ class SerialManager: ObservableObject {
|
|||||||
// Clear any pending data
|
// Clear any pending data
|
||||||
tcflush(fileDescriptor, TCIOFLUSH)
|
tcflush(fileDescriptor, TCIOFLUSH)
|
||||||
|
|
||||||
isConnected = true
|
print("[DEBUG] Serial port configured, setting isConnected=true")
|
||||||
lastError = nil
|
|
||||||
|
|
||||||
print("Connected to \(selectedPortPath) at \(baudRate) baud")
|
// Update UI on main thread
|
||||||
|
DispatchQueue.main.async {
|
||||||
|
print("[DEBUG] Main thread: setting isConnected=true")
|
||||||
|
self.isConnected = true
|
||||||
|
self.lastError = nil
|
||||||
|
print("[DEBUG] Main thread: isConnected is now \(self.isConnected)")
|
||||||
|
}
|
||||||
|
|
||||||
// Start update timer
|
print("[DEBUG] Connected to \(selectedPortPath) at \(baudRate) baud")
|
||||||
startUpdateTimer()
|
|
||||||
|
// Start update timer (must be on main thread)
|
||||||
|
DispatchQueue.main.async {
|
||||||
|
print("[DEBUG] Starting update timer")
|
||||||
|
self.startUpdateTimer()
|
||||||
|
}
|
||||||
|
|
||||||
|
// For VU-Server: start response reader and query device info
|
||||||
|
if selectedProtocol == .vuServer {
|
||||||
|
print("[DEBUG] VU-Server protocol: starting response reader")
|
||||||
|
startResponseReader()
|
||||||
|
|
||||||
|
// Query device info after short delay
|
||||||
|
DispatchQueue.main.asyncAfter(deadline: .now() + 0.5) { [weak self] in
|
||||||
|
print("[DEBUG] Requesting device info")
|
||||||
|
self?.requestDeviceInfo()
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Request device information from VU-Server hardware
|
||||||
|
func requestDeviceInfo() {
|
||||||
|
guard isConnected, fileDescriptor != -1, selectedProtocol == .vuServer else { return }
|
||||||
|
|
||||||
|
writeQueue.async { [weak self] in
|
||||||
|
guard let self = self else { return }
|
||||||
|
|
||||||
|
// Query firmware version
|
||||||
|
let fwCmd = VUServerProtocol.buildCommand(.getFirmwareVersion, payload: [])
|
||||||
|
self.writeData(fwCmd)
|
||||||
|
usleep(50_000) // 50ms delay between commands
|
||||||
|
|
||||||
|
// Query hardware version
|
||||||
|
let hwCmd = VUServerProtocol.buildCommand(.getHardwareVersion, payload: [])
|
||||||
|
self.writeData(hwCmd)
|
||||||
|
usleep(50_000)
|
||||||
|
|
||||||
|
// Query UID
|
||||||
|
let uidCmd = VUServerProtocol.buildCommand(.getUID, payload: [])
|
||||||
|
self.writeData(uidCmd)
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Auto-connect: probe and connect to first found device
|
/// Auto-connect: probe and connect to first found device
|
||||||
@@ -562,15 +827,26 @@ class SerialManager: ObservableObject {
|
|||||||
|
|
||||||
/// Disconnect from serial port
|
/// Disconnect from serial port
|
||||||
func disconnect() {
|
func disconnect() {
|
||||||
stopUpdateTimer()
|
print("[DEBUG] disconnect() called, fd=\(fileDescriptor)")
|
||||||
|
|
||||||
|
// Stop timer on main thread
|
||||||
|
DispatchQueue.main.async {
|
||||||
|
print("[DEBUG] Stopping update timer")
|
||||||
|
self.stopUpdateTimer()
|
||||||
|
}
|
||||||
|
|
||||||
if fileDescriptor != -1 {
|
if fileDescriptor != -1 {
|
||||||
|
print("[DEBUG] Closing file descriptor \(fileDescriptor)")
|
||||||
close(fileDescriptor)
|
close(fileDescriptor)
|
||||||
fileDescriptor = -1
|
fileDescriptor = -1
|
||||||
}
|
}
|
||||||
|
|
||||||
isConnected = false
|
// Update UI on main thread
|
||||||
print("Disconnected from serial port")
|
DispatchQueue.main.async {
|
||||||
|
print("[DEBUG] Main thread: setting isConnected=false")
|
||||||
|
self.isConnected = false
|
||||||
|
}
|
||||||
|
print("[DEBUG] Disconnected from serial port")
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Toggle connection state
|
/// Toggle connection state
|
||||||
@@ -630,7 +906,10 @@ class SerialManager: ObservableObject {
|
|||||||
|
|
||||||
/// Send current values to hardware
|
/// Send current values to hardware
|
||||||
func sendValues() {
|
func sendValues() {
|
||||||
guard isConnected, fileDescriptor != -1 else { return }
|
guard isConnected, fileDescriptor != -1 else {
|
||||||
|
// Only print occasionally to avoid spam
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
writeQueue.async { [weak self] in
|
writeQueue.async { [weak self] in
|
||||||
guard let self = self else { return }
|
guard let self = self else { return }
|
||||||
@@ -680,37 +959,175 @@ class SerialManager: ObservableObject {
|
|||||||
return Data()
|
return Data()
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Format for VU-Server compatible hardware
|
// Debug counter to limit output spam
|
||||||
/// Protocol: #<dial_id>:<value>\n
|
private static var debugCounter = 0
|
||||||
|
|
||||||
|
/// Format for VU-Server hardware using binary protocol
|
||||||
|
/// Sends percentage values (0-100) for each dial
|
||||||
private func formatVUServer() -> Data {
|
private func formatVUServer() -> Data {
|
||||||
var message = ""
|
// Convert 0-255 values to 0-100 percentage
|
||||||
for (index, value) in dialValues.enumerated() {
|
let percentValues = dialValues.map { UInt8((($0) * 100) / 255) }
|
||||||
// VU-Server uses percentage values 0-100
|
|
||||||
let percentage = (value * 100) / 255
|
// Use the optimized "set all dials" command
|
||||||
message += "#\(index):\(percentage)\n"
|
let data = VUServerProtocol.setAllDialsPercent(values: percentValues)
|
||||||
|
|
||||||
|
// Debug: print hex bytes (only every 30 frames = ~1 second)
|
||||||
|
SerialManager.debugCounter += 1
|
||||||
|
if SerialManager.debugCounter % 30 == 0 {
|
||||||
|
let hexString = data.map { String(format: "%02X", $0) }.joined(separator: " ")
|
||||||
|
print("[DEBUG] formatVUServer: dialValues=\(dialValues) -> percent=\(percentValues)")
|
||||||
|
print("[DEBUG] formatVUServer: sending \(data.count) bytes: \(hexString)")
|
||||||
|
}
|
||||||
|
|
||||||
|
return data
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Send individual dial value using VU-Server binary protocol
|
||||||
|
func sendDialValue(dialIndex: Int, value: Int) {
|
||||||
|
guard isConnected, fileDescriptor != -1, selectedProtocol == .vuServer else { return }
|
||||||
|
|
||||||
|
writeQueue.async { [weak self] in
|
||||||
|
guard let self = self else { return }
|
||||||
|
|
||||||
|
let percent = UInt8((value * 100) / 255)
|
||||||
|
let data = VUServerProtocol.setDialPercent(dialIndex: UInt8(dialIndex), percent: percent)
|
||||||
|
self.writeData(data)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Set backlight color for a dial (VU-Server only)
|
||||||
|
func setBacklightColor(dialIndex: Int, red: UInt8, green: UInt8, blue: UInt8) {
|
||||||
|
guard isConnected, fileDescriptor != -1, selectedProtocol == .vuServer else { return }
|
||||||
|
|
||||||
|
writeQueue.async { [weak self] in
|
||||||
|
guard let self = self else { return }
|
||||||
|
|
||||||
|
let data = VUServerProtocol.setBacklightRGB(
|
||||||
|
dialIndex: UInt8(dialIndex),
|
||||||
|
red: red,
|
||||||
|
green: green,
|
||||||
|
blue: blue
|
||||||
|
)
|
||||||
|
self.writeData(data)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Request firmware version from hardware
|
||||||
|
func requestFirmwareVersion() {
|
||||||
|
guard isConnected, fileDescriptor != -1, selectedProtocol == .vuServer else { return }
|
||||||
|
|
||||||
|
writeQueue.async { [weak self] in
|
||||||
|
guard let self = self else { return }
|
||||||
|
|
||||||
|
let data = VUServerProtocol.buildCommand(.getFirmwareVersion, payload: [])
|
||||||
|
self.writeData(data)
|
||||||
|
|
||||||
|
// Read response
|
||||||
|
self.readResponse()
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// MARK: - Response Handling
|
||||||
|
|
||||||
|
/// Read and parse response from hardware
|
||||||
|
private func readResponse() {
|
||||||
|
var buffer = [UInt8](repeating: 0, count: 256)
|
||||||
|
let bytesRead = read(fileDescriptor, &buffer, buffer.count)
|
||||||
|
|
||||||
|
if bytesRead > 0 {
|
||||||
|
DispatchQueue.main.async {
|
||||||
|
self.bytesReceived += UInt64(bytesRead)
|
||||||
|
}
|
||||||
|
|
||||||
|
let responseData = Data(buffer.prefix(bytesRead))
|
||||||
|
|
||||||
|
// Parse VU-Server response
|
||||||
|
if let response = VUServerProtocol.parseResponse(responseData) {
|
||||||
|
handleVUServerResponse(command: response.command, payload: response.payload)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Handle parsed VU-Server response
|
||||||
|
private func handleVUServerResponse(command: UInt8, payload: Data) {
|
||||||
|
DispatchQueue.main.async { [weak self] in
|
||||||
|
guard let self = self else { return }
|
||||||
|
|
||||||
|
switch command {
|
||||||
|
case VUServerProtocol.Command.getFirmwareVersion.rawValue:
|
||||||
|
if let version = String(data: payload, encoding: .utf8) {
|
||||||
|
self.firmwareVersion = version.trimmingCharacters(in: .controlCharacters)
|
||||||
|
print("VU-Server Firmware: \(self.firmwareVersion ?? "unknown")")
|
||||||
|
}
|
||||||
|
|
||||||
|
case VUServerProtocol.Command.getHardwareVersion.rawValue:
|
||||||
|
if let version = String(data: payload, encoding: .utf8) {
|
||||||
|
self.hardwareVersion = version.trimmingCharacters(in: .controlCharacters)
|
||||||
|
print("VU-Server Hardware: \(self.hardwareVersion ?? "unknown")")
|
||||||
|
}
|
||||||
|
|
||||||
|
case VUServerProtocol.Command.getUID.rawValue:
|
||||||
|
if let uid = String(data: payload, encoding: .utf8) {
|
||||||
|
self.deviceUID = uid.trimmingCharacters(in: .controlCharacters)
|
||||||
|
print("VU-Server UID: \(self.deviceUID ?? "unknown")")
|
||||||
|
}
|
||||||
|
|
||||||
|
default:
|
||||||
|
print("VU-Server response: cmd=0x\(String(command, radix: 16)), payload=\(payload.count) bytes")
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Start background response reader
|
||||||
|
private func startResponseReader() {
|
||||||
|
guard selectedProtocol == .vuServer else { return }
|
||||||
|
|
||||||
|
DispatchQueue.global(qos: .utility).async { [weak self] in
|
||||||
|
while let self = self, self.isConnected, self.fileDescriptor != -1 {
|
||||||
|
self.readResponse()
|
||||||
|
usleep(10_000) // 10ms
|
||||||
|
}
|
||||||
}
|
}
|
||||||
return message.data(using: .utf8) ?? Data()
|
|
||||||
}
|
}
|
||||||
|
|
||||||
// MARK: - Low-level I/O
|
// MARK: - Low-level I/O
|
||||||
|
|
||||||
/// Write data to serial port
|
/// Write data to serial port
|
||||||
private func writeData(_ data: Data) {
|
private func writeData(_ data: Data) {
|
||||||
guard !data.isEmpty else { return }
|
guard !data.isEmpty else {
|
||||||
|
print("[DEBUG] writeData: empty data, skipping")
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
// Only print every 30th write to reduce spam
|
||||||
|
let shouldDebug = SerialManager.debugCounter % 30 == 0
|
||||||
|
|
||||||
|
if shouldDebug {
|
||||||
|
print("[DEBUG] writeData: writing \(data.count) bytes to fd=\(fileDescriptor)")
|
||||||
|
}
|
||||||
|
|
||||||
data.withUnsafeBytes { buffer in
|
data.withUnsafeBytes { buffer in
|
||||||
guard let baseAddress = buffer.baseAddress else { return }
|
guard let baseAddress = buffer.baseAddress else {
|
||||||
|
print("[DEBUG] writeData: ERROR - no base address")
|
||||||
|
return
|
||||||
|
}
|
||||||
let written = write(fileDescriptor, baseAddress, data.count)
|
let written = write(fileDescriptor, baseAddress, data.count)
|
||||||
|
|
||||||
if written > 0 {
|
if written > 0 {
|
||||||
|
if shouldDebug {
|
||||||
|
print("[DEBUG] writeData: wrote \(written) bytes successfully")
|
||||||
|
}
|
||||||
DispatchQueue.main.async {
|
DispatchQueue.main.async {
|
||||||
self.bytesSent += UInt64(written)
|
self.bytesSent += UInt64(written)
|
||||||
}
|
}
|
||||||
} else if written < 0 {
|
} else if written < 0 {
|
||||||
let error = String(cString: strerror(errno))
|
let error = String(cString: strerror(errno))
|
||||||
|
print("[DEBUG] writeData: ERROR - \(error)")
|
||||||
DispatchQueue.main.async {
|
DispatchQueue.main.async {
|
||||||
self.lastError = "Write error: \(error)"
|
self.lastError = "Write error: \(error)"
|
||||||
}
|
}
|
||||||
|
} else {
|
||||||
|
print("[DEBUG] writeData: wrote 0 bytes")
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -718,13 +1135,16 @@ class SerialManager: ObservableObject {
|
|||||||
// MARK: - Timer Management
|
// MARK: - Timer Management
|
||||||
|
|
||||||
private func startUpdateTimer() {
|
private func startUpdateTimer() {
|
||||||
|
print("[DEBUG] startUpdateTimer called, interval=\(updateInterval)")
|
||||||
stopUpdateTimer()
|
stopUpdateTimer()
|
||||||
updateTimer = Timer.scheduledTimer(withTimeInterval: updateInterval, repeats: true) { [weak self] _ in
|
updateTimer = Timer.scheduledTimer(withTimeInterval: updateInterval, repeats: true) { [weak self] _ in
|
||||||
self?.sendValues()
|
self?.sendValues()
|
||||||
}
|
}
|
||||||
|
print("[DEBUG] Update timer started")
|
||||||
}
|
}
|
||||||
|
|
||||||
private func stopUpdateTimer() {
|
private func stopUpdateTimer() {
|
||||||
|
print("[DEBUG] stopUpdateTimer called")
|
||||||
updateTimer?.invalidate()
|
updateTimer?.invalidate()
|
||||||
updateTimer = nil
|
updateTimer = nil
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -0,0 +1,484 @@
|
|||||||
|
//
|
||||||
|
// ServerView.swift
|
||||||
|
// AudioVUMeter
|
||||||
|
//
|
||||||
|
// Server configuration and status view
|
||||||
|
// Allows enabling/disabling the VU Server for external app connections
|
||||||
|
//
|
||||||
|
|
||||||
|
import SwiftUI
|
||||||
|
|
||||||
|
// MARK: - Server Panel in Main View
|
||||||
|
struct ServerPanelView: View {
|
||||||
|
@EnvironmentObject var vuServer: VUServer
|
||||||
|
|
||||||
|
var body: some View {
|
||||||
|
VStack(spacing: 12) {
|
||||||
|
// Header
|
||||||
|
HStack {
|
||||||
|
Text("VU SERVER")
|
||||||
|
.font(.system(size: 11, weight: .semibold, design: .monospaced))
|
||||||
|
.foregroundColor(.gray)
|
||||||
|
|
||||||
|
Spacer()
|
||||||
|
|
||||||
|
// Status indicator
|
||||||
|
HStack(spacing: 6) {
|
||||||
|
Circle()
|
||||||
|
.fill(statusColor)
|
||||||
|
.frame(width: 8, height: 8)
|
||||||
|
|
||||||
|
Text(statusText)
|
||||||
|
.font(.system(size: 9, weight: .semibold, design: .monospaced))
|
||||||
|
.foregroundColor(statusColor)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// Quick info
|
||||||
|
if vuServer.isRunning {
|
||||||
|
HStack {
|
||||||
|
// Port info
|
||||||
|
Label(":\(vuServer.options.port)", systemImage: "network")
|
||||||
|
.font(.system(size: 10, design: .monospaced))
|
||||||
|
.foregroundColor(.cyan)
|
||||||
|
|
||||||
|
Spacer()
|
||||||
|
|
||||||
|
// Client count
|
||||||
|
Label("\(vuServer.connectedClients.count)", systemImage: "person.2.fill")
|
||||||
|
.font(.system(size: 10, design: .monospaced))
|
||||||
|
.foregroundColor(vuServer.connectedClients.isEmpty ? .gray : .green)
|
||||||
|
|
||||||
|
Spacer()
|
||||||
|
|
||||||
|
// External control indicator
|
||||||
|
if vuServer.externalControlActive {
|
||||||
|
Label("EXT", systemImage: "arrow.down.circle.fill")
|
||||||
|
.font(.system(size: 10, weight: .bold, design: .monospaced))
|
||||||
|
.foregroundColor(.orange)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// Toggle button
|
||||||
|
Button(action: {
|
||||||
|
vuServer.toggle()
|
||||||
|
vuServer.saveOptions()
|
||||||
|
}) {
|
||||||
|
HStack {
|
||||||
|
Image(systemName: vuServer.isRunning ? "stop.fill" : "play.fill")
|
||||||
|
Text(vuServer.isRunning ? "Stop Server" : "Start Server")
|
||||||
|
}
|
||||||
|
.frame(maxWidth: .infinity)
|
||||||
|
}
|
||||||
|
.buttonStyle(ServerButtonStyle(isRunning: vuServer.isRunning))
|
||||||
|
|
||||||
|
// Last command (if any)
|
||||||
|
if vuServer.isRunning && !vuServer.lastReceivedCommand.isEmpty {
|
||||||
|
HStack {
|
||||||
|
Text("Last:")
|
||||||
|
.font(.system(size: 8, design: .monospaced))
|
||||||
|
.foregroundColor(.gray)
|
||||||
|
|
||||||
|
Text(vuServer.lastReceivedCommand.prefix(30) + (vuServer.lastReceivedCommand.count > 30 ? "..." : ""))
|
||||||
|
.font(.system(size: 8, design: .monospaced))
|
||||||
|
.foregroundColor(.cyan)
|
||||||
|
.lineLimit(1)
|
||||||
|
|
||||||
|
Spacer()
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
.padding()
|
||||||
|
.background(
|
||||||
|
RoundedRectangle(cornerRadius: 12)
|
||||||
|
.fill(Color.black.opacity(0.3))
|
||||||
|
.overlay(
|
||||||
|
RoundedRectangle(cornerRadius: 12)
|
||||||
|
.stroke(borderColor, lineWidth: 1)
|
||||||
|
)
|
||||||
|
)
|
||||||
|
.padding(.horizontal)
|
||||||
|
}
|
||||||
|
|
||||||
|
private var statusColor: Color {
|
||||||
|
if vuServer.isRunning {
|
||||||
|
return vuServer.connectedClients.isEmpty ? .yellow : .green
|
||||||
|
}
|
||||||
|
return .gray
|
||||||
|
}
|
||||||
|
|
||||||
|
private var statusText: String {
|
||||||
|
if vuServer.isRunning {
|
||||||
|
if vuServer.connectedClients.isEmpty {
|
||||||
|
return "LISTENING"
|
||||||
|
}
|
||||||
|
return "\(vuServer.connectedClients.count) CLIENT\(vuServer.connectedClients.count == 1 ? "" : "S")"
|
||||||
|
}
|
||||||
|
return "STOPPED"
|
||||||
|
}
|
||||||
|
|
||||||
|
private var borderColor: Color {
|
||||||
|
if vuServer.externalControlActive { return .orange.opacity(0.5) }
|
||||||
|
if vuServer.isRunning { return .cyan.opacity(0.3) }
|
||||||
|
return .clear
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// MARK: - Server Settings View (Full)
|
||||||
|
struct ServerSettingsView: View {
|
||||||
|
@EnvironmentObject var vuServer: VUServer
|
||||||
|
@State private var portString: String = ""
|
||||||
|
@State private var showAdvanced = false
|
||||||
|
|
||||||
|
var body: some View {
|
||||||
|
Form {
|
||||||
|
// Main Server Section
|
||||||
|
Section("Server Control") {
|
||||||
|
// Enable/Disable toggle
|
||||||
|
Toggle(isOn: Binding(
|
||||||
|
get: { vuServer.isRunning },
|
||||||
|
set: { newValue in
|
||||||
|
if newValue {
|
||||||
|
vuServer.start()
|
||||||
|
} else {
|
||||||
|
vuServer.stop()
|
||||||
|
}
|
||||||
|
vuServer.saveOptions()
|
||||||
|
}
|
||||||
|
)) {
|
||||||
|
HStack {
|
||||||
|
Image(systemName: vuServer.isRunning ? "antenna.radiowaves.left.and.right" : "antenna.radiowaves.left.and.right.slash")
|
||||||
|
.foregroundColor(vuServer.isRunning ? .green : .gray)
|
||||||
|
Text("Server Enabled")
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// Status
|
||||||
|
if vuServer.isRunning {
|
||||||
|
HStack {
|
||||||
|
Text("Status")
|
||||||
|
Spacer()
|
||||||
|
Circle()
|
||||||
|
.fill(Color.green)
|
||||||
|
.frame(width: 8, height: 8)
|
||||||
|
Text("Running on port \(vuServer.options.port)")
|
||||||
|
.foregroundColor(.secondary)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// Error display
|
||||||
|
if let error = vuServer.lastError {
|
||||||
|
HStack {
|
||||||
|
Image(systemName: "exclamationmark.triangle.fill")
|
||||||
|
.foregroundColor(.red)
|
||||||
|
Text(error)
|
||||||
|
.foregroundColor(.red)
|
||||||
|
.font(.caption)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// Connection Settings
|
||||||
|
Section("Connection Settings") {
|
||||||
|
// Port
|
||||||
|
HStack {
|
||||||
|
Text("Port")
|
||||||
|
Spacer()
|
||||||
|
TextField("Port", text: $portString)
|
||||||
|
.frame(width: 80)
|
||||||
|
.textFieldStyle(.roundedBorder)
|
||||||
|
.onAppear {
|
||||||
|
portString = String(vuServer.options.port)
|
||||||
|
}
|
||||||
|
.onChange(of: portString) { newValue in
|
||||||
|
if let port = UInt16(newValue), port > 0 {
|
||||||
|
vuServer.options.port = port
|
||||||
|
vuServer.saveOptions()
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// Allow remote connections
|
||||||
|
Toggle("Allow Remote Connections", isOn: $vuServer.options.allowRemote)
|
||||||
|
.onChange(of: vuServer.options.allowRemote) { _ in
|
||||||
|
vuServer.saveOptions()
|
||||||
|
if vuServer.isRunning {
|
||||||
|
vuServer.restart()
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
if vuServer.options.allowRemote {
|
||||||
|
HStack {
|
||||||
|
Image(systemName: "exclamationmark.triangle.fill")
|
||||||
|
.foregroundColor(.orange)
|
||||||
|
Text("Warning: Remote access enabled. Anyone on your network can connect.")
|
||||||
|
.font(.caption)
|
||||||
|
.foregroundColor(.orange)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// Max clients
|
||||||
|
Stepper("Max Clients: \(vuServer.options.maxClients)", value: $vuServer.options.maxClients, in: 1...20)
|
||||||
|
.onChange(of: vuServer.options.maxClients) { _ in
|
||||||
|
vuServer.saveOptions()
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// Protocol Settings
|
||||||
|
Section("Protocol") {
|
||||||
|
Picker("Server Protocol", selection: $vuServer.options.serverProtocol) {
|
||||||
|
ForEach(ServerProtocol.allCases) { proto in
|
||||||
|
Text(proto.rawValue).tag(proto)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
.onChange(of: vuServer.options.serverProtocol) { _ in
|
||||||
|
vuServer.saveOptions()
|
||||||
|
}
|
||||||
|
|
||||||
|
// Broadcast settings
|
||||||
|
Toggle("Broadcast Levels to Clients", isOn: $vuServer.options.broadcastLevels)
|
||||||
|
.onChange(of: vuServer.options.broadcastLevels) { _ in
|
||||||
|
vuServer.saveOptions()
|
||||||
|
}
|
||||||
|
|
||||||
|
if vuServer.options.broadcastLevels {
|
||||||
|
HStack {
|
||||||
|
Text("Broadcast Rate")
|
||||||
|
Slider(value: $vuServer.options.broadcastInterval, in: 0.033...1.0)
|
||||||
|
Text("\(Int(1.0 / vuServer.options.broadcastInterval)) Hz")
|
||||||
|
.frame(width: 50)
|
||||||
|
}
|
||||||
|
.onChange(of: vuServer.options.broadcastInterval) { _ in
|
||||||
|
vuServer.saveOptions()
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// Connected Clients
|
||||||
|
Section("Connected Clients (\(vuServer.connectedClients.count))") {
|
||||||
|
if vuServer.connectedClients.isEmpty {
|
||||||
|
HStack {
|
||||||
|
Image(systemName: "person.slash")
|
||||||
|
.foregroundColor(.gray)
|
||||||
|
Text("No clients connected")
|
||||||
|
.foregroundColor(.secondary)
|
||||||
|
}
|
||||||
|
} else {
|
||||||
|
ForEach(vuServer.connectedClients) { client in
|
||||||
|
ClientRowView(client: client, onDisconnect: {
|
||||||
|
vuServer.disconnectClient(client)
|
||||||
|
})
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// Statistics
|
||||||
|
if vuServer.isRunning {
|
||||||
|
Section("Statistics") {
|
||||||
|
HStack {
|
||||||
|
Text("Received")
|
||||||
|
Spacer()
|
||||||
|
Text(formatBytes(vuServer.totalBytesReceived))
|
||||||
|
.foregroundColor(.secondary)
|
||||||
|
.font(.system(.body, design: .monospaced))
|
||||||
|
}
|
||||||
|
|
||||||
|
HStack {
|
||||||
|
Text("Sent")
|
||||||
|
Spacer()
|
||||||
|
Text(formatBytes(vuServer.totalBytesSent))
|
||||||
|
.foregroundColor(.secondary)
|
||||||
|
.font(.system(.body, design: .monospaced))
|
||||||
|
}
|
||||||
|
|
||||||
|
if vuServer.externalControlActive {
|
||||||
|
HStack {
|
||||||
|
Image(systemName: "arrow.down.circle.fill")
|
||||||
|
.foregroundColor(.orange)
|
||||||
|
Text("External Control Active")
|
||||||
|
.foregroundColor(.orange)
|
||||||
|
Spacer()
|
||||||
|
Button("Release") {
|
||||||
|
vuServer.externalControlActive = false
|
||||||
|
vuServer.receivedDialValues = nil
|
||||||
|
}
|
||||||
|
.buttonStyle(.borderless)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
if !vuServer.lastReceivedCommand.isEmpty {
|
||||||
|
VStack(alignment: .leading) {
|
||||||
|
Text("Last Command")
|
||||||
|
Text(vuServer.lastReceivedCommand)
|
||||||
|
.font(.system(.caption, design: .monospaced))
|
||||||
|
.foregroundColor(.cyan)
|
||||||
|
.lineLimit(3)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// Protocol Reference
|
||||||
|
Section("Protocol Reference") {
|
||||||
|
DisclosureGroup("VU Protocol") {
|
||||||
|
VStack(alignment: .leading, spacing: 4) {
|
||||||
|
Text("Send values: #channel:percentage")
|
||||||
|
Text("Example: #0:75 (dial 0 at 75%)")
|
||||||
|
Text("Channels: 0-3")
|
||||||
|
Text("Values: 0-100")
|
||||||
|
Text("Commands: ?, STATUS, RELEASE")
|
||||||
|
}
|
||||||
|
.font(.system(size: 11, design: .monospaced))
|
||||||
|
.foregroundColor(.secondary)
|
||||||
|
}
|
||||||
|
|
||||||
|
DisclosureGroup("JSON Protocol") {
|
||||||
|
VStack(alignment: .leading, spacing: 4) {
|
||||||
|
Text("{\"dials\":[v1,v2,v3,v4]}")
|
||||||
|
Text("or {\"d0\":v,\"d1\":v,...}")
|
||||||
|
Text("Values: 0-255")
|
||||||
|
Text("Commands: {\"cmd\":\"status\"}")
|
||||||
|
}
|
||||||
|
.font(.system(size: 11, design: .monospaced))
|
||||||
|
.foregroundColor(.secondary)
|
||||||
|
}
|
||||||
|
|
||||||
|
DisclosureGroup("Raw Bytes") {
|
||||||
|
VStack(alignment: .leading, spacing: 4) {
|
||||||
|
Text("Frame: [0xAA][D1][D2][D3][D4][0x55]")
|
||||||
|
Text("Values: 0-255 per byte")
|
||||||
|
}
|
||||||
|
.font(.system(size: 11, design: .monospaced))
|
||||||
|
.foregroundColor(.secondary)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// Test Connection
|
||||||
|
Section("Test") {
|
||||||
|
VStack(alignment: .leading, spacing: 8) {
|
||||||
|
Text("Test with netcat:")
|
||||||
|
.font(.caption)
|
||||||
|
.foregroundColor(.secondary)
|
||||||
|
|
||||||
|
Text("echo '#0:50' | nc localhost \(vuServer.options.port)")
|
||||||
|
.font(.system(size: 10, design: .monospaced))
|
||||||
|
.padding(8)
|
||||||
|
.background(Color.black.opacity(0.3))
|
||||||
|
.cornerRadius(4)
|
||||||
|
|
||||||
|
Button("Copy Command") {
|
||||||
|
NSPasteboard.general.clearContents()
|
||||||
|
NSPasteboard.general.setString("echo '#0:50' | nc localhost \(vuServer.options.port)", forType: .string)
|
||||||
|
}
|
||||||
|
.buttonStyle(.borderless)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
.formStyle(.grouped)
|
||||||
|
}
|
||||||
|
|
||||||
|
private func formatBytes(_ bytes: UInt64) -> String {
|
||||||
|
if bytes < 1024 { return "\(bytes) B" }
|
||||||
|
if bytes < 1024 * 1024 { return String(format: "%.1f KB", Double(bytes) / 1024) }
|
||||||
|
return String(format: "%.1f MB", Double(bytes) / (1024 * 1024))
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// MARK: - Client Row View
|
||||||
|
struct ClientRowView: View {
|
||||||
|
let client: ConnectedClient
|
||||||
|
let onDisconnect: () -> Void
|
||||||
|
|
||||||
|
var body: some View {
|
||||||
|
HStack {
|
||||||
|
VStack(alignment: .leading, spacing: 2) {
|
||||||
|
Text(client.address)
|
||||||
|
.font(.system(.body, design: .monospaced))
|
||||||
|
|
||||||
|
HStack(spacing: 10) {
|
||||||
|
Text("RX: \(formatBytes(client.bytesReceived))")
|
||||||
|
Text("TX: \(formatBytes(client.bytesSent))")
|
||||||
|
}
|
||||||
|
.font(.caption)
|
||||||
|
.foregroundColor(.secondary)
|
||||||
|
}
|
||||||
|
|
||||||
|
Spacer()
|
||||||
|
|
||||||
|
Text(timeAgo(client.lastActivity))
|
||||||
|
.font(.caption)
|
||||||
|
.foregroundColor(.secondary)
|
||||||
|
|
||||||
|
Button(action: onDisconnect) {
|
||||||
|
Image(systemName: "xmark.circle.fill")
|
||||||
|
.foregroundColor(.red)
|
||||||
|
}
|
||||||
|
.buttonStyle(.borderless)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private func formatBytes(_ bytes: UInt64) -> String {
|
||||||
|
if bytes < 1024 { return "\(bytes)B" }
|
||||||
|
if bytes < 1024 * 1024 { return String(format: "%.1fK", Double(bytes) / 1024) }
|
||||||
|
return String(format: "%.1fM", Double(bytes) / (1024 * 1024))
|
||||||
|
}
|
||||||
|
|
||||||
|
private func timeAgo(_ date: Date) -> String {
|
||||||
|
let seconds = Int(-date.timeIntervalSinceNow)
|
||||||
|
if seconds < 60 { return "\(seconds)s" }
|
||||||
|
if seconds < 3600 { return "\(seconds / 60)m" }
|
||||||
|
return "\(seconds / 3600)h"
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// MARK: - Server Settings Sheet
|
||||||
|
struct ServerSettingsSheet: View {
|
||||||
|
@EnvironmentObject var vuServer: VUServer
|
||||||
|
@Environment(\.dismiss) var dismiss
|
||||||
|
|
||||||
|
var body: some View {
|
||||||
|
VStack(spacing: 0) {
|
||||||
|
// Header
|
||||||
|
HStack {
|
||||||
|
Text("VU Server Settings")
|
||||||
|
.font(.headline)
|
||||||
|
Spacer()
|
||||||
|
Button("Done") { dismiss() }
|
||||||
|
}
|
||||||
|
.padding()
|
||||||
|
.background(Color(nsColor: .windowBackgroundColor))
|
||||||
|
|
||||||
|
Divider()
|
||||||
|
|
||||||
|
// Settings content
|
||||||
|
ServerSettingsView()
|
||||||
|
.environmentObject(vuServer)
|
||||||
|
}
|
||||||
|
.frame(width: 500, height: 650)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// MARK: - Button Style
|
||||||
|
struct ServerButtonStyle: ButtonStyle {
|
||||||
|
let isRunning: Bool
|
||||||
|
|
||||||
|
func makeBody(configuration: Configuration) -> some View {
|
||||||
|
configuration.label
|
||||||
|
.font(.system(size: 12, weight: .semibold))
|
||||||
|
.foregroundColor(.white)
|
||||||
|
.padding(.vertical, 8)
|
||||||
|
.background(
|
||||||
|
RoundedRectangle(cornerRadius: 8)
|
||||||
|
.fill(isRunning ? Color.red.opacity(0.7) : Color.cyan.opacity(0.7))
|
||||||
|
.opacity(configuration.isPressed ? 0.6 : 1.0)
|
||||||
|
)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// MARK: - Preview
|
||||||
|
#Preview {
|
||||||
|
ServerSettingsView()
|
||||||
|
.environmentObject(VUServer())
|
||||||
|
.frame(width: 500, height: 700)
|
||||||
|
}
|
||||||
@@ -10,6 +10,7 @@ import SwiftUI
|
|||||||
struct SettingsView: View {
|
struct SettingsView: View {
|
||||||
@EnvironmentObject var audioEngine: AudioEngine
|
@EnvironmentObject var audioEngine: AudioEngine
|
||||||
@EnvironmentObject var serialManager: SerialManager
|
@EnvironmentObject var serialManager: SerialManager
|
||||||
|
@EnvironmentObject var vuServer: VUServer
|
||||||
|
|
||||||
@AppStorage("showPeakIndicator") private var showPeakIndicator = true
|
@AppStorage("showPeakIndicator") private var showPeakIndicator = true
|
||||||
@AppStorage("meterStyle") private var meterStyle = "classic"
|
@AppStorage("meterStyle") private var meterStyle = "classic"
|
||||||
@@ -70,6 +71,13 @@ struct SettingsView: View {
|
|||||||
Label("Hardware", systemImage: "cable.connector")
|
Label("Hardware", systemImage: "cable.connector")
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// Server Settings
|
||||||
|
ServerSettingsView()
|
||||||
|
.environmentObject(vuServer)
|
||||||
|
.tabItem {
|
||||||
|
Label("Server", systemImage: "server.rack")
|
||||||
|
}
|
||||||
|
|
||||||
// Display Settings
|
// Display Settings
|
||||||
Form {
|
Form {
|
||||||
Section("Meter Display") {
|
Section("Meter Display") {
|
||||||
@@ -106,7 +114,7 @@ struct SettingsView: View {
|
|||||||
.font(.title)
|
.font(.title)
|
||||||
.fontWeight(.bold)
|
.fontWeight(.bold)
|
||||||
|
|
||||||
Text("Version 1.1.0")
|
Text("Version 1.2.0")
|
||||||
.foregroundColor(.secondary)
|
.foregroundColor(.secondary)
|
||||||
|
|
||||||
Divider()
|
Divider()
|
||||||
@@ -123,8 +131,9 @@ struct SettingsView: View {
|
|||||||
Spacer()
|
Spacer()
|
||||||
|
|
||||||
VStack(spacing: 4) {
|
VStack(spacing: 4) {
|
||||||
Text("Supports BlackHole virtual audio device")
|
Text("Supports BlackHole virtual audio device,")
|
||||||
Text("and USB/Serial VU meter hardware")
|
Text("USB/Serial VU meter hardware,")
|
||||||
|
Text("and TCP server for external apps")
|
||||||
}
|
}
|
||||||
.font(.caption)
|
.font(.caption)
|
||||||
.foregroundColor(.secondary)
|
.foregroundColor(.secondary)
|
||||||
@@ -134,7 +143,7 @@ struct SettingsView: View {
|
|||||||
Label("About", systemImage: "info.circle")
|
Label("About", systemImage: "info.circle")
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
.frame(width: 500, height: 400)
|
.frame(width: 500, height: 500)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -142,4 +151,5 @@ struct SettingsView: View {
|
|||||||
SettingsView()
|
SettingsView()
|
||||||
.environmentObject(AudioEngine())
|
.environmentObject(AudioEngine())
|
||||||
.environmentObject(SerialManager())
|
.environmentObject(SerialManager())
|
||||||
|
.environmentObject(VUServer())
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -0,0 +1,251 @@
|
|||||||
|
//
|
||||||
|
// SplashView.swift
|
||||||
|
// AudioVUMeter
|
||||||
|
//
|
||||||
|
// Splash screen shown at app startup
|
||||||
|
// Presented by Gnafzgi Software
|
||||||
|
//
|
||||||
|
|
||||||
|
import SwiftUI
|
||||||
|
|
||||||
|
struct SplashView: View {
|
||||||
|
@State private var isAnimating = false
|
||||||
|
@State private var showApp = false
|
||||||
|
@State private var logoScale: CGFloat = 0.5
|
||||||
|
@State private var logoOpacity: Double = 0
|
||||||
|
@State private var textOpacity: Double = 0
|
||||||
|
@State private var subtitleOpacity: Double = 0
|
||||||
|
@State private var waveOffset: CGFloat = 0
|
||||||
|
|
||||||
|
let onComplete: () -> Void
|
||||||
|
|
||||||
|
var body: some View {
|
||||||
|
ZStack {
|
||||||
|
// Background gradient
|
||||||
|
LinearGradient(
|
||||||
|
gradient: Gradient(colors: [
|
||||||
|
Color(red: 0.05, green: 0.05, blue: 0.1),
|
||||||
|
Color(red: 0.1, green: 0.08, blue: 0.15),
|
||||||
|
Color(red: 0.05, green: 0.05, blue: 0.1)
|
||||||
|
]),
|
||||||
|
startPoint: .topLeading,
|
||||||
|
endPoint: .bottomTrailing
|
||||||
|
)
|
||||||
|
.ignoresSafeArea()
|
||||||
|
|
||||||
|
// Animated wave background
|
||||||
|
WaveBackground(offset: waveOffset)
|
||||||
|
.opacity(0.3)
|
||||||
|
|
||||||
|
VStack(spacing: 30) {
|
||||||
|
Spacer()
|
||||||
|
|
||||||
|
// Animated VU Meter Icon
|
||||||
|
ZStack {
|
||||||
|
// Glow effect
|
||||||
|
Circle()
|
||||||
|
.fill(
|
||||||
|
RadialGradient(
|
||||||
|
gradient: Gradient(colors: [
|
||||||
|
Color.green.opacity(0.4),
|
||||||
|
Color.clear
|
||||||
|
]),
|
||||||
|
center: .center,
|
||||||
|
startRadius: 30,
|
||||||
|
endRadius: 80
|
||||||
|
)
|
||||||
|
)
|
||||||
|
.frame(width: 160, height: 160)
|
||||||
|
.blur(radius: 20)
|
||||||
|
.scaleEffect(isAnimating ? 1.2 : 1.0)
|
||||||
|
|
||||||
|
// Main icon
|
||||||
|
Image(systemName: "waveform.circle.fill")
|
||||||
|
.font(.system(size: 100))
|
||||||
|
.foregroundStyle(
|
||||||
|
LinearGradient(
|
||||||
|
colors: [.green, .cyan, .blue],
|
||||||
|
startPoint: .topLeading,
|
||||||
|
endPoint: .bottomTrailing
|
||||||
|
)
|
||||||
|
)
|
||||||
|
.shadow(color: .green.opacity(0.5), radius: 20)
|
||||||
|
}
|
||||||
|
.scaleEffect(logoScale)
|
||||||
|
.opacity(logoOpacity)
|
||||||
|
|
||||||
|
// App Title
|
||||||
|
VStack(spacing: 8) {
|
||||||
|
Text("Audio VU Meter")
|
||||||
|
.font(.system(size: 36, weight: .bold, design: .rounded))
|
||||||
|
.foregroundStyle(
|
||||||
|
LinearGradient(
|
||||||
|
colors: [.white, .gray.opacity(0.8)],
|
||||||
|
startPoint: .top,
|
||||||
|
endPoint: .bottom
|
||||||
|
)
|
||||||
|
)
|
||||||
|
|
||||||
|
Text("Professional Audio Monitoring")
|
||||||
|
.font(.system(size: 14, weight: .medium, design: .rounded))
|
||||||
|
.foregroundColor(.gray)
|
||||||
|
}
|
||||||
|
.opacity(textOpacity)
|
||||||
|
|
||||||
|
Spacer()
|
||||||
|
|
||||||
|
// Presented by
|
||||||
|
VStack(spacing: 6) {
|
||||||
|
Text("presented by")
|
||||||
|
.font(.system(size: 11, weight: .regular, design: .rounded))
|
||||||
|
.foregroundColor(.gray.opacity(0.6))
|
||||||
|
.tracking(2)
|
||||||
|
|
||||||
|
Text("GNAFZGI SOFTWARE")
|
||||||
|
.font(.system(size: 16, weight: .bold, design: .rounded))
|
||||||
|
.foregroundStyle(
|
||||||
|
LinearGradient(
|
||||||
|
colors: [.cyan, .blue],
|
||||||
|
startPoint: .leading,
|
||||||
|
endPoint: .trailing
|
||||||
|
)
|
||||||
|
)
|
||||||
|
.tracking(3)
|
||||||
|
}
|
||||||
|
.opacity(subtitleOpacity)
|
||||||
|
.padding(.bottom, 50)
|
||||||
|
}
|
||||||
|
|
||||||
|
// Version badge
|
||||||
|
VStack {
|
||||||
|
Spacer()
|
||||||
|
HStack {
|
||||||
|
Spacer()
|
||||||
|
Text("v1.3")
|
||||||
|
.font(.system(size: 10, weight: .medium, design: .monospaced))
|
||||||
|
.foregroundColor(.gray.opacity(0.5))
|
||||||
|
.padding(8)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
.frame(width: 400, height: 500)
|
||||||
|
.onAppear {
|
||||||
|
startAnimations()
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private func startAnimations() {
|
||||||
|
// Wave animation (continuous)
|
||||||
|
withAnimation(.linear(duration: 8).repeatForever(autoreverses: false)) {
|
||||||
|
waveOffset = 1
|
||||||
|
}
|
||||||
|
|
||||||
|
// Logo animation
|
||||||
|
withAnimation(.spring(response: 0.8, dampingFraction: 0.6).delay(0.2)) {
|
||||||
|
logoScale = 1.0
|
||||||
|
logoOpacity = 1.0
|
||||||
|
}
|
||||||
|
|
||||||
|
// Pulse animation
|
||||||
|
withAnimation(.easeInOut(duration: 1.5).repeatForever(autoreverses: true).delay(0.5)) {
|
||||||
|
isAnimating = true
|
||||||
|
}
|
||||||
|
|
||||||
|
// Title animation
|
||||||
|
withAnimation(.easeOut(duration: 0.8).delay(0.6)) {
|
||||||
|
textOpacity = 1.0
|
||||||
|
}
|
||||||
|
|
||||||
|
// Subtitle animation
|
||||||
|
withAnimation(.easeOut(duration: 0.8).delay(1.0)) {
|
||||||
|
subtitleOpacity = 1.0
|
||||||
|
}
|
||||||
|
|
||||||
|
// Auto-dismiss after delay
|
||||||
|
DispatchQueue.main.asyncAfter(deadline: .now() + 2.5) {
|
||||||
|
withAnimation(.easeOut(duration: 0.3)) {
|
||||||
|
onComplete()
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// MARK: - Wave Background
|
||||||
|
struct WaveBackground: View {
|
||||||
|
let offset: CGFloat
|
||||||
|
|
||||||
|
var body: some View {
|
||||||
|
GeometryReader { geometry in
|
||||||
|
ZStack {
|
||||||
|
// First wave
|
||||||
|
WavePath(offset: offset, amplitude: 20, frequency: 1.5)
|
||||||
|
.stroke(
|
||||||
|
LinearGradient(
|
||||||
|
colors: [.green.opacity(0.3), .cyan.opacity(0.2)],
|
||||||
|
startPoint: .leading,
|
||||||
|
endPoint: .trailing
|
||||||
|
),
|
||||||
|
lineWidth: 2
|
||||||
|
)
|
||||||
|
|
||||||
|
// Second wave
|
||||||
|
WavePath(offset: offset + 0.3, amplitude: 15, frequency: 2)
|
||||||
|
.stroke(
|
||||||
|
LinearGradient(
|
||||||
|
colors: [.blue.opacity(0.2), .purple.opacity(0.2)],
|
||||||
|
startPoint: .leading,
|
||||||
|
endPoint: .trailing
|
||||||
|
),
|
||||||
|
lineWidth: 1.5
|
||||||
|
)
|
||||||
|
|
||||||
|
// Third wave
|
||||||
|
WavePath(offset: offset + 0.6, amplitude: 25, frequency: 1)
|
||||||
|
.stroke(
|
||||||
|
LinearGradient(
|
||||||
|
colors: [.cyan.opacity(0.15), .green.opacity(0.1)],
|
||||||
|
startPoint: .leading,
|
||||||
|
endPoint: .trailing
|
||||||
|
),
|
||||||
|
lineWidth: 1
|
||||||
|
)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// MARK: - Wave Path
|
||||||
|
struct WavePath: Shape {
|
||||||
|
var offset: CGFloat
|
||||||
|
var amplitude: CGFloat
|
||||||
|
var frequency: CGFloat
|
||||||
|
|
||||||
|
var animatableData: CGFloat {
|
||||||
|
get { offset }
|
||||||
|
set { offset = newValue }
|
||||||
|
}
|
||||||
|
|
||||||
|
func path(in rect: CGRect) -> Path {
|
||||||
|
var path = Path()
|
||||||
|
let midY = rect.midY
|
||||||
|
|
||||||
|
path.move(to: CGPoint(x: 0, y: midY))
|
||||||
|
|
||||||
|
for x in stride(from: 0, through: rect.width, by: 2) {
|
||||||
|
let relativeX = x / rect.width
|
||||||
|
let sine = sin((relativeX + offset) * .pi * 2 * frequency)
|
||||||
|
let y = midY + sine * amplitude
|
||||||
|
|
||||||
|
path.addLine(to: CGPoint(x: x, y: y))
|
||||||
|
}
|
||||||
|
|
||||||
|
return path
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// MARK: - Preview
|
||||||
|
#Preview {
|
||||||
|
SplashView {
|
||||||
|
print("Splash complete")
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,568 @@
|
|||||||
|
//
|
||||||
|
// VUServer.swift
|
||||||
|
// AudioVUMeter
|
||||||
|
//
|
||||||
|
// TCP Server for external applications to send VU meter data
|
||||||
|
// Allows other apps to control the physical VU meters remotely
|
||||||
|
//
|
||||||
|
|
||||||
|
import Foundation
|
||||||
|
import Network
|
||||||
|
|
||||||
|
/// Server protocol for incoming data
|
||||||
|
enum ServerProtocol: String, CaseIterable, Identifiable {
|
||||||
|
case vuProtocol = "VU Protocol (#channel:value)"
|
||||||
|
case json = "JSON ({\"dials\":[...]})"
|
||||||
|
case rawBytes = "Raw Bytes (binary)"
|
||||||
|
|
||||||
|
var id: String { rawValue }
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Connected client info
|
||||||
|
struct ConnectedClient: Identifiable {
|
||||||
|
let id: UUID
|
||||||
|
let address: String
|
||||||
|
let connectedAt: Date
|
||||||
|
var lastActivity: Date
|
||||||
|
var bytesReceived: UInt64
|
||||||
|
var bytesSent: UInt64
|
||||||
|
|
||||||
|
init(address: String) {
|
||||||
|
self.id = UUID()
|
||||||
|
self.address = address
|
||||||
|
self.connectedAt = Date()
|
||||||
|
self.lastActivity = Date()
|
||||||
|
self.bytesReceived = 0
|
||||||
|
self.bytesSent = 0
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Server options
|
||||||
|
struct ServerOptions: Codable {
|
||||||
|
var enabled: Bool = false
|
||||||
|
var port: UInt16 = 9876
|
||||||
|
var allowRemote: Bool = false // Only localhost by default
|
||||||
|
var requireAuth: Bool = false
|
||||||
|
var authToken: String = ""
|
||||||
|
var broadcastLevels: Bool = true // Send current levels to clients
|
||||||
|
var broadcastInterval: Double = 0.1 // 10 Hz
|
||||||
|
var maxClients: Int = 5
|
||||||
|
var protocol_: String = ServerProtocol.vuProtocol.rawValue
|
||||||
|
|
||||||
|
var serverProtocol: ServerProtocol {
|
||||||
|
get { ServerProtocol(rawValue: protocol_) ?? .vuProtocol }
|
||||||
|
set { protocol_ = newValue.rawValue }
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// VU Meter Server for external app connections
|
||||||
|
class VUServer: ObservableObject {
|
||||||
|
// MARK: - Published Properties
|
||||||
|
|
||||||
|
@Published var isRunning = false
|
||||||
|
@Published var options = ServerOptions()
|
||||||
|
@Published var connectedClients: [ConnectedClient] = []
|
||||||
|
@Published var lastError: String?
|
||||||
|
@Published var totalBytesReceived: UInt64 = 0
|
||||||
|
@Published var totalBytesSent: UInt64 = 0
|
||||||
|
@Published var lastReceivedCommand: String = ""
|
||||||
|
|
||||||
|
// Received dial values from clients (override local values when set)
|
||||||
|
@Published var receivedDialValues: [Int]? = nil // nil = use local values
|
||||||
|
@Published var externalControlActive = false
|
||||||
|
|
||||||
|
// MARK: - Private Properties
|
||||||
|
|
||||||
|
private var listener: NWListener?
|
||||||
|
private var connections: [UUID: NWConnection] = [:]
|
||||||
|
private let queue = DispatchQueue(label: "vu.server", qos: .userInteractive)
|
||||||
|
private var broadcastTimer: Timer?
|
||||||
|
|
||||||
|
// Reference to serial manager for broadcasting
|
||||||
|
weak var serialManager: SerialManager?
|
||||||
|
|
||||||
|
// MARK: - Initialization
|
||||||
|
|
||||||
|
init() {
|
||||||
|
loadOptions()
|
||||||
|
}
|
||||||
|
|
||||||
|
deinit {
|
||||||
|
stop()
|
||||||
|
}
|
||||||
|
|
||||||
|
// MARK: - Server Control
|
||||||
|
|
||||||
|
/// Start the server
|
||||||
|
func start() {
|
||||||
|
guard !isRunning else { return }
|
||||||
|
|
||||||
|
do {
|
||||||
|
// Configure parameters
|
||||||
|
let parameters = NWParameters.tcp
|
||||||
|
parameters.allowLocalEndpointReuse = true
|
||||||
|
|
||||||
|
// Create listener
|
||||||
|
let port = NWEndpoint.Port(rawValue: options.port)!
|
||||||
|
listener = try NWListener(using: parameters, on: port)
|
||||||
|
|
||||||
|
listener?.stateUpdateHandler = { [weak self] state in
|
||||||
|
DispatchQueue.main.async {
|
||||||
|
self?.handleListenerState(state)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
listener?.newConnectionHandler = { [weak self] connection in
|
||||||
|
self?.handleNewConnection(connection)
|
||||||
|
}
|
||||||
|
|
||||||
|
listener?.start(queue: queue)
|
||||||
|
|
||||||
|
DispatchQueue.main.async {
|
||||||
|
self.isRunning = true
|
||||||
|
self.lastError = nil
|
||||||
|
}
|
||||||
|
|
||||||
|
// Start broadcast timer if enabled
|
||||||
|
if options.broadcastLevels {
|
||||||
|
startBroadcastTimer()
|
||||||
|
}
|
||||||
|
|
||||||
|
print("VU Server started on port \(options.port)")
|
||||||
|
|
||||||
|
} catch {
|
||||||
|
DispatchQueue.main.async {
|
||||||
|
self.lastError = "Failed to start server: \(error.localizedDescription)"
|
||||||
|
self.isRunning = false
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Stop the server
|
||||||
|
func stop() {
|
||||||
|
stopBroadcastTimer()
|
||||||
|
|
||||||
|
// Close all connections
|
||||||
|
for (_, connection) in connections {
|
||||||
|
connection.cancel()
|
||||||
|
}
|
||||||
|
connections.removeAll()
|
||||||
|
|
||||||
|
// Stop listener
|
||||||
|
listener?.cancel()
|
||||||
|
listener = nil
|
||||||
|
|
||||||
|
DispatchQueue.main.async {
|
||||||
|
self.isRunning = false
|
||||||
|
self.connectedClients.removeAll()
|
||||||
|
self.externalControlActive = false
|
||||||
|
self.receivedDialValues = nil
|
||||||
|
}
|
||||||
|
|
||||||
|
print("VU Server stopped")
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Toggle server state
|
||||||
|
func toggle() {
|
||||||
|
if isRunning {
|
||||||
|
stop()
|
||||||
|
} else {
|
||||||
|
start()
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Restart server (after options change)
|
||||||
|
func restart() {
|
||||||
|
if isRunning {
|
||||||
|
stop()
|
||||||
|
DispatchQueue.main.asyncAfter(deadline: .now() + 0.5) {
|
||||||
|
self.start()
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// MARK: - Connection Handling
|
||||||
|
|
||||||
|
private func handleListenerState(_ state: NWListener.State) {
|
||||||
|
switch state {
|
||||||
|
case .ready:
|
||||||
|
print("Server ready on port \(options.port)")
|
||||||
|
case .failed(let error):
|
||||||
|
lastError = "Server failed: \(error.localizedDescription)"
|
||||||
|
isRunning = false
|
||||||
|
case .cancelled:
|
||||||
|
isRunning = false
|
||||||
|
default:
|
||||||
|
break
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private func handleNewConnection(_ connection: NWConnection) {
|
||||||
|
let clientID = UUID()
|
||||||
|
|
||||||
|
// Check max clients
|
||||||
|
if connections.count >= options.maxClients {
|
||||||
|
connection.cancel()
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
// Check if remote connections are allowed
|
||||||
|
if !options.allowRemote {
|
||||||
|
if let endpoint = connection.currentPath?.remoteEndpoint,
|
||||||
|
case let .hostPort(host, _) = endpoint {
|
||||||
|
let hostStr = "\(host)"
|
||||||
|
if !hostStr.contains("127.0.0.1") && !hostStr.contains("localhost") && !hostStr.contains("::1") {
|
||||||
|
connection.cancel()
|
||||||
|
return
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
connections[clientID] = connection
|
||||||
|
|
||||||
|
// Get client address
|
||||||
|
var address = "Unknown"
|
||||||
|
if let endpoint = connection.currentPath?.remoteEndpoint,
|
||||||
|
case let .hostPort(host, port) = endpoint {
|
||||||
|
address = "\(host):\(port)"
|
||||||
|
}
|
||||||
|
|
||||||
|
let client = ConnectedClient(address: address)
|
||||||
|
|
||||||
|
DispatchQueue.main.async {
|
||||||
|
self.connectedClients.append(client)
|
||||||
|
}
|
||||||
|
|
||||||
|
connection.stateUpdateHandler = { [weak self] state in
|
||||||
|
self?.handleConnectionState(clientID: clientID, state: state)
|
||||||
|
}
|
||||||
|
|
||||||
|
connection.start(queue: queue)
|
||||||
|
|
||||||
|
// Start receiving data
|
||||||
|
receiveData(clientID: clientID, connection: connection)
|
||||||
|
|
||||||
|
// Send welcome message
|
||||||
|
let welcome = "VU-Server Ready\n"
|
||||||
|
sendData(welcome.data(using: .utf8)!, to: clientID)
|
||||||
|
}
|
||||||
|
|
||||||
|
private func handleConnectionState(clientID: UUID, state: NWConnection.State) {
|
||||||
|
switch state {
|
||||||
|
case .ready:
|
||||||
|
print("Client connected: \(clientID)")
|
||||||
|
case .failed(_), .cancelled:
|
||||||
|
removeClient(clientID: clientID)
|
||||||
|
default:
|
||||||
|
break
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private func removeClient(clientID: UUID) {
|
||||||
|
connections[clientID]?.cancel()
|
||||||
|
connections.removeValue(forKey: clientID)
|
||||||
|
|
||||||
|
DispatchQueue.main.async {
|
||||||
|
self.connectedClients.removeAll { $0.id == clientID }
|
||||||
|
|
||||||
|
// If no more clients, disable external control
|
||||||
|
if self.connectedClients.isEmpty {
|
||||||
|
self.externalControlActive = false
|
||||||
|
self.receivedDialValues = nil
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// MARK: - Data Handling
|
||||||
|
|
||||||
|
private func receiveData(clientID: UUID, connection: NWConnection) {
|
||||||
|
connection.receive(minimumIncompleteLength: 1, maximumLength: 1024) { [weak self] data, _, isComplete, error in
|
||||||
|
guard let self = self else { return }
|
||||||
|
|
||||||
|
if let data = data, !data.isEmpty {
|
||||||
|
DispatchQueue.main.async {
|
||||||
|
self.totalBytesReceived += UInt64(data.count)
|
||||||
|
|
||||||
|
if let index = self.connectedClients.firstIndex(where: { $0.id == clientID }) {
|
||||||
|
self.connectedClients[index].bytesReceived += UInt64(data.count)
|
||||||
|
self.connectedClients[index].lastActivity = Date()
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
self.processReceivedData(data, from: clientID)
|
||||||
|
}
|
||||||
|
|
||||||
|
if let error = error {
|
||||||
|
print("Receive error: \(error)")
|
||||||
|
self.removeClient(clientID: clientID)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
if isComplete {
|
||||||
|
self.removeClient(clientID: clientID)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
// Continue receiving
|
||||||
|
self.receiveData(clientID: clientID, connection: connection)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private func processReceivedData(_ data: Data, from clientID: UUID) {
|
||||||
|
// Try to parse based on protocol
|
||||||
|
switch options.serverProtocol {
|
||||||
|
case .vuProtocol:
|
||||||
|
parseVUProtocol(data, from: clientID)
|
||||||
|
case .json:
|
||||||
|
parseJSON(data, from: clientID)
|
||||||
|
case .rawBytes:
|
||||||
|
parseRawBytes(data, from: clientID)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Parse VU Protocol: #channel:value\n
|
||||||
|
private func parseVUProtocol(_ data: Data, from clientID: UUID) {
|
||||||
|
guard let string = String(data: data, encoding: .utf8) else { return }
|
||||||
|
|
||||||
|
DispatchQueue.main.async {
|
||||||
|
self.lastReceivedCommand = string.trimmingCharacters(in: .whitespacesAndNewlines)
|
||||||
|
}
|
||||||
|
|
||||||
|
// Parse commands line by line
|
||||||
|
let lines = string.components(separatedBy: .newlines)
|
||||||
|
var values = receivedDialValues ?? [0, 0, 0, 0]
|
||||||
|
var hasUpdate = false
|
||||||
|
|
||||||
|
for line in lines {
|
||||||
|
let trimmed = line.trimmingCharacters(in: .whitespaces)
|
||||||
|
|
||||||
|
// Handle special commands
|
||||||
|
if trimmed == "?" || trimmed == "STATUS" {
|
||||||
|
sendStatus(to: clientID)
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
|
||||||
|
if trimmed == "RELEASE" {
|
||||||
|
// Release external control
|
||||||
|
DispatchQueue.main.async {
|
||||||
|
self.externalControlActive = false
|
||||||
|
self.receivedDialValues = nil
|
||||||
|
}
|
||||||
|
sendData("OK:RELEASED\n".data(using: .utf8)!, to: clientID)
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
|
||||||
|
// Parse #channel:value format
|
||||||
|
if trimmed.hasPrefix("#") {
|
||||||
|
let parts = trimmed.dropFirst().components(separatedBy: ":")
|
||||||
|
if parts.count == 2,
|
||||||
|
let channel = Int(parts[0]),
|
||||||
|
let value = Int(parts[1]),
|
||||||
|
channel >= 0 && channel < 4 {
|
||||||
|
// Value is percentage 0-100, convert to 0-255
|
||||||
|
let byteValue = (value * 255) / 100
|
||||||
|
values[channel] = max(0, min(255, byteValue))
|
||||||
|
hasUpdate = true
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// Also support CH1:value format
|
||||||
|
if trimmed.hasPrefix("CH") {
|
||||||
|
let parts = trimmed.dropFirst(2).components(separatedBy: ":")
|
||||||
|
if parts.count == 2,
|
||||||
|
let channel = Int(parts[0]),
|
||||||
|
let value = Int(parts[1]),
|
||||||
|
channel >= 1 && channel <= 4 {
|
||||||
|
values[channel - 1] = max(0, min(255, value))
|
||||||
|
hasUpdate = true
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
if hasUpdate {
|
||||||
|
DispatchQueue.main.async {
|
||||||
|
self.receivedDialValues = values
|
||||||
|
self.externalControlActive = true
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Parse JSON: {"dials":[v1,v2,v3,v4]} or {"d0":v,"d1":v,...}
|
||||||
|
private func parseJSON(_ data: Data, from clientID: UUID) {
|
||||||
|
guard let json = try? JSONSerialization.jsonObject(with: data) as? [String: Any] else { return }
|
||||||
|
|
||||||
|
DispatchQueue.main.async {
|
||||||
|
if let str = String(data: data, encoding: .utf8) {
|
||||||
|
self.lastReceivedCommand = str.trimmingCharacters(in: .whitespacesAndNewlines)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
var values = receivedDialValues ?? [0, 0, 0, 0]
|
||||||
|
var hasUpdate = false
|
||||||
|
|
||||||
|
// Array format
|
||||||
|
if let dials = json["dials"] as? [Int] {
|
||||||
|
for (i, v) in dials.prefix(4).enumerated() {
|
||||||
|
values[i] = max(0, min(255, v))
|
||||||
|
}
|
||||||
|
hasUpdate = true
|
||||||
|
}
|
||||||
|
|
||||||
|
// Individual dial format
|
||||||
|
for i in 0..<4 {
|
||||||
|
if let v = json["d\(i)"] as? Int {
|
||||||
|
values[i] = max(0, min(255, v))
|
||||||
|
hasUpdate = true
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// Command handling
|
||||||
|
if let cmd = json["cmd"] as? String {
|
||||||
|
switch cmd {
|
||||||
|
case "status":
|
||||||
|
sendStatus(to: clientID)
|
||||||
|
case "release":
|
||||||
|
DispatchQueue.main.async {
|
||||||
|
self.externalControlActive = false
|
||||||
|
self.receivedDialValues = nil
|
||||||
|
}
|
||||||
|
default:
|
||||||
|
break
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
if hasUpdate {
|
||||||
|
DispatchQueue.main.async {
|
||||||
|
self.receivedDialValues = values
|
||||||
|
self.externalControlActive = true
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Parse raw bytes: [0xAA, d1, d2, d3, d4, 0x55]
|
||||||
|
private func parseRawBytes(_ data: Data, from clientID: UUID) {
|
||||||
|
DispatchQueue.main.async {
|
||||||
|
self.lastReceivedCommand = data.map { String(format: "%02X", $0) }.joined(separator: " ")
|
||||||
|
}
|
||||||
|
|
||||||
|
// Look for frame: 0xAA ... 0x55
|
||||||
|
var values = receivedDialValues ?? [0, 0, 0, 0]
|
||||||
|
let bytes = Array(data)
|
||||||
|
|
||||||
|
var i = 0
|
||||||
|
while i < bytes.count {
|
||||||
|
if bytes[i] == 0xAA && i + 5 < bytes.count && bytes[i + 5] == 0x55 {
|
||||||
|
// Found valid frame
|
||||||
|
for j in 0..<4 {
|
||||||
|
values[j] = Int(bytes[i + 1 + j])
|
||||||
|
}
|
||||||
|
|
||||||
|
DispatchQueue.main.async {
|
||||||
|
self.receivedDialValues = values
|
||||||
|
self.externalControlActive = true
|
||||||
|
}
|
||||||
|
|
||||||
|
i += 6
|
||||||
|
} else {
|
||||||
|
i += 1
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// MARK: - Send Data
|
||||||
|
|
||||||
|
private func sendData(_ data: Data, to clientID: UUID) {
|
||||||
|
guard let connection = connections[clientID] else { return }
|
||||||
|
|
||||||
|
connection.send(content: data, completion: .contentProcessed { [weak self] error in
|
||||||
|
if error == nil {
|
||||||
|
DispatchQueue.main.async {
|
||||||
|
self?.totalBytesSent += UInt64(data.count)
|
||||||
|
|
||||||
|
if let index = self?.connectedClients.firstIndex(where: { $0.id == clientID }) {
|
||||||
|
self?.connectedClients[index].bytesSent += UInt64(data.count)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
private func sendStatus(to clientID: UUID) {
|
||||||
|
guard let sm = serialManager else { return }
|
||||||
|
|
||||||
|
let status: [String: Any] = [
|
||||||
|
"connected": sm.isConnected,
|
||||||
|
"dials": sm.dialValues,
|
||||||
|
"port": sm.selectedPortPath,
|
||||||
|
"external": externalControlActive
|
||||||
|
]
|
||||||
|
|
||||||
|
if let data = try? JSONSerialization.data(withJSONObject: status, options: []),
|
||||||
|
let string = String(data: data, encoding: .utf8) {
|
||||||
|
sendData((string + "\n").data(using: .utf8)!, to: clientID)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Broadcast current levels to all clients
|
||||||
|
func broadcastLevels() {
|
||||||
|
guard !connections.isEmpty, let sm = serialManager else { return }
|
||||||
|
|
||||||
|
let message: String
|
||||||
|
|
||||||
|
switch options.serverProtocol {
|
||||||
|
case .vuProtocol:
|
||||||
|
message = sm.dialValues.enumerated()
|
||||||
|
.map { "#\($0.offset):\(($0.element * 100) / 255)" }
|
||||||
|
.joined(separator: "\n") + "\n"
|
||||||
|
case .json:
|
||||||
|
message = "{\"dials\":[\(sm.dialValues.map(String.init).joined(separator: ","))]}\n"
|
||||||
|
case .rawBytes:
|
||||||
|
// Don't broadcast for raw bytes
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
guard let data = message.data(using: .utf8) else { return }
|
||||||
|
|
||||||
|
for clientID in connections.keys {
|
||||||
|
sendData(data, to: clientID)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// MARK: - Broadcast Timer
|
||||||
|
|
||||||
|
private func startBroadcastTimer() {
|
||||||
|
stopBroadcastTimer()
|
||||||
|
|
||||||
|
DispatchQueue.main.async {
|
||||||
|
self.broadcastTimer = Timer.scheduledTimer(withTimeInterval: self.options.broadcastInterval, repeats: true) { [weak self] _ in
|
||||||
|
self?.broadcastLevels()
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private func stopBroadcastTimer() {
|
||||||
|
broadcastTimer?.invalidate()
|
||||||
|
broadcastTimer = nil
|
||||||
|
}
|
||||||
|
|
||||||
|
// MARK: - Persistence
|
||||||
|
|
||||||
|
private func loadOptions() {
|
||||||
|
if let data = UserDefaults.standard.data(forKey: "VUServerOptions"),
|
||||||
|
let loaded = try? JSONDecoder().decode(ServerOptions.self, from: data) {
|
||||||
|
options = loaded
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func saveOptions() {
|
||||||
|
if let data = try? JSONEncoder().encode(options) {
|
||||||
|
UserDefaults.standard.set(data, forKey: "VUServerOptions")
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// MARK: - Disconnect Client
|
||||||
|
|
||||||
|
func disconnectClient(_ client: ConnectedClient) {
|
||||||
|
removeClient(clientID: client.id)
|
||||||
|
}
|
||||||
|
}
|
||||||
Reference in New Issue
Block a user