forked from fritob/Camper-Monitor
Uhr: Neigungsmesser direkt, Fahrzeugansicht, kein Kalibrieren
Die Uhr funkt den Neigungsmesser jetzt selbst an, statt die Werte vom iPhone weiterreichen zu lassen. Bei diesem einen Gerät geht das, und nur bei ihm: Es bewirbt seinen Dienst, ist also ohne Einrichtung auffindbar, und es ist unverschlüsselt – es gibt keinen Schlüssel, der auf der Uhr ein zweites Mal lagern müsste. Damit steht die Nivellierung am Handgelenk ohne geöffnetes iPhone, und genau dafür hebt man beim Rangieren den Arm. Batterie, Solar und Kühlbox bleiben beim Weg über das iPhone: Sie lassen nur eine Verbindung zu, und die Victron-Schlüssel liegen in dessen Keychain. Die Einbaulage des Sensors reist einmal mit dem Datensatz herüber und bleibt auf der Uhr gespeichert – ohne sie stünden längs und quer je nach Einbau vertauscht. LevelSession und VanAlignProtocol wandern nach Shared/Bluetooth; beide sind reines CoreBluetooth und laufen auf watchOS unverändert. Die Fahrzeugansicht gibt es jetzt auch auf der Uhr, umschaltbar zur Libelle; Überhöhung und Farbregeln stehen in Shared/VehicleTilt.swift, damit iPhone und Uhr nicht auseinanderlaufen. Kalibrieren fällt auf der Uhr weg, samt Befehl. Das gehört einmalig ans iPhone mit ebenem Fahrzeug; ein Knopf dafür am Handgelenk wäre vor allem eine Gelegenheit, die Nullage aus Versehen zu verstellen. Zwei Fehler dabei behoben: * Beim Start meldete die Uhr dem iPhone nie, dass jemand hinschaut – onChange(of: scenePhase) feuert beim ersten Erscheinen nicht. Der schnelle Sendetakt blieb aus, bis die App einmal im Hintergrund war. * Ein einmal direkt gemessener Wert hatte für immer Vorrang. Blieb der Sensor stehen, ohne die Verbindung zu trennen, klebte die Anzeige daran. Jetzt gilt er drei Sekunden als frisch, danach übernimmt der Stand des iPhones – mit Alter und Grund daneben. Ausserdem WATCHOS_DEPLOYMENT_TARGET auf 10.0 (Xcode hatte 11.6 gesetzt) und die Bluetooth-Begründung für das Watch-Target. Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
This commit is contained in:
@@ -1,251 +0,0 @@
|
||||
import CoreBluetooth
|
||||
import Foundation
|
||||
|
||||
/// Hält die Verbindung zum Neigungsmesser.
|
||||
///
|
||||
/// Deutlich einfacher als die BMS-Sitzung: Dienst und Charakteristiken sind
|
||||
/// bekannt, es gibt kein Rahmenprotokoll und keine Protokollerkennung. Jede
|
||||
/// Messgrösse liegt in einer eigenen Charakteristik.
|
||||
///
|
||||
/// Bevorzugt werden die Werte abonniert – die Firmware ab v1.1 schickt sie
|
||||
/// dann von selbst, sobald sie sich ändern. Ältere Firmware bietet nur
|
||||
/// Lesen an; dafür bleibt das Abfragen im Takt als Rückfallebene, damit die
|
||||
/// App auch ohne Neuaufspielen funktioniert.
|
||||
final class LevelSession: NSObject {
|
||||
|
||||
static let serviceUUID = CBUUID(string: VanAlignProtocol.serviceUUID)
|
||||
private static let pitchUUID = CBUUID(string: VanAlignProtocol.pitchUUID)
|
||||
private static let rollUUID = CBUUID(string: VanAlignProtocol.rollUUID)
|
||||
private static let offsetsUUID = CBUUID(string: VanAlignProtocol.offsetsUUID)
|
||||
private static let calibrateUUID = CBUUID(string: VanAlignProtocol.calibrateUUID)
|
||||
|
||||
let deviceID: UUID
|
||||
private let queue: DispatchQueue
|
||||
private let peripheral: CBPeripheral
|
||||
private let onUpdate: (DeviceSnapshot) -> Void
|
||||
private let onStateChange: (DeviceLinkState) -> Void
|
||||
private let onLevelState: (LevelState) -> Void
|
||||
|
||||
private var pitchCharacteristic: CBCharacteristic?
|
||||
private var rollCharacteristic: CBCharacteristic?
|
||||
private var offsetsCharacteristic: CBCharacteristic?
|
||||
private var calibrateCharacteristic: CBCharacteristic?
|
||||
|
||||
private var state = LevelState()
|
||||
/// Aus den Geräteeinstellungen; rechnet Sensor- in Fahrzeugachsen um.
|
||||
var orientation = SensorOrientation.identity {
|
||||
didSet { applyOrientation() }
|
||||
}
|
||||
private var pollTimer: DispatchSourceTimer?
|
||||
/// Nur nötig, solange das Gerät die Werte nicht von selbst schickt.
|
||||
private var needsPolling = false
|
||||
|
||||
/// Beim Ausrichten schaut man dauernd aufs Gerät, deshalb dichter als bei
|
||||
/// den übrigen Geräten.
|
||||
var pollInterval: TimeInterval = 0.5
|
||||
|
||||
init(deviceID: UUID,
|
||||
peripheral: CBPeripheral,
|
||||
queue: DispatchQueue,
|
||||
onUpdate: @escaping (DeviceSnapshot) -> Void,
|
||||
onStateChange: @escaping (DeviceLinkState) -> Void,
|
||||
onLevelState: @escaping (LevelState) -> Void) {
|
||||
self.deviceID = deviceID
|
||||
self.queue = queue
|
||||
self.peripheral = peripheral
|
||||
self.onUpdate = onUpdate
|
||||
self.onStateChange = onStateChange
|
||||
self.onLevelState = onLevelState
|
||||
super.init()
|
||||
peripheral.delegate = self
|
||||
}
|
||||
|
||||
// MARK: - Lebenszyklus
|
||||
|
||||
func start() {
|
||||
onStateChange(.connecting)
|
||||
peripheral.discoverServices([Self.serviceUUID])
|
||||
}
|
||||
|
||||
func stop() {
|
||||
pollTimer?.cancel()
|
||||
pollTimer = nil
|
||||
if peripheral.state == .connected {
|
||||
for characteristic in [pitchCharacteristic, rollCharacteristic] {
|
||||
guard let characteristic, characteristic.isNotifying else { continue }
|
||||
peripheral.setNotifyValue(false, for: characteristic)
|
||||
}
|
||||
}
|
||||
pitchCharacteristic = nil
|
||||
rollCharacteristic = nil
|
||||
offsetsCharacteristic = nil
|
||||
calibrateCharacteristic = nil
|
||||
}
|
||||
|
||||
func handleDisconnect() {
|
||||
pollTimer?.cancel()
|
||||
pollTimer = nil
|
||||
pitchCharacteristic = nil
|
||||
rollCharacteristic = nil
|
||||
offsetsCharacteristic = nil
|
||||
calibrateCharacteristic = nil
|
||||
}
|
||||
|
||||
// MARK: - Kalibrieren
|
||||
|
||||
/// Setzt die aktuelle Lage als neue Null.
|
||||
func calibrate() {
|
||||
write(VanAlignProtocol.calibrateCommand)
|
||||
}
|
||||
|
||||
/// Verwirft die Kalibrierung.
|
||||
func resetCalibration() {
|
||||
write(VanAlignProtocol.resetCommand)
|
||||
}
|
||||
|
||||
private func write(_ data: Data) {
|
||||
guard let characteristic = calibrateCharacteristic, peripheral.state == .connected else {
|
||||
return
|
||||
}
|
||||
let type: CBCharacteristicWriteType =
|
||||
characteristic.properties.contains(.write) ? .withResponse : .withoutResponse
|
||||
peripheral.writeValue(data, for: characteristic, type: type)
|
||||
// Die Offsets erst nach dem Rechnen im Gerät zurücklesen.
|
||||
queue.asyncAfter(deadline: .now() + 0.4) { [weak self] in
|
||||
self?.readOffsets()
|
||||
}
|
||||
}
|
||||
|
||||
private func readOffsets() {
|
||||
guard let offsetsCharacteristic, peripheral.state == .connected else { return }
|
||||
peripheral.readValue(for: offsetsCharacteristic)
|
||||
}
|
||||
|
||||
// MARK: - Abfrage
|
||||
|
||||
private func startPollingIfNeeded() {
|
||||
guard needsPolling, pollTimer == nil else { return }
|
||||
let timer = DispatchSource.makeTimerSource(queue: queue)
|
||||
timer.schedule(deadline: .now(), repeating: pollInterval)
|
||||
timer.setEventHandler { [weak self] in
|
||||
guard let self, self.peripheral.state == .connected else { return }
|
||||
if let pitchCharacteristic = self.pitchCharacteristic {
|
||||
self.peripheral.readValue(for: pitchCharacteristic)
|
||||
}
|
||||
if let rollCharacteristic = self.rollCharacteristic {
|
||||
self.peripheral.readValue(for: rollCharacteristic)
|
||||
}
|
||||
}
|
||||
timer.resume()
|
||||
pollTimer = timer
|
||||
}
|
||||
|
||||
/// Rechnet die Rohwerte in Fahrzeugachsen um.
|
||||
private func applyOrientation() {
|
||||
let corrected = orientation.apply(pitch: state.rawPitch, roll: state.rawRoll)
|
||||
state.pitch = corrected.pitch
|
||||
state.roll = corrected.roll
|
||||
}
|
||||
|
||||
private func publish() {
|
||||
guard state.hasReading else { return }
|
||||
onStateChange(.live)
|
||||
onLevelState(state)
|
||||
onUpdate(state.snapshot(deviceID: deviceID, rssi: nil))
|
||||
}
|
||||
}
|
||||
|
||||
// MARK: - CBPeripheralDelegate
|
||||
|
||||
extension LevelSession: CBPeripheralDelegate {
|
||||
|
||||
func peripheral(_ peripheral: CBPeripheral, didDiscoverServices error: Error?) {
|
||||
if let error {
|
||||
onStateChange(.failed(error.localizedDescription))
|
||||
return
|
||||
}
|
||||
guard let service = peripheral.services?.first(where: { $0.uuid == Self.serviceUUID }) else {
|
||||
onStateChange(.failed("Neigungsmesser-Dienst nicht gefunden"))
|
||||
return
|
||||
}
|
||||
peripheral.discoverCharacteristics(
|
||||
[Self.pitchUUID, Self.rollUUID, Self.offsetsUUID, Self.calibrateUUID],
|
||||
for: service
|
||||
)
|
||||
}
|
||||
|
||||
func peripheral(_ peripheral: CBPeripheral,
|
||||
didDiscoverCharacteristicsFor service: CBService,
|
||||
error: Error?) {
|
||||
guard error == nil, let characteristics = service.characteristics else {
|
||||
onStateChange(.failed(error?.localizedDescription ?? "Keine Merkmale gefunden"))
|
||||
return
|
||||
}
|
||||
|
||||
for characteristic in characteristics {
|
||||
switch characteristic.uuid {
|
||||
case Self.pitchUUID: pitchCharacteristic = characteristic
|
||||
case Self.rollUUID: rollCharacteristic = characteristic
|
||||
case Self.offsetsUUID: offsetsCharacteristic = characteristic
|
||||
case Self.calibrateUUID: calibrateCharacteristic = characteristic
|
||||
default: break
|
||||
}
|
||||
}
|
||||
|
||||
guard pitchCharacteristic != nil || rollCharacteristic != nil else {
|
||||
onStateChange(.failed("Neigungswerte nicht gefunden"))
|
||||
return
|
||||
}
|
||||
|
||||
// Abonnieren, wo möglich; sonst im Takt abfragen.
|
||||
var subscribed = false
|
||||
for characteristic in [pitchCharacteristic, rollCharacteristic] {
|
||||
guard let characteristic else { continue }
|
||||
if characteristic.properties.contains(.notify) {
|
||||
peripheral.setNotifyValue(true, for: characteristic)
|
||||
subscribed = true
|
||||
}
|
||||
}
|
||||
needsPolling = !subscribed
|
||||
startPollingIfNeeded()
|
||||
|
||||
// Einmal alles lesen, damit sofort etwas dasteht.
|
||||
for characteristic in [pitchCharacteristic, rollCharacteristic, offsetsCharacteristic] {
|
||||
guard let characteristic, characteristic.properties.contains(.read) else { continue }
|
||||
peripheral.readValue(for: characteristic)
|
||||
}
|
||||
}
|
||||
|
||||
func peripheral(_ peripheral: CBPeripheral,
|
||||
didUpdateValueFor characteristic: CBCharacteristic,
|
||||
error: Error?) {
|
||||
guard error == nil, let value = characteristic.value else { return }
|
||||
|
||||
switch characteristic.uuid {
|
||||
case Self.pitchUUID:
|
||||
state.rawPitch = VanAlignProtocol.angle(from: value)
|
||||
applyOrientation()
|
||||
case Self.rollUUID:
|
||||
state.rawRoll = VanAlignProtocol.angle(from: value)
|
||||
applyOrientation()
|
||||
case Self.offsetsUUID:
|
||||
if let offsets = VanAlignProtocol.offsets(from: value) {
|
||||
state.pitchOffset = offsets.pitch
|
||||
state.rollOffset = offsets.roll
|
||||
}
|
||||
default:
|
||||
return
|
||||
}
|
||||
publish()
|
||||
}
|
||||
|
||||
func peripheral(_ peripheral: CBPeripheral,
|
||||
didUpdateNotificationStateFor characteristic: CBCharacteristic,
|
||||
error: Error?) {
|
||||
// Lässt sich nicht abonnieren, dann eben abfragen.
|
||||
if error != nil {
|
||||
needsPolling = true
|
||||
startPollingIfNeeded()
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,51 +0,0 @@
|
||||
import Foundation
|
||||
|
||||
/// Neigungsmesser „VanAlign Pro“ – ein ESP32 mit MPU6050, der Längs- und
|
||||
/// Querneigung des Fahrzeugs über Bluetooth bereitstellt.
|
||||
///
|
||||
/// Anders als die übrigen Geräte gibt es hier kein Rahmenprotokoll: Jede
|
||||
/// Messgrösse liegt in einer eigenen Charakteristik als 32-Bit-Float.
|
||||
enum VanAlignProtocol {
|
||||
|
||||
/// Wird vom Gerät beworben, das Gerät ist darüber auffindbar.
|
||||
static let serviceUUID = "2A24B789-7AAB-4535-AF3E-EE76A35CC42D"
|
||||
|
||||
static let pitchUUID = "CAD48E28-7FBE-41CF-BAE9-D77A6C233424"
|
||||
static let rollUUID = "CAD48E28-7FBE-41CF-BAE9-D77A6C233425"
|
||||
/// Zwei Floats: die gespeicherten Kalibrier-Offsets.
|
||||
static let offsetsUUID = "CAD48E28-7FBE-41CF-BAE9-D77A6C233426"
|
||||
/// Ein Byte: 0 setzt zurück, alles andere kalibriert auf die aktuelle Lage.
|
||||
static let calibrateUUID = "CAD48E28-7FBE-41CF-BAE9-D77A6C233427"
|
||||
|
||||
static let calibrateCommand = Data([0x01])
|
||||
static let resetCommand = Data([0x00])
|
||||
|
||||
/// Liest einen Winkel aus vier Bytes, little-endian.
|
||||
///
|
||||
/// Die Firmware legt den Float per `memcpy` ab, und der ESP32 ist
|
||||
/// little-endian – die Reihenfolge steht also fest. Die Web-Oberfläche des
|
||||
/// Ursprungsprojekts probiert zusätzlich die umgekehrte Reihenfolge, falls
|
||||
/// die erste unplausibel aussieht. Das ist nicht nur unnötig, sondern
|
||||
/// schädlich: ein vertauschter Float von 4,25° ergibt gelesen etwa 0,0 und
|
||||
/// wirkt damit völlig plausibel. Ein Vorzeichen- oder Wertfehler bliebe so
|
||||
/// unbemerkt.
|
||||
static func angle(from data: Data) -> Double? {
|
||||
guard data.count >= 4 else { return nil }
|
||||
var raw: UInt32 = 0
|
||||
for (index, byte) in data.prefix(4).enumerated() {
|
||||
raw |= UInt32(byte) << UInt32(8 * index)
|
||||
}
|
||||
let value = Float(bitPattern: raw)
|
||||
// NAN meldet die Firmware, solange der Sensor nichts liefert.
|
||||
guard value.isFinite, abs(value) <= 180 else { return nil }
|
||||
return Double(value)
|
||||
}
|
||||
|
||||
/// Die beiden gespeicherten Offsets.
|
||||
static func offsets(from data: Data) -> (pitch: Double, roll: Double)? {
|
||||
guard data.count >= 8,
|
||||
let pitch = angle(from: data.prefix(4)),
|
||||
let roll = angle(from: data.dropFirst(4).prefix(4)) else { return nil }
|
||||
return (pitch, roll)
|
||||
}
|
||||
}
|
||||
@@ -16,11 +16,6 @@ struct VehicleTiltView: View {
|
||||
let pitch: Double?
|
||||
let roll: Double?
|
||||
|
||||
/// Kleine Neigungen sind am Fahrzeug sonst kaum zu erkennen – zwei Grad
|
||||
/// wären ein knappes Grad Bildneigung. Die Überhöhung wird angeschrieben,
|
||||
/// damit niemand den Winkel für bare Münze nimmt.
|
||||
static let exaggeration: Double = 3
|
||||
|
||||
var body: some View {
|
||||
VStack(spacing: 20) {
|
||||
tiltPanel(image: "VehicleSide",
|
||||
@@ -28,19 +23,19 @@ struct VehicleTiltView: View {
|
||||
title: "Längs",
|
||||
lowerLabel: "Front",
|
||||
upperLabel: "Heck",
|
||||
aspect: 925.0 / 600.0)
|
||||
aspect: VehicleTilt.sideAspect)
|
||||
|
||||
tiltPanel(image: "VehicleRear",
|
||||
angle: roll,
|
||||
title: "Quer",
|
||||
lowerLabel: "links",
|
||||
upperLabel: "rechts",
|
||||
aspect: 1)
|
||||
aspect: VehicleTilt.rearAspect)
|
||||
|
||||
// Ohne diesen Hinweis nähme man den Bildwinkel für den echten.
|
||||
Text(String(format: "Neigung %.0f-fach überhöht dargestellt – "
|
||||
+ "sonst wäre sie kaum zu erkennen. Die Gradzahlen sind echt.",
|
||||
Self.exaggeration))
|
||||
VehicleTilt.exaggeration))
|
||||
.font(.caption2)
|
||||
.foregroundStyle(.secondary)
|
||||
.multilineTextAlignment(.center)
|
||||
@@ -61,7 +56,7 @@ struct VehicleTiltView: View {
|
||||
Spacer()
|
||||
Text(angle.map { String(format: "%.1f°", $0) } ?? "–")
|
||||
.font(.subheadline.weight(.semibold).monospacedDigit())
|
||||
.foregroundStyle(colour(for: angle))
|
||||
.foregroundStyle(VehicleTilt.colour(for: angle))
|
||||
}
|
||||
|
||||
ZStack {
|
||||
@@ -74,9 +69,9 @@ struct VehicleTiltView: View {
|
||||
Image(image)
|
||||
.resizable()
|
||||
.scaledToFit()
|
||||
.foregroundStyle(colour(for: angle))
|
||||
.foregroundStyle(VehicleTilt.colour(for: angle))
|
||||
.aspectRatio(aspect, contentMode: .fit)
|
||||
.rotationEffect(.degrees(-(angle ?? 0) * Self.exaggeration))
|
||||
.rotationEffect(.degrees(-(angle ?? 0) * VehicleTilt.exaggeration))
|
||||
.animation(.spring(duration: 0.4), value: angle)
|
||||
.opacity(angle == nil ? 0.3 : 1)
|
||||
}
|
||||
@@ -92,12 +87,6 @@ struct VehicleTiltView: View {
|
||||
}
|
||||
}
|
||||
|
||||
private func colour(for angle: Double?) -> Color {
|
||||
guard let angle else { return .secondary }
|
||||
if abs(angle) <= LevelState.levelTolerance { return .green }
|
||||
if abs(angle) <= 2 { return .orange }
|
||||
return .red
|
||||
}
|
||||
}
|
||||
|
||||
/// Umschalter zwischen den beiden Darstellungen, gemerkt über Starts hinweg.
|
||||
|
||||
@@ -134,6 +134,7 @@ final class PhoneWatchLink: NSObject {
|
||||
link: bluetooth.linkStates[device.id] ?? .searching,
|
||||
snapshot: bluetooth.snapshots[device.id],
|
||||
level: device.role == .leveling ? bluetooth.levelStates[device.id] : nil,
|
||||
orientation: device.role == .leveling ? device.sensorOrientation : nil,
|
||||
fridge: device.role == .fridge
|
||||
? bluetooth.fridgeStates[device.id].map(WatchFridge.init) : nil)
|
||||
}
|
||||
@@ -167,8 +168,6 @@ final class PhoneWatchLink: NSObject {
|
||||
bluetooth.setFridgeLock(locked, for: device)
|
||||
case .fridgeTarget(let device, let zone, let value):
|
||||
bluetooth.setFridgeTarget(value, zone: zone == .left ? .left : .right, for: device)
|
||||
case .calibrateLevel(let device):
|
||||
bluetooth.calibrateLevel(for: device)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user