-
Notifications
You must be signed in to change notification settings - Fork 442
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
3
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 all commits
Commits
Show all changes
3 commits
Select commit
Hold shift + click to select a range
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() | ||
|
|
||
| if let data { | ||
| seal.fulfill(data) | ||
| } else if let error { | ||
| seal.reject(error) | ||
| } else { | ||
| seal.reject(BarometerError.noData) | ||
| } | ||
| } | ||
|
|
||
| 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.
There was a problem hiding this comment.
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?
There was a problem hiding this comment.
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.
There was a problem hiding this comment.
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
There was a problem hiding this comment.
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.
There was a problem hiding this comment.
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 (🤞)