-
Notifications
You must be signed in to change notification settings - Fork 441
Add barometer as an entity that iPhone/some iPads expose #4491
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Open
teancom
wants to merge
7
commits into
home-assistant:main
Choose a base branch
from
teancom:feat/barometer
base: main
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
Open
Changes from 3 commits
Commits
Show all changes
7 commits
Select commit
Hold shift + click to select a range
2196611
Add barometer sensor exposing iPhone pressure data to Home Assistant
teancom 0bb5706
Add tests for BarometerSensor
teancom b71926a
Add continuous pressure updates via SensorProviderUpdateSignaler
teancom 9284e8c
Guard against double-resolving promise in one-shot barometer read
teancom 4b6e9b8
Merge branch 'main' into feat/barometer
bgoncal 523bbaf
Address Copilot review feedback on barometer sensor
teancom 8b3be6c
Fix flaky testSensorsUsesCachedDataWhenSignalerIsActive
teancom File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
128 changes: 128 additions & 0 deletions
128
Sources/Shared/API/Webhook/Sensors/BarometerSensor.swift
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| 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() | ||
teancom marked this conversation as resolved.
Show resolved
Hide resolved
|
||
|
|
||
| if let data { | ||
| seal.fulfill(data) | ||
| } else if let error { | ||
| seal.reject(error) | ||
| } else { | ||
| seal.reject(BarometerError.noData) | ||
| } | ||
| } | ||
teancom marked this conversation as resolved.
Show resolved
Hide resolved
|
||
|
|
||
| return promise | ||
| } | ||
| } | ||
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.