Initial commit
11
.gitignore
vendored
Normal file
@ -0,0 +1,11 @@
|
||||
*.iml
|
||||
.gradle
|
||||
/local.properties
|
||||
/.idea
|
||||
.DS_Store
|
||||
/build
|
||||
/captures
|
||||
.externalNativeBuild
|
||||
.cxx
|
||||
local.properties
|
||||
/app/release
|
||||
9
ICON_LICENSE
Normal file
@ -0,0 +1,9 @@
|
||||
The MIT License (MIT)
|
||||
|
||||
Copyright (c) 2015-2021 Aniket Suvarna
|
||||
|
||||
Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the “Software”), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
|
||||
|
||||
The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
|
||||
|
||||
THE SOFTWARE IS PROVIDED “AS IS”, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
|
||||
201
LICENSE
Normal file
@ -0,0 +1,201 @@
|
||||
Apache License
|
||||
Version 2.0, January 2004
|
||||
http://www.apache.org/licenses/
|
||||
|
||||
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
|
||||
|
||||
1. Definitions.
|
||||
|
||||
"License" shall mean the terms and conditions for use, reproduction,
|
||||
and distribution as defined by Sections 1 through 9 of this document.
|
||||
|
||||
"Licensor" shall mean the copyright owner or entity authorized by
|
||||
the copyright owner that is granting the License.
|
||||
|
||||
"Legal Entity" shall mean the union of the acting entity and all
|
||||
other entities that control, are controlled by, or are under common
|
||||
control with that entity. For the purposes of this definition,
|
||||
"control" means (i) the power, direct or indirect, to cause the
|
||||
direction or management of such entity, whether by contract or
|
||||
otherwise, or (ii) ownership of fifty percent (50%) or more of the
|
||||
outstanding shares, or (iii) beneficial ownership of such entity.
|
||||
|
||||
"You" (or "Your") shall mean an individual or Legal Entity
|
||||
exercising permissions granted by this License.
|
||||
|
||||
"Source" form shall mean the preferred form for making modifications,
|
||||
including but not limited to software source code, documentation
|
||||
source, and configuration files.
|
||||
|
||||
"Object" form shall mean any form resulting from mechanical
|
||||
transformation or translation of a Source form, including but
|
||||
not limited to compiled object code, generated documentation,
|
||||
and conversions to other media types.
|
||||
|
||||
"Work" shall mean the work of authorship, whether in Source or
|
||||
Object form, made available under the License, as indicated by a
|
||||
copyright notice that is included in or attached to the work
|
||||
(an example is provided in the Appendix below).
|
||||
|
||||
"Derivative Works" shall mean any work, whether in Source or Object
|
||||
form, that is based on (or derived from) the Work and for which the
|
||||
editorial revisions, annotations, elaborations, or other modifications
|
||||
represent, as a whole, an original work of authorship. For the purposes
|
||||
of this License, Derivative Works shall not include works that remain
|
||||
separable from, or merely link (or bind by name) to the interfaces of,
|
||||
the Work and Derivative Works thereof.
|
||||
|
||||
"Contribution" shall mean any work of authorship, including
|
||||
the original version of the Work and any modifications or additions
|
||||
to that Work or Derivative Works thereof, that is intentionally
|
||||
submitted to Licensor for inclusion in the Work by the copyright owner
|
||||
or by an individual or Legal Entity authorized to submit on behalf of
|
||||
the copyright owner. For the purposes of this definition, "submitted"
|
||||
means any form of electronic, verbal, or written communication sent
|
||||
to the Licensor or its representatives, including but not limited to
|
||||
communication on electronic mailing lists, source code control systems,
|
||||
and issue tracking systems that are managed by, or on behalf of, the
|
||||
Licensor for the purpose of discussing and improving the Work, but
|
||||
excluding communication that is conspicuously marked or otherwise
|
||||
designated in writing by the copyright owner as "Not a Contribution."
|
||||
|
||||
"Contributor" shall mean Licensor and any individual or Legal Entity
|
||||
on behalf of whom a Contribution has been received by Licensor and
|
||||
subsequently incorporated within the Work.
|
||||
|
||||
2. Grant of Copyright License. Subject to the terms and conditions of
|
||||
this License, each Contributor hereby grants to You a perpetual,
|
||||
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
||||
copyright license to reproduce, prepare Derivative Works of,
|
||||
publicly display, publicly perform, sublicense, and distribute the
|
||||
Work and such Derivative Works in Source or Object form.
|
||||
|
||||
3. Grant of Patent License. Subject to the terms and conditions of
|
||||
this License, each Contributor hereby grants to You a perpetual,
|
||||
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
||||
(except as stated in this section) patent license to make, have made,
|
||||
use, offer to sell, sell, import, and otherwise transfer the Work,
|
||||
where such license applies only to those patent claims licensable
|
||||
by such Contributor that are necessarily infringed by their
|
||||
Contribution(s) alone or by combination of their Contribution(s)
|
||||
with the Work to which such Contribution(s) was submitted. If You
|
||||
institute patent litigation against any entity (including a
|
||||
cross-claim or counterclaim in a lawsuit) alleging that the Work
|
||||
or a Contribution incorporated within the Work constitutes direct
|
||||
or contributory patent infringement, then any patent licenses
|
||||
granted to You under this License for that Work shall terminate
|
||||
as of the date such litigation is filed.
|
||||
|
||||
4. Redistribution. You may reproduce and distribute copies of the
|
||||
Work or Derivative Works thereof in any medium, with or without
|
||||
modifications, and in Source or Object form, provided that You
|
||||
meet the following conditions:
|
||||
|
||||
(a) You must give any other recipients of the Work or
|
||||
Derivative Works a copy of this License; and
|
||||
|
||||
(b) You must cause any modified files to carry prominent notices
|
||||
stating that You changed the files; and
|
||||
|
||||
(c) You must retain, in the Source form of any Derivative Works
|
||||
that You distribute, all copyright, patent, trademark, and
|
||||
attribution notices from the Source form of the Work,
|
||||
excluding those notices that do not pertain to any part of
|
||||
the Derivative Works; and
|
||||
|
||||
(d) If the Work includes a "NOTICE" text file as part of its
|
||||
distribution, then any Derivative Works that You distribute must
|
||||
include a readable copy of the attribution notices contained
|
||||
within such NOTICE file, excluding those notices that do not
|
||||
pertain to any part of the Derivative Works, in at least one
|
||||
of the following places: within a NOTICE text file distributed
|
||||
as part of the Derivative Works; within the Source form or
|
||||
documentation, if provided along with the Derivative Works; or,
|
||||
within a display generated by the Derivative Works, if and
|
||||
wherever such third-party notices normally appear. The contents
|
||||
of the NOTICE file are for informational purposes only and
|
||||
do not modify the License. You may add Your own attribution
|
||||
notices within Derivative Works that You distribute, alongside
|
||||
or as an addendum to the NOTICE text from the Work, provided
|
||||
that such additional attribution notices cannot be construed
|
||||
as modifying the License.
|
||||
|
||||
You may add Your own copyright statement to Your modifications and
|
||||
may provide additional or different license terms and conditions
|
||||
for use, reproduction, or distribution of Your modifications, or
|
||||
for any such Derivative Works as a whole, provided Your use,
|
||||
reproduction, and distribution of the Work otherwise complies with
|
||||
the conditions stated in this License.
|
||||
|
||||
5. Submission of Contributions. Unless You explicitly state otherwise,
|
||||
any Contribution intentionally submitted for inclusion in the Work
|
||||
by You to the Licensor shall be under the terms and conditions of
|
||||
this License, without any additional terms or conditions.
|
||||
Notwithstanding the above, nothing herein shall supersede or modify
|
||||
the terms of any separate license agreement you may have executed
|
||||
with Licensor regarding such Contributions.
|
||||
|
||||
6. Trademarks. This License does not grant permission to use the trade
|
||||
names, trademarks, service marks, or product names of the Licensor,
|
||||
except as required for reasonable and customary use in describing the
|
||||
origin of the Work and reproducing the content of the NOTICE file.
|
||||
|
||||
7. Disclaimer of Warranty. Unless required by applicable law or
|
||||
agreed to in writing, Licensor provides the Work (and each
|
||||
Contributor provides its Contributions) on an "AS IS" BASIS,
|
||||
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
|
||||
implied, including, without limitation, any warranties or conditions
|
||||
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
|
||||
PARTICULAR PURPOSE. You are solely responsible for determining the
|
||||
appropriateness of using or redistributing the Work and assume any
|
||||
risks associated with Your exercise of permissions under this License.
|
||||
|
||||
8. Limitation of Liability. In no event and under no legal theory,
|
||||
whether in tort (including negligence), contract, or otherwise,
|
||||
unless required by applicable law (such as deliberate and grossly
|
||||
negligent acts) or agreed to in writing, shall any Contributor be
|
||||
liable to You for damages, including any direct, indirect, special,
|
||||
incidental, or consequential damages of any character arising as a
|
||||
result of this License or out of the use or inability to use the
|
||||
Work (including but not limited to damages for loss of goodwill,
|
||||
work stoppage, computer failure or malfunction, or any and all
|
||||
other commercial damages or losses), even if such Contributor
|
||||
has been advised of the possibility of such damages.
|
||||
|
||||
9. Accepting Warranty or Additional Liability. While redistributing
|
||||
the Work or Derivative Works thereof, You may choose to offer,
|
||||
and charge a fee for, acceptance of support, warranty, indemnity,
|
||||
or other liability obligations and/or rights consistent with this
|
||||
License. However, in accepting such obligations, You may act only
|
||||
on Your own behalf and on Your sole responsibility, not on behalf
|
||||
of any other Contributor, and only if You agree to indemnify,
|
||||
defend, and hold each Contributor harmless for any liability
|
||||
incurred by, or claims asserted against, such Contributor by reason
|
||||
of your accepting any such warranty or additional liability.
|
||||
|
||||
END OF TERMS AND CONDITIONS
|
||||
|
||||
APPENDIX: How to apply the Apache License to your work.
|
||||
|
||||
To apply the Apache License to your work, attach the following
|
||||
boilerplate notice, with the fields enclosed by brackets "[]"
|
||||
replaced with your own identifying information. (Don't include
|
||||
the brackets!) The text should be enclosed in the appropriate
|
||||
comment syntax for the file format. We also recommend that a
|
||||
file or class name and description of purpose be included on the
|
||||
same "printed page" as the copyright notice for easier
|
||||
identification within third-party archives.
|
||||
|
||||
Copyright 2024 Hammerhead Navigation, Inc. All Rights Reserved.
|
||||
|
||||
Licensed under the Apache License, Version 2.0 (the "License");
|
||||
you may not use this file except in compliance with the License.
|
||||
You may obtain a copy of the License at
|
||||
|
||||
http://www.apache.org/licenses/LICENSE-2.0
|
||||
|
||||
Unless required by applicable law or agreed to in writing, software
|
||||
distributed under the License is distributed on an "AS IS" BASIS,
|
||||
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
See the License for the specific language governing permissions and
|
||||
limitations under the License.
|
||||
35
README.md
Normal file
@ -0,0 +1,35 @@
|
||||
# Karoo Winddir Extension
|
||||
|
||||
> [!WARNING]
|
||||
> This app is currently in prototype stage and its main features might not work at all. If you want to test it anyway and encounter issues, please report them in the [issue tracker](https://github.com/timklge/karoo-winddir/issues), ideally with adb logs attached.
|
||||
|
||||
This extension for Karoo devices adds a graphical data field that shows the current wind direction relative to the rider as an arrow. It also provides data fields for relative humidity, cloud coverage, wind speed, wind gust speed, surface pressure, and rainfall at the current location.
|
||||
|
||||
Compatible with Karoo 2 and Karoo 3 devices running Karoo OS version 1.524.2003 and later.
|
||||
|
||||

|
||||

|
||||

|
||||

|
||||
|
||||
## Installation
|
||||
|
||||
Currently, Hammerhead has not yet released an on-device app store for easy installation of extensions like this. Until then, you can sideload the app.
|
||||
|
||||
1. Download the APK from the [releases page](https://github.com/timklge/karoo-winddir/releases) (or build it from source).
|
||||
2. Prepare your Karoo for sideloading by following the [step-by-step guide](https://www.dcrainmaker.com/2021/02/how-to-sideload-android-apps-on-your-hammerhead-karoo-1-karoo-2.html) by DC Rainmaker.
|
||||
3. Install the app using the command `adb install app-release.apk`.
|
||||
|
||||
## Usage
|
||||
|
||||
After installing this app on your Karoo, you can add a data field showing the relative wind direction or one of the auxiliary fields to your data pages. The relative wind direction will be shown as an arrow image, with an optional overlay of the wind speed in your chosen unit of measurement (default is kilometers per hour).
|
||||
|
||||
The app will automatically attempt to download weather data for your current approximate location from the [open-meteo.com](https://open-meteo.com) API once your device has acquired a GPS fix. The API service is free for non-commercial use. Your location is rounded to approximately two kilometers to maintain privacy. The data is updated when you ride more than two kilometers from the location where the weather data was downloaded or after one hour at the latest. If the app cannot connect to the weather service, it will retry the download every minute. Downloading weather data should work on Karoo 2 if you have a SIM card inserted or on Karoo 3 via the companion app.
|
||||
|
||||
## Credits
|
||||
|
||||
Icons are from [boxicons.com](https://boxicons.com) (MIT-licensed).
|
||||
|
||||
## Links
|
||||
|
||||
[karoo-ext source](https://github.com/hammerheadnav/karoo-ext)
|
||||
1
app/.gitignore
vendored
Normal file
@ -0,0 +1 @@
|
||||
/build
|
||||
51
app/build.gradle.kts
Normal file
@ -0,0 +1,51 @@
|
||||
plugins {
|
||||
alias(libs.plugins.android.application)
|
||||
alias(libs.plugins.jetbrains.kotlin.android)
|
||||
alias(libs.plugins.compose.compiler)
|
||||
kotlin("plugin.serialization") version "2.0.20"
|
||||
}
|
||||
|
||||
android {
|
||||
namespace = "de.timklge.karoowinddir"
|
||||
compileSdk = 34
|
||||
|
||||
defaultConfig {
|
||||
applicationId = "de.timklge.karoowinddir"
|
||||
minSdk = 26
|
||||
targetSdk = 34
|
||||
versionCode = 1
|
||||
versionName = "1.0.0-beta1"
|
||||
}
|
||||
|
||||
buildTypes {
|
||||
release {
|
||||
isMinifyEnabled = false
|
||||
proguardFiles(getDefaultProguardFile("proguard-android-optimize.txt"), "proguard-rules.pro")
|
||||
}
|
||||
}
|
||||
compileOptions {
|
||||
sourceCompatibility = JavaVersion.VERSION_1_8
|
||||
targetCompatibility = JavaVersion.VERSION_1_8
|
||||
}
|
||||
kotlinOptions {
|
||||
jvmTarget = "1.8"
|
||||
}
|
||||
buildFeatures {
|
||||
compose = true
|
||||
}
|
||||
}
|
||||
|
||||
dependencies {
|
||||
implementation(libs.hammerhead.karoo.ext)
|
||||
implementation(libs.androidx.core.ktx)
|
||||
implementation(libs.bundles.androidx.lifeycle)
|
||||
implementation(libs.androidx.activity.compose)
|
||||
implementation(libs.bundles.compose.ui)
|
||||
implementation(libs.androidx.navigation.runtime.ktx)
|
||||
implementation(libs.androidx.navigation.compose)
|
||||
implementation(libs.kotlinx.serialization.json)
|
||||
implementation(libs.androidx.datastore.preferences)
|
||||
implementation(libs.androidx.glance.appwidget)
|
||||
implementation(libs.androidx.glance.appwidget.preview)
|
||||
implementation(libs.androidx.glance.preview)
|
||||
}
|
||||
BIN
app/karoo-winddir.png
Normal file
|
After Width: | Height: | Size: 5.6 KiB |
11
app/manifest.json
Normal file
@ -0,0 +1,11 @@
|
||||
{
|
||||
"label": "karoo-winddir",
|
||||
"packageName": "de.timklge.karoowinddir",
|
||||
"iconUrl": "https://github.com/timklge/karoo-winddir/releases/latest/download/karoo-winddir.png",
|
||||
"latestApkUrl": "https://github.com/timklge/karoo-winddir/releases/latest/download/app-release.apk",
|
||||
"latestVersion": "1.0.0-beta1",
|
||||
"latestVersionCode": 1,
|
||||
"developer": "timklge",
|
||||
"description": "Provides relative wind direction, wind speed and other weather data fields",
|
||||
"releaseNotes": "Initial release"
|
||||
}
|
||||
21
app/proguard-rules.pro
vendored
Normal file
@ -0,0 +1,21 @@
|
||||
# Add project specific ProGuard rules here.
|
||||
# You can control the set of applied configuration files using the
|
||||
# proguardFiles setting in build.gradle.kts.
|
||||
#
|
||||
# For more details, see
|
||||
# http://developer.android.com/guide/developing/tools/proguard.html
|
||||
|
||||
# If your project uses WebView with JS, uncomment the following
|
||||
# and specify the fully qualified class name to the JavaScript interface
|
||||
# class:
|
||||
#-keepclassmembers class fqcn.of.javascript.interface.for.webview {
|
||||
# public *;
|
||||
#}
|
||||
|
||||
# Uncomment this to preserve the line number information for
|
||||
# debugging stack traces.
|
||||
#-keepattributes SourceFile,LineNumberTable
|
||||
|
||||
# If you keep the line number information, uncomment this to
|
||||
# hide the original source file name.
|
||||
#-renamesourcefileattribute SourceFile
|
||||
37
app/src/main/AndroidManifest.xml
Normal file
@ -0,0 +1,37 @@
|
||||
<?xml version="1.0" encoding="utf-8"?>
|
||||
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
|
||||
xmlns:tools="http://schemas.android.com/tools">
|
||||
|
||||
<application
|
||||
android:allowBackup="true"
|
||||
android:icon="@mipmap/ic_launcher"
|
||||
android:label="@string/app_name"
|
||||
android:roundIcon="@mipmap/ic_launcher_round"
|
||||
android:supportsRtl="true"
|
||||
android:theme="@style/Theme.AppCompat">
|
||||
<activity
|
||||
android:name="de.timklge.karoowinddir.MainActivity"
|
||||
android:exported="true">
|
||||
<intent-filter>
|
||||
<action android:name="android.intent.action.MAIN" />
|
||||
<category android:name="android.intent.category.LAUNCHER" />
|
||||
</intent-filter>
|
||||
</activity>
|
||||
|
||||
<service
|
||||
android:name="de.timklge.karoowinddir.KarooWinddirExtension"
|
||||
android:exported="true"
|
||||
tools:ignore="ExportedService">
|
||||
<intent-filter>
|
||||
<action android:name="io.hammerhead.karooext.KAROO_EXTENSION" />
|
||||
</intent-filter>
|
||||
<meta-data
|
||||
android:name="io.hammerhead.karooext.EXTENSION_INFO"
|
||||
android:resource="@xml/extension_info" />
|
||||
</service>
|
||||
|
||||
<meta-data
|
||||
android:name="io.hammerhead.karooext.MANIFEST_URL"
|
||||
android:value="https://github.com/timklge/karoo-winddir/releases/latest/download/manifest.json" />
|
||||
</application>
|
||||
</manifest>
|
||||
BIN
app/src/main/ic_launcher-playstore.png
Normal file
|
After Width: | Height: | Size: 21 KiB |
175
app/src/main/kotlin/de/timklge/karoowinddir/Extensions.kt
Normal file
@ -0,0 +1,175 @@
|
||||
package de.timklge.karoowinddir
|
||||
|
||||
import android.content.Context
|
||||
import android.util.Log
|
||||
import androidx.datastore.preferences.core.edit
|
||||
import androidx.datastore.preferences.core.stringPreferencesKey
|
||||
import de.timklge.karoowinddir.datatypes.GpsCoordinates
|
||||
import de.timklge.karoowinddir.screens.WinddirSettings
|
||||
import de.timklge.karoowinddir.screens.WinddirStats
|
||||
import io.hammerhead.karooext.KarooSystemService
|
||||
import io.hammerhead.karooext.models.DataType
|
||||
import io.hammerhead.karooext.models.HttpResponseState
|
||||
import io.hammerhead.karooext.models.OnHttpResponse
|
||||
import io.hammerhead.karooext.models.OnStreamState
|
||||
import io.hammerhead.karooext.models.StreamState
|
||||
import kotlinx.coroutines.FlowPreview
|
||||
import kotlinx.coroutines.TimeoutCancellationException
|
||||
import kotlinx.coroutines.channels.awaitClose
|
||||
import kotlinx.coroutines.channels.trySendBlocking
|
||||
import kotlinx.coroutines.flow.Flow
|
||||
import kotlinx.coroutines.flow.callbackFlow
|
||||
import kotlinx.coroutines.flow.catch
|
||||
import kotlinx.coroutines.flow.distinctUntilChanged
|
||||
import kotlinx.coroutines.flow.filter
|
||||
import kotlinx.coroutines.flow.filterNotNull
|
||||
import kotlinx.coroutines.flow.flowOf
|
||||
import kotlinx.coroutines.flow.map
|
||||
import kotlinx.coroutines.flow.mapNotNull
|
||||
import kotlinx.coroutines.flow.single
|
||||
import kotlinx.coroutines.flow.timeout
|
||||
import kotlinx.coroutines.time.debounce
|
||||
import kotlinx.serialization.encodeToString
|
||||
import kotlinx.serialization.json.Json
|
||||
import java.time.Duration
|
||||
import kotlin.math.absoluteValue
|
||||
import kotlin.math.roundToInt
|
||||
import kotlin.time.Duration.Companion.seconds
|
||||
|
||||
val jsonWithUnknownKeys = Json { ignoreUnknownKeys = true }
|
||||
|
||||
val settingsKey = stringPreferencesKey("settings")
|
||||
val currentDataKey = stringPreferencesKey("current")
|
||||
val statsKey = stringPreferencesKey("stats")
|
||||
|
||||
suspend fun saveSettings(context: Context, settings: WinddirSettings) {
|
||||
context.dataStore.edit { t ->
|
||||
t[settingsKey] = Json.encodeToString(settings)
|
||||
}
|
||||
}
|
||||
|
||||
suspend fun saveStats(context: Context, stats: WinddirStats) {
|
||||
context.dataStore.edit { t ->
|
||||
t[statsKey] = Json.encodeToString(stats)
|
||||
}
|
||||
}
|
||||
|
||||
suspend fun saveCurrentData(context: Context, forecast: OpenMeteoCurrentWeatherResponse) {
|
||||
context.dataStore.edit { t ->
|
||||
t[currentDataKey] = Json.encodeToString(forecast)
|
||||
}
|
||||
}
|
||||
|
||||
fun KarooSystemService.streamDataFlow(dataTypeId: String): Flow<StreamState> {
|
||||
return callbackFlow {
|
||||
val listenerId = addConsumer(OnStreamState.StartStreaming(dataTypeId)) { event: OnStreamState ->
|
||||
trySendBlocking(event.state)
|
||||
}
|
||||
awaitClose {
|
||||
removeConsumer(listenerId)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fun Context.streamCurrentWeatherData(): Flow<OpenMeteoCurrentWeatherResponse> {
|
||||
return dataStore.data.map { settingsJson ->
|
||||
try {
|
||||
val data = settingsJson[currentDataKey]
|
||||
data?.let { d -> jsonWithUnknownKeys.decodeFromString<OpenMeteoCurrentWeatherResponse>(d) }
|
||||
} catch (e: Throwable) {
|
||||
Log.e(KarooWinddirExtension.TAG, "Failed to read preferences", e)
|
||||
null
|
||||
}
|
||||
}.filterNotNull().distinctUntilChanged().filter { it.current.time * 1000 >= System.currentTimeMillis() - (1000 * 60 * 60 * 3) }
|
||||
}
|
||||
|
||||
fun Context.streamSettings(): Flow<WinddirSettings> {
|
||||
return dataStore.data.map { settingsJson ->
|
||||
try {
|
||||
jsonWithUnknownKeys.decodeFromString<WinddirSettings>(
|
||||
settingsJson[settingsKey] ?: WinddirSettings.defaultSettings
|
||||
)
|
||||
} catch(e: Throwable){
|
||||
Log.e(KarooWinddirExtension.TAG, "Failed to read preferences", e)
|
||||
jsonWithUnknownKeys.decodeFromString<WinddirSettings>(WinddirSettings.defaultSettings)
|
||||
}
|
||||
}.distinctUntilChanged()
|
||||
}
|
||||
|
||||
fun Context.streamStats(): Flow<WinddirStats> {
|
||||
return dataStore.data.map { statsJson ->
|
||||
try {
|
||||
jsonWithUnknownKeys.decodeFromString<WinddirStats>(
|
||||
statsJson[statsKey] ?: WinddirStats.defaultStats
|
||||
)
|
||||
} catch(e: Throwable){
|
||||
Log.e(KarooWinddirExtension.TAG, "Failed to read stats", e)
|
||||
jsonWithUnknownKeys.decodeFromString<WinddirStats>(WinddirStats.defaultStats)
|
||||
}
|
||||
}.distinctUntilChanged()
|
||||
}
|
||||
|
||||
@OptIn(FlowPreview::class)
|
||||
suspend fun KarooSystemService.makeOpenMeteoHttpRequest(gpsCoordinates: GpsCoordinates, settings: WinddirSettings): HttpResponseState.Complete {
|
||||
return callbackFlow {
|
||||
// https://open-meteo.com/en/docs#current=temperature_2m,relative_humidity_2m,apparent_temperature,precipitation,cloud_cover,wind_speed_10m,wind_direction_10m,wind_gusts_10m&hourly=&daily=&location_mode=csv_coordinates&timeformat=unixtime&forecast_days=3
|
||||
val url = "https://api.open-meteo.com/v1/forecast?latitude=${gpsCoordinates.lat}&longitude=${gpsCoordinates.lon}¤t=temperature_2m,relative_humidity_2m,apparent_temperature,precipitation,cloud_cover,wind_speed_10m,wind_direction_10m,wind_gusts_10m,surface_pressure&timeformat=unixtime&wind_speed_unit=${settings.windUnit.id}&precipitation_unit=${settings.precipitationUnit.id}"
|
||||
|
||||
Log.d(KarooWinddirExtension.TAG, "Http request to ${url}...")
|
||||
|
||||
val listenerId = addConsumer(
|
||||
OnHttpResponse.MakeHttpRequest(
|
||||
"GET",
|
||||
url,
|
||||
waitForConnection = false,
|
||||
),
|
||||
) { event: OnHttpResponse ->
|
||||
Log.d(KarooWinddirExtension.TAG, "Http response event $event")
|
||||
if (event.state is HttpResponseState.Complete){
|
||||
trySend(event.state as HttpResponseState.Complete)
|
||||
close()
|
||||
}
|
||||
}
|
||||
awaitClose {
|
||||
removeConsumer(listenerId)
|
||||
}
|
||||
}.timeout(20.seconds).catch { e: Throwable ->
|
||||
if (e is TimeoutCancellationException){
|
||||
emit(HttpResponseState.Complete(500, mapOf(), null, "Timeout"))
|
||||
} else {
|
||||
throw e
|
||||
}
|
||||
}.single()
|
||||
}
|
||||
|
||||
fun KarooSystemService.getHeadingFlow(): Flow<Int> {
|
||||
// return flowOf(2)
|
||||
|
||||
return streamDataFlow(DataType.Type.HEADING)
|
||||
.mapNotNull { (it as? StreamState.Streaming)?.dataPoint?.singleValue }
|
||||
.map { it.roundToInt() }
|
||||
.distinctUntilChanged()
|
||||
}
|
||||
|
||||
@OptIn(FlowPreview::class)
|
||||
fun KarooSystemService.getGpsCoordinateFlow(): Flow<GpsCoordinates> {
|
||||
// return flowOf(GpsCoordinates(52.5164069,13.3784))
|
||||
|
||||
return streamDataFlow("TYPE_LOCATION_ID")
|
||||
.mapNotNull { (it as? StreamState.Streaming)?.dataPoint?.values }
|
||||
.mapNotNull { values ->
|
||||
val lat = values[DataType.Field.LOC_LATITUDE]
|
||||
val lon = values[DataType.Field.LOC_LONGITUDE]
|
||||
|
||||
if (lat != null && lon != null){
|
||||
Log.d(KarooWinddirExtension.TAG, "Updated gps coords: $lat $lon")
|
||||
GpsCoordinates(lat, lon)
|
||||
} else {
|
||||
Log.e(KarooWinddirExtension.TAG, "Missing gps values: $values")
|
||||
null
|
||||
}
|
||||
}
|
||||
.map { it.round() }
|
||||
.distinctUntilChanged { old, new -> old.distanceTo(new).absoluteValue < 0.001 }
|
||||
.debounce(Duration.ofSeconds(10))
|
||||
}
|
||||
@ -0,0 +1,132 @@
|
||||
package de.timklge.karoowinddir
|
||||
|
||||
import android.util.Log
|
||||
import de.timklge.karoowinddir.datatypes.CloudCoverDataType
|
||||
import de.timklge.karoowinddir.datatypes.GpsCoordinates
|
||||
import de.timklge.karoowinddir.datatypes.PrecipitationDataType
|
||||
import de.timklge.karoowinddir.datatypes.RelativeHumidityDataType
|
||||
import de.timklge.karoowinddir.datatypes.SurfacePressureDataType
|
||||
import de.timklge.karoowinddir.datatypes.WindDirectionDataType
|
||||
import de.timklge.karoowinddir.datatypes.WindGustsDataType
|
||||
import de.timklge.karoowinddir.datatypes.WindSpeedDataType
|
||||
import de.timklge.karoowinddir.datatypes.WinddirDataType
|
||||
import de.timklge.karoowinddir.screens.WinddirStats
|
||||
import io.hammerhead.karooext.KarooSystemService
|
||||
import io.hammerhead.karooext.extension.KarooExtension
|
||||
import kotlinx.coroutines.CoroutineScope
|
||||
import kotlinx.coroutines.Dispatchers
|
||||
import kotlinx.coroutines.ExperimentalCoroutinesApi
|
||||
import kotlinx.coroutines.Job
|
||||
import kotlinx.coroutines.delay
|
||||
import kotlinx.coroutines.flow.combine
|
||||
import kotlinx.coroutines.flow.filter
|
||||
import kotlinx.coroutines.flow.first
|
||||
import kotlinx.coroutines.flow.map
|
||||
import kotlinx.coroutines.flow.retry
|
||||
import kotlinx.coroutines.flow.transformLatest
|
||||
import kotlinx.coroutines.launch
|
||||
import kotlin.time.Duration.Companion.hours
|
||||
import kotlin.time.Duration.Companion.minutes
|
||||
|
||||
class KarooWinddirExtension : KarooExtension("karoo-winddir", "1.0.0-beta1") {
|
||||
companion object {
|
||||
const val TAG = "karoo-winddir"
|
||||
}
|
||||
|
||||
lateinit var karooSystem: KarooSystemService
|
||||
|
||||
private var serviceJob: Job? = null
|
||||
|
||||
override val types by lazy {
|
||||
listOf(
|
||||
WinddirDataType(karooSystem, applicationContext),
|
||||
RelativeHumidityDataType(applicationContext),
|
||||
CloudCoverDataType(applicationContext),
|
||||
WindSpeedDataType(applicationContext),
|
||||
WindGustsDataType(applicationContext),
|
||||
WindDirectionDataType(karooSystem, applicationContext),
|
||||
PrecipitationDataType(applicationContext),
|
||||
SurfacePressureDataType(applicationContext)
|
||||
)
|
||||
}
|
||||
|
||||
@OptIn(ExperimentalCoroutinesApi::class)
|
||||
override fun onCreate() {
|
||||
super.onCreate()
|
||||
|
||||
karooSystem = KarooSystemService(applicationContext)
|
||||
|
||||
serviceJob = CoroutineScope(Dispatchers.IO).launch {
|
||||
karooSystem.connect { connected ->
|
||||
if (connected) {
|
||||
Log.d(TAG, "Connected to Karoo system")
|
||||
}
|
||||
}
|
||||
|
||||
val gpsFlow = karooSystem
|
||||
.getGpsCoordinateFlow()
|
||||
.transformLatest { value: GpsCoordinates ->
|
||||
while(true){
|
||||
emit(value)
|
||||
delay(1.hours)
|
||||
}
|
||||
}
|
||||
|
||||
streamSettings()
|
||||
.filter { it.welcomeDialogAccepted }
|
||||
.combine(gpsFlow) { settings, gps -> settings to gps }
|
||||
.map { (settings, gps) ->
|
||||
Log.d(TAG, "Acquired updated gps coordinates: $gps")
|
||||
|
||||
val lastKnownStats = try {
|
||||
streamStats().first()
|
||||
} catch(e: Exception){
|
||||
Log.e(TAG, "Failed to read stats", e)
|
||||
WinddirStats()
|
||||
}
|
||||
|
||||
val response = karooSystem.makeOpenMeteoHttpRequest(gps, settings)
|
||||
if (response.error != null){
|
||||
try {
|
||||
val stats = lastKnownStats.copy(failedWeatherRequest = System.currentTimeMillis())
|
||||
launch { saveStats(this@KarooWinddirExtension, stats) }
|
||||
} catch(e: Exception){
|
||||
Log.e(TAG, "Failed to write stats", e)
|
||||
}
|
||||
error("HTTP request failed: ${response.error}")
|
||||
} else {
|
||||
try {
|
||||
val stats = lastKnownStats.copy(
|
||||
lastSuccessfulWeatherRequest = System.currentTimeMillis(),
|
||||
lastSuccessfulWeatherPosition = gps
|
||||
)
|
||||
launch { saveStats(this@KarooWinddirExtension, stats) }
|
||||
} catch(e: Exception){
|
||||
Log.e(TAG, "Failed to write stats", e)
|
||||
}
|
||||
}
|
||||
|
||||
response
|
||||
}
|
||||
.retry(Long.MAX_VALUE) { delay(1.minutes); true }
|
||||
.collect { response ->
|
||||
try {
|
||||
val responseString = String(response.body ?: ByteArray(0))
|
||||
val data = jsonWithUnknownKeys.decodeFromString<OpenMeteoCurrentWeatherResponse>(responseString)
|
||||
|
||||
saveCurrentData(applicationContext, data)
|
||||
Log.d(TAG, "Got updated weather info: $data")
|
||||
} catch(e: Exception){
|
||||
Log.e(TAG, "Failed to read current weather data", e)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
override fun onDestroy() {
|
||||
serviceJob?.cancel()
|
||||
serviceJob = null
|
||||
karooSystem.disconnect()
|
||||
super.onDestroy()
|
||||
}
|
||||
}
|
||||
26
app/src/main/kotlin/de/timklge/karoowinddir/MainActivity.kt
Normal file
@ -0,0 +1,26 @@
|
||||
package de.timklge.karoowinddir
|
||||
|
||||
import android.content.Context
|
||||
import android.os.Bundle
|
||||
import androidx.activity.ComponentActivity
|
||||
import androidx.activity.compose.setContent
|
||||
import androidx.compose.material3.Text
|
||||
import androidx.datastore.core.DataStore
|
||||
import androidx.datastore.preferences.core.Preferences
|
||||
import androidx.datastore.preferences.preferencesDataStore
|
||||
import de.timklge.karoowinddir.screens.MainScreen
|
||||
import de.timklge.karoowinddir.theme.AppTheme
|
||||
|
||||
val Context.dataStore: DataStore<Preferences> by preferencesDataStore(name = "settings")
|
||||
|
||||
class MainActivity : ComponentActivity() {
|
||||
override fun onCreate(savedInstanceState: Bundle?) {
|
||||
super.onCreate(savedInstanceState)
|
||||
|
||||
setContent {
|
||||
AppTheme {
|
||||
MainScreen()
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
27
app/src/main/kotlin/de/timklge/karoowinddir/OpenMeteoData.kt
Normal file
@ -0,0 +1,27 @@
|
||||
package de.timklge.karoowinddir
|
||||
|
||||
import kotlinx.serialization.SerialName
|
||||
import kotlinx.serialization.Serializable
|
||||
|
||||
@Serializable
|
||||
data class OpenMeteoData(
|
||||
val time: Long, val interval: Int,
|
||||
@SerialName("temperature_2m") val temperature: Double,
|
||||
@SerialName("relative_humidity_2m") val relativeHumidity: Int,
|
||||
@SerialName("precipitation") val precipitation: Double,
|
||||
@SerialName("cloud_cover") val cloudCover: Int,
|
||||
@SerialName("surface_pressure") val surfacePressure: Double,
|
||||
@SerialName("wind_speed_10m") val windSpeed: Double,
|
||||
@SerialName("wind_direction_10m") val windDirection: Double,
|
||||
@SerialName("wind_gusts_10m") val windGusts: Double
|
||||
)
|
||||
|
||||
@Serializable
|
||||
data class OpenMeteoCurrentWeatherResponse(
|
||||
val current: OpenMeteoData,
|
||||
val latitude: Double,
|
||||
val longitude: Double,
|
||||
val timezone: String,
|
||||
val elevation: Double,
|
||||
@SerialName("utc_offset_seconds") val utfOffsetSeconds: Int
|
||||
)
|
||||
@ -0,0 +1,10 @@
|
||||
package de.timklge.karoowinddir.datatypes
|
||||
|
||||
import android.content.Context
|
||||
import de.timklge.karoowinddir.OpenMeteoCurrentWeatherResponse
|
||||
|
||||
class CloudCoverDataType(context: Context) : WeatherDataType(context, "cloudCover"){
|
||||
override fun getValue(data: OpenMeteoCurrentWeatherResponse): Double {
|
||||
return data.current.cloudCover.toDouble()
|
||||
}
|
||||
}
|
||||
@ -0,0 +1,41 @@
|
||||
package de.timklge.karoowinddir.datatypes
|
||||
|
||||
import kotlinx.serialization.Serializable
|
||||
import kotlin.math.atan2
|
||||
import kotlin.math.cos
|
||||
import kotlin.math.pow
|
||||
import kotlin.math.roundToInt
|
||||
import kotlin.math.sin
|
||||
import kotlin.math.sqrt
|
||||
|
||||
@Serializable
|
||||
data class GpsCoordinates(val lat: Double, val lon: Double){
|
||||
companion object {
|
||||
private fun roundDegrees(degrees: Double, km: Double): Double {
|
||||
val nkm = degrees * 111
|
||||
val rounded = (nkm / km).roundToInt() * km
|
||||
|
||||
return rounded / 111
|
||||
}
|
||||
}
|
||||
|
||||
fun round(km: Double = 2.0): GpsCoordinates {
|
||||
return copy(lat = roundDegrees(lat, km), lon = roundDegrees(lon, km))
|
||||
}
|
||||
|
||||
// Haversine formula in kilometers
|
||||
fun distanceTo(other: GpsCoordinates): Double {
|
||||
val lat1 = Math.toRadians(lat)
|
||||
val lon1 = Math.toRadians(lon)
|
||||
val lat2 = Math.toRadians(other.lat)
|
||||
val lon2 = Math.toRadians(other.lon)
|
||||
val dlat = lat2 - lat1
|
||||
val dlon = lon2 - lon1
|
||||
val a = sin(dlat / 2).pow(2) + cos(lat1) * cos(lat2) * sin(dlon / 2).pow(2)
|
||||
val c = 2 * atan2(sqrt(a), sqrt(1 - a))
|
||||
val r = 6371.0
|
||||
val distance = r * c
|
||||
|
||||
return distance
|
||||
}
|
||||
}
|
||||
@ -0,0 +1,10 @@
|
||||
package de.timklge.karoowinddir.datatypes
|
||||
|
||||
import android.content.Context
|
||||
import de.timklge.karoowinddir.OpenMeteoCurrentWeatherResponse
|
||||
|
||||
class PrecipitationDataType(context: Context) : WeatherDataType(context, "precipitation"){
|
||||
override fun getValue(data: OpenMeteoCurrentWeatherResponse): Double {
|
||||
return data.current.precipitation
|
||||
}
|
||||
}
|
||||
@ -0,0 +1,10 @@
|
||||
package de.timklge.karoowinddir.datatypes
|
||||
|
||||
import android.content.Context
|
||||
import de.timklge.karoowinddir.OpenMeteoCurrentWeatherResponse
|
||||
|
||||
class RelativeHumidityDataType(context: Context) : WeatherDataType(context, "relativeHumidity"){
|
||||
override fun getValue(data: OpenMeteoCurrentWeatherResponse): Double {
|
||||
return data.current.relativeHumidity.toDouble()
|
||||
}
|
||||
}
|
||||
@ -0,0 +1,74 @@
|
||||
package de.timklge.karoowinddir.datatypes
|
||||
|
||||
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.background
|
||||
import androidx.glance.color.ColorProvider
|
||||
import androidx.glance.layout.Alignment
|
||||
import androidx.glance.layout.Box
|
||||
import androidx.glance.layout.ContentScale
|
||||
import androidx.glance.layout.fillMaxSize
|
||||
import androidx.glance.layout.padding
|
||||
import androidx.glance.preview.ExperimentalGlancePreviewApi
|
||||
import androidx.glance.preview.Preview
|
||||
import androidx.glance.text.Text
|
||||
import androidx.glance.text.TextStyle
|
||||
import de.timklge.karoowinddir.R
|
||||
import kotlin.math.roundToInt
|
||||
|
||||
fun getArrowResourceByBearing(bearing: Int): Int {
|
||||
val oclock = ((bearing % 360) / 30.0).roundToInt()
|
||||
|
||||
return when (oclock){
|
||||
0 -> R.drawable.arrow_0
|
||||
1 -> R.drawable.arrow_1
|
||||
2 -> R.drawable.arrow_2
|
||||
3 -> R.drawable.arrow_3
|
||||
4 -> R.drawable.arrow_4
|
||||
5 -> R.drawable.arrow_5
|
||||
6 -> R.drawable.arrow_6
|
||||
7 -> R.drawable.arrow_7
|
||||
8 -> R.drawable.arrow_8
|
||||
9 -> R.drawable.arrow_9
|
||||
10 -> R.drawable.arrow_10
|
||||
11 -> R.drawable.arrow_11
|
||||
12 -> R.drawable.arrow_0
|
||||
else -> error("Bearing $bearing out of range")
|
||||
}
|
||||
}
|
||||
|
||||
@OptIn(ExperimentalGlancePreviewApi::class)
|
||||
@Preview(widthDp = 200, heightDp = 150)
|
||||
@Composable
|
||||
fun RelativeWindDirection(bearing: Int, fontSize: Int, overlayText: String? = null) {
|
||||
Box(
|
||||
modifier = GlanceModifier.fillMaxSize().padding(5.dp),
|
||||
contentAlignment = Alignment(
|
||||
vertical = Alignment.Vertical.CenterVertically,
|
||||
horizontal = Alignment.Horizontal.CenterHorizontally,
|
||||
),
|
||||
) {
|
||||
Image(
|
||||
modifier = GlanceModifier.fillMaxSize(),
|
||||
provider = ImageProvider(getArrowResourceByBearing(bearing)),
|
||||
contentDescription = "Relative wind direction indicator",
|
||||
contentScale = ContentScale.Fit,
|
||||
colorFilter = ColorFilter.tint(ColorProvider(Color.Black, Color.White))
|
||||
)
|
||||
|
||||
overlayText?.let {
|
||||
Text(
|
||||
overlayText,
|
||||
style = TextStyle(ColorProvider(Color.White, Color.White), fontSize = TextUnit(fontSize.toFloat()*0.7f, TextUnitType.Sp)),
|
||||
modifier = GlanceModifier.background(Color(0f, 0f, 0f, 0.5f)).padding(5.dp)
|
||||
)
|
||||
}
|
||||
}
|
||||
}
|
||||
@ -0,0 +1,10 @@
|
||||
package de.timklge.karoowinddir.datatypes
|
||||
|
||||
import android.content.Context
|
||||
import de.timklge.karoowinddir.OpenMeteoCurrentWeatherResponse
|
||||
|
||||
class SurfacePressureDataType(context: Context) : WeatherDataType(context, "surfacePressure"){
|
||||
override fun getValue(data: OpenMeteoCurrentWeatherResponse): Double {
|
||||
return data.current.surfacePressure
|
||||
}
|
||||
}
|
||||
@ -0,0 +1,39 @@
|
||||
package de.timklge.karoowinddir.datatypes
|
||||
|
||||
import android.content.Context
|
||||
import android.util.Log
|
||||
import de.timklge.karoowinddir.KarooWinddirExtension
|
||||
import de.timklge.karoowinddir.OpenMeteoCurrentWeatherResponse
|
||||
import de.timklge.karoowinddir.streamCurrentWeatherData
|
||||
import io.hammerhead.karooext.extension.DataTypeImpl
|
||||
import io.hammerhead.karooext.internal.Emitter
|
||||
import io.hammerhead.karooext.models.DataPoint
|
||||
import io.hammerhead.karooext.models.DataType
|
||||
import io.hammerhead.karooext.models.StreamState
|
||||
import kotlinx.coroutines.CoroutineScope
|
||||
import kotlinx.coroutines.Dispatchers
|
||||
import kotlinx.coroutines.launch
|
||||
|
||||
abstract class WeatherDataType(
|
||||
private val applicationContext: Context,
|
||||
dataTypeId: String
|
||||
) : DataTypeImpl("karoo-winddir", dataTypeId) {
|
||||
abstract fun getValue(data: OpenMeteoCurrentWeatherResponse): Double
|
||||
|
||||
override fun startStream(emitter: Emitter<StreamState>) {
|
||||
Log.d(KarooWinddirExtension.TAG, "start $dataTypeId stream")
|
||||
val job = CoroutineScope(Dispatchers.IO).launch {
|
||||
val currentWeatherData = applicationContext.streamCurrentWeatherData()
|
||||
|
||||
currentWeatherData.collect { data ->
|
||||
val value = getValue(data)
|
||||
Log.d(KarooWinddirExtension.TAG, "$dataTypeId: $value")
|
||||
emitter.onNext(StreamState.Streaming(DataPoint(dataTypeId, mapOf(DataType.Field.SINGLE to value))))
|
||||
}
|
||||
}
|
||||
emitter.setCancellable {
|
||||
Log.d(KarooWinddirExtension.TAG, "stop $dataTypeId stream")
|
||||
job.cancel()
|
||||
}
|
||||
}
|
||||
}
|
||||
@ -0,0 +1,94 @@
|
||||
package de.timklge.karoowinddir.datatypes
|
||||
|
||||
import android.content.Context
|
||||
import android.util.Log
|
||||
import androidx.compose.ui.graphics.Color
|
||||
import androidx.compose.ui.text.style.TextAlign
|
||||
import androidx.compose.ui.unit.DpSize
|
||||
import androidx.compose.ui.unit.TextUnit
|
||||
import androidx.compose.ui.unit.TextUnitType
|
||||
import androidx.compose.ui.unit.dp
|
||||
import androidx.glance.GlanceModifier
|
||||
import androidx.glance.appwidget.ExperimentalGlanceRemoteViewsApi
|
||||
import androidx.glance.appwidget.GlanceRemoteViews
|
||||
import androidx.glance.background
|
||||
import androidx.glance.color.ColorProvider
|
||||
import androidx.glance.layout.Alignment
|
||||
import androidx.glance.layout.Box
|
||||
import androidx.glance.layout.fillMaxSize
|
||||
import androidx.glance.layout.padding
|
||||
import androidx.glance.text.FontFamily
|
||||
import androidx.glance.text.FontStyle
|
||||
import androidx.glance.text.Text
|
||||
import androidx.glance.text.TextStyle
|
||||
import de.timklge.karoowinddir.KarooWinddirExtension
|
||||
import de.timklge.karoowinddir.OpenMeteoCurrentWeatherResponse
|
||||
import de.timklge.karoowinddir.streamDataFlow
|
||||
import io.hammerhead.karooext.KarooSystemService
|
||||
import io.hammerhead.karooext.internal.ViewEmitter
|
||||
import io.hammerhead.karooext.models.StreamState
|
||||
import io.hammerhead.karooext.models.UpdateGraphicConfig
|
||||
import io.hammerhead.karooext.models.ViewConfig
|
||||
import kotlinx.coroutines.CoroutineScope
|
||||
import kotlinx.coroutines.Dispatchers
|
||||
import kotlinx.coroutines.awaitCancellation
|
||||
import kotlinx.coroutines.flow.onCompletion
|
||||
import kotlinx.coroutines.launch
|
||||
import kotlin.math.roundToInt
|
||||
|
||||
class WindDirectionDataType(val karooSystem: KarooSystemService, context: Context) : WeatherDataType(context, "windDirection"){
|
||||
@OptIn(ExperimentalGlanceRemoteViewsApi::class)
|
||||
private val glance = GlanceRemoteViews()
|
||||
|
||||
override fun getValue(data: OpenMeteoCurrentWeatherResponse): Double {
|
||||
return data.current.windDirection
|
||||
}
|
||||
|
||||
@OptIn(ExperimentalGlanceRemoteViewsApi::class)
|
||||
override fun startView(context: Context, config: ViewConfig, emitter: ViewEmitter) {
|
||||
val configJob = CoroutineScope(Dispatchers.IO).launch {
|
||||
emitter.onNext(UpdateGraphicConfig(showHeader = true))
|
||||
awaitCancellation()
|
||||
}
|
||||
|
||||
val viewJob = CoroutineScope(Dispatchers.IO).launch {
|
||||
karooSystem.streamDataFlow(dataTypeId)
|
||||
.onCompletion {
|
||||
val result = glance.compose(context, DpSize.Unspecified) { }
|
||||
emitter.updateView(result.remoteViews)
|
||||
}
|
||||
.collect {
|
||||
val windBearing = (it as? StreamState.Streaming)?.dataPoint?.singleValue?.toInt() ?: 0
|
||||
val windCardinalDirection = ((windBearing % 360) / 45.0).roundToInt() % 8
|
||||
val text = when(windCardinalDirection){
|
||||
0 -> "N"
|
||||
1 -> "NE"
|
||||
2 -> "E"
|
||||
3 -> "SE"
|
||||
4 -> "S"
|
||||
5 -> "SW"
|
||||
6 -> "W"
|
||||
7 -> "NW"
|
||||
else -> "N/A"
|
||||
}
|
||||
Log.d( KarooWinddirExtension.TAG,"Updating wind direction view")
|
||||
val result = glance.compose(context, DpSize.Unspecified) {
|
||||
Box(modifier = GlanceModifier.fillMaxSize(),
|
||||
contentAlignment = Alignment(
|
||||
vertical = Alignment.Vertical.Top,
|
||||
horizontal = Alignment.Horizontal.End,
|
||||
)) {
|
||||
Text(text, style = TextStyle(color = ColorProvider(Color.Black, Color.White), fontFamily = FontFamily.Monospace, fontSize = TextUnit(
|
||||
config.textSize.toFloat(), TextUnitType.Sp) /* FIXME: Read data field alignment config, karoo-ext #10 */))
|
||||
}
|
||||
}
|
||||
emitter.updateView(result.remoteViews)
|
||||
}
|
||||
}
|
||||
|
||||
emitter.setCancellable {
|
||||
configJob.cancel()
|
||||
viewJob.cancel()
|
||||
}
|
||||
}
|
||||
}
|
||||
@ -0,0 +1,10 @@
|
||||
package de.timklge.karoowinddir.datatypes
|
||||
|
||||
import android.content.Context
|
||||
import de.timklge.karoowinddir.OpenMeteoCurrentWeatherResponse
|
||||
|
||||
class WindGustsDataType(context: Context) : WeatherDataType(context, "windGusts"){
|
||||
override fun getValue(data: OpenMeteoCurrentWeatherResponse): Double {
|
||||
return data.current.windGusts
|
||||
}
|
||||
}
|
||||
@ -0,0 +1,10 @@
|
||||
package de.timklge.karoowinddir.datatypes
|
||||
|
||||
import android.content.Context
|
||||
import de.timklge.karoowinddir.OpenMeteoCurrentWeatherResponse
|
||||
|
||||
class WindSpeedDataType(context: Context) : WeatherDataType(context, "windSpeed"){
|
||||
override fun getValue(data: OpenMeteoCurrentWeatherResponse): Double {
|
||||
return data.current.windSpeed
|
||||
}
|
||||
}
|
||||
@ -0,0 +1,121 @@
|
||||
package de.timklge.karoowinddir.datatypes
|
||||
|
||||
import android.util.Log
|
||||
import android.content.Context
|
||||
import androidx.compose.ui.unit.DpSize
|
||||
import androidx.glance.appwidget.ExperimentalGlanceRemoteViewsApi
|
||||
import androidx.glance.appwidget.GlanceRemoteViews
|
||||
import de.timklge.karoowinddir.KarooWinddirExtension
|
||||
import de.timklge.karoowinddir.OpenMeteoCurrentWeatherResponse
|
||||
import de.timklge.karoowinddir.getHeadingFlow
|
||||
import de.timklge.karoowinddir.screens.WinddirSettings
|
||||
import de.timklge.karoowinddir.streamCurrentWeatherData
|
||||
import de.timklge.karoowinddir.streamDataFlow
|
||||
import de.timklge.karoowinddir.streamSettings
|
||||
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.StreamState
|
||||
import io.hammerhead.karooext.models.UpdateGraphicConfig
|
||||
import io.hammerhead.karooext.models.ViewConfig
|
||||
import kotlinx.coroutines.CoroutineScope
|
||||
import kotlinx.coroutines.Dispatchers
|
||||
import kotlinx.coroutines.ObsoleteCoroutinesApi
|
||||
import kotlinx.coroutines.awaitCancellation
|
||||
import kotlinx.coroutines.flow.combine
|
||||
import kotlinx.coroutines.flow.filter
|
||||
import kotlinx.coroutines.flow.mapNotNull
|
||||
import kotlinx.coroutines.flow.onCompletion
|
||||
import kotlinx.coroutines.launch
|
||||
import kotlin.math.abs
|
||||
import kotlin.math.roundToInt
|
||||
|
||||
@OptIn(ExperimentalGlanceRemoteViewsApi::class)
|
||||
class WinddirDataType(
|
||||
private val karooSystem: KarooSystemService,
|
||||
private val applicationContext: Context
|
||||
) : DataTypeImpl("karoo-winddir", "winddir") {
|
||||
private val glance = GlanceRemoteViews()
|
||||
|
||||
private fun signedAngleDifference(angle1: Double, angle2: Double): Double {
|
||||
val a1 = angle1 % 360
|
||||
val a2 = angle2 % 360
|
||||
var diff = abs(a1 - a2)
|
||||
|
||||
val sign = if (a1 < a2) {
|
||||
if (diff > 180.0) -1 else 1
|
||||
} else {
|
||||
if (diff > 180.0) 1 else -1
|
||||
}
|
||||
|
||||
if (diff > 180.0) {
|
||||
diff = 360.0 - diff
|
||||
}
|
||||
|
||||
return sign * diff
|
||||
}
|
||||
|
||||
override fun startStream(emitter: Emitter<StreamState>) {
|
||||
Log.d(KarooWinddirExtension.TAG, "start winddir stream")
|
||||
val job = CoroutineScope(Dispatchers.IO).launch {
|
||||
val currentWeatherData = applicationContext.streamCurrentWeatherData()
|
||||
|
||||
karooSystem
|
||||
.getHeadingFlow()
|
||||
.filter { it >= 0 }
|
||||
.combine(currentWeatherData) { cardinalDirection, data -> cardinalDirection to data }
|
||||
.collect { (cardinalDirection, data) ->
|
||||
val bearing = cardinalDirection * 45.0
|
||||
val windBearing = data.current.windDirection + 180
|
||||
|
||||
val diff = (signedAngleDifference(bearing, windBearing) + 360) % 360
|
||||
Log.d(KarooWinddirExtension.TAG, "wind bearing: $bearing vs $windBearing => $diff")
|
||||
emitter.onNext(StreamState.Streaming(DataPoint(dataTypeId, mapOf(DataType.Field.SINGLE to diff))))
|
||||
}
|
||||
}
|
||||
emitter.setCancellable {
|
||||
Log.d(KarooWinddirExtension.TAG, "stop winddir stream")
|
||||
job.cancel()
|
||||
}
|
||||
}
|
||||
|
||||
@OptIn(ObsoleteCoroutinesApi::class)
|
||||
override fun startView(context: Context, config: ViewConfig, emitter: ViewEmitter) {
|
||||
Log.d(KarooWinddirExtension.TAG, "Starting winddir view with $emitter")
|
||||
val configJob = CoroutineScope(Dispatchers.IO).launch {
|
||||
emitter.onNext(UpdateGraphicConfig(showHeader = false))
|
||||
awaitCancellation()
|
||||
}
|
||||
|
||||
data class StreamData(val value: Double, val data: OpenMeteoCurrentWeatherResponse, val settings: WinddirSettings)
|
||||
|
||||
val viewJob = CoroutineScope(Dispatchers.IO).launch {
|
||||
karooSystem.streamDataFlow(dataTypeId)
|
||||
.mapNotNull { (it as? StreamState.Streaming)?.dataPoint?.singleValue }
|
||||
.combine(context.streamCurrentWeatherData()) { value, data -> value to data }
|
||||
.combine(context.streamSettings()) { (value, data), settings -> StreamData(value, data, settings) }
|
||||
.onCompletion {
|
||||
val result = glance.compose(context, DpSize.Unspecified) { }
|
||||
emitter.updateView(result.remoteViews)
|
||||
}
|
||||
.collect { streamData ->
|
||||
Log.d(KarooWinddirExtension.TAG, "Updating view")
|
||||
val windSpeedText = if(streamData.settings.showWindspeedOverlay) "${streamData.data.current.windSpeed.roundToInt()}" else null
|
||||
|
||||
val result = glance.compose(context, DpSize.Unspecified) {
|
||||
RelativeWindDirection(streamData.value.roundToInt(), config.textSize, windSpeedText)
|
||||
}
|
||||
|
||||
emitter.updateView(result.remoteViews)
|
||||
}
|
||||
}
|
||||
emitter.setCancellable {
|
||||
Log.d(KarooWinddirExtension.TAG, "Stopping winddir view with $emitter")
|
||||
configJob.cancel()
|
||||
viewJob.cancel()
|
||||
}
|
||||
}
|
||||
}
|
||||
@ -0,0 +1,63 @@
|
||||
package de.timklge.karoowinddir.screens
|
||||
|
||||
import androidx.compose.foundation.layout.fillMaxWidth
|
||||
import androidx.compose.material3.DropdownMenuItem
|
||||
import androidx.compose.material3.ExperimentalMaterial3Api
|
||||
import androidx.compose.material3.ExposedDropdownMenuBox
|
||||
import androidx.compose.material3.ExposedDropdownMenuDefaults
|
||||
import androidx.compose.material3.MaterialTheme
|
||||
import androidx.compose.material3.MenuAnchorType
|
||||
import androidx.compose.material3.OutlinedTextField
|
||||
import androidx.compose.material3.Text
|
||||
import androidx.compose.material3.TextField
|
||||
import androidx.compose.runtime.Composable
|
||||
import androidx.compose.runtime.getValue
|
||||
import androidx.compose.runtime.mutableStateOf
|
||||
import androidx.compose.runtime.remember
|
||||
import androidx.compose.runtime.setValue
|
||||
import androidx.compose.ui.Modifier
|
||||
|
||||
|
||||
data class DropdownOption(val id: String, val name: String)
|
||||
|
||||
@OptIn(ExperimentalMaterial3Api::class)
|
||||
@Composable
|
||||
fun Dropdown(label: String, options: List<DropdownOption>, initialSelection: DropdownOption, onSelect: (selectedOption: DropdownOption) -> Unit) {
|
||||
var expanded by remember { mutableStateOf(false) }
|
||||
var selected by remember { mutableStateOf(initialSelection) }
|
||||
|
||||
ExposedDropdownMenuBox(
|
||||
expanded = expanded,
|
||||
onExpandedChange = { expanded = it },
|
||||
) {
|
||||
OutlinedTextField(
|
||||
readOnly = true,
|
||||
value = selected.name,
|
||||
onValueChange = { },
|
||||
modifier = Modifier.menuAnchor(MenuAnchorType.PrimaryEditable, true).fillMaxWidth(),
|
||||
label = { Text(label) },
|
||||
trailingIcon = {
|
||||
ExposedDropdownMenuDefaults.TrailingIcon(
|
||||
expanded = expanded
|
||||
)
|
||||
},
|
||||
colors = ExposedDropdownMenuDefaults.textFieldColors()
|
||||
)
|
||||
ExposedDropdownMenu(
|
||||
expanded = expanded,
|
||||
onDismissRequest = { expanded = false },
|
||||
) {
|
||||
options.forEach { option ->
|
||||
DropdownMenuItem(
|
||||
text = { Text(option.name, style = MaterialTheme.typography.bodyLarge) },
|
||||
onClick = {
|
||||
selected = option
|
||||
expanded = false
|
||||
onSelect(selected)
|
||||
},
|
||||
contentPadding = ExposedDropdownMenuDefaults.ItemContentPadding,
|
||||
)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@ -0,0 +1,219 @@
|
||||
package de.timklge.karoowinddir.screens
|
||||
|
||||
import androidx.compose.foundation.background
|
||||
import androidx.compose.foundation.layout.Arrangement
|
||||
import androidx.compose.foundation.layout.Column
|
||||
import androidx.compose.foundation.layout.Row
|
||||
import androidx.compose.foundation.layout.Spacer
|
||||
import androidx.compose.foundation.layout.fillMaxSize
|
||||
import androidx.compose.foundation.layout.fillMaxWidth
|
||||
import androidx.compose.foundation.layout.height
|
||||
import androidx.compose.foundation.layout.padding
|
||||
import androidx.compose.foundation.layout.width
|
||||
import androidx.compose.foundation.rememberScrollState
|
||||
import androidx.compose.foundation.verticalScroll
|
||||
import androidx.compose.material.icons.Icons
|
||||
import androidx.compose.material.icons.filled.Done
|
||||
import androidx.compose.material3.AlertDialog
|
||||
import androidx.compose.material3.Button
|
||||
import androidx.compose.material3.ExperimentalMaterial3Api
|
||||
import androidx.compose.material3.FilledTonalButton
|
||||
import androidx.compose.material3.Icon
|
||||
import androidx.compose.material3.MaterialTheme
|
||||
import androidx.compose.material3.Switch
|
||||
import androidx.compose.material3.Text
|
||||
import androidx.compose.material3.TopAppBar
|
||||
import androidx.compose.runtime.Composable
|
||||
import androidx.compose.runtime.LaunchedEffect
|
||||
import androidx.compose.runtime.collectAsState
|
||||
import androidx.compose.runtime.getValue
|
||||
import androidx.compose.runtime.mutableStateOf
|
||||
import androidx.compose.runtime.remember
|
||||
import androidx.compose.runtime.rememberCoroutineScope
|
||||
import androidx.compose.runtime.setValue
|
||||
import androidx.compose.ui.Alignment
|
||||
import androidx.compose.ui.Modifier
|
||||
import androidx.compose.ui.platform.LocalContext
|
||||
import androidx.compose.ui.unit.dp
|
||||
import de.timklge.karoowinddir.datatypes.GpsCoordinates
|
||||
import de.timklge.karoowinddir.getGpsCoordinateFlow
|
||||
import de.timklge.karoowinddir.saveSettings
|
||||
import de.timklge.karoowinddir.streamSettings
|
||||
import de.timklge.karoowinddir.streamStats
|
||||
import io.hammerhead.karooext.KarooSystemService
|
||||
import kotlinx.coroutines.launch
|
||||
import kotlinx.serialization.Serializable
|
||||
import kotlinx.serialization.encodeToString
|
||||
import kotlinx.serialization.json.Json
|
||||
import java.time.Instant
|
||||
import java.time.LocalDateTime
|
||||
import java.time.ZoneOffset
|
||||
import java.time.temporal.ChronoUnit
|
||||
import kotlin.math.roundToInt
|
||||
|
||||
enum class WindUnit(val id: String, val label: String, val unitDisplay: String){
|
||||
KILOMETERS_PER_HOUR("kmh", "Kilometers (km/h)", "km/h"),
|
||||
METERS_PER_SECOND("ms", "Meters (m/s)", "m/s"),
|
||||
MILES_PER_HOUR("mph", "Miles (mph)", "mph"),
|
||||
KNOTS("kn", "Knots (kn)", "kn")
|
||||
}
|
||||
|
||||
enum class PrecipitationUnit(val id: String, val label: String){
|
||||
MILLIMETERS("mm", "Millimeters (mm)"),
|
||||
INCH("inch", "Inch")
|
||||
}
|
||||
|
||||
@Serializable
|
||||
data class WinddirSettings(
|
||||
val windUnit: WindUnit = WindUnit.KILOMETERS_PER_HOUR,
|
||||
val precipitationUnit: PrecipitationUnit = PrecipitationUnit.MILLIMETERS,
|
||||
val welcomeDialogAccepted: Boolean = false,
|
||||
val showWindspeedOverlay: Boolean = true
|
||||
){
|
||||
companion object {
|
||||
val defaultSettings = Json.encodeToString(WinddirSettings())
|
||||
}
|
||||
}
|
||||
|
||||
@Serializable
|
||||
data class WinddirStats(
|
||||
val lastSuccessfulWeatherRequest: Long? = null,
|
||||
val lastSuccessfulWeatherPosition: GpsCoordinates? = null,
|
||||
val failedWeatherRequest: Long? = null,
|
||||
){
|
||||
companion object {
|
||||
val defaultStats = Json.encodeToString(WinddirStats())
|
||||
}
|
||||
}
|
||||
|
||||
@OptIn(ExperimentalMaterial3Api::class)
|
||||
@Composable
|
||||
fun MainScreen() {
|
||||
var karooConnected by remember { mutableStateOf(false) }
|
||||
val ctx = LocalContext.current
|
||||
val coroutineScope = rememberCoroutineScope()
|
||||
val karooSystem = remember { KarooSystemService(ctx) }
|
||||
|
||||
var selectedWindUnit by remember { mutableStateOf(WindUnit.KILOMETERS_PER_HOUR) }
|
||||
var selectedPrecipitationUnit by remember { mutableStateOf(PrecipitationUnit.MILLIMETERS) }
|
||||
var welcomeDialogVisible by remember { mutableStateOf(false) }
|
||||
var showWindspeedOverlay by remember { mutableStateOf(false) }
|
||||
|
||||
val stats by ctx.streamStats().collectAsState(WinddirStats())
|
||||
val location by karooSystem.getGpsCoordinateFlow().collectAsState(initial = null)
|
||||
|
||||
var savedDialogVisible by remember { mutableStateOf(false) }
|
||||
|
||||
LaunchedEffect(Unit) {
|
||||
ctx.streamSettings().collect { settings ->
|
||||
selectedWindUnit = settings.windUnit
|
||||
selectedPrecipitationUnit = settings.precipitationUnit
|
||||
welcomeDialogVisible = !settings.welcomeDialogAccepted
|
||||
showWindspeedOverlay = settings.showWindspeedOverlay
|
||||
}
|
||||
}
|
||||
|
||||
LaunchedEffect(Unit) {
|
||||
karooSystem.connect { connected ->
|
||||
karooConnected = connected
|
||||
}
|
||||
}
|
||||
|
||||
Column(modifier = Modifier
|
||||
.fillMaxSize()
|
||||
.background(MaterialTheme.colorScheme.background)) {
|
||||
TopAppBar(title = { Text("WindDir") })
|
||||
Column(modifier = Modifier
|
||||
.padding(5.dp)
|
||||
.verticalScroll(rememberScrollState())
|
||||
.fillMaxWidth(), verticalArrangement = Arrangement.spacedBy(10.dp)) {
|
||||
|
||||
val windSpeedUnitDropdownOptions = WindUnit.entries.toList().map { unit -> DropdownOption(unit.id, unit.label) }
|
||||
val windSpeedUnitInitialSelection = windSpeedUnitDropdownOptions.find { option -> option.id == selectedWindUnit.id }!!
|
||||
Dropdown(label = "Wind Speed Unit", options = windSpeedUnitDropdownOptions, initialSelection = windSpeedUnitInitialSelection) { selectedOption ->
|
||||
selectedWindUnit = WindUnit.entries.find { unit -> unit.id == selectedOption.id }!!
|
||||
}
|
||||
|
||||
val precipitationUnitDropdownOptions = PrecipitationUnit.entries.toList().map { unit -> DropdownOption(unit.id, unit.label) }
|
||||
val precipitationUnitInitialSelection = precipitationUnitDropdownOptions.find { option -> option.id == selectedPrecipitationUnit.id }!!
|
||||
Dropdown(label = "Precipitation Unit", options = precipitationUnitDropdownOptions, initialSelection = precipitationUnitInitialSelection) { selectedOption ->
|
||||
selectedPrecipitationUnit = PrecipitationUnit.entries.find { unit -> unit.id == selectedOption.id }!!
|
||||
}
|
||||
|
||||
Row(verticalAlignment = Alignment.CenterVertically) {
|
||||
Switch(checked = showWindspeedOverlay, onCheckedChange = { showWindspeedOverlay = it})
|
||||
Spacer(modifier = Modifier.width(10.dp))
|
||||
Text("Show wind speed on direction field")
|
||||
}
|
||||
|
||||
FilledTonalButton(modifier = Modifier
|
||||
.fillMaxWidth()
|
||||
.height(50.dp), onClick = {
|
||||
val newSettings = WinddirSettings(windUnit = selectedWindUnit, precipitationUnit = selectedPrecipitationUnit, welcomeDialogAccepted = true, showWindspeedOverlay = showWindspeedOverlay)
|
||||
|
||||
coroutineScope.launch {
|
||||
saveSettings(ctx, newSettings)
|
||||
savedDialogVisible = true
|
||||
}
|
||||
}) {
|
||||
Icon(Icons.Default.Done, contentDescription = "Save")
|
||||
Spacer(modifier = Modifier.width(5.dp))
|
||||
Text("Save")
|
||||
}
|
||||
|
||||
if (!karooConnected){
|
||||
Text(modifier = Modifier.padding(5.dp), text = "Could not read device status. Is your Karoo updated?")
|
||||
}
|
||||
|
||||
val lastPosition = location?.let { l -> stats.lastSuccessfulWeatherPosition?.distanceTo(l) }
|
||||
val lastPositionDistanceStr = lastPosition?.let { dist -> " (${dist.roundToInt()} km away)" } ?: ""
|
||||
|
||||
if (stats.failedWeatherRequest != null && (stats.lastSuccessfulWeatherRequest == null || stats.failedWeatherRequest!! > stats.lastSuccessfulWeatherRequest!!)){
|
||||
val localTime = LocalDateTime.ofInstant(Instant.ofEpochMilli(stats.failedWeatherRequest!!), ZoneOffset.systemDefault()).toLocalTime().truncatedTo(
|
||||
ChronoUnit.SECONDS)
|
||||
|
||||
val successStr = if(lastPosition != null) " Last data received at ${localTime}${lastPositionDistanceStr}." else ""
|
||||
Text(modifier = Modifier.padding(5.dp), text = "Failed to update weather data; last try at ${localTime}.${successStr}")
|
||||
} else if(stats.lastSuccessfulWeatherRequest != null){
|
||||
val localTime = LocalDateTime.ofInstant(Instant.ofEpochMilli(stats.lastSuccessfulWeatherRequest!!), ZoneOffset.systemDefault()).toLocalTime().truncatedTo(
|
||||
ChronoUnit.SECONDS)
|
||||
|
||||
Text(modifier = Modifier.padding(5.dp), text = "Last weather data received at ${localTime}${lastPositionDistanceStr}")
|
||||
} else {
|
||||
Text(modifier = Modifier.padding(5.dp), text = "No weather data received yet, waiting for GPS fix...")
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if (savedDialogVisible){
|
||||
AlertDialog(onDismissRequest = { savedDialogVisible = false },
|
||||
confirmButton = { Button(onClick = {
|
||||
savedDialogVisible = false
|
||||
}) { Text("OK") } },
|
||||
text = { Text("Settings saved successfully.") }
|
||||
)
|
||||
}
|
||||
|
||||
if (welcomeDialogVisible){
|
||||
AlertDialog(onDismissRequest = { },
|
||||
confirmButton = { Button(onClick = {
|
||||
coroutineScope.launch {
|
||||
saveSettings(ctx, WinddirSettings(windUnit = selectedWindUnit, precipitationUnit = selectedPrecipitationUnit, welcomeDialogAccepted = true))
|
||||
}
|
||||
}) { Text("OK") } },
|
||||
text = {
|
||||
Column(modifier = Modifier.verticalScroll(rememberScrollState())) {
|
||||
Text("Welcome to karoo-winddir!")
|
||||
|
||||
Spacer(Modifier.padding(10.dp))
|
||||
|
||||
Text("You can add relative wind direction and other fields to your data pages in your profile settings.")
|
||||
|
||||
Spacer(Modifier.padding(10.dp))
|
||||
|
||||
Text("Please note that this app periodically fetches data from the Open-Meteo API to know the current weather at your approximate location.")
|
||||
}
|
||||
}
|
||||
)
|
||||
}
|
||||
}
|
||||
13
app/src/main/kotlin/de/timklge/karoowinddir/theme/Theme.kt
Normal file
@ -0,0 +1,13 @@
|
||||
package de.timklge.karoowinddir.theme
|
||||
|
||||
import androidx.compose.material3.MaterialTheme
|
||||
import androidx.compose.runtime.Composable
|
||||
|
||||
@Composable
|
||||
fun AppTheme(
|
||||
content: @Composable () -> Unit,
|
||||
) {
|
||||
MaterialTheme(
|
||||
content = content,
|
||||
)
|
||||
}
|
||||
BIN
app/src/main/res/drawable-hdpi/ic_cloud.png
Normal file
|
After Width: | Height: | Size: 613 B |
BIN
app/src/main/res/drawable-hdpi/ic_launcher.png
Normal file
|
After Width: | Height: | Size: 617 B |
BIN
app/src/main/res/drawable-hdpi/ic_water.png
Normal file
|
After Width: | Height: | Size: 458 B |
BIN
app/src/main/res/drawable-mdpi/ic_cloud.png
Normal file
|
After Width: | Height: | Size: 386 B |
BIN
app/src/main/res/drawable-mdpi/ic_launcher.png
Normal file
|
After Width: | Height: | Size: 316 B |
BIN
app/src/main/res/drawable-mdpi/ic_water.png
Normal file
|
After Width: | Height: | Size: 199 B |
BIN
app/src/main/res/drawable-xhdpi/ic_cloud.png
Normal file
|
After Width: | Height: | Size: 756 B |
BIN
app/src/main/res/drawable-xhdpi/ic_launcher.png
Normal file
|
After Width: | Height: | Size: 666 B |
BIN
app/src/main/res/drawable-xhdpi/ic_water.png
Normal file
|
After Width: | Height: | Size: 432 B |
BIN
app/src/main/res/drawable-xxhdpi/ic_cloud.png
Normal file
|
After Width: | Height: | Size: 1.2 KiB |
BIN
app/src/main/res/drawable-xxhdpi/ic_launcher.png
Normal file
|
After Width: | Height: | Size: 1.1 KiB |
BIN
app/src/main/res/drawable-xxhdpi/ic_water.png
Normal file
|
After Width: | Height: | Size: 724 B |
BIN
app/src/main/res/drawable-xxxhdpi/ic_cloud.png
Normal file
|
After Width: | Height: | Size: 1.7 KiB |
BIN
app/src/main/res/drawable-xxxhdpi/ic_launcher.png
Normal file
|
After Width: | Height: | Size: 1.5 KiB |
BIN
app/src/main/res/drawable-xxxhdpi/ic_water.png
Normal file
|
After Width: | Height: | Size: 996 B |
BIN
app/src/main/res/drawable/arrow_0.png
Normal file
|
After Width: | Height: | Size: 980 B |
BIN
app/src/main/res/drawable/arrow_1.png
Normal file
|
After Width: | Height: | Size: 3.0 KiB |
BIN
app/src/main/res/drawable/arrow_10.png
Normal file
|
After Width: | Height: | Size: 2.8 KiB |
BIN
app/src/main/res/drawable/arrow_11.png
Normal file
|
After Width: | Height: | Size: 3.0 KiB |
BIN
app/src/main/res/drawable/arrow_2.png
Normal file
|
After Width: | Height: | Size: 2.9 KiB |
BIN
app/src/main/res/drawable/arrow_3.png
Normal file
|
After Width: | Height: | Size: 749 B |
BIN
app/src/main/res/drawable/arrow_4.png
Normal file
|
After Width: | Height: | Size: 2.8 KiB |
BIN
app/src/main/res/drawable/arrow_5.png
Normal file
|
After Width: | Height: | Size: 3.1 KiB |
BIN
app/src/main/res/drawable/arrow_6.png
Normal file
|
After Width: | Height: | Size: 943 B |
BIN
app/src/main/res/drawable/arrow_7.png
Normal file
|
After Width: | Height: | Size: 3.0 KiB |
BIN
app/src/main/res/drawable/arrow_8.png
Normal file
|
After Width: | Height: | Size: 2.9 KiB |
BIN
app/src/main/res/drawable/arrow_9.png
Normal file
|
After Width: | Height: | Size: 758 B |
5
app/src/main/res/mipmap-anydpi-v26/ic_launcher.xml
Normal file
@ -0,0 +1,5 @@
|
||||
<?xml version="1.0" encoding="utf-8"?>
|
||||
<adaptive-icon xmlns:android="http://schemas.android.com/apk/res/android">
|
||||
<background android:drawable="@color/ic_launcher_background"/>
|
||||
<foreground android:drawable="@mipmap/ic_launcher_foreground"/>
|
||||
</adaptive-icon>
|
||||
5
app/src/main/res/mipmap-anydpi-v26/ic_launcher_round.xml
Normal file
@ -0,0 +1,5 @@
|
||||
<?xml version="1.0" encoding="utf-8"?>
|
||||
<adaptive-icon xmlns:android="http://schemas.android.com/apk/res/android">
|
||||
<background android:drawable="@color/ic_launcher_background"/>
|
||||
<foreground android:drawable="@mipmap/ic_launcher_foreground"/>
|
||||
</adaptive-icon>
|
||||
BIN
app/src/main/res/mipmap-hdpi/ic_launcher.webp
Normal file
|
After Width: | Height: | Size: 844 B |
BIN
app/src/main/res/mipmap-hdpi/ic_launcher_foreground.webp
Normal file
|
After Width: | Height: | Size: 824 B |
BIN
app/src/main/res/mipmap-hdpi/ic_launcher_round.webp
Normal file
|
After Width: | Height: | Size: 1.7 KiB |
BIN
app/src/main/res/mipmap-mdpi/ic_launcher.webp
Normal file
|
After Width: | Height: | Size: 608 B |
BIN
app/src/main/res/mipmap-mdpi/ic_launcher_foreground.webp
Normal file
|
After Width: | Height: | Size: 534 B |
BIN
app/src/main/res/mipmap-mdpi/ic_launcher_round.webp
Normal file
|
After Width: | Height: | Size: 1.1 KiB |
BIN
app/src/main/res/mipmap-xhdpi/ic_launcher.webp
Normal file
|
After Width: | Height: | Size: 1.0 KiB |
BIN
app/src/main/res/mipmap-xhdpi/ic_launcher_foreground.webp
Normal file
|
After Width: | Height: | Size: 1.1 KiB |
BIN
app/src/main/res/mipmap-xhdpi/ic_launcher_round.webp
Normal file
|
After Width: | Height: | Size: 2.3 KiB |
BIN
app/src/main/res/mipmap-xxhdpi/ic_launcher.webp
Normal file
|
After Width: | Height: | Size: 1.5 KiB |
BIN
app/src/main/res/mipmap-xxhdpi/ic_launcher_foreground.webp
Normal file
|
After Width: | Height: | Size: 1.8 KiB |
BIN
app/src/main/res/mipmap-xxhdpi/ic_launcher_round.webp
Normal file
|
After Width: | Height: | Size: 3.6 KiB |
BIN
app/src/main/res/mipmap-xxxhdpi/ic_launcher.webp
Normal file
|
After Width: | Height: | Size: 2.1 KiB |
BIN
app/src/main/res/mipmap-xxxhdpi/ic_launcher_foreground.webp
Normal file
|
After Width: | Height: | Size: 2.6 KiB |
BIN
app/src/main/res/mipmap-xxxhdpi/ic_launcher_round.webp
Normal file
|
After Width: | Height: | Size: 5.3 KiB |
7
app/src/main/res/values/colors.xml
Normal file
@ -0,0 +1,7 @@
|
||||
<?xml version="1.0" encoding="utf-8"?>
|
||||
<resources>
|
||||
<color name="colorPrimary">#6200EE</color>
|
||||
<color name="colorPrimaryDark">#2600B3</color>
|
||||
|
||||
<color name="white">#ffffff</color>
|
||||
</resources>
|
||||
4
app/src/main/res/values/ic_launcher_background.xml
Normal file
@ -0,0 +1,4 @@
|
||||
<?xml version="1.0" encoding="utf-8"?>
|
||||
<resources>
|
||||
<color name="ic_launcher_background">#000000</color>
|
||||
</resources>
|
||||
20
app/src/main/res/values/strings.xml
Normal file
@ -0,0 +1,20 @@
|
||||
<resources>
|
||||
<string name="app_name">Winddir</string>
|
||||
<string name="extension_name">winddir</string>
|
||||
<string name="winddir">Wind direction</string>
|
||||
<string name="winddir_description">Current wind direction relative to the riding direction</string>
|
||||
<string name="relativeHumidity">Humidity</string>
|
||||
<string name="relativeHumidity_description">Relative humidity in percent</string>
|
||||
<string name="cloudCover">Cloud cover</string>
|
||||
<string name="cloudCover_description">Current cloud cover in percent</string>
|
||||
<string name="windSpeed">Wind speed</string>
|
||||
<string name="windSpeed_description">Current wind speed in configured unit</string>
|
||||
<string name="windGusts">Wind gusts</string>
|
||||
<string name="windGusts_description">Current wind gust speed in configured unit</string>
|
||||
<string name="windDirection">Absolute wind direction</string>
|
||||
<string name="windDirection_description">Current wind direction</string>
|
||||
<string name="precipitation">Rainfall</string>
|
||||
<string name="precipitation_description">Current precipitation (rainfall / snowfall)</string>
|
||||
<string name="surfacePressure">Surface pressure</string>
|
||||
<string name="surfacePressure_description">Atmospheric pressure at surface in configured unit</string>
|
||||
</resources>
|
||||
62
app/src/main/res/xml/extension_info.xml
Normal file
@ -0,0 +1,62 @@
|
||||
<?xml version="1.0" encoding="utf-8"?>
|
||||
<ExtensionInfo
|
||||
displayName="@string/extension_name"
|
||||
icon="@drawable/ic_launcher"
|
||||
id="karoo-winddir"
|
||||
scansDevices="false">
|
||||
<DataType
|
||||
description="@string/winddir_description"
|
||||
displayName="@string/winddir"
|
||||
graphical="true"
|
||||
icon="@drawable/ic_launcher"
|
||||
typeId="winddir" />
|
||||
|
||||
<DataType
|
||||
description="@string/relativeHumidity_description"
|
||||
displayName="@string/relativeHumidity"
|
||||
graphical="false"
|
||||
icon="@drawable/ic_water"
|
||||
typeId="relativeHumidity" />
|
||||
|
||||
<DataType
|
||||
description="@string/cloudCover_description"
|
||||
displayName="@string/cloudCover"
|
||||
graphical="false"
|
||||
icon="@drawable/ic_cloud"
|
||||
typeId="cloudCover" />
|
||||
|
||||
<DataType
|
||||
description="@string/windSpeed_description"
|
||||
displayName="@string/windSpeed"
|
||||
graphical="false"
|
||||
icon="@drawable/ic_launcher"
|
||||
typeId="windSpeed" />
|
||||
|
||||
<DataType
|
||||
description="@string/windGusts_description"
|
||||
displayName="@string/windGusts"
|
||||
graphical="false"
|
||||
icon="@drawable/ic_launcher"
|
||||
typeId="windGusts" />
|
||||
|
||||
<DataType
|
||||
description="@string/windDirection_description"
|
||||
displayName="@string/windDirection"
|
||||
graphical="true"
|
||||
icon="@drawable/ic_launcher"
|
||||
typeId="windDirection" />
|
||||
|
||||
<DataType
|
||||
description="@string/precipitation_description"
|
||||
displayName="@string/precipitation"
|
||||
graphical="false"
|
||||
icon="@drawable/ic_water"
|
||||
typeId="precipitation" />
|
||||
|
||||
<DataType
|
||||
description="@string/surfacePressure_description"
|
||||
displayName="@string/surfacePressure"
|
||||
graphical="false"
|
||||
icon="@drawable/ic_cloud"
|
||||
typeId="surfacePressure" />
|
||||
</ExtensionInfo>
|
||||
6
build.gradle.kts
Normal file
@ -0,0 +1,6 @@
|
||||
// Top-level build file where you can add configuration options common to all sub-projects/modules.
|
||||
plugins {
|
||||
alias(libs.plugins.android.application) apply false
|
||||
alias(libs.plugins.jetbrains.kotlin.android) apply false
|
||||
alias(libs.plugins.compose.compiler) apply false
|
||||
}
|
||||
23
gradle.properties
Normal file
@ -0,0 +1,23 @@
|
||||
# Project-wide Gradle settings.
|
||||
# IDE (e.g. Android Studio) users:
|
||||
# Gradle settings configured through the IDE *will override*
|
||||
# any settings specified in this file.
|
||||
# For more details on how to configure your build environment visit
|
||||
# http://www.gradle.org/docs/current/userguide/build_environment.html
|
||||
# Specifies the JVM arguments used for the daemon process.
|
||||
# The setting is particularly useful for tweaking memory settings.
|
||||
org.gradle.jvmargs=-Xmx2048m -Dfile.encoding=UTF-8
|
||||
# When configured, Gradle will run in incubating parallel mode.
|
||||
# This option should only be used with decoupled projects. More details, visit
|
||||
# http://www.gradle.org/docs/current/userguide/multi_project_builds.html#sec:decoupled_projects
|
||||
# org.gradle.parallel=true
|
||||
# AndroidX package structure to make it clearer which packages are bundled with the
|
||||
# Android operating system, and which are packaged with your app"s APK
|
||||
# https://developer.android.com/topic/libraries/support-library/androidx-rn
|
||||
android.useAndroidX=true
|
||||
# Kotlin code style for this project: "official" or "obsolete":
|
||||
kotlin.code.style=official
|
||||
# Enables namespacing of each library's R class so that its R class includes only the
|
||||
# resources declared in the library itself and none from the library's dependencies,
|
||||
# thereby reducing the size of the R class for that library
|
||||
android.nonTransitiveRClass=true
|
||||
49
gradle/libs.versions.toml
Normal file
@ -0,0 +1,49 @@
|
||||
[versions]
|
||||
agp = "8.5.0"
|
||||
color = "1.3.0"
|
||||
datastorePreferences = "1.1.1"
|
||||
kotlin = "2.0.0"
|
||||
|
||||
androidxCore = "1.13.1"
|
||||
androidxLifecycle = "2.8.6"
|
||||
androidxActivity = "1.9.3"
|
||||
androidxComposeUi = "1.7.4"
|
||||
androidxComposeMaterial = "1.3.0"
|
||||
glance = "1.1.1"
|
||||
kotlinxDatetime = "0.6.1"
|
||||
kotlinxSerializationJson = "1.7.3"
|
||||
navigationRuntimeKtx = "2.8.4"
|
||||
navigationCompose = "2.8.4"
|
||||
|
||||
[plugins]
|
||||
android-application = { id = "com.android.application", version.ref = "agp" }
|
||||
jetbrains-kotlin-android = { id = "org.jetbrains.kotlin.android", version.ref = "kotlin" }
|
||||
compose-compiler = { id = "org.jetbrains.kotlin.plugin.compose", version.ref = "kotlin" }
|
||||
|
||||
[libraries]
|
||||
androidx-datastore-preferences = { module = "androidx.datastore:datastore-preferences", version.ref = "datastorePreferences" }
|
||||
hammerhead-karoo-ext = { group = "io.hammerhead", name = "karoo-ext", version = "1.1.1" }
|
||||
|
||||
androidx-core-ktx = { module = "androidx.core:core-ktx", version.ref = "androidxCore" }
|
||||
|
||||
# compose
|
||||
androidx-lifecycle-runtime-compose = { module = "androidx.lifecycle:lifecycle-runtime-compose", version.ref = "androidxLifecycle" }
|
||||
androidx-lifecycle-viewmodel-compose = { module = "androidx.lifecycle:lifecycle-viewmodel-compose", version.ref = "androidxLifecycle" }
|
||||
|
||||
androidx-activity-compose = { module = "androidx.activity:activity-compose", version.ref = "androidxActivity" }
|
||||
androidx-compose-ui = { module = "androidx.compose.ui:ui", version.ref = "androidxComposeUi" }
|
||||
androidx-compose-ui-tooling-preview = { module = "androidx.compose.ui:ui-tooling-preview", version.ref = "androidxComposeUi" }
|
||||
androidx-compose-ui-tooling = { module = "androidx.compose.ui:ui-tooling", version.ref = "androidxComposeUi" }
|
||||
androidx-compose-material = { module = "androidx.compose.material3:material3", version.ref = "androidxComposeMaterial" }
|
||||
|
||||
# Glance
|
||||
androidx-glance-appwidget = { group = "androidx.glance", name = "glance-appwidget", version.ref = "glance" }
|
||||
androidx-glance-appwidget-preview = { group = "androidx.glance", name = "glance-appwidget-preview", version.ref = "glance" }
|
||||
androidx-glance-preview = { group = "androidx.glance", name = "glance-preview", version.ref = "glance" }
|
||||
androidx-navigation-runtime-ktx = { group = "androidx.navigation", name = "navigation-runtime-ktx", version.ref = "navigationRuntimeKtx" }
|
||||
androidx-navigation-compose = { group = "androidx.navigation", name = "navigation-compose", version.ref = "navigationCompose" }
|
||||
kotlinx-serialization-json = { module = "org.jetbrains.kotlinx:kotlinx-serialization-json", version.ref = "kotlinxSerializationJson" }
|
||||
|
||||
[bundles]
|
||||
androidx-lifeycle = ["androidx-lifecycle-runtime-compose", "androidx-lifecycle-viewmodel-compose"]
|
||||
compose-ui = ["androidx-compose-ui", "androidx-compose-material", "androidx-compose-ui-tooling-preview", "androidx-compose-ui-tooling"]
|
||||
BIN
gradle/wrapper/gradle-wrapper.jar
vendored
Normal file
6
gradle/wrapper/gradle-wrapper.properties
vendored
Normal file
@ -0,0 +1,6 @@
|
||||
distributionBase=GRADLE_USER_HOME
|
||||
distributionPath=wrapper/dists
|
||||
distributionUrl=https\://services.gradle.org/distributions/gradle-8.7-bin.zip
|
||||
networkTimeout=10000
|
||||
zipStoreBase=GRADLE_USER_HOME
|
||||
zipStorePath=wrapper/dists
|
||||
244
gradlew
vendored
Executable file
@ -0,0 +1,244 @@
|
||||
#!/bin/sh
|
||||
|
||||
#
|
||||
# Copyright © 2015-2021 the original authors.
|
||||
#
|
||||
# Licensed under the Apache License, Version 2.0 (the "License");
|
||||
# you may not use this file except in compliance with the License.
|
||||
# You may obtain a copy of the License at
|
||||
#
|
||||
# https://www.apache.org/licenses/LICENSE-2.0
|
||||
#
|
||||
# Unless required by applicable law or agreed to in writing, software
|
||||
# distributed under the License is distributed on an "AS IS" BASIS,
|
||||
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
# See the License for the specific language governing permissions and
|
||||
# limitations under the License.
|
||||
#
|
||||
|
||||
##############################################################################
|
||||
#
|
||||
# Gradle start up script for POSIX generated by Gradle.
|
||||
#
|
||||
# Important for running:
|
||||
#
|
||||
# (1) You need a POSIX-compliant shell to run this script. If your /bin/sh is
|
||||
# noncompliant, but you have some other compliant shell such as ksh or
|
||||
# bash, then to run this script, type that shell name before the whole
|
||||
# command line, like:
|
||||
#
|
||||
# ksh Gradle
|
||||
#
|
||||
# Busybox and similar reduced shells will NOT work, because this script
|
||||
# requires all of these POSIX shell features:
|
||||
# * functions;
|
||||
# * expansions «$var», «${var}», «${var:-default}», «${var+SET}»,
|
||||
# «${var#prefix}», «${var%suffix}», and «$( cmd )»;
|
||||
# * compound commands having a testable exit status, especially «case»;
|
||||
# * various built-in commands including «command», «set», and «ulimit».
|
||||
#
|
||||
# Important for patching:
|
||||
#
|
||||
# (2) This script targets any POSIX shell, so it avoids extensions provided
|
||||
# by Bash, Ksh, etc; in particular arrays are avoided.
|
||||
#
|
||||
# The "traditional" practice of packing multiple parameters into a
|
||||
# space-separated string is a well documented source of bugs and security
|
||||
# problems, so this is (mostly) avoided, by progressively accumulating
|
||||
# options in "$@", and eventually passing that to Java.
|
||||
#
|
||||
# Where the inherited environment variables (DEFAULT_JVM_OPTS, JAVA_OPTS,
|
||||
# and GRADLE_OPTS) rely on word-splitting, this is performed explicitly;
|
||||
# see the in-line comments for details.
|
||||
#
|
||||
# There are tweaks for specific operating systems such as AIX, CygWin,
|
||||
# Darwin, MinGW, and NonStop.
|
||||
#
|
||||
# (3) This script is generated from the Groovy template
|
||||
# https://github.com/gradle/gradle/blob/HEAD/subprojects/plugins/src/main/resources/org/gradle/api/internal/plugins/unixStartScript.txt
|
||||
# within the Gradle project.
|
||||
#
|
||||
# You can find Gradle at https://github.com/gradle/gradle/.
|
||||
#
|
||||
##############################################################################
|
||||
|
||||
# Attempt to set APP_HOME
|
||||
|
||||
# Resolve links: $0 may be a link
|
||||
app_path=$0
|
||||
|
||||
# Need this for daisy-chained symlinks.
|
||||
while
|
||||
APP_HOME=${app_path%"${app_path##*/}"} # leaves a trailing /; empty if no leading path
|
||||
[ -h "$app_path" ]
|
||||
do
|
||||
ls=$( ls -ld "$app_path" )
|
||||
link=${ls#*' -> '}
|
||||
case $link in #(
|
||||
/*) app_path=$link ;; #(
|
||||
*) app_path=$APP_HOME$link ;;
|
||||
esac
|
||||
done
|
||||
|
||||
# This is normally unused
|
||||
# shellcheck disable=SC2034
|
||||
APP_BASE_NAME=${0##*/}
|
||||
APP_HOME=$( cd "${APP_HOME:-./}" && pwd -P ) || exit
|
||||
|
||||
# Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script.
|
||||
DEFAULT_JVM_OPTS='"-Xmx64m" "-Xms64m"'
|
||||
|
||||
# Use the maximum available, or set MAX_FD != -1 to use that value.
|
||||
MAX_FD=maximum
|
||||
|
||||
warn () {
|
||||
echo "$*"
|
||||
} >&2
|
||||
|
||||
die () {
|
||||
echo
|
||||
echo "$*"
|
||||
echo
|
||||
exit 1
|
||||
} >&2
|
||||
|
||||
# OS specific support (must be 'true' or 'false').
|
||||
cygwin=false
|
||||
msys=false
|
||||
darwin=false
|
||||
nonstop=false
|
||||
case "$( uname )" in #(
|
||||
CYGWIN* ) cygwin=true ;; #(
|
||||
Darwin* ) darwin=true ;; #(
|
||||
MSYS* | MINGW* ) msys=true ;; #(
|
||||
NONSTOP* ) nonstop=true ;;
|
||||
esac
|
||||
|
||||
CLASSPATH=$APP_HOME/gradle/wrapper/gradle-wrapper.jar
|
||||
|
||||
|
||||
# Determine the Java command to use to start the JVM.
|
||||
if [ -n "$JAVA_HOME" ] ; then
|
||||
if [ -x "$JAVA_HOME/jre/sh/java" ] ; then
|
||||
# IBM's JDK on AIX uses strange locations for the executables
|
||||
JAVACMD=$JAVA_HOME/jre/sh/java
|
||||
else
|
||||
JAVACMD=$JAVA_HOME/bin/java
|
||||
fi
|
||||
if [ ! -x "$JAVACMD" ] ; then
|
||||
die "ERROR: JAVA_HOME is set to an invalid directory: $JAVA_HOME
|
||||
|
||||
Please set the JAVA_HOME variable in your environment to match the
|
||||
location of your Java installation."
|
||||
fi
|
||||
else
|
||||
JAVACMD=java
|
||||
which java >/dev/null 2>&1 || die "ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH.
|
||||
|
||||
Please set the JAVA_HOME variable in your environment to match the
|
||||
location of your Java installation."
|
||||
fi
|
||||
|
||||
# Increase the maximum file descriptors if we can.
|
||||
if ! "$cygwin" && ! "$darwin" && ! "$nonstop" ; then
|
||||
case $MAX_FD in #(
|
||||
max*)
|
||||
# In POSIX sh, ulimit -H is undefined. That's why the result is checked to see if it worked.
|
||||
# shellcheck disable=SC3045
|
||||
MAX_FD=$( ulimit -H -n ) ||
|
||||
warn "Could not query maximum file descriptor limit"
|
||||
esac
|
||||
case $MAX_FD in #(
|
||||
'' | soft) :;; #(
|
||||
*)
|
||||
# In POSIX sh, ulimit -n is undefined. That's why the result is checked to see if it worked.
|
||||
# shellcheck disable=SC3045
|
||||
ulimit -n "$MAX_FD" ||
|
||||
warn "Could not set maximum file descriptor limit to $MAX_FD"
|
||||
esac
|
||||
fi
|
||||
|
||||
# Collect all arguments for the java command, stacking in reverse order:
|
||||
# * args from the command line
|
||||
# * the main class name
|
||||
# * -classpath
|
||||
# * -D...appname settings
|
||||
# * --module-path (only if needed)
|
||||
# * DEFAULT_JVM_OPTS, JAVA_OPTS, and GRADLE_OPTS environment variables.
|
||||
|
||||
# For Cygwin or MSYS, switch paths to Windows format before running java
|
||||
if "$cygwin" || "$msys" ; then
|
||||
APP_HOME=$( cygpath --path --mixed "$APP_HOME" )
|
||||
CLASSPATH=$( cygpath --path --mixed "$CLASSPATH" )
|
||||
|
||||
JAVACMD=$( cygpath --unix "$JAVACMD" )
|
||||
|
||||
# Now convert the arguments - kludge to limit ourselves to /bin/sh
|
||||
for arg do
|
||||
if
|
||||
case $arg in #(
|
||||
-*) false ;; # don't mess with options #(
|
||||
/?*) t=${arg#/} t=/${t%%/*} # looks like a POSIX filepath
|
||||
[ -e "$t" ] ;; #(
|
||||
*) false ;;
|
||||
esac
|
||||
then
|
||||
arg=$( cygpath --path --ignore --mixed "$arg" )
|
||||
fi
|
||||
# Roll the args list around exactly as many times as the number of
|
||||
# args, so each arg winds up back in the position where it started, but
|
||||
# possibly modified.
|
||||
#
|
||||
# NB: a `for` loop captures its iteration list before it begins, so
|
||||
# changing the positional parameters here affects neither the number of
|
||||
# iterations, nor the values presented in `arg`.
|
||||
shift # remove old arg
|
||||
set -- "$@" "$arg" # push replacement arg
|
||||
done
|
||||
fi
|
||||
|
||||
# Collect all arguments for the java command;
|
||||
# * $DEFAULT_JVM_OPTS, $JAVA_OPTS, and $GRADLE_OPTS can contain fragments of
|
||||
# shell script including quotes and variable substitutions, so put them in
|
||||
# double quotes to make sure that they get re-expanded; and
|
||||
# * put everything else in single quotes, so that it's not re-expanded.
|
||||
|
||||
set -- \
|
||||
"-Dorg.gradle.appname=$APP_BASE_NAME" \
|
||||
-classpath "$CLASSPATH" \
|
||||
org.gradle.wrapper.GradleWrapperMain \
|
||||
"$@"
|
||||
|
||||
# Stop when "xargs" is not available.
|
||||
if ! command -v xargs >/dev/null 2>&1
|
||||
then
|
||||
die "xargs is not available"
|
||||
fi
|
||||
|
||||
# Use "xargs" to parse quoted args.
|
||||
#
|
||||
# With -n1 it outputs one arg per line, with the quotes and backslashes removed.
|
||||
#
|
||||
# In Bash we could simply go:
|
||||
#
|
||||
# readarray ARGS < <( xargs -n1 <<<"$var" ) &&
|
||||
# set -- "${ARGS[@]}" "$@"
|
||||
#
|
||||
# but POSIX shell has neither arrays nor command substitution, so instead we
|
||||
# post-process each arg (as a line of input to sed) to backslash-escape any
|
||||
# character that might be a shell metacharacter, then use eval to reverse
|
||||
# that process (while maintaining the separation between arguments), and wrap
|
||||
# the whole thing up as a single "set" statement.
|
||||
#
|
||||
# This will of course break if any of these variables contains a newline or
|
||||
# an unmatched quote.
|
||||
#
|
||||
|
||||
eval "set -- $(
|
||||
printf '%s\n' "$DEFAULT_JVM_OPTS $JAVA_OPTS $GRADLE_OPTS" |
|
||||
xargs -n1 |
|
||||
sed ' s~[^-[:alnum:]+,./:=@_]~\\&~g; ' |
|
||||
tr '\n' ' '
|
||||
)" '"$@"'
|
||||
|
||||
exec "$JAVACMD" "$@"
|
||||
92
gradlew.bat
vendored
Normal file
@ -0,0 +1,92 @@
|
||||
@rem
|
||||
@rem Copyright 2015 the original author or authors.
|
||||
@rem
|
||||
@rem Licensed under the Apache License, Version 2.0 (the "License");
|
||||
@rem you may not use this file except in compliance with the License.
|
||||
@rem You may obtain a copy of the License at
|
||||
@rem
|
||||
@rem https://www.apache.org/licenses/LICENSE-2.0
|
||||
@rem
|
||||
@rem Unless required by applicable law or agreed to in writing, software
|
||||
@rem distributed under the License is distributed on an "AS IS" BASIS,
|
||||
@rem WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
@rem See the License for the specific language governing permissions and
|
||||
@rem limitations under the License.
|
||||
@rem
|
||||
|
||||
@if "%DEBUG%"=="" @echo off
|
||||
@rem ##########################################################################
|
||||
@rem
|
||||
@rem Gradle startup script for Windows
|
||||
@rem
|
||||
@rem ##########################################################################
|
||||
|
||||
@rem Set local scope for the variables with windows NT shell
|
||||
if "%OS%"=="Windows_NT" setlocal
|
||||
|
||||
set DIRNAME=%~dp0
|
||||
if "%DIRNAME%"=="" set DIRNAME=.
|
||||
@rem This is normally unused
|
||||
set APP_BASE_NAME=%~n0
|
||||
set APP_HOME=%DIRNAME%
|
||||
|
||||
@rem Resolve any "." and ".." in APP_HOME to make it shorter.
|
||||
for %%i in ("%APP_HOME%") do set APP_HOME=%%~fi
|
||||
|
||||
@rem Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script.
|
||||
set DEFAULT_JVM_OPTS="-Xmx64m" "-Xms64m"
|
||||
|
||||
@rem Find java.exe
|
||||
if defined JAVA_HOME goto findJavaFromJavaHome
|
||||
|
||||
set JAVA_EXE=java.exe
|
||||
%JAVA_EXE% -version >NUL 2>&1
|
||||
if %ERRORLEVEL% equ 0 goto execute
|
||||
|
||||
echo.
|
||||
echo ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH.
|
||||
echo.
|
||||
echo Please set the JAVA_HOME variable in your environment to match the
|
||||
echo location of your Java installation.
|
||||
|
||||
goto fail
|
||||
|
||||
:findJavaFromJavaHome
|
||||
set JAVA_HOME=%JAVA_HOME:"=%
|
||||
set JAVA_EXE=%JAVA_HOME%/bin/java.exe
|
||||
|
||||
if exist "%JAVA_EXE%" goto execute
|
||||
|
||||
echo.
|
||||
echo ERROR: JAVA_HOME is set to an invalid directory: %JAVA_HOME%
|
||||
echo.
|
||||
echo Please set the JAVA_HOME variable in your environment to match the
|
||||
echo location of your Java installation.
|
||||
|
||||
goto fail
|
||||
|
||||
:execute
|
||||
@rem Setup the command line
|
||||
|
||||
set CLASSPATH=%APP_HOME%\gradle\wrapper\gradle-wrapper.jar
|
||||
|
||||
|
||||
@rem Execute Gradle
|
||||
"%JAVA_EXE%" %DEFAULT_JVM_OPTS% %JAVA_OPTS% %GRADLE_OPTS% "-Dorg.gradle.appname=%APP_BASE_NAME%" -classpath "%CLASSPATH%" org.gradle.wrapper.GradleWrapperMain %*
|
||||
|
||||
:end
|
||||
@rem End local scope for the variables with windows NT shell
|
||||
if %ERRORLEVEL% equ 0 goto mainEnd
|
||||
|
||||
:fail
|
||||
rem Set variable GRADLE_EXIT_CONSOLE if you need the _script_ return code instead of
|
||||
rem the _cmd.exe /c_ return code!
|
||||
set EXIT_CODE=%ERRORLEVEL%
|
||||
if %EXIT_CODE% equ 0 set EXIT_CODE=1
|
||||
if not ""=="%GRADLE_EXIT_CONSOLE%" exit %EXIT_CODE%
|
||||
exit /b %EXIT_CODE%
|
||||
|
||||
:mainEnd
|
||||
if "%OS%"=="Windows_NT" endlocal
|
||||
|
||||
:omega
|
||||
BIN
preview0.png
Normal file
|
After Width: | Height: | Size: 71 KiB |
BIN
preview1.png
Normal file
|
After Width: | Height: | Size: 42 KiB |
BIN
preview2.png
Normal file
|
After Width: | Height: | Size: 37 KiB |
BIN
preview3.png
Normal file
|
After Width: | Height: | Size: 45 KiB |
38
settings.gradle.kts
Normal file
@ -0,0 +1,38 @@
|
||||
fun getLocalProperty(key: String, file: String = "local.properties"): String? {
|
||||
val properties = java.util.Properties()
|
||||
val localProperties = File(file)
|
||||
if (localProperties.isFile) {
|
||||
java.io.InputStreamReader(java.io.FileInputStream(localProperties), Charsets.UTF_8).use { reader ->
|
||||
properties.load(reader)
|
||||
}
|
||||
} else error("File from not found")
|
||||
|
||||
return properties.getProperty(key)
|
||||
}
|
||||
pluginManagement {
|
||||
repositories {
|
||||
gradlePluginPortal()
|
||||
google()
|
||||
mavenCentral()
|
||||
}
|
||||
}
|
||||
val gprUser = getLocalProperty("gpr.user")
|
||||
val gprKey = getLocalProperty("gpr.key")
|
||||
dependencyResolutionManagement {
|
||||
repositoriesMode.set(RepositoriesMode.FAIL_ON_PROJECT_REPOS)
|
||||
repositories {
|
||||
google()
|
||||
mavenCentral()
|
||||
// karoo-ext from Github Packages
|
||||
maven {
|
||||
url = uri("https://maven.pkg.github.com/hammerheadnav/karoo-ext")
|
||||
credentials {
|
||||
username = gprUser
|
||||
password = gprKey
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
rootProject.name = "Karoo Winddir"
|
||||
include("app")
|
||||