Skip to content
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

Use correct sensor precision in sensors widget #3269

Merged
merged 6 commits into from
Dec 12, 2024
Merged
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
Original file line number Diff line number Diff line change
Expand Up @@ -123,7 +123,12 @@ struct WidgetSensorsAppIntentTimelineProvider: AppIntentTimelineProvider {
throw WidgetSensorsDataError.badResponse
}

let stateValue = (state?["state"] as? String) ?? "N/A"
var stateValue = (state?["state"] as? String) ?? "N/A"
stateValue = adjustPrecision(
serverId: server.identifier.rawValue,
entityId: sensor.entityId,
stateValue: stateValue
)
let unitOfMeasurement = (state?["attributes"] as? [String: Any])?["unit_of_measurement"] as? String

return WidgetSensorsEntry.SensorData(
Expand All @@ -135,6 +140,39 @@ struct WidgetSensorsAppIntentTimelineProvider: AppIntentTimelineProvider {
)
}

private func adjustPrecision(serverId: String, entityId: String, stateValue: String) -> String {
guard let stateValueFloat = Float(stateValue) else {
return stateValue
}
if let decimalPlacesForEntityId: Int = {
do {
return try Current.database.read { db in
try AppEntityRegistryListForDisplay
.filter(
Column(DatabaseTables.AppEntityRegistryListForDisplay.id.rawValue) == ServerEntity
.uniqueId(
serverId: serverId,
entityId: entityId
)
)
.fetchOne(db)?.registry.decimalPlaces
}
} catch {
Current.Log.error("Failed to fetch decimal places for entity ID: \(entityId)")
return nil
}
}() {
let numberFormatter = NumberFormatter()
numberFormatter.numberStyle = .decimal
numberFormatter.locale = Locale.current
numberFormatter.maximumFractionDigits = decimalPlacesForEntityId
numberFormatter.minimumFractionDigits = decimalPlacesForEntityId
return numberFormatter.string(from: NSNumber(value: stateValueFloat)) ?? stateValue
} else {
return stateValue
}
}

private func suggestions() async -> [(Server, [HAAppEntity])] {
ControlEntityProvider(domains: WidgetSensorsConfig.domains).getEntities()
}
Expand Down
2 changes: 1 addition & 1 deletion Sources/Shared/EntityRegistryListForDisplay.swift
Original file line number Diff line number Diff line change
Expand Up @@ -29,5 +29,5 @@ public struct AppEntityRegistryListForDisplay: Codable, FetchableRecord, Persist
let id: String
let serverId: String
let entityId: String
let registry: EntityRegistryListForDisplay.Entity
public let registry: EntityRegistryListForDisplay.Entity
}
Loading