From f24cb72668ab5a00dbe001711d53f88726b8cb2c Mon Sep 17 00:00:00 2001 From: timklge <2026103+timklge@users.noreply.github.com> Date: Thu, 24 Apr 2025 18:10:05 +0200 Subject: [PATCH] Fix openweathermap provider also returns metric units if Karoo is set to imperial (#100) --- .../OpenWeatherMapWeatherProvider.kt | 16 ++++++++++++---- 1 file changed, 12 insertions(+), 4 deletions(-) diff --git a/app/src/main/kotlin/de/timklge/karooheadwind/weatherprovider/openweathermap/OpenWeatherMapWeatherProvider.kt b/app/src/main/kotlin/de/timklge/karooheadwind/weatherprovider/openweathermap/OpenWeatherMapWeatherProvider.kt index 0f60f77..18a4eb0 100644 --- a/app/src/main/kotlin/de/timklge/karooheadwind/weatherprovider/openweathermap/OpenWeatherMapWeatherProvider.kt +++ b/app/src/main/kotlin/de/timklge/karooheadwind/weatherprovider/openweathermap/OpenWeatherMapWeatherProvider.kt @@ -69,7 +69,7 @@ class OpenWeatherMapWeatherProvider(private val apiKey: String) : WeatherProvide profile: UserProfile? ): 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 responses = mutableListOf() @@ -89,13 +89,21 @@ class OpenWeatherMapWeatherProvider(private val apiKey: String) : WeatherProvide private suspend fun makeOpenWeatherMapRequest( service: KarooSystemService, coordinates: List, - apiKey: String + apiKey: String, + profile: UserProfile? ): HttpResponseState.Complete { 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() + // URL API 3.0 with onecall endpoint - val url = "https://api.openweathermap.org/data/3.0/onecall?lat=${coordinate.lat}&lon=${coordinate.lon}" + - "&appid=$apiKey&units=metric&exclude=minutely,daily,alerts" + val url = "https://api.openweathermap.org/data/3.0/onecall?lat=${coordinate.lat}&lon=${coordinate.lon}" + + "&appid=$apiKey&exclude=minutely,daily,alerts&units=${unitsString}" Log.d(KarooHeadwindExtension.TAG, "Http request to OpenWeatherMap API 3.0: $url")