Fix openweathermap provider also returns metric units if Karoo is set to imperial (#100)

This commit is contained in:
timklge 2025-04-24 18:10:05 +02:00 committed by GitHub
parent 9346b17c68
commit f24cb72668
No known key found for this signature in database
GPG Key ID: B5690EEEBB952194

View File

@ -69,7 +69,7 @@ class OpenWeatherMapWeatherProvider(private val apiKey: String) : WeatherProvide
profile: UserProfile? profile: UserProfile?
): WeatherDataResponse { ): WeatherDataResponse {
val response = makeOpenWeatherMapRequest(karooSystem, coordinates, apiKey) val response = makeOpenWeatherMapRequest(karooSystem, coordinates, apiKey, profile)
val responseBody = response.body?.let { String(it) } ?: throw Exception("Null response from OpenWeatherMap") val responseBody = response.body?.let { String(it) } ?: throw Exception("Null response from OpenWeatherMap")
val responses = mutableListOf<WeatherDataForLocation>() val responses = mutableListOf<WeatherDataForLocation>()
@ -89,13 +89,21 @@ class OpenWeatherMapWeatherProvider(private val apiKey: String) : WeatherProvide
private suspend fun makeOpenWeatherMapRequest( private suspend fun makeOpenWeatherMapRequest(
service: KarooSystemService, service: KarooSystemService,
coordinates: List<GpsCoordinates>, coordinates: List<GpsCoordinates>,
apiKey: String apiKey: String,
profile: UserProfile?
): HttpResponseState.Complete { ): HttpResponseState.Complete {
val response = callbackFlow { val response = callbackFlow {
// OpenWeatherMap only supports setting imperial or metric units for all measurements, not individually for distance / temperature
val unitsString = if (profile?.preferredUnit?.temperature == UserProfile.PreferredUnit.UnitType.IMPERIAL || profile?.preferredUnit?.distance == UserProfile.PreferredUnit.UnitType.IMPERIAL) {
"imperial"
} else {
"metric"
}
val coordinate = coordinates.first() val coordinate = coordinates.first()
// URL API 3.0 with onecall endpoint // URL API 3.0 with onecall endpoint
val url = "https://api.openweathermap.org/data/3.0/onecall?lat=${coordinate.lat}&lon=${coordinate.lon}" + val url = "https://api.openweathermap.org/data/3.0/onecall?lat=${coordinate.lat}&lon=${coordinate.lon}" +
"&appid=$apiKey&units=metric&exclude=minutely,daily,alerts" "&appid=$apiKey&exclude=minutely,daily,alerts&units=${unitsString}"
Log.d(KarooHeadwindExtension.TAG, "Http request to OpenWeatherMap API 3.0: $url") Log.d(KarooHeadwindExtension.TAG, "Http request to OpenWeatherMap API 3.0: $url")