Skip to content

Commit

Permalink
Adjust sensors widget value to the correct precision
Browse files Browse the repository at this point in the history
  • Loading branch information
bgoncal committed Dec 12, 2024
1 parent 88764ce commit 6296c70
Show file tree
Hide file tree
Showing 2 changed files with 40 additions and 2 deletions.
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 var stateValueFloat = Float(stateValue) else {
return stateValue
}
if var 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]] {
await withCheckedContinuation { continuation in
var entities: [Server: [HAAppEntity]] = [:]
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
}

0 comments on commit 6296c70

Please sign in to comment.