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

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
10 changes: 10 additions & 0 deletions HomeAssistant.xcodeproj/project.pbxproj
Original file line number Diff line number Diff line change
Expand Up @@ -388,6 +388,7 @@
11C9E43C2505B04E00492A88 /* HACoreAudioObjectSystem.swift in Sources */ = {isa = PBXBuildFile; fileRef = 11C9E43A2505B04E00492A88 /* HACoreAudioObjectSystem.swift */; };
11CB98C6249DE15B00B05222 /* LastUpdateSensor.test.swift in Sources */ = {isa = PBXBuildFile; fileRef = 11CB98C5249DE15B00B05222 /* LastUpdateSensor.test.swift */; };
11CB98C8249DE24100B05222 /* PedometerSensor.test.swift in Sources */ = {isa = PBXBuildFile; fileRef = 11CB98C7249DE24000B05222 /* PedometerSensor.test.swift */; };
8DFA3DEE4881E59961C3B5E2 /* BarometerSensor.test.swift in Sources */ = {isa = PBXBuildFile; fileRef = 07A4CD40BADC119045547D77 /* BarometerSensor.test.swift */; };
11CB98CA249E62E700B05222 /* Version+HA.swift in Sources */ = {isa = PBXBuildFile; fileRef = 11CB98C9249E62E700B05222 /* Version+HA.swift */; };
11CB98CB249E62E700B05222 /* Version+HA.swift in Sources */ = {isa = PBXBuildFile; fileRef = 11CB98C9249E62E700B05222 /* Version+HA.swift */; };
11CB98CD249E637300B05222 /* Version+HA.test.swift in Sources */ = {isa = PBXBuildFile; fileRef = 11CB98CC249E637300B05222 /* Version+HA.test.swift */; };
Expand Down Expand Up @@ -1137,6 +1138,8 @@
42E95C592CA46AD50010ECE3 /* ShareActivityView.swift in Sources */ = {isa = PBXBuildFile; fileRef = 42E95C582CA46AD50010ECE3 /* ShareActivityView.swift */; };
42E9AFFF2CE63944009DDA46 /* AudioOutputSensor.swift in Sources */ = {isa = PBXBuildFile; fileRef = 42E9AFFE2CE63944009DDA46 /* AudioOutputSensor.swift */; };
42E9B0002CE63944009DDA46 /* AudioOutputSensor.swift in Sources */ = {isa = PBXBuildFile; fileRef = 42E9AFFE2CE63944009DDA46 /* AudioOutputSensor.swift */; };
C3EB3740FA097F36D51F525E /* BarometerSensor.swift in Sources */ = {isa = PBXBuildFile; fileRef = 1396822195C7FF562AB891F2 /* BarometerSensor.swift */; };
D87EC7A89E0515C4CAB93220 /* BarometerSensor.swift in Sources */ = {isa = PBXBuildFile; fileRef = 1396822195C7FF562AB891F2 /* BarometerSensor.swift */; };
42EB030A2C6E4D0E00A184A6 /* WatchMagicViewRow.swift in Sources */ = {isa = PBXBuildFile; fileRef = 42EB03092C6E4D0E00A184A6 /* WatchMagicViewRow.swift */; };
42EEEFE22E2791430080E973 /* Service.swift in Sources */ = {isa = PBXBuildFile; fileRef = 42EEEFE12E2791430080E973 /* Service.swift */; };
42EEEFE32E2791430080E973 /* Service.swift in Sources */ = {isa = PBXBuildFile; fileRef = 42EEEFE12E2791430080E973 /* Service.swift */; };
Expand Down Expand Up @@ -2175,6 +2178,7 @@
11C9E43A2505B04E00492A88 /* HACoreAudioObjectSystem.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = HACoreAudioObjectSystem.swift; sourceTree = "<group>"; };
11CB98C5249DE15B00B05222 /* LastUpdateSensor.test.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = LastUpdateSensor.test.swift; sourceTree = "<group>"; };
11CB98C7249DE24000B05222 /* PedometerSensor.test.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = PedometerSensor.test.swift; sourceTree = "<group>"; };
07A4CD40BADC119045547D77 /* BarometerSensor.test.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = BarometerSensor.test.swift; sourceTree = "<group>"; };
11CB98C9249E62E700B05222 /* Version+HA.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = "Version+HA.swift"; sourceTree = "<group>"; };
11CB98CC249E637300B05222 /* Version+HA.test.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = "Version+HA.test.swift"; sourceTree = "<group>"; };
11CD94B424B2C06700BA801D /* WebhookResponseUpdateSensors.test.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = WebhookResponseUpdateSensors.test.swift; sourceTree = "<group>"; };
Expand Down Expand Up @@ -2971,6 +2975,7 @@
42E95C562CA45EFA0010ECE3 /* OnboardingErrorView.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = OnboardingErrorView.swift; sourceTree = "<group>"; };
42E95C582CA46AD50010ECE3 /* ShareActivityView.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = ShareActivityView.swift; sourceTree = "<group>"; };
42E9AFFE2CE63944009DDA46 /* AudioOutputSensor.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = AudioOutputSensor.swift; sourceTree = "<group>"; };
1396822195C7FF562AB891F2 /* BarometerSensor.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = BarometerSensor.swift; sourceTree = "<group>"; };
42EB03092C6E4D0E00A184A6 /* WatchMagicViewRow.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = WatchMagicViewRow.swift; sourceTree = "<group>"; };
42EEEFE12E2791430080E973 /* Service.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = Service.swift; sourceTree = "<group>"; };
42EEEFE42E2792B20080E973 /* Service.test.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = Service.test.swift; sourceTree = "<group>"; };
Expand Down Expand Up @@ -4212,6 +4217,7 @@
B6D3B4EB225B26300082BB4F /* SensorContainer.swift */,
42E9AFFE2CE63944009DDA46 /* AudioOutputSensor.swift */,
11AF4D10249C7DFD006C74C0 /* ActivitySensor.swift */,
1396822195C7FF562AB891F2 /* BarometerSensor.swift */,
11AF4D1B249C8AA0006C74C0 /* BatterySensor.swift */,
11AF4D1E249C8AF0006C74C0 /* ConnectivitySensor.swift */,
11AF4D21249C924B006C74C0 /* GeocoderSensor.swift */,
Expand All @@ -4237,6 +4243,7 @@
isa = PBXGroup;
children = (
11AF4D29249D88C5006C74C0 /* ActivitySensor.test.swift */,
07A4CD40BADC119045547D77 /* BarometerSensor.test.swift */,
11AF4D2B249D965C006C74C0 /* BatterySensor.test.swift */,
11AF4D2F249DCA87006C74C0 /* ConnectivitySensor.test.swift */,
11AF4D2D249DA5AF006C74C0 /* GeocoderSensor.test.swift */,
Expand Down Expand Up @@ -9866,6 +9873,7 @@
1120C580274638330046C38B /* PerServerContainer.swift in Sources */,
427647262C8F38590027B21F /* HAAreasRegistryResponse.swift in Sources */,
42E9AFFF2CE63944009DDA46 /* AudioOutputSensor.swift in Sources */,
C3EB3740FA097F36D51F525E /* BarometerSensor.swift in Sources */,
110ED56425A563D600489AF7 /* DisplaySensor.swift in Sources */,
42383F702D9576F700C745F2 /* AppTriggerSource.swift in Sources */,
4251AAC22C6CE9CB004CCC9D /* WatchConfig.swift in Sources */,
Expand Down Expand Up @@ -10316,6 +10324,7 @@
42FCCFDA2B9B19F70057783F /* ThreadClientService.swift in Sources */,
1101568724D7712F009424C9 /* TagManagerProtocol.swift in Sources */,
42E9B0002CE63944009DDA46 /* AudioOutputSensor.swift in Sources */,
D87EC7A89E0515C4CAB93220 /* BarometerSensor.swift in Sources */,
1141182624AF9A0500E6525C /* WebhookManager.swift in Sources */,
119A7E0F2529769A00D7000D /* UIImageView+UIActivityIndicator.swift in Sources */,
111858D624CB620500B8CDDC /* Intents.intentdefinition in Sources */,
Expand Down Expand Up @@ -10377,6 +10386,7 @@
1165707C2702BAF5003906A7 /* DiskCache.test.swift in Sources */,
11AF4D30249DCA88006C74C0 /* ConnectivitySensor.test.swift in Sources */,
11CB98C8249DE24100B05222 /* PedometerSensor.test.swift in Sources */,
8DFA3DEE4881E59961C3B5E2 /* BarometerSensor.test.swift in Sources */,
42EEEFE52E2792B20080E973 /* Service.test.swift in Sources */,
118511C224B25BEB00D18F60 /* WebhookManager.test.swift in Sources */,
114CBAEB2839FC2500A9BAFF /* SecurityExceptions.test.swift in Sources */,
Expand Down
128 changes: 128 additions & 0 deletions Sources/Shared/API/Webhook/Sensors/BarometerSensor.swift
Original file line number Diff line number Diff line change
@@ -0,0 +1,128 @@
import CoreMotion
import Foundation
import PromiseKit

final class BarometerSensorUpdateSignaler: BaseSensorUpdateSignaler, SensorProviderUpdateSignaler {
private let signal: () -> Void
private var lastPressureKpa: Double?
private var observationQueue: OperationQueue?

/// The most recent altitude data received from CMAltimeter, used by BarometerSensor
/// to avoid starting a separate one-shot read that would conflict with the signaler's stream.
private(set) var latestData: CMAltitudeData?

required init(signal: @escaping () -> Void) {
self.signal = signal
super.init(relatedSensorsIds: [.pressure])
}

override func observe() {
super.observe()
guard !isObserving else { return }
guard Current.barometer.isAvailable(), Current.barometer.isAuthorized() else { return }

let queue = OperationQueue()
queue.name = "barometer-signaler"
observationQueue = queue

Current.barometer.startUpdatesOnQueueHandler(queue) { [weak self] data, _ in
guard let self, let data else { return }
latestData = data
let newPressure = data.pressure.doubleValue
if let last = lastPressureKpa, abs(newPressure - last) < 0.01 {
// Less than 0.1 hPa change, skip update
return
}
lastPressureKpa = newPressure
signal()
}
isObserving = true

#if DEBUG
notifyObservation?()
#endif
}

override func stopObserving() {
super.stopObserving()
guard isObserving else { return }
Current.barometer.stopUpdates()
observationQueue = nil
lastPressureKpa = nil
latestData = nil
isObserving = false
}
}

public class BarometerSensor: SensorProvider {
public enum BarometerError: Error, Equatable {
case unauthorized
case unavailable
case noData
}

public let request: SensorProviderRequest
public required init(request: SensorProviderRequest) {
self.request = request
}

public func sensors() -> Promise<[WebhookSensor]> {
let signaler: BarometerSensorUpdateSignaler = request.dependencies.updateSignaler(for: self)

return firstly {
// If the signaler is actively observing, use its cached data to avoid
// starting a separate one-shot read that would stop the signaler's stream.
// If observing but no data yet, fall back to noData rather than racing.
if let cached = signaler.latestData {
return Promise.value(cached)
} else if signaler.isObserving {
return .init(error: BarometerError.noData)
}
return latestBarometerData()
}.map { data in
// CMAltitudeData.pressure is in kilopascals; HA pressure device class expects hPa (= mbar)
let pressureHpa = data.pressure.doubleValue * 10.0

let pressureSensor = WebhookSensor(
name: "Pressure",
uniqueID: WebhookSensorId.pressure.rawValue,
icon: "mdi:gauge",
deviceClass: .pressure,
state: round(pressureHpa * 100) / 100,
unit: "hPa"
)

return [pressureSensor]
}
}

private func latestBarometerData() -> Promise<CMAltitudeData> {
guard Current.barometer.isAuthorized() else {
return .init(error: BarometerError.unauthorized)
}

guard Current.barometer.isAvailable() else {
Current.Log.warning("Barometer is not available")
return .init(error: BarometerError.unavailable)
}

let (promise, seal) = Promise<CMAltitudeData>.pending()
let queue = OperationQueue()
queue.name = "barometer-sensor"

Current.barometer.startUpdatesOnQueueHandler(queue) { data, error in
// We only need a single reading, so stop updates immediately
Current.barometer.stopUpdates()
Comment on lines +113 to +115
Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Isn't this something that should update often?

Copy link
Copy Markdown
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I was following the pedometer sensor as a bit of a template, but I can absolutely switch over to SensorProviderUpdateSignaler like BatterySensor does and have it send more continuous updates if you would prefer that approach. Frankly, I'm just not sure what the impact is to battery life so I went with a conservative approach. If that's not an issue, great.

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

What are the use cases you have in mind for this sensor?

Then we can define how often we want to update it.

I would expect that who activates this sensor would expect it updating more than just once every long period of time

Copy link
Copy Markdown
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Yeah, I was probably being overly cautious. I was thinking about triggers on "big" drops in a short time as an alert source, which would require more frequent updates. I used to live in Nebraska and that was a sign to head for shelter.

I'll update the PR tonight to switch over.

Copy link
Copy Markdown
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Alright, that was a little trickier than I thought (async stuff can be tricky, who knew) but that has been working on my phone and should be good to go (🤞)


if let data {
seal.fulfill(data)
} else if let error {
seal.reject(error)
} else {
seal.reject(BarometerError.noData)
}
}

return promise
}
}
1 change: 1 addition & 0 deletions Sources/Shared/API/Webhook/WebhookSensorId.swift
Original file line number Diff line number Diff line change
Expand Up @@ -22,4 +22,5 @@ public enum WebhookSensorId: String, CaseIterable {
case appVersion = "app-version"
case locationPermission = "location-permission"
case focus
case pressure
}
25 changes: 25 additions & 0 deletions Sources/Shared/Environment/Environment.swift
Original file line number Diff line number Diff line change
Expand Up @@ -225,6 +225,7 @@ public class AppEnvironment {
$0.register(provider: AppVersionSensor.self)
$0.register(provider: LocationPermissionSensor.self)
$0.register(provider: AudioOutputSensor.self)
$0.register(provider: BarometerSensor.self)
}

public var localized = LocalizedManager()
Expand Down Expand Up @@ -452,6 +453,30 @@ public class AppEnvironment {

public var pedometer = Pedometer()

/// Wrapper around CMAltimeter for barometric pressure readings
public struct Barometer {
private let underlyingAltimeter = CMAltimeter()
// isRelativeAltitudeAvailable checks for a barometer chip; the same hardware delivers
// both relative altitude and barometric pressure via startRelativeAltitudeUpdates.
public var isAvailable: () -> Bool = CMAltimeter.isRelativeAltitudeAvailable
public var isAuthorized: () -> Bool = {
guard !Current.isCatalyst else { return false }
return CMAltimeter.authorizationStatus() == .authorized
}

public lazy var startUpdatesOnQueueHandler: (
OperationQueue, @escaping CMAltitudeHandler
) -> Void = { [underlyingAltimeter] queue, handler in
underlyingAltimeter.startRelativeAltitudeUpdates(to: queue, withHandler: handler)
}

public lazy var stopUpdates: () -> Void = { [underlyingAltimeter] in
underlyingAltimeter.stopRelativeAltitudeUpdates()
}
}

public var barometer = Barometer()

public var device = DeviceWrapper()

public var matter = MatterWrapper()
Expand Down
3 changes: 2 additions & 1 deletion Tests/App/Webhook/WebhookSensorIdTests.swift
Original file line number Diff line number Diff line change
Expand Up @@ -24,8 +24,9 @@ struct WebhookSensorIdTests {
assert(WebhookSensorId.appVersion.rawValue == "app-version")
assert(WebhookSensorId.locationPermission.rawValue == "location-permission")
assert(WebhookSensorId.focus.rawValue == "focus")
assert(WebhookSensorId.pressure.rawValue == "pressure")
assert(
WebhookSensorId.allCases.count == 21,
WebhookSensorId.allCases.count == 22,
"WebhookSensorId has different number of cases than defined in test, \(WebhookSensorId.allCases.count)"
)
}
Expand Down
Loading