diff --git a/README.md b/README.md index d8593ca..d0bde84 100644 --- a/README.md +++ b/README.md @@ -23,11 +23,9 @@ After installing this app on your Karoo and opening it once from the main menu, - Headwind (graphical, 1x1 field): Shows the headwind direction and speed as a circle with a triangular direction indicator. The speed is shown at the center in your set unit of measurement (default is kilometers per hour if you have set up metric units in your Karoo, otherwise miles per hour). Both direction and speed are relative to the current riding direction by default, i. e., riding directly into a wind of 20 km/h will show a headwind speed of 20 km/h, while riding in the same direction will show -20 km/h. - Tailwind with riding speed (graphical, 1x1 field): Shows an arrow indicating the current headwind direction next to a label reading your current speed and the speed of the tailwind. If you ride against a headwind of 5 mph, it will show "-5". If you ride in the same direction of a 5 mph wind, it will read "+5". Text and arrow are colored based on the tailwind speed, with red indicating a strong headwind and green indicating a strong tailwind. -- Tailwind (graphical, 1x1 field): Similar to the tailwind and riding speed field, but shows tailwind speed, wind speed and wind gust speed instead of riding speed. - Wind direction and speed (graphical, 1x1 field): Similar to the tailwind data field, but shows the absolute wind speed and gust speed instead. - Wind forecast / Temperature Forecast / Precipitation forecast (graphical, 2x1 field): Line graphs showing the forecasted wind speeds, temperature or precipitation for the next 12 hours if no route is loaded. If a route is loaded, forecasts along the route will be used instead of the current location. -- Weather forecast (graphical, 2x1 field): Shows three columns indicating the current weather conditions (sunny, cloudy, ...), wind direction, precipitation and temperature forecasted for the next three hours. Tap on this widget to cycle through the 12 hour forecast. If you have a route loaded, the forecast widget will show the forecasted weather along points of the route, with an estimated traveled distance per hour of 20 km / 12 miles by default. -- Current weather (graphical, 1x1 field): Shows current weather conditions (same as forecast widget, but only for the current time). +- Weather forecast (graphical, 2x1 field): Shows three columns indicating the current weather conditions (sunny, cloudy, ...), wind direction, precipitation and temperature forecasted for the next three hours. Tap on this widget to cycle through the 12 hour forecast. If you have a route loaded, the forecast widget will show the forecasted weather along points of the route, with an estimated traveled distance per hour of 20 km / 12 miles by default. If placed in a 1x1 datafield, only the current weather conditions are shown. - Relative grade (numerical): Shows the relative grade. The relative grade is calculated by estimating the force of the headwind, and then calculating the gradient you would need to ride at to experience this resistance if there was no wind. Example: If you are riding on an actual gradient of 2 %, face a headwind of 18 km/h while riding at 29 km/h, the relative grade will be shown as 5.2 % (with 3.2 % added to the actual grade due to the headwind). - Relative elevation gain (numerical): Shows the relative elegation gain. The relative elevation gain is calculated using the relative grade and is an estimation of how much climbing would have been equivalent to the headwind you faced during the ride. - Additionally, data fields that only show the current data value for headwind speed, humidity, cloud cover, absolute wind speed, absolute wind gust speed, absolute wind direction, rainfall and surface pressure can be added if desired. diff --git a/app/src/main/kotlin/de/timklge/karooheadwind/KarooHeadwindExtension.kt b/app/src/main/kotlin/de/timklge/karooheadwind/KarooHeadwindExtension.kt index fac0c37..2913fbe 100644 --- a/app/src/main/kotlin/de/timklge/karooheadwind/KarooHeadwindExtension.kt +++ b/app/src/main/kotlin/de/timklge/karooheadwind/KarooHeadwindExtension.kt @@ -6,7 +6,6 @@ import com.mapbox.turf.TurfConstants import com.mapbox.turf.TurfMeasurement import de.timklge.karooheadwind.datatypes.CloudCoverDataType import de.timklge.karooheadwind.datatypes.GpsCoordinates -import de.timklge.karooheadwind.datatypes.GraphicalForecastDataType import de.timklge.karooheadwind.datatypes.HeadwindDirectionDataType import de.timklge.karooheadwind.datatypes.HeadwindSpeedDataType import de.timklge.karooheadwind.datatypes.PrecipitationDataType @@ -17,11 +16,9 @@ import de.timklge.karooheadwind.datatypes.RelativeHumidityDataType import de.timklge.karooheadwind.datatypes.SealevelPressureDataType import de.timklge.karooheadwind.datatypes.SurfacePressureDataType import de.timklge.karooheadwind.datatypes.TailwindAndRideSpeedDataType -import de.timklge.karooheadwind.datatypes.WindDirectionAndSpeedDataType -import de.timklge.karooheadwind.datatypes.TemperatureDataType import de.timklge.karooheadwind.datatypes.TemperatureForecastDataType -import de.timklge.karooheadwind.datatypes.WeatherDataType import de.timklge.karooheadwind.datatypes.WeatherForecastDataType +import de.timklge.karooheadwind.datatypes.WindDirectionAndSpeedDataType import de.timklge.karooheadwind.datatypes.WindDirectionDataType import de.timklge.karooheadwind.datatypes.WindForecastDataType import de.timklge.karooheadwind.datatypes.WindGustsDataType @@ -68,14 +65,12 @@ class KarooHeadwindExtension : KarooExtension("karoo-headwind", BuildConfig.VERS listOf( HeadwindDirectionDataType(karooSystem, applicationContext), TailwindAndRideSpeedDataType(karooSystem, applicationContext), - WeatherDataType(karooSystem, applicationContext), WeatherForecastDataType(karooSystem), HeadwindSpeedDataType(karooSystem, applicationContext), RelativeHumidityDataType(karooSystem, applicationContext), CloudCoverDataType(karooSystem, applicationContext), WindGustsDataType(karooSystem, applicationContext), WindSpeedDataType(karooSystem, applicationContext), - TemperatureDataType(karooSystem, applicationContext), WindDirectionDataType(karooSystem, applicationContext), WindDirectionAndSpeedDataType(karooSystem, applicationContext), PrecipitationDataType(karooSystem, applicationContext), @@ -84,7 +79,6 @@ class KarooHeadwindExtension : KarooExtension("karoo-headwind", BuildConfig.VERS TemperatureForecastDataType(karooSystem), PrecipitationForecastDataType(karooSystem), WindForecastDataType(karooSystem), - GraphicalForecastDataType(karooSystem), WindDirectionAndSpeedDataType(karooSystem, applicationContext), RelativeGradeDataType(karooSystem, applicationContext), RelativeElevationGainDataType(karooSystem, applicationContext), diff --git a/app/src/main/kotlin/de/timklge/karooheadwind/datatypes/ForecastDataType.kt b/app/src/main/kotlin/de/timklge/karooheadwind/datatypes/ForecastDataType.kt index aac3f32..83025d0 100644 --- a/app/src/main/kotlin/de/timklge/karooheadwind/datatypes/ForecastDataType.kt +++ b/app/src/main/kotlin/de/timklge/karooheadwind/datatypes/ForecastDataType.kt @@ -256,7 +256,7 @@ abstract class ForecastDataType(private val karooSystem: KarooSystemService, typ if (!config.preview) modifier = modifier.clickable(onClick = actionRunCallback()) - Row(modifier = modifier, horizontalAlignment = Alignment.Horizontal.Start) { + Row(modifier = modifier, horizontalAlignment = Alignment.Horizontal.CenterHorizontally) { val hourOffset = widgetSettings?.currentForecastHourOffset ?: 0 val positionOffset = if (allData?.data?.size == 1) 0 else hourOffset @@ -270,6 +270,9 @@ abstract class ForecastDataType(private val karooSystem: KarooSystemService, typ } for (baseIndex in hourOffset..hourOffset + 2) { + // Only show first value if placed in a 1x1 grid cell + if (baseIndex > 0 && config.gridSize.first == 30) break + val positionIndex = if (allData?.data?.size == 1) 0 else baseIndex if (allData?.data?.getOrNull(positionIndex) == null) break diff --git a/app/src/main/kotlin/de/timklge/karooheadwind/datatypes/GraphicalForecast.kt b/app/src/main/kotlin/de/timklge/karooheadwind/datatypes/GraphicalForecast.kt deleted file mode 100644 index c2e77e3..0000000 --- a/app/src/main/kotlin/de/timklge/karooheadwind/datatypes/GraphicalForecast.kt +++ /dev/null @@ -1,110 +0,0 @@ -package de.timklge.karooheadwind.datatypes - -import android.graphics.Bitmap -import androidx.compose.runtime.Composable -import androidx.compose.ui.graphics.Color -import androidx.compose.ui.unit.TextUnit -import androidx.compose.ui.unit.TextUnitType -import androidx.compose.ui.unit.dp -import androidx.glance.ColorFilter -import androidx.glance.GlanceModifier -import androidx.glance.Image -import androidx.glance.ImageProvider -import androidx.glance.color.ColorProvider -import androidx.glance.layout.Alignment -import androidx.glance.layout.Column -import androidx.glance.layout.ContentScale -import androidx.glance.layout.Row -import androidx.glance.layout.fillMaxHeight -import androidx.glance.layout.padding -import androidx.glance.layout.width -import androidx.glance.layout.wrapContentWidth -import androidx.glance.text.FontFamily -import androidx.glance.text.FontWeight -import androidx.glance.text.Text -import androidx.glance.text.TextStyle -import de.timklge.karooheadwind.TemperatureUnit -import de.timklge.karooheadwind.weatherprovider.WeatherInterpretation -import io.hammerhead.karooext.KarooSystemService -import kotlin.math.absoluteValue - -@Composable -fun GraphicalForecast( - current: WeatherInterpretation, - distance: Double? = null, - timeLabel: String? = null, - rowAlignment: Alignment.Horizontal = Alignment.Horizontal.CenterHorizontally, - isImperial: Boolean?, - isNight: Boolean, -) { - Column(modifier = GlanceModifier.fillMaxHeight().padding(1.dp).width(86.dp), horizontalAlignment = rowAlignment) { - Row(modifier = GlanceModifier.defaultWeight().wrapContentWidth(), horizontalAlignment = rowAlignment, verticalAlignment = Alignment.CenterVertically) { - Image( - modifier = GlanceModifier.defaultWeight().wrapContentWidth().padding(1.dp), - provider = ImageProvider(getWeatherIcon(current, isNight)), - contentDescription = "Current weather information", - contentScale = ContentScale.Fit, - ) - } - - if (distance != null && isImperial != null){ - val distanceInUserUnit = (distance / (if(!isImperial) 1000.0 else 1609.34)).toInt() - val label = "${distanceInUserUnit.absoluteValue}${if(!isImperial) "km" else "mi"}" - val text = if(distanceInUserUnit > 0){ - "In $label" - } else { - "$label ago" - } - - if (distanceInUserUnit != 0){ - Row(verticalAlignment = Alignment.CenterVertically) { - Text( - text = text, - style = TextStyle( - color = ColorProvider(Color.Black, Color.White), - fontFamily = FontFamily.Monospace, - fontSize = TextUnit(18f, TextUnitType.Sp) - ) - ) - } - } - } - - if (timeLabel != null){ - Text( - text = timeLabel, - style = TextStyle(color = ColorProvider(Color.Black, Color.White), fontWeight = FontWeight.Bold, - fontFamily = FontFamily.Monospace, fontSize = TextUnit(18f, TextUnitType.Sp) - ) - ) - } - } -} - -class GraphicalForecastDataType(karooSystem: KarooSystemService) : ForecastDataType(karooSystem, "graphicalForecast") { - @Composable - override fun RenderWidget( - arrowBitmap: Bitmap, - current: WeatherInterpretation, - windBearing: Int, - windSpeed: Int, - windGusts: Int, - precipitation: Double, - precipitationProbability: Int?, - temperature: Int, - temperatureUnit: TemperatureUnit, - timeLabel: String, - dateLabel: String?, - distance: Double?, - isImperial: Boolean, - isNight: Boolean, - ) { - GraphicalForecast( - current = current, - distance = distance, - timeLabel = timeLabel, - isImperial = isImperial, - isNight = isNight - ) - } -} \ No newline at end of file diff --git a/app/src/main/kotlin/de/timklge/karooheadwind/datatypes/TailwindAndRideSpeedDataType.kt b/app/src/main/kotlin/de/timklge/karooheadwind/datatypes/TailwindAndRideSpeedDataType.kt index c07aebb..a2a4279 100644 --- a/app/src/main/kotlin/de/timklge/karooheadwind/datatypes/TailwindAndRideSpeedDataType.kt +++ b/app/src/main/kotlin/de/timklge/karooheadwind/datatypes/TailwindAndRideSpeedDataType.kt @@ -15,7 +15,6 @@ import de.timklge.karooheadwind.HeadingResponse import de.timklge.karooheadwind.HeadwindSettings import de.timklge.karooheadwind.KarooHeadwindExtension import de.timklge.karooheadwind.R -import de.timklge.karooheadwind.datatypes.TailwindDataType.StreamData import de.timklge.karooheadwind.getRelativeHeadingFlow import de.timklge.karooheadwind.streamCurrentWeatherData import de.timklge.karooheadwind.streamDataFlow @@ -75,6 +74,17 @@ class TailwindAndRideSpeedDataType( ) : DataTypeImpl("karoo-headwind", "tailwind-and-ride-speed") { private val glance = GlanceRemoteViews() + data class StreamData( + val headingResponse: HeadingResponse, + val absoluteWindDirection: Double?, + val windSpeed: Double?, + val settings: HeadwindSettings, + val rideSpeed: Double? = null, + val gustSpeed: Double? = null, + val isImperial: Boolean = false, + val isVisible: Boolean = true + ) + private fun previewFlow(profileFlow: Flow): Flow { return flow { val profile = profileFlow.first() diff --git a/app/src/main/kotlin/de/timklge/karooheadwind/datatypes/TailwindDataType.kt b/app/src/main/kotlin/de/timklge/karooheadwind/datatypes/TailwindDataType.kt deleted file mode 100644 index 7c005dd..0000000 --- a/app/src/main/kotlin/de/timklge/karooheadwind/datatypes/TailwindDataType.kt +++ /dev/null @@ -1,192 +0,0 @@ -package de.timklge.karooheadwind.datatypes - -import android.content.Context -import android.graphics.BitmapFactory -import android.util.Log -import androidx.compose.ui.unit.DpSize -import androidx.glance.appwidget.ExperimentalGlanceRemoteViewsApi -import androidx.glance.appwidget.GlanceRemoteViews -import de.timklge.karooheadwind.HeadingResponse -import de.timklge.karooheadwind.HeadwindSettings -import de.timklge.karooheadwind.KarooHeadwindExtension -import de.timklge.karooheadwind.R -import de.timklge.karooheadwind.getRelativeHeadingFlow -import de.timklge.karooheadwind.streamCurrentWeatherData -import de.timklge.karooheadwind.streamDataFlow -import de.timklge.karooheadwind.streamDatatypeIsVisible -import de.timklge.karooheadwind.streamSettings -import de.timklge.karooheadwind.streamUserProfile -import de.timklge.karooheadwind.throttle -import de.timklge.karooheadwind.util.msInUserUnit -import de.timklge.karooheadwind.weatherprovider.WeatherData -import io.hammerhead.karooext.KarooSystemService -import io.hammerhead.karooext.extension.DataTypeImpl -import io.hammerhead.karooext.internal.ViewEmitter -import io.hammerhead.karooext.models.DataType -import io.hammerhead.karooext.models.ShowCustomStreamState -import io.hammerhead.karooext.models.StreamState -import io.hammerhead.karooext.models.UpdateGraphicConfig -import io.hammerhead.karooext.models.UserProfile -import io.hammerhead.karooext.models.ViewConfig -import kotlinx.coroutines.CoroutineScope -import kotlinx.coroutines.Dispatchers -import kotlinx.coroutines.awaitCancellation -import kotlinx.coroutines.delay -import kotlinx.coroutines.flow.Flow -import kotlinx.coroutines.flow.combine -import kotlinx.coroutines.flow.filter -import kotlinx.coroutines.flow.first -import kotlinx.coroutines.flow.flow -import kotlinx.coroutines.flow.map -import kotlinx.coroutines.launch -import kotlin.math.absoluteValue -import kotlin.math.cos -import kotlin.math.roundToInt - -class TailwindDataType( - private val karooSystem: KarooSystemService, - private val applicationContext: Context -) : DataTypeImpl("karoo-headwind", "tailwind") { - @OptIn(ExperimentalGlanceRemoteViewsApi::class) - private val glance = GlanceRemoteViews() - - data class StreamData(val headingResponse: HeadingResponse, - val absoluteWindDirection: Double?, - val windSpeed: Double?, - val settings: HeadwindSettings, - val rideSpeed: Double?, - val gustSpeed: Double?, - val isImperial: Boolean, - val isVisible: Boolean) - - private fun previewFlow(profileFlow: Flow): Flow { - return flow { - val profile = profileFlow.first() - - while (true) { - val bearing = (0..360).random().toDouble() - val windSpeed = (0..10).random() - val rideSpeed = (5..10).random().toDouble() - val gustSpeed = windSpeed * ((10..40).random().toDouble() / 10) - val isImperial = profile.preferredUnit.distance == UserProfile.PreferredUnit.UnitType.IMPERIAL - - emit(StreamData(HeadingResponse.Value(bearing), bearing, windSpeed.toDouble(), HeadwindSettings(), rideSpeed, gustSpeed = gustSpeed, isImperial = isImperial, isVisible = true)) - - delay(2_000) - } - } - } - - private fun streamSpeedInMs(): Flow { - return karooSystem.streamDataFlow(DataType.Type.SMOOTHED_3S_AVERAGE_SPEED) - .map { (it as? StreamState.Streaming)?.dataPoint?.singleValue ?: 0.0 } - } - - @OptIn(ExperimentalGlanceRemoteViewsApi::class) - override fun startView(context: Context, config: ViewConfig, emitter: ViewEmitter) { - Log.d(KarooHeadwindExtension.TAG, "Starting headwind direction view with $emitter") - - val baseBitmap = BitmapFactory.decodeResource( - context.resources, - R.drawable.arrow_0 - ) - - val configJob = CoroutineScope(Dispatchers.IO).launch { - emitter.onNext(UpdateGraphicConfig(showHeader = false)) - awaitCancellation() - } - - val flow = if (config.preview) { - previewFlow(karooSystem.streamUserProfile()) - } else { - combine(karooSystem.getRelativeHeadingFlow(context), - context.streamCurrentWeatherData(karooSystem), - context.streamSettings(karooSystem), - karooSystem.streamUserProfile(), - streamSpeedInMs(), - karooSystem.streamDatatypeIsVisible(dataTypeId) - ) { data -> - val headingResponse = data[0] as HeadingResponse - val weatherData = data[1] as? WeatherData - val settings = data[2] as HeadwindSettings - val userProfile = data[3] as UserProfile - val rideSpeedInMs = data[4] as Double - val isVisible = data[5] as Boolean - - val isImperial = userProfile.preferredUnit.distance == UserProfile.PreferredUnit.UnitType.IMPERIAL - val absoluteWindDirection = weatherData?.windDirection - val windSpeed = weatherData?.windSpeed - val gustSpeed = weatherData?.windGusts - - StreamData(headingResponse, absoluteWindDirection, windSpeed, settings, rideSpeed = rideSpeedInMs, isImperial = isImperial, gustSpeed = gustSpeed, isVisible = isVisible) - } - } - - val viewJob = CoroutineScope(Dispatchers.IO).launch { - emitter.onNext(ShowCustomStreamState("", null)) - - val refreshRate = karooSystem.getRefreshRateInMilliseconds(context) - flow.filter { it.isVisible }.throttle(refreshRate).collect { streamData -> - Log.d(KarooHeadwindExtension.TAG, "Updating tailwind direction view") - - val value = (streamData.headingResponse as? HeadingResponse.Value)?.diff - if (value == null || streamData.absoluteWindDirection == null || streamData.windSpeed == null){ - var headingResponse = streamData.headingResponse - - if (headingResponse is HeadingResponse.Value && (streamData.absoluteWindDirection == null || streamData.windSpeed == null)){ - headingResponse = HeadingResponse.NoWeatherData - } - - emitter.updateView(getErrorWidget(glance, context, streamData.settings, headingResponse).remoteViews) - - return@collect - } - - val windSpeed = streamData.windSpeed - val windDirection = streamData.headingResponse.diff - - val mainText = let { - val headwindSpeed = cos( (windDirection + 180) * Math.PI / 180.0) * windSpeed - headwindSpeed.roundToInt().toString() - - val sign = if (headwindSpeed < 0) "+" else { - if (headwindSpeed > 0) "-" else "" - } - - val headwindSpeedUserUnit = msInUserUnit(headwindSpeed, streamData.isImperial) - - "$sign${headwindSpeedUserUnit.roundToInt().absoluteValue}" - } - - val windSpeedUserUnit = msInUserUnit(windSpeed, streamData.isImperial) - val gustSpeedUserUnit = msInUserUnit(streamData.gustSpeed ?: 0.0, streamData.isImperial) - - val subtext = "${windSpeedUserUnit.roundToInt()}-${gustSpeedUserUnit.roundToInt()}" - - val headwindSpeed = cos( (windDirection + 180) * Math.PI / 180.0) * windSpeed - val windSpeedInKmh = headwindSpeed * 3.6 - - val result = glance.compose(context, DpSize.Unspecified) { - HeadwindDirection( - baseBitmap, - windDirection.roundToInt(), - config.textSize, - mainText, - subtext, - interpolateWindColor(windSpeedInKmh, false, context), - interpolateWindColor(windSpeedInKmh, true, context), - wideMode = config.gridSize.first == 60, - preview = config.preview, - ) - } - - emitter.updateView(result.remoteViews) - } - } - emitter.setCancellable { - Log.d(KarooHeadwindExtension.TAG, "Stopping headwind view with $emitter") - configJob.cancel() - viewJob.cancel() - } - } -} \ No newline at end of file diff --git a/app/src/main/kotlin/de/timklge/karooheadwind/datatypes/TemperatureDataType.kt b/app/src/main/kotlin/de/timklge/karooheadwind/datatypes/TemperatureDataType.kt deleted file mode 100644 index b174df3..0000000 --- a/app/src/main/kotlin/de/timklge/karooheadwind/datatypes/TemperatureDataType.kt +++ /dev/null @@ -1,17 +0,0 @@ -package de.timklge.karooheadwind.datatypes - -import android.content.Context -import de.timklge.karooheadwind.weatherprovider.WeatherData -import io.hammerhead.karooext.KarooSystemService -import io.hammerhead.karooext.models.DataType -import io.hammerhead.karooext.models.UserProfile - -class TemperatureDataType(karooSystemService: KarooSystemService, context: Context) : BaseDataType(karooSystemService, context, "temperature"){ - override fun getValue(data: WeatherData, userProfile: UserProfile): Double { - return data.temperature - } - - override fun getFormatDataType(): String? { - return DataType.Type.TEMPERATURE - } -} \ No newline at end of file diff --git a/app/src/main/kotlin/de/timklge/karooheadwind/datatypes/WeatherDataType.kt b/app/src/main/kotlin/de/timklge/karooheadwind/datatypes/WeatherDataType.kt deleted file mode 100644 index 872825d..0000000 --- a/app/src/main/kotlin/de/timklge/karooheadwind/datatypes/WeatherDataType.kt +++ /dev/null @@ -1,182 +0,0 @@ -package de.timklge.karooheadwind.datatypes - -import android.content.Context -import android.graphics.BitmapFactory -import android.util.Log -import androidx.compose.ui.unit.DpSize -import androidx.glance.GlanceModifier -import androidx.glance.action.actionStartActivity -import androidx.glance.action.clickable -import androidx.glance.appwidget.ExperimentalGlanceRemoteViewsApi -import androidx.glance.appwidget.GlanceRemoteViews -import androidx.glance.layout.Alignment -import androidx.glance.layout.Box -import androidx.glance.layout.fillMaxSize -import de.timklge.karooheadwind.HeadingResponse -import de.timklge.karooheadwind.HeadwindSettings -import de.timklge.karooheadwind.KarooHeadwindExtension -import de.timklge.karooheadwind.MainActivity -import de.timklge.karooheadwind.R -import de.timklge.karooheadwind.TemperatureUnit -import de.timklge.karooheadwind.getHeadingFlow -import de.timklge.karooheadwind.streamCurrentWeatherData -import de.timklge.karooheadwind.streamDatatypeIsVisible -import de.timklge.karooheadwind.streamSettings -import de.timklge.karooheadwind.streamUserProfile -import de.timklge.karooheadwind.throttle -import de.timklge.karooheadwind.util.celciusInUserUnit -import de.timklge.karooheadwind.util.millimetersInUserUnit -import de.timklge.karooheadwind.util.msInUserUnit -import de.timklge.karooheadwind.weatherprovider.WeatherData -import de.timklge.karooheadwind.weatherprovider.WeatherInterpretation -import io.hammerhead.karooext.KarooSystemService -import io.hammerhead.karooext.extension.DataTypeImpl -import io.hammerhead.karooext.internal.Emitter -import io.hammerhead.karooext.internal.ViewEmitter -import io.hammerhead.karooext.models.DataPoint -import io.hammerhead.karooext.models.DataType -import io.hammerhead.karooext.models.ShowCustomStreamState -import io.hammerhead.karooext.models.StreamState -import io.hammerhead.karooext.models.UpdateGraphicConfig -import io.hammerhead.karooext.models.UserProfile -import io.hammerhead.karooext.models.ViewConfig -import kotlinx.coroutines.CoroutineScope -import kotlinx.coroutines.Dispatchers -import kotlinx.coroutines.awaitCancellation -import kotlinx.coroutines.delay -import kotlinx.coroutines.flow.Flow -import kotlinx.coroutines.flow.combine -import kotlinx.coroutines.flow.filter -import kotlinx.coroutines.flow.flow -import kotlinx.coroutines.launch -import java.time.Instant -import java.time.ZoneId -import java.time.format.DateTimeFormatter -import kotlin.math.roundToInt - -@OptIn(ExperimentalGlanceRemoteViewsApi::class) -class WeatherDataType( - private val karooSystem: KarooSystemService, - private val applicationContext: Context -) : DataTypeImpl("karoo-headwind", "weather") { - private val glance = GlanceRemoteViews() - - companion object { - val timeFormatter = DateTimeFormatter.ofPattern("HH:mm").withZone(ZoneId.systemDefault()) - } - - override fun startStream(emitter: Emitter) { - val job = CoroutineScope(Dispatchers.IO).launch { - val currentWeatherData = applicationContext.streamCurrentWeatherData(karooSystem) - - currentWeatherData.collect { data -> - Log.d(KarooHeadwindExtension.TAG, "Wind code: ${data?.weatherCode}") - emitter.onNext(StreamState.Streaming(DataPoint(dataTypeId, mapOf(DataType.Field.SINGLE to (data?.weatherCode?.toDouble() ?: 0.0))))) - } - } - emitter.setCancellable { - job.cancel() - } - } - - data class StreamData(val data: WeatherData?, val settings: HeadwindSettings, - val profile: UserProfile? = null, val headingResponse: HeadingResponse? = null, - val isVisible: Boolean) - - private fun previewFlow(): Flow = flow { - while (true){ - emit(StreamData( - WeatherData( - Instant.now().epochSecond, 0.0, - 20, 50.0, 3.0, 0.0, 1013.25, 980.0, 5.0, 30.0, 10.0, - WeatherInterpretation.getKnownWeatherCodes().random(), isForecast = false, - isNight = listOf(true, false).random() - ), HeadwindSettings(), isVisible = true)) - - delay(5_000) - } - } - - override fun startView(context: Context, config: ViewConfig, emitter: ViewEmitter) { - Log.d(KarooHeadwindExtension.TAG, "Starting weather view with $emitter") - val configJob = CoroutineScope(Dispatchers.IO).launch { - emitter.onNext(UpdateGraphicConfig(showHeader = false)) - awaitCancellation() - } - - val baseBitmap = BitmapFactory.decodeResource( - context.resources, - R.drawable.arrow_0 - ) - - val dataFlow = if (config.preview){ - previewFlow() - } else { - combine( - context.streamCurrentWeatherData(karooSystem), - context.streamSettings(karooSystem), - karooSystem.streamUserProfile(), - karooSystem.getHeadingFlow(context), - karooSystem.streamDatatypeIsVisible(dataTypeId) - ) { data, settings, profile, heading, isVisible -> - StreamData(data, settings, profile, heading, isVisible) - } - } - - val viewJob = CoroutineScope(Dispatchers.IO).launch { - emitter.onNext(ShowCustomStreamState("", null)) - - val refreshRate = karooSystem.getRefreshRateInMilliseconds(context) - - dataFlow.filter { it.isVisible }.throttle(refreshRate).collect { (data, settings, userProfile, headingResponse) -> - Log.d(KarooHeadwindExtension.TAG, "Updating weather view") - - if (data == null){ - emitter.updateView(getErrorWidget(glance, context, settings, headingResponse).remoteViews) - - return@collect - } - - val interpretation = WeatherInterpretation.fromWeatherCode(data.weatherCode) - val formattedTime = timeFormatter.format(Instant.ofEpochSecond(data.time)) - val formattedDate = getShortDateFormatter().format(Instant.ofEpochSecond(data.time)) - - val result = glance.compose(context, DpSize.Unspecified) { - var modifier = GlanceModifier.fillMaxSize() - // TODO reenable once swipes are no longer interpreted as clicks if (!config.preview) modifier = modifier.clickable(onClick = actionStartActivity()) - - Box(modifier = modifier, contentAlignment = Alignment.CenterEnd) { - Weather( - baseBitmap, - current = interpretation, - windBearing = data.windDirection.roundToInt(), - windSpeed = msInUserUnit(data.windSpeed, userProfile?.preferredUnit?.distance == UserProfile.PreferredUnit.UnitType.IMPERIAL).roundToInt(), - windGusts = msInUserUnit(data.windGusts, userProfile?.preferredUnit?.distance == UserProfile.PreferredUnit.UnitType.IMPERIAL).roundToInt(), - precipitation = millimetersInUserUnit(data.precipitation, userProfile?.preferredUnit?.distance == UserProfile.PreferredUnit.UnitType.IMPERIAL), - precipitationProbability = null, - temperature = celciusInUserUnit(data.temperature, userProfile?.preferredUnit?.temperature == UserProfile.PreferredUnit.UnitType.IMPERIAL).roundToInt(), - temperatureUnit = if (userProfile?.preferredUnit?.temperature != UserProfile.PreferredUnit.UnitType.IMPERIAL) TemperatureUnit.CELSIUS else TemperatureUnit.FAHRENHEIT, - timeLabel = formattedTime, - rowAlignment = when (config.alignment){ - ViewConfig.Alignment.LEFT -> Alignment.Horizontal.Start - ViewConfig.Alignment.CENTER -> Alignment.Horizontal.CenterHorizontally - ViewConfig.Alignment.RIGHT -> Alignment.Horizontal.End - }, - dateLabel = formattedDate, - singleDisplay = true, - isImperial = userProfile?.preferredUnit?.distance == UserProfile.PreferredUnit.UnitType.IMPERIAL, - isNight = data.isNight, - ) - } - } - - emitter.updateView(result.remoteViews) - } - } - emitter.setCancellable { - Log.d(KarooHeadwindExtension.TAG, "Stopping headwind view with $emitter") - configJob.cancel() - viewJob.cancel() - } - } -} \ No newline at end of file diff --git a/app/src/main/kotlin/de/timklge/karooheadwind/screens/WeatherScreen.kt b/app/src/main/kotlin/de/timklge/karooheadwind/screens/WeatherScreen.kt index 6e2b158..d48c6bd 100644 --- a/app/src/main/kotlin/de/timklge/karooheadwind/screens/WeatherScreen.kt +++ b/app/src/main/kotlin/de/timklge/karooheadwind/screens/WeatherScreen.kt @@ -27,9 +27,7 @@ import de.timklge.karooheadwind.HeadwindStats import de.timklge.karooheadwind.R import de.timklge.karooheadwind.ServiceStatusSingleton import de.timklge.karooheadwind.TemperatureUnit -import de.timklge.karooheadwind.weatherprovider.WeatherInterpretation import de.timklge.karooheadwind.datatypes.ForecastDataType -import de.timklge.karooheadwind.datatypes.WeatherDataType.Companion.timeFormatter import de.timklge.karooheadwind.datatypes.getShortDateFormatter import de.timklge.karooheadwind.getGpsCoordinateFlow import de.timklge.karooheadwind.streamCurrentForecastWeatherData @@ -40,6 +38,7 @@ import de.timklge.karooheadwind.streamUserProfile import de.timklge.karooheadwind.util.celciusInUserUnit import de.timklge.karooheadwind.util.millimetersInUserUnit import de.timklge.karooheadwind.util.msInUserUnit +import de.timklge.karooheadwind.weatherprovider.WeatherInterpretation import io.hammerhead.karooext.KarooSystemService import io.hammerhead.karooext.models.UserProfile import java.time.Instant @@ -105,7 +104,7 @@ fun WeatherScreen(onFinish: () -> Unit) { val requestedWeatherPosition = forecastData?.data?.firstOrNull()?.coords - val formattedTime = currentWeatherData?.let { timeFormatter.format(Instant.ofEpochSecond(it.time)) } + val formattedTime = currentWeatherData?.let { ForecastDataType.timeFormatter.format(Instant.ofEpochSecond(it.time)) } val formattedDate = currentWeatherData?.let { getShortDateFormatter().format(Instant.ofEpochSecond(it.time)) } if (karooConnected == true && currentWeatherData != null) { diff --git a/app/src/main/res/values/strings.xml b/app/src/main/res/values/strings.xml index 130d790..caaa0a3 100644 --- a/app/src/main/res/values/strings.xml +++ b/app/src/main/res/values/strings.xml @@ -21,8 +21,6 @@ Atmospheric pressure at surface in configured unit Sealevel pressure Atmospheric pressure at sea level in configured unit - Weather - Current weather conditions Weather Forecast Current hourly weather forecast Temperature Forecast @@ -33,14 +31,8 @@ Current hourly precipitation forecast Headwind speed Current headwind speed - Temperature - Current temperature in configured unit Current headwind or wind speed based on user setting Set wind speed - Graphical Forecast - Current graphical weather forecast - Tailwind - Current tailwind, wind speed and gust speed Relative Grade Perceived grade in percent Relative Elevation Gain diff --git a/app/src/main/res/xml/extension_info.xml b/app/src/main/res/xml/extension_info.xml index ce8c08b..dfb1cc1 100644 --- a/app/src/main/res/xml/extension_info.xml +++ b/app/src/main/res/xml/extension_info.xml @@ -12,13 +12,6 @@ icon="@drawable/wind" typeId="tailwind-and-ride-speed" /> - - + typeId="windDirectionAndSpeed" /> - - - - - -