21 Commits
Author SHA1 Message Date
Marcus Handte 4d21dea4cd Release 1.0.29
LocationBasedServices/mowesta/pipeline/head This commit looks good
2022-11-11 11:46:36 +01:00
Marcus Handte e4603a231e Add obfuscator for data release.
LocationBasedServices/mowesta/pipeline/head This commit looks good
2022-11-08 08:30:51 +01:00
Marcus Handte 316df58af6 Added docs for data release.
LocationBasedServices/mowesta/pipeline/head This commit looks good
2022-11-08 08:28:33 +01:00
Marcus Handte 35516af52b Update to 1.0.29-SNAPSHOT
LocationBasedServices/mowesta/pipeline/head This commit looks good
2022-11-03 17:35:44 +01:00
Marcus Handte 3bded2af7a Release 1.0.28
LocationBasedServices/mowesta/pipeline/head This commit looks good
2022-11-03 17:12:48 +01:00
Marcus Handte 2c788e3329 Add weather station configuration to ios app.
LocationBasedServices/mowesta/pipeline/head This commit looks good
2022-11-03 16:47:26 +01:00
Marcus Handte af2409a16d Improve handling of intent.
LocationBasedServices/mowesta/pipeline/head This commit looks good
2022-11-01 18:25:01 +01:00
Marcus Handte 7e390ed56f Fix navigation graph issues.
LocationBasedServices/mowesta/pipeline/head This commit looks good
2022-11-01 17:41:25 +01:00
Marcus Handte 756a816abb Add app updates and paper evaluation.
LocationBasedServices/mowesta/pipeline/head This commit looks good
Add fix for iOS app contained in release 1.1.
Add support for Android 13 to Android app.
Add tools for PerCom paper evaluation.
2022-11-01 17:11:21 +01:00
handte 1e174f77f7 Upgrade to 1.0.28-SNAPSHOT
LocationBasedServices/mowesta/pipeline/head This commit looks good
2022-08-03 14:21:27 +02:00
handte ae8e1ddb82 Release 1.0.27
LocationBasedServices/mowesta/pipeline/head This commit looks good
2022-07-25 19:03:10 +02:00
handte 9381065cf2 Fix touch bug in android, resubmit ios app.
LocationBasedServices/mowesta/pipeline/head This commit looks good
2022-07-25 16:20:30 +02:00
handte 98b4ee71ae Reduce debug output, fix ordering of favorites.
LocationBasedServices/mowesta/pipeline/head This commit looks good
2022-07-25 14:05:05 +02:00
handte 1b84c6fc15 Finish gradient view and prepare app store submission.
LocationBasedServices/mowesta/pipeline/head This commit looks good
2022-07-25 12:27:20 +02:00
handte ad9fb99205 Fix bugs and optimize (somewhat) for tablets.
LocationBasedServices/mowesta/pipeline/head This commit looks good
2022-07-23 17:48:09 +02:00
handte 4fdbf10054 Add 2-way (background) synchronization and favorites.
LocationBasedServices/mowesta/pipeline/head This commit looks good
2022-07-23 16:58:25 +02:00
handte 3505c379cf Finish ios ui.
LocationBasedServices/mowesta/pipeline/head This commit looks good
2022-07-22 17:37:02 +02:00
handte 6322022f47 Backup ios app.
LocationBasedServices/mowesta/pipeline/head This commit looks good
2022-07-21 22:46:49 +02:00
handte adf60f289b Backup ios app.
LocationBasedServices/mowesta/pipeline/head This commit looks good
2022-07-20 23:34:43 +02:00
handte 27ccac205b Fix bug in android timezone, backup ios.
LocationBasedServices/mowesta/pipeline/head This commit looks good
2022-07-17 19:28:10 +02:00
handte 664a7d4cea Update to 1.0.27-SNAPSHOT
LocationBasedServices/mowesta/pipeline/head This commit looks good
2022-06-10 22:00:04 +02:00
186 changed files with 15865 additions and 695 deletions
Vendored
+1 -1
View File
@@ -49,7 +49,7 @@ node {
if (env.BRANCH_NAME == "master" && release) {
echo "Deploying to production server ..."
withCredentials([sshUserPrivateKey(credentialsId: "mowesta-server-key", keyFileVariable: "KEYFILE")]) {
sh 'scp -i $KEYFILE site-ear/build/libs/site-ear-' + version + '.ear wildfly@apps-pro.nes.uni-due.de:/opt/wildfly-21-mowesta/standalone/deployments/mowesta.ear'
// sh 'scp -i $KEYFILE site-ear/build/libs/site-ear-' + version + '.ear wildfly@apps-pro.nes.uni-due.de:/opt/wildfly-21-mowesta/standalone/deployments/mowesta.ear'
sh 'scp -i $KEYFILE android-app/build/outputs/apk/prod/release/*.apk wildfly@apps-pro.nes.uni-due.de:/opt/android/mowesta/'
sh 'scp -i $KEYFILE android-app/build/outputs/bundle/prodRelease/*.aab wildfly@apps-pro.nes.uni-due.de:/opt/android/mowesta/'
}
+9 -9
View File
@@ -14,16 +14,16 @@ ext {
versionAndroidXPaging = '2.1.2'
versionAndroidXCard = '1.0.0'
versionAndroidXCoordinator = '1.2.0'
versionAndroidXConstraint = '2.1.3'
versionAndroidXNavigation = '2.3.5'
versionAndroidXLifecycle = '2.4.1'
versionAndroidXConstraint = '2.1.4'
versionAndroidXNavigation = '2.5.3'
versionAndroidXLifecycle = '2.5.1'
versionAndroidXSecurity = '1.0.0'
versionAndroidXViewpager = '1.0.0'
versionAndroidXWork = '2.7.1'
versionGoogleMaterial = '1.6.0'
versionGoogleMaterial = '1.7.0'
versionAndroidXSwipeRefresh = '1.1.0'
versionAndroidXWebkit = '1.4.0'
versionExoPlayer = '2.17.1'
versionAndroidXWebkit = '1.5.0'
versionExoPlayer = '2.18.1'
versionApp = project.version
}
@@ -95,12 +95,12 @@ configurations {
android {
compileSdkVersion 31
compileSdkVersion 33
defaultConfig {
applicationId "com.mowesta.android.app"
minSdkVersion 19
targetSdkVersion 30
versionCode 26
targetSdkVersion 33
versionCode 29
versionName "${versionApp}"
buildConfigField "long", "BUILD_TIME", System.currentTimeMillis() + "L"
testInstrumentationRunner "androidx.test.runner.AndroidJUnitRunner"
+2 -1
View File
@@ -4,6 +4,7 @@
<uses-permission android:name="android.permission.INTERNET"/>
<uses-permission android:name="android.permission.WAKE_LOCK"/>
<uses-permission android:name="android.permission.POST_NOTIFICATIONS"/>
<uses-permission android:name="android.permission.ACCESS_BACKGROUND_LOCATION"/>
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION"/>
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION"/>
@@ -28,7 +29,7 @@
android:supportsRtl="true"
android:fullBackupContent="@xml/backup">
<activity
android:launchMode="singleTask"
android:launchMode="singleTop"
android:name=".MowestaActivity"
android:windowSoftInputMode="adjustResize"
android:exported="true">
@@ -11,6 +11,7 @@ import android.net.Uri;
import android.net.http.HttpResponseCache;
import android.os.Build;
import android.os.Bundle;
import android.os.PersistableBundle;
import android.provider.Settings;
import android.util.Log;
import android.view.View;
@@ -20,8 +21,10 @@ import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.app.ActivityCompat;
import androidx.fragment.app.DialogFragment;
import androidx.navigation.NavBackStackEntry;
import androidx.navigation.NavController;
import androidx.navigation.NavDirections;
import androidx.navigation.NavOptionsBuilder;
import androidx.navigation.Navigation;
import com.google.android.material.dialog.MaterialAlertDialogBuilder;
@@ -32,6 +35,7 @@ import com.mowesta.android.app.task.DatabaseTask;
import com.mowesta.android.app.task.RefreshTask;
import com.mowesta.android.app.task.SyncTask;
import com.mowesta.android.app.util.PermissionUtil;
import com.mowesta.android.app.widget.PeriodicWidgetWorker;
import com.mowesta.android.feign.api.DefaultApi;
import com.mowesta.android.sdk.SdkRepository;
import com.mowesta.android.sdk.task.ClearTask;
@@ -58,6 +62,10 @@ public class MowestaActivity extends AppCompatActivity {
*/
private static final int DELAY_REFRESH = 15 * 60 * 1000;
/**
* Requests the permission to issue notifications.
*/
public static final int CODE_REQUEST_POST_NOTIFICATION = 3333;
/**
* The code used to request the permission for localizing in the foreground.
*/
@@ -113,7 +121,9 @@ public class MowestaActivity extends AppCompatActivity {
private OnSharedPreferenceChangeListener preferenceListener = (prefs, key) -> {
if (MowestaSettings.PRIVACY_MEASURE.equals(key)) {
if (settings.isPrivacyMeasure()) {
if (!PermissionUtil.hasBackgroundPermissions(this)) requestPermissions();
if (!PermissionUtil.hasBackgroundPermissions(this) ||
!PermissionUtil.hasNotificationPermission(this))
requestPermissions(false);
else MowestaService.startService(this);
} else {
MowestaService.stopService(this);
@@ -139,7 +149,6 @@ public class MowestaActivity extends AppCompatActivity {
protected void onNewIntent(Intent intent) {
super.onNewIntent(intent);
setIntent(intent);
}
// got to navigation drawer when user presses notification
@@ -152,7 +161,17 @@ public class MowestaActivity extends AppCompatActivity {
if (controller.getGraph().getId() == R.id.navigation_core) {
controller.navigate(R.id.action_drawer);
} else {
controller.navigate(R.id.action_core);
boolean hasDrawer = false;
for (NavBackStackEntry entry: controller.getBackQueue()) {
if (entry.getDestination().getId() == R.id.destination_drawer) {
hasDrawer = true;
}
}
if (hasDrawer) {
controller.navigate(R.id.action_drawer);
} else {
controller.navigate(R.id.action_core);
}
}
}
}
@@ -165,6 +184,12 @@ public class MowestaActivity extends AppCompatActivity {
handleNotificationIntent();
}
@Override
protected void onPostResume() {
super.onPostResume();
MowestaService.startService(this);
}
@Override
protected void onPause() {
super.onPause();
@@ -205,9 +230,11 @@ public class MowestaActivity extends AppCompatActivity {
/**
* Method to request location permission for the app.
*/
public void requestPermissions() {
public void requestPermissions(boolean skipNotification) {
Log.d(TAG, "Requesting permissions.");
if (!PermissionUtil.hasPermissions(this, PermissionUtil.getForegroundPermissions(this))) {
if (!skipNotification && Build.VERSION.SDK_INT >= Build.VERSION_CODES.TIRAMISU && !PermissionUtil.hasNotificationPermission(this)) {
ActivityCompat.requestPermissions(this, new String[] { Manifest.permission.POST_NOTIFICATIONS }, CODE_REQUEST_POST_NOTIFICATION);
} else if (!PermissionUtil.hasPermissions(this, PermissionUtil.getForegroundPermissions(this))) {
ActivityCompat.requestPermissions(this, PermissionUtil.getForegroundPermissions(this), CODE_REQUEST_BACKGROUND_PERMISSIONS);
} else if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q){
ActivityCompat.requestPermissions(this, new String[] {Manifest.permission.ACCESS_BACKGROUND_LOCATION }, CODE_REQUEST_BACKGROUND_PERMISSIONS);
@@ -225,6 +252,12 @@ public class MowestaActivity extends AppCompatActivity {
public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
super.onRequestPermissionsResult(requestCode, permissions, grantResults);
switch (requestCode) {
case CODE_REQUEST_POST_NOTIFICATION: {
if (!PermissionUtil.hasBackgroundPermissions(this))
requestPermissions(true);
else MowestaService.startService(this);
break;
}
case CODE_REQUEST_BACKGROUND_PERMISSIONS:
case CODE_REQUEST_FOREGROUND_PERMISSIONS: {
boolean granted = true;
@@ -238,8 +271,9 @@ public class MowestaActivity extends AppCompatActivity {
if (!granted) {
settings.setPrivacyMeasure(false);
showMissingPermission(requestCode == CODE_REQUEST_FOREGROUND_PERMISSIONS);
} else if (requestCode == CODE_REQUEST_BACKGROUND_PERMISSIONS){
if (!PermissionUtil.hasBackgroundPermissions(this)) requestPermissions();
} else {
if (!PermissionUtil.hasBackgroundPermissions(this))
settings.setPrivacyMeasure(false);
else MowestaService.startService(this);
}
break;
@@ -257,8 +291,6 @@ public class MowestaActivity extends AppCompatActivity {
pdf.show(getSupportFragmentManager(), "permissions");
}
/**
* A dialog fragment to explain the need for permissions.
*
@@ -86,7 +86,6 @@ public class MowestaApp extends Application implements IApp {
deviceRepository = new DeviceRepository.Builder().setTrace(false).build(this);
favoriteRepository = new FavoriteRepository(this);
widgetRepository = new WidgetRepository(this);
MowestaService.startService(this);
PeriodicWidgetWorker.updateWidgets(this);
PeriodicWidgetWorker.scheduleUpdates(this);
//if(BuildConfig.DEBUG)
@@ -5,9 +5,11 @@ import android.os.Bundle;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.core.view.MenuProvider;
import androidx.recyclerview.widget.RecyclerView;
import com.mowesta.android.app.IApp;
@@ -41,7 +43,6 @@ public abstract class AbstractDiagramFragment extends AbstractNetworkFragment {
public void onCreate(@Nullable Bundle savedInstanceState) {
settings = ((IApp)getContext().getApplicationContext()).getSettings();
super.onCreate(savedInstanceState);
setHasOptionsMenu(true);
}
@Override
@@ -64,25 +65,29 @@ public abstract class AbstractDiagramFragment extends AbstractNetworkFragment {
public abstract void onRefreshDiagram();
@Override
public void onCreateOptionsMenu(@NonNull Menu menu, @NonNull MenuInflater inflater) {
super.onCreateOptionsMenu(menu, inflater);
inflater.inflate(R.menu.menu_unit, menu);
}
public void onViewCreated(@NonNull View view, @Nullable Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
getActivity().addMenuProvider(new MenuProvider() {
@Override
public void onCreateMenu(@NonNull Menu menu, @NonNull MenuInflater inflater) {
inflater.inflate(R.menu.menu_unit, menu);
}
@Override
public boolean onOptionsItemSelected(@NonNull MenuItem item) {
int itemId = item.getItemId();
if (itemId == R.id.action_unit_system) {
UnitSystemDialogFragment system = new UnitSystemDialogFragment();
system.show(getChildFragmentManager(), "system");
return true;
} else if (itemId == R.id.action_temperature_unit) {
TemperatureUnitDialogFragment unit = new TemperatureUnitDialogFragment();
unit.show(getChildFragmentManager(), "unit");
return true;
}
return super.onOptionsItemSelected(item);
@Override
public boolean onMenuItemSelected(@NonNull MenuItem item) {
int itemId = item.getItemId();
if (itemId == R.id.action_unit_system) {
UnitSystemDialogFragment system = new UnitSystemDialogFragment();
system.show(getChildFragmentManager(), "system");
return true;
} else if (itemId == R.id.action_temperature_unit) {
TemperatureUnitDialogFragment unit = new TemperatureUnitDialogFragment();
unit.show(getChildFragmentManager(), "unit");
return true;
}
return false;
}
}, getViewLifecycleOwner());
}
}
@@ -11,6 +11,7 @@ import android.view.View;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.core.view.MenuProvider;
import androidx.fragment.app.Fragment;
import com.mowesta.android.app.R;
@@ -44,12 +45,6 @@ public abstract class AbstractPlaceFragment extends AbstractNetworkFragment {
*/
protected abstract AbstractPlaceViewModel getPlaceViewModel();
@Override
public void onCreate(@Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setHasOptionsMenu(true);
}
@Override
public void onViewCreated(@NonNull View view, @Nullable Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
@@ -58,45 +53,46 @@ public abstract class AbstractPlaceFragment extends AbstractNetworkFragment {
model.getCoordinate().observe(getViewLifecycleOwner(), (v) -> getActivity().invalidateOptionsMenu());
model.getFavorite().observe(getViewLifecycleOwner(), (v) -> getActivity().invalidateOptionsMenu());
model.getWikipedia().observe(getViewLifecycleOwner() ,(v) -> getActivity().invalidateOptionsMenu());
}
getActivity().addMenuProvider(new MenuProvider() {
@Override
public void onCreateMenu(@NonNull Menu menu, @NonNull MenuInflater inflater) {
inflater.inflate(R.menu.menu_place, menu);
AbstractPlaceViewModel model = getPlaceViewModel();
Boolean favorite = model.getFavorite().getValue();
if (favorite == null || favorite) {
menu.removeItem(R.id.action_favorite_add);
}
if (favorite == null || !favorite) {
menu.removeItem(R.id.action_favorite_remove);
}
if (model.getWikipedia().getValue() == null) {
menu.removeItem(R.id.action_wikipedia);
}
if (model.getCoordinate().getValue() == null) {
menu.removeItem(R.id.action_google_maps);
}
}
@Override
public void onCreateOptionsMenu(@NonNull Menu menu, @NonNull MenuInflater inflater) {
super.onCreateOptionsMenu(menu, inflater);
inflater.inflate(R.menu.menu_place, menu);
AbstractPlaceViewModel model = getPlaceViewModel();
Boolean favorite = model.getFavorite().getValue();
if (favorite == null || favorite) {
menu.removeItem(R.id.action_favorite_add);
}
if (favorite == null || !favorite) {
menu.removeItem(R.id.action_favorite_remove);
}
if (model.getWikipedia().getValue() == null) {
menu.removeItem(R.id.action_wikipedia);
}
if (model.getCoordinate().getValue() == null) {
menu.removeItem(R.id.action_google_maps);
}
}
@Override
public boolean onMenuItemSelected(@NonNull MenuItem item) {
int itemId = item.getItemId();
if (itemId == R.id.action_favorite_add) {
getPlaceViewModel().addFavorite();
return true;
} else if (itemId == R.id.action_favorite_remove) {
getPlaceViewModel().removeFavorite();
return true;
} else if (itemId == R.id.action_wikipedia) {
openWikipedia();
return true;
} else if (itemId == R.id.action_google_maps) {
openGoogleMaps();
return true;
}
return false;
}
}, getViewLifecycleOwner());
@Override
public boolean onOptionsItemSelected(@NonNull MenuItem item) {
int itemId = item.getItemId();
if (itemId == R.id.action_favorite_add) {
getPlaceViewModel().addFavorite();
return true;
} else if (itemId == R.id.action_favorite_remove) {
getPlaceViewModel().removeFavorite();
return true;
} else if (itemId == R.id.action_wikipedia) {
openWikipedia();
return true;
} else if (itemId == R.id.action_google_maps) {
openGoogleMaps();
return true;
}
return false;
}
/**
@@ -12,6 +12,7 @@ import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;
import androidx.appcompat.widget.Toolbar;
import androidx.core.view.MenuProvider;
import androidx.databinding.DataBindingUtil;
import androidx.fragment.app.Fragment;
import androidx.lifecycle.ViewModelProvider;
@@ -71,30 +72,6 @@ public class CityFragment extends AbstractPlaceFragment {
return getView().findViewById(R.id.bottom_navigation);
}
@Override
public void onCreate(@Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setHasOptionsMenu(true);
}
@Override
public void onCreateOptionsMenu(@NonNull Menu menu, @NonNull MenuInflater inflater) {
super.onCreateOptionsMenu(menu, inflater);
inflater.inflate(R.menu.menu_customize, menu);
}
@Override
public boolean onOptionsItemSelected(@NonNull MenuItem item) {
if (item.getItemId() == R.id.action_customize) {
getChildFragmentManager()
.beginTransaction()
.add(new CustomizeDialogFragment(), "customize")
.commit();
return true;
}
return super.onOptionsItemSelected(item);
}
@Nullable
@Override
public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
@@ -126,5 +103,26 @@ public class CityFragment extends AbstractPlaceFragment {
return root;
}
@Override
public void onViewCreated(@NonNull View view, @Nullable Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
getActivity().addMenuProvider(new MenuProvider() {
@Override
public void onCreateMenu(@NonNull Menu menu, @NonNull MenuInflater inflater) {
inflater.inflate(R.menu.menu_customize, menu);
}
@Override
public boolean onMenuItemSelected(@NonNull MenuItem item) {
if (item.getItemId() == R.id.action_customize) {
getChildFragmentManager()
.beginTransaction()
.add(new CustomizeDialogFragment(), "customize")
.commit();
return true;
}
return false;
}
}, getViewLifecycleOwner());
}
}
@@ -55,11 +55,6 @@ public class CityGradientFragment extends CityFragment.ChildFragment {
*/
private TimeUtils timeUtils = new TimeUtils(System.currentTimeMillis(), null);
/**
* The view pager of the parent.
*/
private ViewPager2 pager;
/**
* The date formatter.
*/
@@ -94,8 +89,6 @@ public class CityGradientFragment extends CityFragment.ChildFragment {
dateFormatter = new DateFormatter(getContext());
binding = DataBindingUtil.inflate(inflater, R.layout.fragment_gradient, container, false);
// this is quite ugly, but we need to disable the view pager and collapse the toolbar
pager = getActivity().findViewById(R.id.pager);
AppBarLayout layout = getActivity().findViewById(R.id.layout_appbar);
binding.gradientProgress1.setMax(TIMEOUT_REMOVER);
binding.gradientProgress2.setMax(TIMEOUT_REMOVER);
animator = ValueAnimator.ofInt(TIMEOUT_REMOVER, 0);
@@ -110,34 +103,7 @@ public class CityGradientFragment extends CityFragment.ChildFragment {
binding.gradientText.setAlpha(Math.min(1, Math.max(0, value / 1000f)));
}
});
binding.gradientScroll.setOnTouchListener(binding.gradientTouch.createOnTouchListener(new TimeView.OnSlideListener() {
@Override
public void onSlide(float relative) {
if (!hasData()) return;
animator.cancel();
binding.gradientProgress1.setProgress(TIMEOUT_REMOVER);
binding.gradientProgress2.setProgress(TIMEOUT_REMOVER);
binding.gradientText.setAlpha(1);
handler.removeCallbacks(remover);
if (!closed) {
layout.setExpanded(false, true);
closed = true;
}
pager.setUserInputEnabled(false);
updateSelection(relative);
updateCondition(relative);
binding.gradientText.setVisibility(View.VISIBLE);
updateGuide(relative);
}
@Override
public void onSlideEnd() {
pager.setUserInputEnabled(true);
closed = false;
animator.start();
handler.postDelayed(remover, TIMEOUT_REMOVER);
}
}));
binding.setLifecycleOwner(getViewLifecycleOwner());
binding.gradientText.setVisibility(View.GONE);
@@ -278,7 +244,53 @@ public class CityGradientFragment extends CityFragment.ChildFragment {
public void onPause() {
handler.removeCallbacks(remover);
remover.run();
binding.gradientScroll.setOnTouchListener(null);
super.onPause();
}
@Override
public void onResume() {
super.onResume();
AppBarLayout layout = getActivity().findViewById(R.id.layout_appbar);
ViewPager2 pager = getActivity().findViewById(R.id.pager);
binding.gradientScroll.setOnTouchListener(binding.gradientTouch.createOnTouchListener(new TimeView.OnSlideListener() {
@Override
public void onSlide(float relative) {
if (!hasData()) return;
animator.cancel();
binding.gradientProgress1.setProgress(TIMEOUT_REMOVER);
binding.gradientProgress2.setProgress(TIMEOUT_REMOVER);
binding.gradientText.setAlpha(1);
handler.removeCallbacks(remover);
if (!closed) {
if (layout != null)
layout.setExpanded(false, true);
closed = true;
}
if (pager != null)
pager.setUserInputEnabled(false);
updateSelection(relative);
updateCondition(relative);
binding.gradientText.setVisibility(View.VISIBLE);
updateGuide(relative);
}
@Override
public void onSlideEnd() {
if (pager != null)
pager.setUserInputEnabled(true);
closed = false;
animator.start();
handler.postDelayed(remover, TIMEOUT_REMOVER);
}
}));
}
@Override
public void onDestroyView() {
binding.gradientTouch.setOnTouchListener(null);
super.onDestroyView();
}
}
@@ -10,6 +10,7 @@ import android.view.ViewGroup;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.core.view.MenuProvider;
import androidx.databinding.DataBindingUtil;
import androidx.lifecycle.ViewModelProvider;
import androidx.navigation.NavController;
@@ -39,12 +40,6 @@ public class DevicesFragment extends AbstractNetworkFragment {
return new ViewModelProvider(this).get(DevicesViewModel.class);
}
@Override
public void onCreate(@Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setHasOptionsMenu(true);
}
@Nullable
@Override
public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
@@ -55,6 +50,22 @@ public class DevicesFragment extends AbstractNetworkFragment {
Bundle bundle = new Bundle();
controller.navigate(R.id.destination_setup, bundle, opts.build());
});
getActivity().addMenuProvider(new MenuProvider() {
@Override
public void onCreateMenu(@NonNull Menu menu, @NonNull MenuInflater inflater) {
inflater.inflate(R.menu.menu_refresh, menu);
}
@Override
public boolean onMenuItemSelected(@NonNull MenuItem item) {
if (item.getItemId() == R.id.action_refresh) {
DevicesViewModel model = new ViewModelProvider(DevicesFragment.this).get(DevicesViewModel.class);
model.reload();
return true;
}
return false;
}
}, getViewLifecycleOwner());
return binding.getRoot();
}
@@ -84,21 +95,6 @@ public class DevicesFragment extends AbstractNetworkFragment {
swipeRefreshLayout.setOnRefreshListener(() -> model.reload());
}
@Override
public void onCreateOptionsMenu(@NonNull Menu menu, @NonNull MenuInflater inflater) {
super.onCreateOptionsMenu(menu, inflater);
inflater.inflate(R.menu.menu_refresh, menu);
}
@Override
public boolean onOptionsItemSelected(@NonNull MenuItem item) {
if (item.getItemId() == R.id.action_refresh) {
DevicesViewModel model = new ViewModelProvider(this).get(DevicesViewModel.class);
model.reload();
return true;
}
return false;
}
}
@@ -28,6 +28,7 @@ import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;
import androidx.appcompat.widget.SearchView;
import androidx.appcompat.widget.Toolbar;
import androidx.core.view.MenuProvider;
import androidx.cursoradapter.widget.CursorAdapter;
import androidx.customview.widget.Openable;
import androidx.databinding.DataBindingUtil;
@@ -78,32 +79,12 @@ public class DrawerFragment extends AbstractNetworkFragment {
return new ViewModelProvider(this).get(DrawerViewModel.class);
}
@Override
public void onCreate(@Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setHasOptionsMenu(true);
}
@Override
public void onResume() {
super.onResume();
if (!preventSplashScreen()) {
handleNotificationIntent();
}
handleNotificationIntent();
}
/**
* Prevent going back to the splash screen if opened through deep link.
*/
private boolean preventSplashScreen() {
NavController nav = Navigation.findNavController(getActivity().findViewById(R.id.navigation_app));
if (nav.getGraph().getId() != R.id.navigation_core) {
nav.setGraph(R.navigation.navigation_core);
return true;
} else {
return false;
}
}
/**
* Checks if the intent was generated by the background service and
@@ -127,48 +108,52 @@ public class DrawerFragment extends AbstractNetworkFragment {
Toolbar toolbar = view.findViewById(R.id.toolbar);
((AppCompatActivity)getActivity()).setSupportActionBar(toolbar);
loadingProgressBar = view.findViewById(R.id.progress_bar);
getActivity().addMenuProvider(new MenuProvider() {
@Override
public void onCreateMenu(@NonNull Menu menu, @NonNull MenuInflater menuInflater) {
menuInflater.inflate(R.menu.menu_search, menu);
SearchView search = (SearchView)menu.findItem(R.id.action_search).getActionView();
search.setQueryHint(getString(R.string.action_search));
SearchView.SearchAutoComplete complete = search.findViewById(androidx.appcompat.R.id.search_src_text);
complete.setDropDownBackgroundResource(R.color.bg_search);
final DrawerViewModel model = new ViewModelProvider(DrawerFragment.this).get(DrawerViewModel.class);
search.setOnQueryTextListener(new SearchView.OnQueryTextListener() {
@Override
public boolean onQueryTextSubmit(String query) {
return true;
}
@Override
public boolean onQueryTextChange(String newText) {
model.setTerm(newText);
return true;
}
});
search.setOnSuggestionListener(new SearchView.OnSuggestionListener() {
@Override
public boolean onSuggestionSelect(int position) {
showLocation(model, position);
return true;
}
@Override
public boolean onSuggestionClick(int position) {
showLocation(model, position);
return true;
}
});
search.setSuggestionsAdapter(new LocationCursorAdapter(getContext(), model.getResults()));
AppBarLayout appbar = getView().findViewById(R.id.layout_appbar);
search.setOnSearchClickListener((v)->appbar.setExpanded(false, true));
}
@Override
public boolean onMenuItemSelected(@NonNull MenuItem menuItem) {
return false;
}
}, getViewLifecycleOwner());
return view;
}
@Override
public void onCreateOptionsMenu(@NonNull Menu menu, @NonNull MenuInflater inflater) {
super.onCreateOptionsMenu(menu, inflater);
inflater.inflate(R.menu.menu_search, menu);
SearchView search = (SearchView)menu.findItem(R.id.action_search).getActionView();
search.setQueryHint(getString(R.string.action_search));
SearchView.SearchAutoComplete complete = search.findViewById(androidx.appcompat.R.id.search_src_text);
complete.setDropDownBackgroundResource(R.color.bg_search);
final DrawerViewModel model = new ViewModelProvider(this).get(DrawerViewModel.class);
search.setOnQueryTextListener(new SearchView.OnQueryTextListener() {
@Override
public boolean onQueryTextSubmit(String query) {
return true;
}
@Override
public boolean onQueryTextChange(String newText) {
model.setTerm(newText);
return true;
}
});
search.setOnSuggestionListener(new SearchView.OnSuggestionListener() {
@Override
public boolean onSuggestionSelect(int position) {
showLocation(model, position);
return true;
}
@Override
public boolean onSuggestionClick(int position) {
showLocation(model, position);
return true;
}
});
search.setSuggestionsAdapter(new LocationCursorAdapter(getContext(), model.getResults()));
AppBarLayout appbar = getView().findViewById(R.id.layout_appbar);
search.setOnSearchClickListener((v)->appbar.setExpanded(false, true));
}
private void showLocation(DrawerViewModel model, int position) {
LocationHierarchyPage page = model.getResults().getValue();
LocationHierarchy dest = page.getElements().get(position);
@@ -10,6 +10,7 @@ import android.view.ViewGroup;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.core.view.MenuProvider;
import androidx.fragment.app.Fragment;
import androidx.lifecycle.LifecycleOwner;
import androidx.lifecycle.LiveData;
@@ -45,7 +46,6 @@ public class FavoritesFragment extends Fragment {
@Override
public void onCreate(@Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setHasOptionsMenu(true);
// possibly show the ad for eiszeit
AdvertiseDialogFragment adf = new AdvertiseDialogFragment();
if (adf.shouldShow(getContext()) && getChildFragmentManager().findFragmentByTag(TAG_ADVERTISEMENT) == null) {
@@ -56,7 +56,31 @@ public class FavoritesFragment extends Fragment {
@Nullable
@Override
public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
return inflater.inflate(R.layout.fragment_favorites, container, false);
View view = inflater.inflate(R.layout.fragment_favorites, container, false);
getActivity().addMenuProvider(new MenuProvider() {
@Override
public void onCreateMenu(@NonNull Menu menu, @NonNull MenuInflater inflater) {
inflater.inflate(R.menu.menu_unit, menu);
inflater.inflate(R.menu.menu_refresh, menu);
// remove this item, since it would not have an effect here
MenuItem item = menu.findItem(R.id.action_unit_system);
if (item != null) item.setVisible(false);
}
@Override
public boolean onMenuItemSelected(@NonNull MenuItem item) {
if (item.getItemId() == R.id.action_refresh) {
FavoritesViewModel model = new ViewModelProvider(getActivity()).get(FavoritesViewModel.class);
model.refresh();
return true;
} else if (item.getItemId() == R.id.action_temperature_unit) {
TemperatureUnitDialogFragment unit = new TemperatureUnitDialogFragment();
unit.show(getChildFragmentManager(), "unit");
}
return false;
}
}, getViewLifecycleOwner());
return view;
}
@Override
@@ -147,29 +171,6 @@ public class FavoritesFragment extends Fragment {
});
}
@Override
public void onCreateOptionsMenu(@NonNull Menu menu, @NonNull MenuInflater inflater) {
super.onCreateOptionsMenu(menu, inflater);
inflater.inflate(R.menu.menu_unit, menu);
inflater.inflate(R.menu.menu_refresh, menu);
// remove this item, since it would not have an effect here
MenuItem item = menu.findItem(R.id.action_unit_system);
if (item != null) item.setVisible(false);
}
@Override
public boolean onOptionsItemSelected(@NonNull MenuItem item) {
if (item.getItemId() == R.id.action_refresh) {
FavoritesViewModel model = new ViewModelProvider(getActivity()).get(FavoritesViewModel.class);
model.refresh();
return true;
} else if (item.getItemId() == R.id.action_temperature_unit) {
TemperatureUnitDialogFragment unit = new TemperatureUnitDialogFragment();
unit.show(getChildFragmentManager(), "unit");
}
return false;
}
/**
* The view holder for favorites.
*
@@ -26,6 +26,7 @@ import android.content.Intent;
import android.content.SharedPreferences.OnSharedPreferenceChangeListener;
import android.content.pm.ApplicationInfo;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.os.Build;
import android.os.Bundle;
import android.provider.Settings;
@@ -200,8 +201,6 @@ public class SettingsFragment extends PreferenceFragmentCompat {
*/
private void updateBuild() {
try {
ApplicationInfo ai = getActivity().getPackageManager().getApplicationInfo(getActivity().getPackageName(), 0);
PackageInfo pi = getActivity().getPackageManager().getPackageInfo(getActivity().getPackageName(), 0);
String summary = getResources().getString(R.string.setting_about_build_summary);
summary = summary.replace("$version$", BuildConfig.VERSION_NAME);
summary = summary.replace("$code$", "" + BuildConfig.VERSION_CODE);
@@ -96,4 +96,18 @@ public class PermissionUtil {
return new String[] { Manifest.permission.ACCESS_FINE_LOCATION, Manifest.permission.ACCESS_COARSE_LOCATION };
}
/**
* Determines whether the app has the post notification permission.
*
* @param context The context.
* @return True if the app may post notifications.
*/
public static boolean hasNotificationPermission(@NonNull Context context) {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.TIRAMISU) {
return hasPermissions(context, new String[] { Manifest.permission.POST_NOTIFICATIONS });
} else {
return true;
}
}
}
@@ -1,10 +1,6 @@
package com.mowesta.android.app.util;
import android.content.Context;
import android.content.res.Resources;
import androidx.core.content.ContextCompat;
import androidx.core.content.res.ResourcesCompat;
import androidx.core.os.ConfigurationCompat;
import com.mowesta.android.app.R;
@@ -17,7 +13,7 @@ import java.util.List;
import java.util.TimeZone;
/**
* A utiltiy class to comptue times when aggregating weather
* A utility class to computes times when aggregating weather
* conditions into weather summaries.
*
* @author Marcus
@@ -44,15 +40,15 @@ public class TimeUtils {
* @param tz The time zone.
*/
public TimeUtils(long now, String tz) {
if (tz != null) {
c.setTimeZone(TimeZone.getTimeZone(tz));
}
c.setTimeInMillis(now);
update(today);
c.add(Calendar.DAY_OF_MONTH, -1);
update(yesterday);
c.add(Calendar.DAY_OF_MONTH, 2);
update(tomorrow);
if (tz != null) {
c.setTimeZone(TimeZone.getTimeZone(tz));
}
}
/**
+2 -2
View File
@@ -10,11 +10,11 @@ description = "MoWeSta Android SDK"
project.version = "unspecified"
android {
compileSdkVersion 31
compileSdkVersion 33
defaultConfig {
minSdkVersion 19
targetSdkVersion 30
targetSdkVersion 33
testInstrumentationRunner "androidx.test.runner.AndroidJUnitRunner"
consumerProguardFiles "consumer-rules.pro"
@@ -132,7 +132,11 @@ public abstract class SdkService extends Service {
@Override
public void onReceive(Context context, Intent intent) {
if (intent != null && WifiManager.SCAN_RESULTS_AVAILABLE_ACTION.equals(intent.getAction())) {
setScan(wifiManager.getScanResults());
try {
setScan(wifiManager.getScanResults());
} catch (SecurityException e) {
// will never happen
}
}
}
};
@@ -757,14 +761,16 @@ public abstract class SdkService extends Service {
* @return The pending intent.
*/
public static PendingIntent createIntent(SdkService service) {
int flags = PendingIntent.FLAG_UPDATE_CURRENT;
Intent intent = new Intent();
intent.setClassName(service, service.getClass().getName());
intent.putExtra(EXTRA_ALARM, true);
int code = service.getResources().getInteger(R.integer.mowesta_sdk_alarm_request_code);
if (Build.VERSION.SDK_INT < Build.VERSION_CODES.O) {
return PendingIntent.getService(service, code, intent, PendingIntent.FLAG_UPDATE_CURRENT);
return PendingIntent.getService(service, code, intent, flags);
} else {
return PendingIntent.getForegroundService(service, code, intent, PendingIntent.FLAG_UPDATE_CURRENT);
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.S) flags |= PendingIntent.FLAG_MUTABLE;
return PendingIntent.getForegroundService(service, code, intent, flags);
}
}
@@ -91,17 +91,18 @@ public class ChannelManager {
* @return The notification.
*/
public Notification createNotification(int res) {
int flags = PendingIntent.FLAG_UPDATE_CURRENT;
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.S) flags |= PendingIntent.FLAG_MUTABLE;
NotificationCompat.Builder builder = new NotificationCompat.Builder(application, getChannelId())
.setContentTitle(application.getString(R.string.mowesta_sdk_notification_title))
.setContentText(application.getString(res))
.setOngoing(true)
.setContentIntent(PendingIntent.getActivity(application, getNotificationRequestCode(), createNotificationIntent(), PendingIntent.FLAG_UPDATE_CURRENT))
.setContentIntent(PendingIntent.getActivity(application, getNotificationRequestCode(), createNotificationIntent(), flags))
.setSmallIcon(R.drawable.mowesta_sdk_ic_notification_small)
.setLargeIcon(BitmapFactory.decodeResource(application.getResources(), R.drawable.mowesta_sdk_ic_notification_large));
return builder.build();
}
/**
* Returns the request code used for the pending intent.
*
+5 -6
View File
@@ -5,8 +5,7 @@ apply plugin: 'maven-publish'
buildscript {
dependencies {
classpath "org.openapitools:openapi-generator-gradle-plugin:5.3.0"
classpath 'com.android.tools.build:gradle:7.2.1'
classpath 'com.android.tools.build:gradle:7.3.1'
classpath 'com.google.android.gms:oss-licenses-plugin:0.10.4'
classpath 'org.handte.gradle:gradle-android-eclipse:1.0.0'
classpath "gradle.plugin.org.openbakery:plugin:0.21.0"
@@ -25,7 +24,7 @@ allprojects {
// set version for our project
group = 'com.mowesta'
version = '1.0.26'
version = '1.0.29'
// set versions for our libraries
ext {
@@ -55,10 +54,10 @@ allprojects {
mapstructVersion = '1.3.1.Final'
// shared android dependencies
versionAndroidXTest = '1.4.0'
versionAndroidXAppcompat = '1.4.1'
versionAndroidXRoom = '2.4.2'
versionAndroidXAppcompat = '1.5.1'
versionAndroidXRoom = '2.4.3'
versionAndroidXPreference = '1.2.0'
versionRobolectric = '4.5'
versionRobolectric = '4.9'
// locoslab libraries and code
versionGeometry = '1.1.4'
versionCarta = '1.1.4'
+64
View File
@@ -0,0 +1,64 @@
![](header.png)
# MoWeSta Datensatz
Die beigefügte Datei im CSV Format enthält anonymsierte Batterietemperaturmessungen von Android-Geräten im Außenbereich, die mit Hilfe des [MoWeSta Diensts](https://www.mowesta.com) im Rahmen des vom Bundesministerium für Digitales und Verkehr geförderten [Forschungsprojekts FAIR](https://www.fair-opendata.de) durch Freiwillige erfasst wurden.
## Zeitraum
Der Zeitraum umfasst Messungen die zwischen Januar 2020 und September 2022 erfolgt sind.
## Abdeckung
Die örtliche Abdeckung ist begrenzt auf Deutschland, da hierfür die Basistemperaturwerte des Deutschen Wetterdiensts verfügbar sind.
## Vorverarbeitung
Im o.g. Zeitraum wurden mit Hilfe des MoWeSta Diensts rund 6,2 Millionen Batterietemperaturmessungen erfasst. Die meisten Messungen sind für die Bestimmung der Außentemperatur jedoch nicht geeignet, da sie in Innenräumen erfolgt sind. Darüber hinaus enthalten die in MoWeSta gespeicherten Messungen genaue Standortinformationen, womit sie als personenbezogene Daten gelten, die nicht ohne Einwilligung der Nutzer weitergegeben werden dürfen. Aus diesem Grund wurden die Daten vorverarbeitet, um eine uneingeschränkte Weitergabe an Dritte zu ermöglichen.
### Datenselektion
Um sicherzustellen, dass die Batterietemperaturmessunen im Außenbereich erfolgt sind, wurden zunächst die Messungen identifiziert, bei denen sich das jeweilige Gerät mindestens 5 Minuten lang im Freien befand. Hierzu wurden zunächst anhand der Standortdaten einzelner Geräte alle zurückgelegten Wegstrecken berechnet. Von diesen Wegstrecken wurden diejenigen ausgewählt, bei denen die Bewegungsgeschwindigkeit unter 2 m/s lag. Jede Zeile in der beigefügten Datei repräsentiert eine solche Wegstrecke. Aufgrund der Geschwindigkeitsbeschränkung kann davon ausgegangen werden, dass die Wegstrecke zu Fuß (und damit im Freien) zurückgelegt wurde.
### Außentemperatur
Zur Entwicklung von weiteren Modellen zur Abbildung der Batterietemperaturwerte auf die Außentempeatur wurde jeder Wegstrecke die vorherschende Außentemperatur zugewiesen. Dazu wurde anhand des Gerätestandorts zunächst die nächste synoptische Messstation des DWD identifiziert. Anhand der Startzeit wurde daraufhin die gemessene Außentemperatur der Station abgerufen und der Wegstrecke zugewiesen.
### Pseudonymisierung
Für jedes Gerät wird der Hersteller und die Modellbezeichnung aufgeführt.
Zur Entfernung von nutzerspezifischen Informationen wurde jedem Gerät anstelle der im MoWeSta Dienst verwendeten Kennung eine fortlaufende Nummer zugewiesen.
### Standortverschleierung
Zur Anonymisierung der Standortinformationen wurden der genaue Standort für jedes Gerät verscheiert. Zu diesem Zweck wurde der GPS Standort zunächst mit Hilfe einer sphärischen Mercatorprojektion auf eine [Kachel der Zoomstufe 10](https://wiki.openstreetmap.org/wiki/Slippy_map_tilenames) abgebildet und durch das Zentrum der Kachel (mit Angabe der resultierender maximalen Ungenauigkeit) ersetzt. Darüber hinaus wurden die von MoWeSta erfassten Zeitstempel unter Beibehaltung des Monats durch relative Angaben ersetzt. Abschließend wurden die Messdaten nach Außentemperatur geornet, womit alle zeitlichen Zusammenhänge zwischen Standort und Messzeitpunkt aus dem Datensatz entfernt sind.
## Struktur
Die beigefügte Datei im CSV Format nutzt Strichpunkte als Zellenseparator und Kommas zur Repräsentation von Dezimalzahlen. Damit kann Sie direkt in Microsoft Excel mit deutschen Einstellungen geöffnet werden. Da jede Zeile eine Wegstrecke repräsentiert, ist die Zahl der Spalten variabel und kann sich von Zeile zu Zeile in Abhängigkeit von der Zahl der Messungen pro Strecke unterscheiden. Im Folgenden werden die einzelnen Spalten kurz beschrieben:
- **Gerät:** Eine fortlaufende Nummer, die Wegstrecken des selben Geräts identifiziert.
- **Hersteller:** Der Name des Geräteherstellers.
- **Model:** Die herstellerspezifische Angabe des Gerätemodells.
- **Monat:** Der Monat der Messung (1=Januar, 12=Dezember)
- **Temperatur in °C (DWD):** Die gemessene Außentemperatur (in einer Höhe von 2 Metern) der nächstgelegenen synoptischen Station des Deutschen Wetterdiensts.
- **Latitude (WGS84):** Die Breite des Zentrums der Kachel (auf Zoomstufe 10), die den Standort enthält.
- **Longitude (WGS84):** Die Länge des Zentrums der Kachel (auf Zoomstufe 10), die den Standort enthält.
- **Verschleierung (m):** Die maximale Ungenauigkeit in Metern, die sich durch die Abbildung des Standorts auf das Zentrum der Kachel ergibt.
- **Aufenthaltsdauer im Freien (ms):** Die relative Aufenthaltsdauer im Freien seit Beginn der Bewegung in Millisekunden.
- **Batterietemperatur in °C:** Die gemessene Batterietemperatur des Geräts zum zuvor genannten Zeitpunkt
- **Gerät aktiv:** Ein boolscher Wert (Ja/Nein), der angibt ob sich das Gerät während der Messung der Batterietemperatur im aktiven Zustand befand (ein Indiz für Nutzeraktivität).
Die letzten 3 Spalten können sich beliebig häufig in einer Zeile wiederholen, um mehrere Messungen während der Wegstrecke darzustellen.
## Kontakt
Für Fragen zum beiliegenden Datensatz oder zur Vorverarbeitung wenden Sie sich bitte an [Dr. Marcus Handte](mailto:marcus.handte@uni-due.de). Weitere Kontaktinformationen finden Sie auf der [Homepage des Lehrstuhls Networked Embedded Systems](https://www.nes.uni-due.de) der [Universität Duisburg-Essen](https://www.uni-due.de).
&nbsp;
&nbsp;
![](footer.png)
Binary file not shown.
Binary file not shown.

After

Width:  |  Height:  |  Size: 190 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 19 KiB

+51
View File
@@ -0,0 +1,51 @@
---
Titel: "MoWeSta Datensatz"
Publikationsdatum: "2022-11-07"
Kurzbeschreibung: "Der MoWeSta Datensatz enthält anonymsierte Batterietemperaturmessungen von Android-Geräten im Außenbereich, die mit Hilfe des MoWeSta Diensts im Rahmen des vom Bundesministerium für Digitales und Verkehr geförderten Forschungsprojekts FAIR durch Freiwillige erfasst wurden.\n
\n
Viele der mit MoWeSta erfassten Messungen sind für die Bestimmung der Außentemperatur jedoch nicht geeignet, da sie in Innenräumen erfolgt sind. Darüber hinaus enthalten die in MoWeSta gespeicherten Messungen genaue Standortinformationen, womit sie als personenbezogene Daten gelten, die nicht ohne Einwilligung der Nutzer weitergegeben werden dürfen. Aus diesem Grund wurden die Daten vorverarbeitet, um eine uneingeschränkte Weitergabe an Dritte zu ermöglichen.\n
\n
- Datenselektion: Um sicherzustellen, dass die Batterietemperaturmessunen im Außenbereich erfolgt sind, wurden zunächst die Messungen identifiziert, bei denen sich das jeweilige Gerät mindestens 5 Minuten lang im Freien befand. Hierzu wurden zunächst anhand der Standortdaten einzelner Geräte alle zurückgelegten Wegstrecken berechnet. Von diesen Wegstrecken wurden diejenigen ausgewählt, bei denen die Bewegungsgeschwindigkeit unter 2 m/s lag. Jede Zeile in der beigefügten Datei repräsentiert eine solche Wegstrecke. Aufgrund der Geschwindigkeitsbeschränkung kann davon ausgegangen werden, dass die Wegstrecke zu Fuß (und damit im Freien) zurückgelegt wurde.\n
- Außentemperatur: Zur Entwicklung von weiteren Modellen zur Abbildung der Batterietemperaturwerte auf die Außentempeatur wurde jeder Wegstrecke die vorherschende Außentemperatur zugewiesen. Dazu wurde anhand des Gerätestandorts zunächst die nächste synoptische Messstation des DWD identifiziert. Anhand der Startzeit wurde daraufhin die gemessene Außentemperatur der Station abgerufen und der Wegstrecke zugewiesen.\n
- Pseudonymisierung: Für jedes Gerät wird der Hersteller und die Modellbezeichnung aufgeführt. Zur Entfernung von nutzerspezifischen Informationen wurde jedem Gerät anstelle der im MoWeSta Dienst verwendeten Kennung eine fortlaufende Nummer zugewiesen.\n
- Standortverschleierung: Zur Anonymisierung der Standortinformationen wurden der genaue Standort für jedes Gerät verscheiert. Zu diesem Zweck wurde der GPS Standort zunächst mit Hilfe einer sphärischen Mercatorprojektion auf eine Kachel der Zoomstufe 10 abgebildet und durch das Zentrum der Kachel (mit Angabe der resultierender maximalen Ungenauigkeit) ersetzt. Darüber hinaus wurden die von MoWeSta erfassten Zeitstempel unter Beibehaltung des Monats durch relative Angaben ersetzt. Abschließend wurden die Messdaten nach Außentemperatur geornet, womit alle zeitlichen Zusammenhänge zwischen Standort und Messzeitpunkt aus dem Datensatz entfernt sind.\n
\n
Der Datensatz ist im CSV Format gespeichert und nutzt Strichpunkte als Zellenseparator und Kommas zur Repräsentation von Dezimalzahlen. Damit kann Sie direkt in Microsoft Excel mit deutschen Einstellungen geöffnet werden. Da jede Zeile eine Wegstrecke repräsentiert, ist die Zahl der Spalten variabel und kann sich von Zeile zu Zeile in Abhängigkeit von der Zahl der Messungen pro Strecke unterscheiden. Im Folgenden werden die einzelnen Spalten kurz beschrieben:\n
\n
- Gerät: Eine fortlaufende Nummer, die Wegstrecken des selben Geräts identifiziert.\n
- Hersteller: Der Name des Geräteherstellers.\n
- Model: Die herstellerspezifische Angabe des Gerätemodells.\n
- Monat: Der Monat der Messung (1=Januar, 12=Dezember)\n
- Temperatur in °C (DWD): Die gemessene Außentemperatur (in einer Höhe von 2 Metern) der nächstgelegenen synoptischen Station des Deutschen Wetterdiensts.\n
- Latitude (WGS84): Die Breite des Zentrums der Kachel (auf Zoomstufe 10), die den Standort enthält.\n
- Longitude (WGS84): Die Länge des Zentrums der Kachel (auf Zoomstufe 10), die den Standort enthält.\n
- Verschleierung (m): Die maximale Ungenauigkeit in Metern, die sich durch die Abbildung des Standorts auf das Zentrum der Kachel ergibt.\n
- Aufenthaltsdauer im Freien (ms): Die relative Aufenthaltsdauer im Freien seit Beginn der Bewegung in Millisekunden.\n
- Batterietemperatur in °C: Die gemessene Batterietemperatur des Geräts zum zuvor genannten Zeitpunkt.\n
- Gerät aktiv: Ein boolscher Wert (Ja/Nein), der angibt ob sich das Gerät während der Messung der Batterietemperatur im aktiven Zustand befand (ein Indiz für Nutzeraktivität).\n
\n
Die letzten 3 Spalten können sich beliebig häufig in einer Zeile wiederholen, um mehrere Messungen während der Wegstrecke darzustellen.
"
Zeitliche_Ausdehnung:
Anfangszeitpunkt: "2020-01-18"
Endzeitpunkt: "2022-09-07"
Geographisches_Begrenzungsrechteck:
Westen: "5.80077"
Osten: "13.88672"
Süden: "46.92011"
Norden: "54.67371"
Format:
- "CSV"
Online-Ressource:
- URL: "https://www.mowesta.com/data/measure/mowesta-dataset-20221107.zip"
Protokoll: "WWW:DOWNLOAD-1.0-http--download"
Bezeichnung: "MoWeSta Datensatz"
Beschreibung:
Funktion: "Download"
Herkunft_Erläuterung: "Der MoWeSta Datensatz enthält anonymsierte Batterietemperaturmessungen von Android-Geräten im Außenbereich, die mit Hilfe des MoWeSta Diensts im Rahmen des vom Bundesministerium für Digitales und Verkehr geförderten Forschungsprojekts FAIR durch Freiwillige erfasst wurden."
Referenzsystem:
- EPSG: "4326"
Name: "WGS 84"
Zusätzlicher_Metadatenkontakt:
- Organisation: "Universität Duisburg-Essen (WiWi > ICB > NES)"
E-Mail: "marcus.handte@uni-due.de"
+1 -1
View File
@@ -1,6 +1,6 @@
#Mon May 23 12:33:06 CEST 2022
distributionBase=GRADLE_USER_HOME
distributionUrl=https\://services.gradle.org/distributions/gradle-7.3.3-bin.zip
distributionUrl=https\://services.gradle.org/distributions/gradle-7.4-bin.zip
distributionPath=wrapper/dists
zipStorePath=wrapper/dists
zipStoreBase=GRADLE_USER_HOME
+20 -1
View File
@@ -1,4 +1,6 @@
apply plugin: 'org.openapi.generator'
plugins {
id 'org.openapi.generator' version '6.0.1'
}
description = "MoWeSta iOS Api"
@@ -17,8 +19,25 @@ task clean(type: Delete) {
}
task fixApiClient() {
doLast {
ant.replaceregexp(match:'Optional<T>.none as! T', replace:'E.init(nilLiteral: ()) as! T', flags:'g', byline:true) {
fileset(dir: 'build/swagger/OpenAPIClient/Classes/OpenAPIs', includes: 'URLSessionImplementations.swift')
}
ant.replaceregexp(match:'if T.self is ExpressibleByNilLiteral.Type', replace:'if let E = T.self as? ExpressibleByNilLiteral.Type', flags:'g', byline:true) {
fileset(dir: 'build/swagger/OpenAPIClient/Classes/OpenAPIs', includes: 'URLSessionImplementations.swift')
}
}
}
// require api build to access swagger definition
tasks.register("build") { }
tasks['openApiGenerate'].dependsOn(project(':common-api').tasks['build'])
// require swagger code gen before compilation
build.dependsOn('openApiGenerate')
fixApiClient.dependsOn('openApiGenerate')
build.dependsOn('fixApiClient')
+194 -15
View File
@@ -14,6 +14,12 @@
2C163321283A27D600F78CEE /* AppTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 2C163320283A27D600F78CEE /* AppTests.swift */; };
2C16332B283A27D600F78CEE /* AppUITests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 2C16332A283A27D600F78CEE /* AppUITests.swift */; };
2C16332D283A27D600F78CEE /* AppUITestsLaunchTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 2C16332C283A27D600F78CEE /* AppUITestsLaunchTests.swift */; };
2C369C6628888E6800B5AFB2 /* StationView.swift in Sources */ = {isa = PBXBuildFile; fileRef = 2C369C6528888E6800B5AFB2 /* StationView.swift */; };
2C369C6828889EAE00B5AFB2 /* ErrorView.swift in Sources */ = {isa = PBXBuildFile; fileRef = 2C369C6728889EAE00B5AFB2 /* ErrorView.swift */; };
2C369C6A2889592500B5AFB2 /* StationsView.swift in Sources */ = {isa = PBXBuildFile; fileRef = 2C369C692889592500B5AFB2 /* StationsView.swift */; };
2C369C6C2889719C00B5AFB2 /* MeasurementView.swift in Sources */ = {isa = PBXBuildFile; fileRef = 2C369C6B2889719C00B5AFB2 /* MeasurementView.swift */; };
2C369C6E2889D42700B5AFB2 /* DevicesView.swift in Sources */ = {isa = PBXBuildFile; fileRef = 2C369C6D2889D42700B5AFB2 /* DevicesView.swift */; };
2C369C702889D44100B5AFB2 /* DeviceView.swift in Sources */ = {isa = PBXBuildFile; fileRef = 2C369C6F2889D44100B5AFB2 /* DeviceView.swift */; };
2C865E3B284271C800F1A89A /* MoWeStaApi in Frameworks */ = {isa = PBXBuildFile; productRef = 2C865E3A284271C800F1A89A /* MoWeStaApi */; };
2C865E3D2842850800F1A89A /* HideableTabView.swift in Sources */ = {isa = PBXBuildFile; fileRef = 2C865E3C2842850800F1A89A /* HideableTabView.swift */; };
2C865E3F28428ED600F1A89A /* TextBindings.swift in Sources */ = {isa = PBXBuildFile; fileRef = 2C865E3E28428ED600F1A89A /* TextBindings.swift */; };
@@ -23,6 +29,34 @@
2CA28203283E201B00D4A05A /* KeyChain.swift in Sources */ = {isa = PBXBuildFile; fileRef = 2CA28200283E201B00D4A05A /* KeyChain.swift */; };
2CA28204283E201B00D4A05A /* UserDefault.swift in Sources */ = {isa = PBXBuildFile; fileRef = 2CA28201283E201B00D4A05A /* UserDefault.swift */; };
2CA28205283E201B00D4A05A /* AppInfo.swift in Sources */ = {isa = PBXBuildFile; fileRef = 2CA28202283E201B00D4A05A /* AppInfo.swift */; };
2CA4E74F2885E62500B901ED /* LocosLabLeafles in Frameworks */ = {isa = PBXBuildFile; productRef = 2CA4E74E2885E62500B901ED /* LocosLabLeafles */; };
2CA4E7512887CB9800B901ED /* CountryView.swift in Sources */ = {isa = PBXBuildFile; fileRef = 2CA4E7502887CB9800B901ED /* CountryView.swift */; };
2CA4E7532887CBA300B901ED /* StateView.swift in Sources */ = {isa = PBXBuildFile; fileRef = 2CA4E7522887CBA300B901ED /* StateView.swift */; };
2CA4E7552887D18D00B901ED /* GeojsonConverter.swift in Sources */ = {isa = PBXBuildFile; fileRef = 2CA4E7542887D18D00B901ED /* GeojsonConverter.swift */; };
2CA4E757288826DA00B901ED /* PlaceMapView.swift in Sources */ = {isa = PBXBuildFile; fileRef = 2CA4E756288826DA00B901ED /* PlaceMapView.swift */; };
2CAC431B287F1C8F0088C9FD /* ApiHeader.swift in Sources */ = {isa = PBXBuildFile; fileRef = 2CAC431A287F1C8F0088C9FD /* ApiHeader.swift */; };
2CAC431D287F399F0088C9FD /* CollectionView.swift in Sources */ = {isa = PBXBuildFile; fileRef = 2CAC431C287F399F0088C9FD /* CollectionView.swift */; };
2CB84A35288B1D5B00DB8F41 /* Background.swift in Sources */ = {isa = PBXBuildFile; fileRef = 2CB84A34288B1D5B00DB8F41 /* Background.swift */; };
2CB84A38288B1F2B00DB8F41 /* BaseTask.swift in Sources */ = {isa = PBXBuildFile; fileRef = 2CB84A37288B1F2B00DB8F41 /* BaseTask.swift */; };
2CB84A3A288B206600DB8F41 /* RefreshTask.swift in Sources */ = {isa = PBXBuildFile; fileRef = 2CB84A39288B206600DB8F41 /* RefreshTask.swift */; };
2CB84A3C288B20A200DB8F41 /* SyncTask.swift in Sources */ = {isa = PBXBuildFile; fileRef = 2CB84A3B288B20A200DB8F41 /* SyncTask.swift */; };
2CB84A3E288C0E9200DB8F41 /* Favorites.swift in Sources */ = {isa = PBXBuildFile; fileRef = 2CB84A3D288C0E9200DB8F41 /* Favorites.swift */; };
2CB84A40288C563D00DB8F41 /* GradientViews.swift in Sources */ = {isa = PBXBuildFile; fileRef = 2CB84A3F288C563D00DB8F41 /* GradientViews.swift */; };
2CB84A42288C578500DB8F41 /* DataColorSchemes.swift in Sources */ = {isa = PBXBuildFile; fileRef = 2CB84A41288C578500DB8F41 /* DataColorSchemes.swift */; };
2CB84A44288C585000DB8F41 /* Interpolations.swift in Sources */ = {isa = PBXBuildFile; fileRef = 2CB84A43288C584F00DB8F41 /* Interpolations.swift */; };
2CB84A46288DA48500DB8F41 /* CityGradientView.swift in Sources */ = {isa = PBXBuildFile; fileRef = 2CB84A45288DA48500DB8F41 /* CityGradientView.swift */; };
2CB9AA532881AC0C00E9B888 /* FavoriteExtensions.swift in Sources */ = {isa = PBXBuildFile; fileRef = 2CB9AA522881AC0C00E9B888 /* FavoriteExtensions.swift */; };
2CC38B052911A728002E4DB0 /* ArduinoConfig.swift in Sources */ = {isa = PBXBuildFile; fileRef = 2CC38B042911A728002E4DB0 /* ArduinoConfig.swift */; };
2CC38B07291245AF002E4DB0 /* ArduinoTask.swift in Sources */ = {isa = PBXBuildFile; fileRef = 2CC38B06291245AF002E4DB0 /* ArduinoTask.swift */; };
2CC38B0A29128196002E4DB0 /* SetupView.swift in Sources */ = {isa = PBXBuildFile; fileRef = 2CC38B0929128196002E4DB0 /* SetupView.swift */; };
2CD7E0BF2884402500F9CE57 /* WeatherViews.swift in Sources */ = {isa = PBXBuildFile; fileRef = 2CD7E0BE2884402500F9CE57 /* WeatherViews.swift */; };
2CD7E0C12884415A00F9CE57 /* CityForecastView.swift in Sources */ = {isa = PBXBuildFile; fileRef = 2CD7E0C02884415A00F9CE57 /* CityForecastView.swift */; };
2CD7E0C328849FF900F9CE57 /* WeatherAggregates.swift in Sources */ = {isa = PBXBuildFile; fileRef = 2CD7E0C228849FF900F9CE57 /* WeatherAggregates.swift */; };
2CD7E0C528856C3500F9CE57 /* PageView.swift in Sources */ = {isa = PBXBuildFile; fileRef = 2CD7E0C428856C3500F9CE57 /* PageView.swift */; };
2CD7E0C728857A7900F9CE57 /* CustomizeView.swift in Sources */ = {isa = PBXBuildFile; fileRef = 2CD7E0C628857A7900F9CE57 /* CustomizeView.swift */; };
2CD7E0C92885A0F700F9CE57 /* CityVideoView.swift in Sources */ = {isa = PBXBuildFile; fileRef = 2CD7E0C82885A0F700F9CE57 /* CityVideoView.swift */; };
2CD7E0CD2885AD7D00F9CE57 /* RemoteImageView.swift in Sources */ = {isa = PBXBuildFile; fileRef = 2CD7E0CC2885AD7D00F9CE57 /* RemoteImageView.swift */; };
2CE5E860287ECB98006B8CDF /* ProgressViews.swift in Sources */ = {isa = PBXBuildFile; fileRef = 2CE5E85F287ECB98006B8CDF /* ProgressViews.swift */; };
2CEB0281283EB09B00DF3151 /* Database.xcdatamodeld in Sources */ = {isa = PBXBuildFile; fileRef = 2CEB027F283EB09B00DF3151 /* Database.xcdatamodeld */; };
2CEB02862840C50700DF3151 /* TermsView.swift in Sources */ = {isa = PBXBuildFile; fileRef = 2CEB02822840C50700DF3151 /* TermsView.swift */; };
2CEB02872840C50700DF3151 /* ButtonStyles.swift in Sources */ = {isa = PBXBuildFile; fileRef = 2CEB02832840C50700DF3151 /* ButtonStyles.swift */; };
@@ -40,6 +74,8 @@
2CFC0F18284219C600E597DC /* DrawerView.swift in Sources */ = {isa = PBXBuildFile; fileRef = 2CFC0F17284219C600E597DC /* DrawerView.swift */; };
2CFC0F1A284219D400E597DC /* SearchView.swift in Sources */ = {isa = PBXBuildFile; fileRef = 2CFC0F19284219D400E597DC /* SearchView.swift */; };
2CFC0F1C28421A0300E597DC /* FavoritesView.swift in Sources */ = {isa = PBXBuildFile; fileRef = 2CFC0F1B28421A0300E597DC /* FavoritesView.swift */; };
2CFCF22B291385A5000D0683 /* ArduinoLocator.swift in Sources */ = {isa = PBXBuildFile; fileRef = 2CFCF22A291385A5000D0683 /* ArduinoLocator.swift */; };
2CFCF22D2913C957000D0683 /* ArduinoState.swift in Sources */ = {isa = PBXBuildFile; fileRef = 2CFCF22C2913C957000D0683 /* ArduinoState.swift */; };
/* End PBXBuildFile section */
/* Begin PBXContainerItemProxy section */
@@ -71,6 +107,12 @@
2C163326283A27D600F78CEE /* AppUITests.xctest */ = {isa = PBXFileReference; explicitFileType = wrapper.cfbundle; includeInIndex = 0; path = AppUITests.xctest; sourceTree = BUILT_PRODUCTS_DIR; };
2C16332A283A27D600F78CEE /* AppUITests.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = AppUITests.swift; sourceTree = "<group>"; };
2C16332C283A27D600F78CEE /* AppUITestsLaunchTests.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = AppUITestsLaunchTests.swift; sourceTree = "<group>"; };
2C369C6528888E6800B5AFB2 /* StationView.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = StationView.swift; sourceTree = "<group>"; };
2C369C6728889EAE00B5AFB2 /* ErrorView.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = ErrorView.swift; sourceTree = "<group>"; };
2C369C692889592500B5AFB2 /* StationsView.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = StationsView.swift; sourceTree = "<group>"; };
2C369C6B2889719C00B5AFB2 /* MeasurementView.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = MeasurementView.swift; sourceTree = "<group>"; };
2C369C6D2889D42700B5AFB2 /* DevicesView.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = DevicesView.swift; sourceTree = "<group>"; };
2C369C6F2889D44100B5AFB2 /* DeviceView.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = DeviceView.swift; sourceTree = "<group>"; };
2C865E392842719F00F1A89A /* ios-api */ = {isa = PBXFileReference; lastKnownFileType = wrapper; name = "ios-api"; path = "../ios-api"; sourceTree = "<group>"; };
2C865E3C2842850800F1A89A /* HideableTabView.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = HideableTabView.swift; sourceTree = "<group>"; };
2C865E3E28428ED600F1A89A /* TextBindings.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = TextBindings.swift; sourceTree = "<group>"; };
@@ -80,6 +122,36 @@
2CA28200283E201B00D4A05A /* KeyChain.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = KeyChain.swift; sourceTree = "<group>"; };
2CA28201283E201B00D4A05A /* UserDefault.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = UserDefault.swift; sourceTree = "<group>"; };
2CA28202283E201B00D4A05A /* AppInfo.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = AppInfo.swift; sourceTree = "<group>"; };
2CA4E7502887CB9800B901ED /* CountryView.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = CountryView.swift; sourceTree = "<group>"; };
2CA4E7522887CBA300B901ED /* StateView.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = StateView.swift; sourceTree = "<group>"; };
2CA4E7542887D18D00B901ED /* GeojsonConverter.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = GeojsonConverter.swift; sourceTree = "<group>"; };
2CA4E756288826DA00B901ED /* PlaceMapView.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = PlaceMapView.swift; sourceTree = "<group>"; };
2CAC431A287F1C8F0088C9FD /* ApiHeader.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = ApiHeader.swift; sourceTree = "<group>"; };
2CAC431C287F399F0088C9FD /* CollectionView.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = CollectionView.swift; sourceTree = "<group>"; };
2CB84A33288AFD3400DB8F41 /* Info.plist */ = {isa = PBXFileReference; lastKnownFileType = text.plist; path = Info.plist; sourceTree = "<group>"; };
2CB84A34288B1D5B00DB8F41 /* Background.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = Background.swift; sourceTree = "<group>"; };
2CB84A37288B1F2B00DB8F41 /* BaseTask.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = BaseTask.swift; sourceTree = "<group>"; };
2CB84A39288B206600DB8F41 /* RefreshTask.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = RefreshTask.swift; sourceTree = "<group>"; };
2CB84A3B288B20A200DB8F41 /* SyncTask.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = SyncTask.swift; sourceTree = "<group>"; };
2CB84A3D288C0E9200DB8F41 /* Favorites.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = Favorites.swift; sourceTree = "<group>"; };
2CB84A3F288C563D00DB8F41 /* GradientViews.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = GradientViews.swift; sourceTree = "<group>"; };
2CB84A41288C578500DB8F41 /* DataColorSchemes.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = DataColorSchemes.swift; sourceTree = "<group>"; };
2CB84A43288C584F00DB8F41 /* Interpolations.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = Interpolations.swift; sourceTree = "<group>"; };
2CB84A45288DA48500DB8F41 /* CityGradientView.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = CityGradientView.swift; sourceTree = "<group>"; };
2CB9AA522881AC0C00E9B888 /* FavoriteExtensions.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = FavoriteExtensions.swift; sourceTree = "<group>"; };
2CB9AA552882CD3600E9B888 /* lib-leafless */ = {isa = PBXFileReference; lastKnownFileType = wrapper; name = "lib-leafless"; path = "../ios-locoslab/lib-leafless"; sourceTree = "<group>"; };
2CC38B042911A728002E4DB0 /* ArduinoConfig.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; name = ArduinoConfig.swift; path = app/Arduino/ArduinoConfig.swift; sourceTree = SOURCE_ROOT; };
2CC38B06291245AF002E4DB0 /* ArduinoTask.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; name = ArduinoTask.swift; path = app/Arduino/ArduinoTask.swift; sourceTree = SOURCE_ROOT; };
2CC38B082912463F002E4DB0 /* App.entitlements */ = {isa = PBXFileReference; lastKnownFileType = text.plist.entitlements; path = App.entitlements; sourceTree = "<group>"; };
2CC38B0929128196002E4DB0 /* SetupView.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; name = SetupView.swift; path = app/View/SetupView.swift; sourceTree = SOURCE_ROOT; };
2CD7E0BE2884402500F9CE57 /* WeatherViews.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = WeatherViews.swift; sourceTree = "<group>"; };
2CD7E0C02884415A00F9CE57 /* CityForecastView.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = CityForecastView.swift; sourceTree = "<group>"; };
2CD7E0C228849FF900F9CE57 /* WeatherAggregates.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = WeatherAggregates.swift; sourceTree = "<group>"; };
2CD7E0C428856C3500F9CE57 /* PageView.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = PageView.swift; sourceTree = "<group>"; };
2CD7E0C628857A7900F9CE57 /* CustomizeView.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = CustomizeView.swift; sourceTree = "<group>"; };
2CD7E0C82885A0F700F9CE57 /* CityVideoView.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = CityVideoView.swift; sourceTree = "<group>"; };
2CD7E0CC2885AD7D00F9CE57 /* RemoteImageView.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = RemoteImageView.swift; sourceTree = "<group>"; };
2CE5E85F287ECB98006B8CDF /* ProgressViews.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = ProgressViews.swift; sourceTree = "<group>"; };
2CEB0280283EB09B00DF3151 /* Database.xcdatamodel */ = {isa = PBXFileReference; lastKnownFileType = wrapper.xcdatamodel; path = Database.xcdatamodel; sourceTree = "<group>"; };
2CEB02822840C50700DF3151 /* TermsView.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = TermsView.swift; sourceTree = "<group>"; };
2CEB02832840C50700DF3151 /* ButtonStyles.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = ButtonStyles.swift; sourceTree = "<group>"; };
@@ -97,6 +169,8 @@
2CFC0F17284219C600E597DC /* DrawerView.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = DrawerView.swift; sourceTree = "<group>"; };
2CFC0F19284219D400E597DC /* SearchView.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = SearchView.swift; sourceTree = "<group>"; };
2CFC0F1B28421A0300E597DC /* FavoritesView.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = FavoritesView.swift; sourceTree = "<group>"; };
2CFCF22A291385A5000D0683 /* ArduinoLocator.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; name = ArduinoLocator.swift; path = app/Arduino/ArduinoLocator.swift; sourceTree = SOURCE_ROOT; };
2CFCF22C2913C957000D0683 /* ArduinoState.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; name = ArduinoState.swift; path = app/Arduino/ArduinoState.swift; sourceTree = SOURCE_ROOT; };
/* End PBXFileReference section */
/* Begin PBXFrameworksBuildPhase section */
@@ -104,6 +178,7 @@
isa = PBXFrameworksBuildPhase;
buildActionMask = 2147483647;
files = (
2CA4E74F2885E62500B901ED /* LocosLabLeafles in Frameworks */,
2C865E3B284271C800F1A89A /* MoWeStaApi in Frameworks */,
);
runOnlyForDeploymentPostprocessing = 0;
@@ -128,6 +203,7 @@
2C1632FE283A27D300F78CEE = {
isa = PBXGroup;
children = (
2CB9AA552882CD3600E9B888 /* lib-leafless */,
2C865E392842719F00F1A89A /* ios-api */,
2C163309283A27D300F78CEE /* App */,
2C16331F283A27D600F78CEE /* AppTests */,
@@ -150,16 +226,21 @@
2C163309283A27D300F78CEE /* App */ = {
isa = PBXGroup;
children = (
2CFC0F132841201E00E597DC /* Html */,
2CEB028C2840C96D00DF3151 /* Ui */,
2CC38B082912463F002E4DB0 /* App.entitlements */,
2CB84A33288AFD3400DB8F41 /* Info.plist */,
2CEB027F283EB09B00DF3151 /* Database.xcdatamodeld */,
2CFC0F132841201E00E597DC /* Html */,
2CC38B032911A706002E4DB0 /* Arduino */,
2CEB028C2840C96D00DF3151 /* Ui */,
2CA281FD283E1D1300D4A05A /* Model */,
2CA281FC283E1D0400D4A05A /* View */,
2CB84A36288B1EE900DB8F41 /* Task */,
2CA281FB283E1CEB00D4A05A /* Util */,
2C16330A283A27D300F78CEE /* Application.swift */,
2CB84A34288B1D5B00DB8F41 /* Background.swift */,
2C16330C283A27D300F78CEE /* ContentView.swift */,
2C16330E283A27D600F78CEE /* Assets.xcassets */,
2C163313283A27D600F78CEE /* Persistence.swift */,
2C16330E283A27D600F78CEE /* Assets.xcassets */,
2C163310283A27D600F78CEE /* Preview Content */,
2CEB028A2840C54000DF3151 /* StartScreen.storyboard */,
2CEB029C2840CD3200DF3151 /* Localizable.strings */,
@@ -206,6 +287,8 @@
2CA28200283E201B00D4A05A /* KeyChain.swift */,
2CA28201283E201B00D4A05A /* UserDefault.swift */,
2CF8D62928440FE4008FB7D0 /* UnitConverter.swift */,
2CAC431A287F1C8F0088C9FD /* ApiHeader.swift */,
2CA4E7542887D18D00B901ED /* GeojsonConverter.swift */,
);
path = Util;
sourceTree = "<group>";
@@ -222,6 +305,21 @@
2CFC0F1B28421A0300E597DC /* FavoritesView.swift */,
2C865E402842999600F1A89A /* CityView.swift */,
2C865E42284393DA00F1A89A /* CityInfoView.swift */,
2CD7E0C02884415A00F9CE57 /* CityForecastView.swift */,
2CB84A45288DA48500DB8F41 /* CityGradientView.swift */,
2CD7E0C82885A0F700F9CE57 /* CityVideoView.swift */,
2CA4E7502887CB9800B901ED /* CountryView.swift */,
2CA4E7522887CBA300B901ED /* StateView.swift */,
2CAC431C287F399F0088C9FD /* CollectionView.swift */,
2CD7E0BE2884402500F9CE57 /* WeatherViews.swift */,
2CD7E0C628857A7900F9CE57 /* CustomizeView.swift */,
2CA4E756288826DA00B901ED /* PlaceMapView.swift */,
2C369C6528888E6800B5AFB2 /* StationView.swift */,
2C369C692889592500B5AFB2 /* StationsView.swift */,
2C369C6B2889719C00B5AFB2 /* MeasurementView.swift */,
2C369C6F2889D44100B5AFB2 /* DeviceView.swift */,
2C369C6D2889D42700B5AFB2 /* DevicesView.swift */,
2CC38B0929128196002E4DB0 /* SetupView.swift */,
);
path = View;
sourceTree = "<group>";
@@ -233,16 +331,47 @@
2C865E3E28428ED600F1A89A /* TextBindings.swift */,
2CF8D6252843D0DB008FB7D0 /* ImageBindings.swift */,
2CF8D62728440E05008FB7D0 /* DataBindings.swift */,
2CB9AA522881AC0C00E9B888 /* FavoriteExtensions.swift */,
2CD7E0C228849FF900F9CE57 /* WeatherAggregates.swift */,
2CB84A3D288C0E9200DB8F41 /* Favorites.swift */,
2CB84A41288C578500DB8F41 /* DataColorSchemes.swift */,
2CB84A43288C584F00DB8F41 /* Interpolations.swift */,
);
path = Model;
sourceTree = "<group>";
};
2CB84A36288B1EE900DB8F41 /* Task */ = {
isa = PBXGroup;
children = (
2CB84A37288B1F2B00DB8F41 /* BaseTask.swift */,
2CB84A3B288B20A200DB8F41 /* SyncTask.swift */,
2CB84A39288B206600DB8F41 /* RefreshTask.swift */,
);
path = Task;
sourceTree = "<group>";
};
2CC38B032911A706002E4DB0 /* Arduino */ = {
isa = PBXGroup;
children = (
2CC38B042911A728002E4DB0 /* ArduinoConfig.swift */,
2CC38B06291245AF002E4DB0 /* ArduinoTask.swift */,
2CFCF22A291385A5000D0683 /* ArduinoLocator.swift */,
2CFCF22C2913C957000D0683 /* ArduinoState.swift */,
);
path = Arduino;
sourceTree = "<group>";
};
2CEB028C2840C96D00DF3151 /* Ui */ = {
isa = PBXGroup;
children = (
2CEB029E2840E7FA00DF3151 /* ViewExtensions.swift */,
2CEB02832840C50700DF3151 /* ButtonStyles.swift */,
2C865E3C2842850800F1A89A /* HideableTabView.swift */,
2CE5E85F287ECB98006B8CDF /* ProgressViews.swift */,
2CD7E0C428856C3500F9CE57 /* PageView.swift */,
2CD7E0CC2885AD7D00F9CE57 /* RemoteImageView.swift */,
2C369C6728889EAE00B5AFB2 /* ErrorView.swift */,
2CB84A3F288C563D00DB8F41 /* GradientViews.swift */,
);
path = Ui;
sourceTree = "<group>";
@@ -265,6 +394,7 @@
name = App;
packageProductDependencies = (
2C865E3A284271C800F1A89A /* MoWeStaApi */,
2CA4E74E2885E62500B901ED /* LocosLabLeafles */,
);
productName = App;
productReference = 2C163307283A27D300F78CEE /* MoWeSta.app */;
@@ -329,7 +459,7 @@
};
};
};
buildConfigurationList = 2C163302283A27D300F78CEE /* Build configuration list for PBXProject "App" */;
buildConfigurationList = 2C163302283A27D300F78CEE /* Build configuration list for PBXProject "app" */;
compatibilityVersion = "Xcode 13.0";
developmentRegion = en;
hasScannedForEncodings = 0;
@@ -385,28 +515,63 @@
buildActionMask = 2147483647;
files = (
2C865E3F28428ED600F1A89A /* TextBindings.swift in Sources */,
2CB84A35288B1D5B00DB8F41 /* Background.swift in Sources */,
2CB84A44288C585000DB8F41 /* Interpolations.swift in Sources */,
2CB9AA532881AC0C00E9B888 /* FavoriteExtensions.swift in Sources */,
2C369C702889D44100B5AFB2 /* DeviceView.swift in Sources */,
2C865E412842999600F1A89A /* CityView.swift in Sources */,
2CA4E7512887CB9800B901ED /* CountryView.swift in Sources */,
2CA4E757288826DA00B901ED /* PlaceMapView.swift in Sources */,
2C163314283A27D600F78CEE /* Persistence.swift in Sources */,
2CFCF22B291385A5000D0683 /* ArduinoLocator.swift in Sources */,
2CB84A46288DA48500DB8F41 /* CityGradientView.swift in Sources */,
2CB84A3C288B20A200DB8F41 /* SyncTask.swift in Sources */,
2CF8D6262843D0DB008FB7D0 /* ImageBindings.swift in Sources */,
2CA4E7552887D18D00B901ED /* GeojsonConverter.swift in Sources */,
2CFCF22D2913C957000D0683 /* ArduinoState.swift in Sources */,
2CAC431B287F1C8F0088C9FD /* ApiHeader.swift in Sources */,
2C369C6628888E6800B5AFB2 /* StationView.swift in Sources */,
2CD7E0C528856C3500F9CE57 /* PageView.swift in Sources */,
2CD7E0C12884415A00F9CE57 /* CityForecastView.swift in Sources */,
2CEB02862840C50700DF3151 /* TermsView.swift in Sources */,
2CA28204283E201B00D4A05A /* UserDefault.swift in Sources */,
2CD7E0C728857A7900F9CE57 /* CustomizeView.swift in Sources */,
2CFC0F18284219C600E597DC /* DrawerView.swift in Sources */,
2CEB0281283EB09B00DF3151 /* Database.xcdatamodeld in Sources */,
2CB84A40288C563D00DB8F41 /* GradientViews.swift in Sources */,
2C369C6A2889592500B5AFB2 /* StationsView.swift in Sources */,
2CD7E0CD2885AD7D00F9CE57 /* RemoteImageView.swift in Sources */,
2CC38B07291245AF002E4DB0 /* ArduinoTask.swift in Sources */,
2CD7E0C92885A0F700F9CE57 /* CityVideoView.swift in Sources */,
2CC38B052911A728002E4DB0 /* ArduinoConfig.swift in Sources */,
2CD7E0C328849FF900F9CE57 /* WeatherAggregates.swift in Sources */,
2CA28203283E201B00D4A05A /* KeyChain.swift in Sources */,
2C369C6E2889D42700B5AFB2 /* DevicesView.swift in Sources */,
2CC38B0A29128196002E4DB0 /* SetupView.swift in Sources */,
2CA281FF283E1D2F00D4A05A /* AppState.swift in Sources */,
2CB84A38288B1F2B00DB8F41 /* BaseTask.swift in Sources */,
2C369C6828889EAE00B5AFB2 /* ErrorView.swift in Sources */,
2CA28205283E201B00D4A05A /* AppInfo.swift in Sources */,
2C865E3D2842850800F1A89A /* HideableTabView.swift in Sources */,
2CB84A3A288B206600DB8F41 /* RefreshTask.swift in Sources */,
2CEB029F2840E7FA00DF3151 /* ViewExtensions.swift in Sources */,
2CB84A3E288C0E9200DB8F41 /* Favorites.swift in Sources */,
2CFC0F162842197C00E597DC /* LoginView.swift in Sources */,
2C16330D283A27D300F78CEE /* ContentView.swift in Sources */,
2CF8D62A28440FE4008FB7D0 /* UnitConverter.swift in Sources */,
2CEB02872840C50700DF3151 /* ButtonStyles.swift in Sources */,
2CA4E7532887CBA300B901ED /* StateView.swift in Sources */,
2CB84A42288C578500DB8F41 /* DataColorSchemes.swift in Sources */,
2CAC431D287F399F0088C9FD /* CollectionView.swift in Sources */,
2CFC0F1A284219D400E597DC /* SearchView.swift in Sources */,
2CD7E0BF2884402500F9CE57 /* WeatherViews.swift in Sources */,
2C865E43284393DA00F1A89A /* CityInfoView.swift in Sources */,
2CFC0F1C28421A0300E597DC /* FavoritesView.swift in Sources */,
2CF8D62828440E05008FB7D0 /* DataBindings.swift in Sources */,
2C369C6C2889719C00B5AFB2 /* MeasurementView.swift in Sources */,
2CEB02892840C50700DF3151 /* SettingsView.swift in Sources */,
2C16330B283A27D300F78CEE /* Application.swift in Sources */,
2CE5E860287ECB98006B8CDF /* ProgressViews.swift in Sources */,
2CEB02882840C50700DF3151 /* WebView.swift in Sources */,
);
runOnlyForDeploymentPostprocessing = 0;
@@ -507,7 +672,7 @@
GCC_WARN_UNINITIALIZED_AUTOS = YES_AGGRESSIVE;
GCC_WARN_UNUSED_FUNCTION = YES;
GCC_WARN_UNUSED_VARIABLE = YES;
IPHONEOS_DEPLOYMENT_TARGET = 15.5;
IPHONEOS_DEPLOYMENT_TARGET = 14.1;
MTL_ENABLE_DEBUG_INFO = INCLUDE_SOURCE;
MTL_FAST_MATH = YES;
ONLY_ACTIVE_ARCH = YES;
@@ -562,7 +727,7 @@
GCC_WARN_UNINITIALIZED_AUTOS = YES_AGGRESSIVE;
GCC_WARN_UNUSED_FUNCTION = YES;
GCC_WARN_UNUSED_VARIABLE = YES;
IPHONEOS_DEPLOYMENT_TARGET = 15.5;
IPHONEOS_DEPLOYMENT_TARGET = 14.1;
MTL_ENABLE_DEBUG_INFO = NO;
MTL_FAST_MATH = YES;
SDKROOT = iphoneos;
@@ -577,25 +742,30 @@
buildSettings = {
ASSETCATALOG_COMPILER_APPICON_NAME = AppIcon;
ASSETCATALOG_COMPILER_GLOBAL_ACCENT_COLOR_NAME = AccentColor;
CODE_SIGN_ENTITLEMENTS = App/App.entitlements;
CODE_SIGN_STYLE = Automatic;
CURRENT_PROJECT_VERSION = 1;
CURRENT_PROJECT_VERSION = 4;
DEVELOPMENT_ASSET_PATHS = "\"App/Preview Content\"";
DEVELOPMENT_TEAM = 2KS4Z77UGE;
ENABLE_PREVIEWS = YES;
GENERATE_INFOPLIST_FILE = YES;
INFOPLIST_FILE = App/Info.plist;
INFOPLIST_KEY_CFBundleDisplayName = MoWeSta;
INFOPLIST_KEY_LSApplicationCategoryType = "public.app-category.weather";
INFOPLIST_KEY_UIApplicationSceneManifest_Generation = YES;
INFOPLIST_KEY_UIApplicationSupportsIndirectInputEvents = YES;
INFOPLIST_KEY_UILaunchScreen_Generation = YES;
INFOPLIST_KEY_UILaunchStoryboardName = StartScreen;
INFOPLIST_KEY_UISupportedInterfaceOrientations_iPad = "UIInterfaceOrientationPortrait UIInterfaceOrientationPortraitUpsideDown UIInterfaceOrientationLandscapeLeft UIInterfaceOrientationLandscapeRight";
INFOPLIST_KEY_UISupportedInterfaceOrientations = "UIInterfaceOrientationPortrait UIInterfaceOrientationLandscapeLeft UIInterfaceOrientationLandscapeRight";
INFOPLIST_KEY_UISupportedInterfaceOrientations_iPad = "UIInterfaceOrientationPortrait UIInterfaceOrientationPortraitUpsideDown UIInterfaceOrientationLandscapeLeft UIInterfaceOrientationLandscapeRight UIInterfaceOrientationPortrait";
INFOPLIST_KEY_UISupportedInterfaceOrientations_iPhone = "UIInterfaceOrientationPortrait UIInterfaceOrientationLandscapeLeft UIInterfaceOrientationLandscapeRight";
IPHONEOS_DEPLOYMENT_TARGET = 14.1;
LD_RUNPATH_SEARCH_PATHS = (
"$(inherited)",
"@executable_path/Frameworks",
);
MARKETING_VERSION = 1.0;
PRODUCT_BUNDLE_IDENTIFIER = com.mowesta.ios.App;
MARKETING_VERSION = 1.2;
PRODUCT_BUNDLE_IDENTIFIER = com.mowesta.app;
PRODUCT_NAME = MoWeSta;
SWIFT_EMIT_LOC_STRINGS = YES;
SWIFT_VERSION = 5.0;
@@ -608,25 +778,30 @@
buildSettings = {
ASSETCATALOG_COMPILER_APPICON_NAME = AppIcon;
ASSETCATALOG_COMPILER_GLOBAL_ACCENT_COLOR_NAME = AccentColor;
CODE_SIGN_ENTITLEMENTS = App/App.entitlements;
CODE_SIGN_STYLE = Automatic;
CURRENT_PROJECT_VERSION = 1;
CURRENT_PROJECT_VERSION = 4;
DEVELOPMENT_ASSET_PATHS = "\"App/Preview Content\"";
DEVELOPMENT_TEAM = 2KS4Z77UGE;
ENABLE_PREVIEWS = YES;
GENERATE_INFOPLIST_FILE = YES;
INFOPLIST_FILE = App/Info.plist;
INFOPLIST_KEY_CFBundleDisplayName = MoWeSta;
INFOPLIST_KEY_LSApplicationCategoryType = "public.app-category.weather";
INFOPLIST_KEY_UIApplicationSceneManifest_Generation = YES;
INFOPLIST_KEY_UIApplicationSupportsIndirectInputEvents = YES;
INFOPLIST_KEY_UILaunchScreen_Generation = YES;
INFOPLIST_KEY_UILaunchStoryboardName = StartScreen;
INFOPLIST_KEY_UISupportedInterfaceOrientations_iPad = "UIInterfaceOrientationPortrait UIInterfaceOrientationPortraitUpsideDown UIInterfaceOrientationLandscapeLeft UIInterfaceOrientationLandscapeRight";
INFOPLIST_KEY_UISupportedInterfaceOrientations = "UIInterfaceOrientationPortrait UIInterfaceOrientationLandscapeLeft UIInterfaceOrientationLandscapeRight";
INFOPLIST_KEY_UISupportedInterfaceOrientations_iPad = "UIInterfaceOrientationPortrait UIInterfaceOrientationPortraitUpsideDown UIInterfaceOrientationLandscapeLeft UIInterfaceOrientationLandscapeRight UIInterfaceOrientationPortrait";
INFOPLIST_KEY_UISupportedInterfaceOrientations_iPhone = "UIInterfaceOrientationPortrait UIInterfaceOrientationLandscapeLeft UIInterfaceOrientationLandscapeRight";
IPHONEOS_DEPLOYMENT_TARGET = 14.1;
LD_RUNPATH_SEARCH_PATHS = (
"$(inherited)",
"@executable_path/Frameworks",
);
MARKETING_VERSION = 1.0;
PRODUCT_BUNDLE_IDENTIFIER = com.mowesta.ios.App;
MARKETING_VERSION = 1.2;
PRODUCT_BUNDLE_IDENTIFIER = com.mowesta.app;
PRODUCT_NAME = MoWeSta;
SWIFT_EMIT_LOC_STRINGS = YES;
SWIFT_VERSION = 5.0;
@@ -713,7 +888,7 @@
/* End XCBuildConfiguration section */
/* Begin XCConfigurationList section */
2C163302283A27D300F78CEE /* Build configuration list for PBXProject "App" */ = {
2C163302283A27D300F78CEE /* Build configuration list for PBXProject "app" */ = {
isa = XCConfigurationList;
buildConfigurations = (
2C16332E283A27D600F78CEE /* Debug */,
@@ -756,6 +931,10 @@
isa = XCSwiftPackageProductDependency;
productName = MoWeStaApi;
};
2CA4E74E2885E62500B901ED /* LocosLabLeafles */ = {
isa = XCSwiftPackageProductDependency;
productName = LocosLabLeafles;
};
/* End XCSwiftPackageProductDependency section */
/* Begin XCVersionGroup section */
+10
View File
@@ -0,0 +1,10 @@
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
<plist version="1.0">
<dict>
<key>com.apple.developer.networking.HotspotConfiguration</key>
<true/>
<key>com.apple.developer.networking.wifi-info</key>
<true/>
</dict>
</plist>
+29 -4
View File
@@ -9,16 +9,41 @@ import SwiftUI
@main
struct Application: App {
let persistenceController = PersistenceController.shared
@State var appState = AppState();
let persistenceController = PersistenceController.shared
@UIApplicationDelegateAdaptor(ApplicationDelegate.self) var appDelegate
@Environment(\.scenePhase) var scenePhase
var body: some Scene {
WindowGroup {
ContentView()
.environment(\.managedObjectContext, persistenceController.container.viewContext)
.environment(\.appState, appState)
}.onChange(of: scenePhase) { phase in
switch phase {
case .background:
appDelegate.background.scheduleTask()
case .active:
print("Executing foreground refresh.")
RefreshTask().execute(completion: { success in
print("Completed foreground refresh: \(success)")
})
default:
break
}
}
}
}
class ApplicationDelegate: NSObject, UIApplicationDelegate {
let background = Background()
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey : Any]? = nil) -> Bool {
background.registerTask()
return true
}
}
+57
View File
@@ -0,0 +1,57 @@
//
// ArduinoConfig.swift
// App
//
// Created by Marcus Handte on 01.11.22.
//
import Foundation
struct ArduinoConfig: Codable {
var ssid: String
var password: String
var token: String
var id: String
var latitude: String
var longitude: String
init(ssid: String, password: String, token: String, id: Int64, latitude: Double, longitude: Double) {
self.ssid = ssid
self.password = password
self.token = token
self.id = "\(id)"
self.latitude = "\(latitude)"
self.longitude = "\(longitude)"
}
enum CodingKeys: String, CodingKey {
case ssid = "ssid"
case password = "password"
case token = "token"
case id = "id"
case latitude = "latitude"
case longitude = "longitude"
}
func toJson() -> Data? {
let encoder = JSONEncoder()
let encoded = try? encoder.encode(self)
if let en = encoded, let string = String(data: en, encoding: .utf8) {
return "\(string)\n".data(using: .utf8)
}
return nil
}
}
enum ArduinoConstants: String {
/// The network name of the weather station.
case ssid = "MoWeSta - WiFi"
/// The network password of the weather station.
case password = "mowesta123456wifi"
/// The ip address of the weather station.
case ip = "192.168.4.1"
/// The port of the weather station.
case port = "8080"
}
+73
View File
@@ -0,0 +1,73 @@
//
// ArduinoLocator.swift - A utility class to implement one-shot
// localization using core location.
//
// Created by Marcus Handte on 03.11.22.
//
import Foundation
import CoreLocation
class ArduinoLocator: NSObject, ObservableObject, CLLocationManagerDelegate {
let locationManager = CLLocationManager()
var localizing = false { willSet { objectWillChange.send() }}
var disabled = false { willSet { objectWillChange.send() }}
private var listener: ((Double, Double) -> Void)?
override init() {
super.init()
locationManager.desiredAccuracy = 10
locationManager.delegate = self
disabled = locationManager.authorizationStatus == .denied
}
func setListener(_ listener: @escaping (Double, Double) -> Void) {
self.listener = listener
localizing = true
if locationManager.authorizationStatus != .authorizedWhenInUse &&
locationManager.authorizationStatus != .authorizedAlways {
locationManager.requestWhenInUseAuthorization()
} else {
locationManager.requestLocation()
}
}
func clearListener() {
self.listener = nil
localizing = false
locationManager.stopUpdatingLocation()
}
func locationManagerDidChangeAuthorization(_ manager: CLLocationManager) {
disabled = locationManager.authorizationStatus == .denied
if listener != nil && (manager.authorizationStatus == .authorizedWhenInUse ||
manager.authorizationStatus == .authorizedAlways) {
manager.requestLocation()
} else {
localizing = false
listener = nil
}
}
func locationManager(_ manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) {
if let location = locations.last {
let lat = location.coordinate.latitude
let lon = location.coordinate.longitude
if let l = listener {
l(lon, lat);
listener = nil
localizing = false
}
}
}
func locationManager(_ manager: CLLocationManager, didFailWithError error: Error) {
listener = nil
localizing = false
}
}
+71
View File
@@ -0,0 +1,71 @@
//
// ArduinoState.swift - The state object to store the state of the arduino process.
//
// Created by Marcus Handte on 03.11.22.
//
import Foundation
import NetworkExtension
/// The state to track the progress of the arduino configuration
class ArduinoState: ObservableObject {
var phase = ArduinoPhase.configure { willSet { objectWillChange.send() }}
var failure: ArduinoPhase?
var network = "" { willSet { objectWillChange.send() }}
var password = "" { willSet { objectWillChange.send() }}
var model = "Arduino" { willSet { objectWillChange.send() }}
var longitude = "" { willSet { objectWillChange.send() }}
var latitude = "" { willSet { objectWillChange.send() }}
var lon: Double? {
return Double(longitude)
}
var lat: Double? {
return Double(latitude)
}
init() {
updateNetwork()
}
func updateNetwork() {
guard network.count == 0 else {
return
}
NEHotspotNetwork.fetchCurrent(completionHandler: { net in
if let n = net {
if self.network.count == 0 {
self.network = n.ssid
}
}
})
}
func reset() {
if phase == .failure || phase == .success{
failure = nil
phase = .configure
}
}
func isExecutable() -> Bool {
return phase == .configure &&
network.count > 0 &&
password.count >= 8 &&
model.count > 0 &&
lat != nil &&
lon != nil
}
}
/// The phases of the configuration process
enum ArduinoPhase {
case configure
case register
case connect
case transfer
case success
case failure
}
+276
View File
@@ -0,0 +1,276 @@
//
// ArduinoTask.swift - The task to configure an arduino
// once all configuration has been provided.
//
// Created by Marcus Handte on 02.11.22.
//
import Foundation
import Network
import NetworkExtension
import MoWeStaApi
class ArduinoTask: BaseTask {
let appState = AppState.shared
let credentials = AppState.shared.credentials
let taskState: ArduinoState
init(taskState: ArduinoState) {
self.taskState = taskState
}
public func execute() {
taskState.phase = .register
taskState.failure = nil
super.execute(completion: { success in
if success {
self.taskState.phase = .success
} else {
self.taskState.failure = self.taskState.phase
self.taskState.phase = .failure
}
})
}
override func executeAsync() -> Bool {
// check preconditions
guard let c = credentials, let lon = taskState.lon, let lat = taskState.lat else {
return false
}
let creator = ArduinoCreator(c, taskState.model)
guard let handle = creator.createDevice(), let id = handle.id else {
return false
}
let config = ArduinoConfig(ssid: taskState.network, password: taskState.password, token: handle.token, id: id, latitude: lat, longitude: lon)
DispatchQueue.main.async {
self.taskState.phase = .connect
}
// connect to the network
let joiner = ArduinoJoiner()
if !joiner.connect() {
creator.deleteDevice()
return false
}
DispatchQueue.main.async {
self.taskState.phase = .transfer
}
// transfer the data
let transfer = ArduinoTransfer(config)
if !transfer.transfer() {
joiner.disconnect()
creator.deleteDevice()
return false
}
// disconnect
joiner.disconnect()
return true
}
}
class ArduinoTransfer {
let config: ArduinoConfig
var transmit = false
var success = false
init(_ config: ArduinoConfig) {
self.config = config
}
public func transfer() -> Bool {
let queue = DispatchQueue.init(label: "transfer")
let tcpOptions = NWProtocolTCP.Options()
tcpOptions.connectionTimeout = 60
tcpOptions.noDelay = true
tcpOptions.connectionDropTime = 30
let connection = NWConnection(
host: NWEndpoint.Host(ArduinoConstants.ip.rawValue),
port: NWEndpoint.Port(rawValue: UInt16(ArduinoConstants.port.rawValue)!)!,
using: NWParameters(tls: nil, tcp: tcpOptions))
let sender = DispatchSemaphore(value: 0)
let receiver = DispatchSemaphore(value: 0)
connection.stateUpdateHandler = { state in
switch state {
case .setup:
self.dprint("Tcp setup")
case .cancelled:
self.dprint("Tcp cancelled")
sender.signal()
case let .failed(error):
self.dprint("Tcp failed \(error)")
sender.signal()
case .preparing:
self.dprint("Tcp preparing")
case .ready:
self.dprint("Tcp ready")
sender.signal()
case let .waiting(error):
self.dprint("Tcp waiting \(error)")
default:
self.dprint("Tcp unknown")
}
}
dprint("Waitng for connection")
connection.start(queue: queue)
sender.wait()
dprint("Continue connection")
if connection.state != .ready {
dprint("Connection state not ready but \(connection.state)")
connection.cancel()
return false
}
dprint("Start receiving data")
connection.receive(minimumIncompleteLength: 5, maximumLength: 10, completion: {
data, context, complete, error in
if let d = data {
let s = String(decoding: d, as: UTF8.self)
self.dprint("Reception ok \(s)")
self.success = s.lowercased().contains("success")
receiver.signal()
} else if let e = error {
self.dprint("Reception error \(e)")
receiver.signal()
}
})
dprint("Sending data")
connection.send(
content: config.toJson(),
completion: .contentProcessed({ error in
self.dprint("Processed")
if let e = error {
self.dprint("Transmission error \(e)")
}
self.transmit = error == nil
sender.signal()
})
)
sender.wait()
dprint("Continue sending")
if !transmit {
dprint("Aborting since sending failed")
connection.cancel()
return false
}
let result = receiver.wait(timeout: .now() + 30)
if (result == .timedOut) {
dprint("Timeout")
}
dprint("Closing connection \(success)")
connection.cancel()
return success
}
func dprint(_ text: String) {
// heavy debug
// print(text)
}
}
/// A class to join the wifi network of the station.
class ArduinoJoiner {
let config: NEHotspotConfiguration
var success = false
public init() {
self.config = NEHotspotConfiguration(ssidPrefix: ArduinoConstants.ssid.rawValue, passphrase: ArduinoConstants.password.rawValue, isWEP: false)
self.config.joinOnce = false
}
public func connect() -> Bool {
let group = DispatchGroup()
group.enter()
NEHotspotConfigurationManager.shared.apply(self.config) { error in
if error == nil {
self.success = true
} else {
self.success = false
self.disconnect()
}
group.leave()
}
group.wait()
return success
}
public func disconnect() {
NEHotspotConfigurationManager.shared.removeConfiguration(forSSID: ArduinoConstants.ssid.rawValue)
}
}
/// A class to create and delete a device entry for a weather station.
class ArduinoCreator {
private static let MAX_ATTEMPT = 8
let credential: UserCredentials
let model: String
var handle: DeviceHandle? = nil
init(_ credential: UserCredentials, _ model: String) {
self.credential = credential
self.model = model
}
public func createDevice() -> DeviceHandle? {
print("Creating device handle.")
let info = DeviceInfo(device: "Arduino", manufacturer: "MoWeSta", model: model, os: .arduino)
let group = DispatchGroup()
group.enter()
let rb = DefaultAPI.createDeviceWithRequestBuilder(body: info)
rb.addHeaders(ApiHeader.create(credential))
rb.execute() { result in
switch result {
case let .success(response):
print("Sucessfully created device.")
self.handle = response.body
case let .failure(.error(code, _, _, _)):
print("Failed to create device \(code).")
}
group.leave()
}
group.wait()
return handle
}
public func deleteDevice() {
retryDeleteDevice(attempt: 0)
}
private func retryDeleteDevice(attempt: Int) {
if let h = handle, let id = h.id {
print("Deleting device \(id) (\(attempt)).")
let group = DispatchGroup()
group.enter()
let rb = DefaultAPI.deleteDeviceWithRequestBuilder(id: id)
rb.addHeaders(ApiHeader.create(credential))
rb.execute() { result in
switch result {
case .success(_):
print("Successfully deleted device.")
self.handle = nil
case let .failure(.error(code, _, _, _)):
if (code == -1 && attempt < ArduinoCreator.MAX_ATTEMPT) {
BaseTask.queue.asyncAfter(deadline: .now() + 5) {
self.retryDeleteDevice(attempt: attempt + 1)
}
} else {
print("Failed to delete device \(code).")
}
}
group.leave()
}
group.wait()
}
}
}
@@ -0,0 +1,16 @@
{
"images" : [
{
"filename" : "icon_android.svg",
"idiom" : "universal"
}
],
"info" : {
"author" : "xcode",
"version" : 1
},
"properties" : {
"preserves-vector-representation" : true,
"template-rendering-intent" : "template"
}
}
@@ -0,0 +1 @@
<svg xmlns="http://www.w3.org/2000/svg" height="24" width="24" viewBox="0 0 48 48"><path d="M19.9 41.75h8.2v-2h-8.2ZM13 46q-1.2 0-2.1-.9-.9-.9-.9-2.1V5q0-1.2.9-2.1.9-.9 2.1-.9h22q1.2 0 2.1.9.9.9.9 2.1v38q0 1.2-.9 2.1-.9.9-2.1.9Zm0-7.5V43h22v-4.5Zm0-3h22v-26H13Zm0-29h22V5H13Zm0 32V43Zm0-32V5v1.5Z"/></svg>

After

Width:  |  Height:  |  Size: 305 B

@@ -0,0 +1,16 @@
{
"images" : [
{
"filename" : "icon_arduino.svg",
"idiom" : "universal"
}
],
"info" : {
"author" : "xcode",
"version" : 1
},
"properties" : {
"preserves-vector-representation" : true,
"template-rendering-intent" : "template"
}
}
@@ -0,0 +1 @@
<svg xmlns="http://www.w3.org/2000/svg" height="24" width="24" viewBox="0 0 48 48"><path d="M18.85 29.15V18.9H29.1v10.25Zm3-3h4.25V21.9h-4.25ZM18 42v-4h-5q-1.2 0-2.1-.9-.9-.9-.9-2.1v-5H6v-3h4v-6.2H6v-3h4v-5q0-1.2.9-2.1.9-.9 2.1-.9h5V6h3v3.8h6.2V6h3v3.8h5q1.2 0 2.1.9.9.9.9 2.1v5H42v3h-3.8V27H42v3h-3.8v5q0 1.2-.9 2.1-.9.9-2.1.9h-5v4h-3v-4H21v4Zm17.2-7V12.8H13V35ZM24 24Z"/></svg>

After

Width:  |  Height:  |  Size: 379 B

@@ -10,6 +10,7 @@
"version" : 1
},
"properties" : {
"preserves-vector-representation" : true
"preserves-vector-representation" : true,
"template-rendering-intent" : "template"
}
}
@@ -10,6 +10,7 @@
"version" : 1
},
"properties" : {
"preserves-vector-representation" : true
"preserves-vector-representation" : true,
"template-rendering-intent" : "template"
}
}
@@ -10,6 +10,7 @@
"version" : 1
},
"properties" : {
"preserves-vector-representation" : true
"preserves-vector-representation" : true,
"template-rendering-intent" : "template"
}
}
@@ -10,6 +10,7 @@
"version" : 1
},
"properties" : {
"preserves-vector-representation" : true
"preserves-vector-representation" : true,
"template-rendering-intent" : "template"
}
}
@@ -10,6 +10,7 @@
"version" : 1
},
"properties" : {
"preserves-vector-representation" : true
"preserves-vector-representation" : true,
"template-rendering-intent" : "template"
}
}
@@ -10,6 +10,7 @@
"version" : 1
},
"properties" : {
"preserves-vector-representation" : true
"preserves-vector-representation" : true,
"template-rendering-intent" : "template"
}
}
@@ -10,6 +10,7 @@
"version" : 1
},
"properties" : {
"preserves-vector-representation" : true
"preserves-vector-representation" : true,
"template-rendering-intent" : "template"
}
}
@@ -10,6 +10,7 @@
"version" : 1
},
"properties" : {
"preserves-vector-representation" : true
"preserves-vector-representation" : true,
"template-rendering-intent" : "template"
}
}
@@ -10,6 +10,7 @@
"version" : 1
},
"properties" : {
"preserves-vector-representation" : true
"preserves-vector-representation" : true,
"template-rendering-intent" : "template"
}
}
@@ -10,6 +10,7 @@
"version" : 1
},
"properties" : {
"preserves-vector-representation" : true
"preserves-vector-representation" : true,
"template-rendering-intent" : "template"
}
}
@@ -10,6 +10,7 @@
"version" : 1
},
"properties" : {
"preserves-vector-representation" : true
"preserves-vector-representation" : true,
"template-rendering-intent" : "template"
}
}
@@ -10,6 +10,7 @@
"version" : 1
},
"properties" : {
"preserves-vector-representation" : true
"preserves-vector-representation" : true,
"template-rendering-intent" : "template"
}
}
@@ -0,0 +1,16 @@
{
"images" : [
{
"filename" : "icon_devices.svg",
"idiom" : "universal"
}
],
"info" : {
"author" : "xcode",
"version" : 1
},
"properties" : {
"preserves-vector-representation" : true,
"template-rendering-intent" : "template"
}
}
@@ -0,0 +1 @@
<svg xmlns="http://www.w3.org/2000/svg" height="25" width="25" viewBox="0 0 48 48"><path d="M4 40v-4.5h4.3V11q0-1.2.9-2.1.9-.9 2.1-.9h31v3h-31v24.5H23V40Zm23.95 0q-.8 0-1.375-.6T26 37.8V15.95q0-.8.575-1.375T27.95 14h13.6q1 0 1.725.575.725.575.725 1.375V37.8q0 1-.725 1.6-.725.6-1.725.6ZM29 35.5h12V17H29Z"/></svg>

After

Width:  |  Height:  |  Size: 313 B

@@ -10,6 +10,7 @@
"version" : 1
},
"properties" : {
"preserves-vector-representation" : true
"preserves-vector-representation" : true,
"template-rendering-intent" : "template"
}
}
@@ -0,0 +1,16 @@
{
"images" : [
{
"filename" : "icon_ios.svg",
"idiom" : "universal"
}
],
"info" : {
"author" : "xcode",
"version" : 1
},
"properties" : {
"preserves-vector-representation" : true,
"template-rendering-intent" : "template"
}
}
@@ -0,0 +1 @@
<svg xmlns="http://www.w3.org/2000/svg" height="24" width="24" viewBox="0 0 48 48"><path d="M13 46q-1.2 0-2.1-.9-.9-.9-.9-2.1V5q0-1.2.9-2.1.9-.9 2.1-.9h22q1.2 0 2.1.9.9.9.9 2.1v38q0 1.2-.9 2.1-.9.9-2.1.9Zm0-7.5V43h22v-4.5Zm11 3.75q.65 0 1.075-.425.425-.425.425-1.075 0-.65-.425-1.075-.425-.425-1.075-.425-.65 0-1.075.425-.425.425-.425 1.075 0 .65.425 1.075.425.425 1.075.425ZM13 35.5h22v-26H13Zm0-29h22V5H13Zm0 32V43Zm0-32V5v1.5Z"/></svg>

After

Width:  |  Height:  |  Size: 438 B

@@ -10,6 +10,7 @@
"version" : 1
},
"properties" : {
"preserves-vector-representation" : true
"preserves-vector-representation" : true,
"template-rendering-intent" : "template"
}
}
@@ -10,6 +10,7 @@
"version" : 1
},
"properties" : {
"preserves-vector-representation" : true
"preserves-vector-representation" : true,
"template-rendering-intent" : "template"
}
}
@@ -10,6 +10,7 @@
"version" : 1
},
"properties" : {
"preserves-vector-representation" : true
"preserves-vector-representation" : true,
"template-rendering-intent" : "template"
}
}
@@ -10,6 +10,7 @@
"version" : 1
},
"properties" : {
"preserves-vector-representation" : true
"preserves-vector-representation" : true,
"template-rendering-intent" : "template"
}
}
@@ -10,6 +10,7 @@
"version" : 1
},
"properties" : {
"preserves-vector-representation" : true
"preserves-vector-representation" : true,
"template-rendering-intent" : "template"
}
}
@@ -10,6 +10,7 @@
"version" : 1
},
"properties" : {
"preserves-vector-representation" : true
"preserves-vector-representation" : true,
"template-rendering-intent" : "template"
}
}
@@ -10,6 +10,7 @@
"version" : 1
},
"properties" : {
"preserves-vector-representation" : true
"preserves-vector-representation" : true,
"template-rendering-intent" : "template"
}
}
@@ -10,6 +10,7 @@
"version" : 1
},
"properties" : {
"preserves-vector-representation" : true
"preserves-vector-representation" : true,
"template-rendering-intent" : "template"
}
}
@@ -10,6 +10,7 @@
"version" : 1
},
"properties" : {
"preserves-vector-representation" : true
"preserves-vector-representation" : true,
"template-rendering-intent" : "template"
}
}
@@ -10,6 +10,7 @@
"version" : 1
},
"properties" : {
"preserves-vector-representation" : true
"preserves-vector-representation" : true,
"template-rendering-intent" : "template"
}
}
@@ -10,6 +10,7 @@
"version" : 1
},
"properties" : {
"preserves-vector-representation" : true
"preserves-vector-representation" : true,
"template-rendering-intent" : "template"
}
}
@@ -10,6 +10,7 @@
"version" : 1
},
"properties" : {
"preserves-vector-representation" : true
"preserves-vector-representation" : true,
"template-rendering-intent" : "template"
}
}
@@ -10,6 +10,7 @@
"version" : 1
},
"properties" : {
"preserves-vector-representation" : true
"preserves-vector-representation" : true,
"template-rendering-intent" : "template"
}
}
@@ -10,6 +10,7 @@
"version" : 1
},
"properties" : {
"preserves-vector-representation" : true
"preserves-vector-representation" : true,
"template-rendering-intent" : "template"
}
}
@@ -10,6 +10,7 @@
"version" : 1
},
"properties" : {
"preserves-vector-representation" : true
"preserves-vector-representation" : true,
"template-rendering-intent" : "template"
}
}
@@ -10,6 +10,7 @@
"version" : 1
},
"properties" : {
"preserves-vector-representation" : true
"preserves-vector-representation" : true,
"template-rendering-intent" : "template"
}
}
@@ -0,0 +1,16 @@
{
"images" : [
{
"filename" : "icon_station.svg",
"idiom" : "universal"
}
],
"info" : {
"author" : "xcode",
"version" : 1
},
"properties" : {
"preserves-vector-representation" : true,
"template-rendering-intent" : "template"
}
}
@@ -0,0 +1 @@
<svg xmlns="http://www.w3.org/2000/svg" height="22" width="22" viewBox="0 0 48 48"><path d="M24 24q0-4.55 3.225-7.775Q30.45 13 35 13q4.55 0 7.775 3.225Q46 19.45 46 24ZM13 35q-4.55 0-7.775-3.225Q2 28.55 2 24h22q0 4.55-3.225 7.775Q17.55 35 13 35Zm11-11q-4.55 0-7.775-3.225Q13 17.55 13 13q0-4.55 3.225-7.775Q19.45 2 24 2Zm0 22V24q4.55 0 7.775 3.225Q35 30.45 35 35q0 4.55-3.225 7.775Q28.55 46 24 46Z"/></svg>

After

Width:  |  Height:  |  Size: 404 B

@@ -10,6 +10,7 @@
"version" : 1
},
"properties" : {
"preserves-vector-representation" : true
"preserves-vector-representation" : true,
"template-rendering-intent" : "template"
}
}
@@ -10,6 +10,7 @@
"version" : 1
},
"properties" : {
"preserves-vector-representation" : true
"preserves-vector-representation" : true,
"template-rendering-intent" : "template"
}
}
@@ -10,6 +10,7 @@
"version" : 1
},
"properties" : {
"preserves-vector-representation" : true
"preserves-vector-representation" : true,
"template-rendering-intent" : "template"
}
}
@@ -0,0 +1,16 @@
{
"images" : [
{
"filename" : "icon_wind.svg",
"idiom" : "universal"
}
],
"info" : {
"author" : "xcode",
"version" : 1
},
"properties" : {
"preserves-vector-representation" : true,
"template-rendering-intent" : "template"
}
}
@@ -0,0 +1,15 @@
<?xml version="1.0" encoding="utf-8"?>
<!-- Generator: Adobe Illustrator 22.0.1, SVG Export Plug-In . SVG Version: 6.00 Build 0) -->
<svg version="1.1" id="Layer_1" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" x="0px" y="0px"
viewBox="0 0 30 30" style="enable-background:new 0 0 30 30;" xml:space="preserve">
<path d="M3.1,16.97c0,0.24,0.09,0.45,0.28,0.62c0.16,0.19,0.37,0.28,0.63,0.28H18.7c0.29,0,0.53,0.1,0.73,0.3
c0.2,0.2,0.3,0.45,0.3,0.74c0,0.29-0.1,0.53-0.3,0.72c-0.2,0.19-0.44,0.29-0.74,0.29c-0.29,0-0.54-0.1-0.73-0.29
c-0.16-0.18-0.36-0.26-0.6-0.26c-0.25,0-0.46,0.09-0.64,0.26s-0.27,0.38-0.27,0.61c0,0.25,0.09,0.46,0.28,0.63
c0.56,0.55,1.22,0.83,1.96,0.83c0.78,0,1.45-0.27,2.01-0.81c0.56-0.54,0.83-1.19,0.83-1.97s-0.28-1.44-0.84-2
c-0.56-0.56-1.23-0.84-2-0.84H4.01c-0.25,0-0.46,0.09-0.64,0.26C3.19,16.51,3.1,16.72,3.1,16.97z M3.1,13.69
c0,0.23,0.09,0.43,0.28,0.61c0.17,0.18,0.38,0.26,0.63,0.26h20.04c0.78,0,1.45-0.27,2.01-0.82c0.56-0.54,0.84-1.2,0.84-1.97
c0-0.77-0.28-1.44-0.84-1.99s-1.23-0.83-2.01-0.83c-0.77,0-1.42,0.27-1.95,0.8c-0.18,0.16-0.27,0.38-0.27,0.67
c0,0.26,0.09,0.47,0.26,0.63c0.17,0.16,0.38,0.24,0.63,0.24c0.24,0,0.45-0.08,0.63-0.24c0.19-0.21,0.42-0.31,0.7-0.31
c0.29,0,0.53,0.1,0.73,0.3c0.2,0.2,0.3,0.44,0.3,0.73c0,0.29-0.1,0.53-0.3,0.72c-0.2,0.19-0.44,0.29-0.73,0.29H4.01
c-0.25,0-0.46,0.09-0.64,0.26C3.19,13.23,3.1,13.44,3.1,13.69z"/>
</svg>

After

Width:  |  Height:  |  Size: 1.4 KiB

@@ -0,0 +1,16 @@
{
"images" : [
{
"filename" : "icon_wind_direction.svg",
"idiom" : "universal"
}
],
"info" : {
"author" : "xcode",
"version" : 1
},
"properties" : {
"preserves-vector-representation" : true,
"template-rendering-intent" : "template"
}
}
@@ -0,0 +1,12 @@
<?xml version="1.0" encoding="utf-8"?>
<!-- Generator: Adobe Illustrator 22.0.1, SVG Export Plug-In . SVG Version: 6.00 Build 0) -->
<svg version="1.1" id="Layer_1" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" x="0px" y="0px"
viewBox="0 0 30 30" style="enable-background:new 0 0 30 30;" xml:space="preserve">
<path d="M3.74,14.5c0-2.04,0.51-3.93,1.52-5.66s2.38-3.1,4.11-4.11s3.61-1.51,5.64-1.51c1.52,0,2.98,0.3,4.37,0.89
s2.58,1.4,3.59,2.4s1.81,2.2,2.4,3.6s0.89,2.85,0.89,4.39c0,1.52-0.3,2.98-0.89,4.37s-1.4,2.59-2.4,3.59s-2.2,1.8-3.59,2.39
s-2.84,0.89-4.37,0.89c-1.53,0-3-0.3-4.39-0.89s-2.59-1.4-3.6-2.4s-1.8-2.2-2.4-3.58S3.74,16.03,3.74,14.5z M6.22,14.5
c0,2.37,0.86,4.43,2.59,6.18c1.73,1.73,3.79,2.59,6.2,2.59c1.58,0,3.05-0.39,4.39-1.18s2.42-1.85,3.21-3.2s1.19-2.81,1.19-4.39
s-0.4-3.05-1.19-4.4s-1.86-2.42-3.21-3.21s-2.81-1.18-4.39-1.18s-3.05,0.39-4.39,1.18S8.2,8.75,7.4,10.1S6.22,12.92,6.22,14.5z
M11.11,20.35l3.75-13.11c0.01-0.1,0.06-0.15,0.15-0.15s0.14,0.05,0.15,0.15l3.74,13.11c0.04,0.11,0.03,0.19-0.02,0.25
s-0.13,0.06-0.24,0l-3.47-1.3c-0.1-0.04-0.2-0.04-0.29,0l-3.5,1.3c-0.1,0.06-0.17,0.06-0.21,0S11.09,20.45,11.11,20.35z"/>
</svg>

After

Width:  |  Height:  |  Size: 1.2 KiB

@@ -0,0 +1,12 @@
{
"images" : [
{
"filename" : "logo_fair.png",
"idiom" : "universal"
}
],
"info" : {
"author" : "xcode",
"version" : 1
}
}
Binary file not shown.

After

Width:  |  Height:  |  Size: 84 KiB

@@ -0,0 +1,12 @@
{
"images" : [
{
"filename" : "logo_ude.png",
"idiom" : "universal"
}
],
"info" : {
"author" : "xcode",
"version" : 1
}
}
Binary file not shown.

After

Width:  |  Height:  |  Size: 39 KiB

+52
View File
@@ -0,0 +1,52 @@
//
// BackgroundManager.swift
// App
//
// Created by Marcus Handte on 22.07.22.
//
import Foundation
import BackgroundTasks
/// A class to handle the background fetching
public class Background {
public func registerTask() {
print("Register background refresh.")
BGTaskScheduler.shared.register(forTaskWithIdentifier: "com.mowesta.app.refresh", using: DispatchQueue.global()) { task in
if let t = task as? BGAppRefreshTask {
self.executeTask(task: t)
}
}
}
public func scheduleTask() {
print("Schedule background refresh.")
let request = BGAppRefreshTaskRequest(identifier: "com.mowesta.app.refresh")
request.earliestBeginDate = Date(timeIntervalSinceNow: 60 * 60)
do {
try BGTaskScheduler.shared.submit(request)
} catch {
print("Could not schedule refresh: \(error)")
}
}
func executeTask(task: BGAppRefreshTask) {
print("Perform background refresh.")
let state = AppState.shared
var tasks: [BaseTask] = []
if state.credentials != nil {
tasks.append(SyncTask())
}
tasks.append(RefreshTask())
task.expirationHandler = {
BaseTask.cancel(all: tasks)
}
BaseTask.execute(all: tasks) { success in
print("Completed background refresh: \(success)")
task.setTaskCompleted(success: success)
self.scheduleTask()
}
}
}
+7 -45
View File
@@ -9,14 +9,8 @@ import SwiftUI
import CoreData
struct ContentView: View {
@Environment(\.managedObjectContext) private var viewContext
@FetchRequest(
sortDescriptors: [NSSortDescriptor(keyPath: \Item.timestamp, ascending: true)],
animation: .default)
private var items: FetchedResults<Item>
@Environment(\.appState) var appState
@ObservedObject var appState = AppState.shared
@Environment(\.tabViewState) var tabViewState
var body: some View {
@@ -24,6 +18,12 @@ struct ContentView: View {
TermsView() {
appState.terms = AppState.TERMS_VERSION
}
.environmentObject(tabViewState)
} else if (appState.device == nil) {
NavigationView {
LoginView(mode: .createDevice)
}
.navigationViewStyle(StackNavigationViewStyle())
} else {
NavigationView {
DrawerView()
@@ -32,46 +32,8 @@ struct ContentView: View {
.environmentObject(tabViewState)
}
}
private func addItem() {
withAnimation {
let newItem = Item(context: viewContext)
newItem.timestamp = Date()
do {
try viewContext.save()
} catch {
// Replace this implementation with code to handle the error appropriately.
// fatalError() causes the application to generate a crash log and terminate. You should not use this function in a shipping application, although it may be useful during development.
let nsError = error as NSError
fatalError("Unresolved error \(nsError), \(nsError.userInfo)")
}
}
}
private func deleteItems(offsets: IndexSet) {
withAnimation {
offsets.map { items[$0] }.forEach(viewContext.delete)
do {
try viewContext.save()
} catch {
// Replace this implementation with code to handle the error appropriately.
// fatalError() causes the application to generate a crash log and terminate. You should not use this function in a shipping application, although it may be useful during development.
let nsError = error as NSError
fatalError("Unresolved error \(nsError), \(nsError.userInfo)")
}
}
}
}
private let itemFormatter: DateFormatter = {
let formatter = DateFormatter()
formatter.dateStyle = .short
formatter.timeStyle = .medium
return formatter
}()
struct ContentView_Previews: PreviewProvider {
static var previews: some View {
ContentView().environment(\.managedObjectContext, PersistenceController.preview.container.viewContext).preferredColorScheme(.dark)
@@ -9,16 +9,21 @@
<attribute name="identifier" attributeType="Integer 64" defaultValueString="0" usesScalarValueType="YES"/>
<attribute name="location" optional="YES" attributeType="String"/>
<attribute name="locationTime" attributeType="Integer 64" defaultValueString="0" usesScalarValueType="YES"/>
<attribute name="locationType" optional="YES" attributeType="Integer 16" defaultValueString="0" usesScalarValueType="YES"/>
<attribute name="position" optional="YES" attributeType="Integer 16" defaultValueString="0" usesScalarValueType="YES"/>
<attribute name="removed" attributeType="Boolean" defaultValueString="NO" usesScalarValueType="YES"/>
<attribute name="station" optional="YES" attributeType="String"/>
<attribute name="type" optional="YES" attributeType="Integer 16" defaultValueString="0" usesScalarValueType="YES"/>
<attribute name="weatherTime" attributeType="Integer 64" defaultValueString="0" usesScalarValueType="YES"/>
<fetchIndex name="byPositionIndex">
<fetchIndexElement property="position" type="Binary" order="ascending"/>
<fetchIndexElement property="removed" type="Binary" order="ascending"/>
</fetchIndex>
</entity>
<entity name="Item" representedClassName="Item" syncable="YES" codeGenerationType="class">
<attribute name="timestamp" optional="YES" attributeType="Date" usesScalarValueType="NO"/>
</entity>
<elements>
<element name="Favorite" positionX="-63" positionY="-9" width="128" height="224"/>
<element name="Item" positionX="-63" positionY="-18" width="128" height="44"/>
<element name="Favorite" positionX="-63" positionY="-9" width="128" height="209"/>
</elements>
</model>
+16
View File
@@ -0,0 +1,16 @@
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
<plist version="1.0">
<dict>
<key>BGTaskSchedulerPermittedIdentifiers</key>
<array>
<string>com.mowesta.app.refresh</string>
</array>
<key>NSLocationWhenInUseUsageDescription</key>
<string>MoWeSta associates your location with the measurements of your devices.</string>
<key>UIBackgroundModes</key>
<array>
<string>fetch</string>
</array>
</dict>
</plist>
+77 -18
View File
@@ -7,6 +7,7 @@
import Foundation
import SwiftUI
import MoWeStaApi
/// The global application state that can be accessed all throughout the user interface
/// to access the user and ui state and settings.
@@ -14,36 +15,94 @@ public class AppState: ObservableObject {
// The current version of the license terms.
static let TERMS_VERSION = 1
// The shared application state.
public static let shared = AppState()
// The version of the license terms that the user has accepted.
@UserDefault("terms", defaultValue: 0) var terms: Int { willSet { objectWillChange.send() }}
@UserDefault("terms", defaultValue: 0) var terms: Int { willSet { objectWillChange.send(); }}
// A boolean to indicate whether the app is in development mode.
@UserDefault("development", defaultValue: false ) var development: Bool { willSet { objectWillChange.send() }}
// The device token used to upload data
@UserDefault("token", defaultValue: "") var token: String
// The device created upon initialization.
@UserDefault("device", defaultValue: "") var device: String
@UserDefault("precipitation", defaultValue: true) var precipitation: Bool { willSet { objectWillChange.send() }}
@UserDefault("windSpeed", defaultValue: true) var windSpeed: Bool { willSet { objectWillChange.send() }}
@UserDefault("cloudCoverage", defaultValue: true) var cloudCoverage: Bool { willSet { objectWillChange.send() }}
@UserDefault("humidity", defaultValue: true) var humidity: Bool { willSet { objectWillChange.send() }}
@UserDefault("snowDepth", defaultValue: true) var snowDepth: Bool { willSet { objectWillChange.send() }}
@UserDefault("pressure", defaultValue: true) var pressure: Bool { willSet { objectWillChange.send() }}
@UserDefault("unitSystem", defaultValue: .si) var unitSystem: UnitSystem { willSet { objectWillChange.send() }}
@UserDefault("temperatureUnit", defaultValue: .both) var temperatureUnit: TemperatureUnit { willSet { objectWillChange.send() }}
var credentialFailure = false { willSet { objectWillChange.send() }}
private var loadedDevice: Device? = nil
var device: Device? {
get {
return loadedDevice
}
set(value) {
objectWillChange.send()
loadedDevice = value
if (value != nil) {
if let encoded = try? JSONEncoder().encode(value) {
UserDefaults.standard.set(encoded, forKey: "device")
}
} else {
UserDefaults.standard.removeObject(forKey: "device")
}
}
}
private var keyChain: KeyChain
var credentials: UserCredentials? {
get {
if let result = try? keyChain.get() {
return result
}
return nil
}
set(value) {
try? keyChain.clear()
if let v = value {
try? keyChain.add(credentials: v)
}
}
}
/// Sets the base url of the mowesta service
public func setUrl(_ url: String) {
UserDefaults.standard.set(url, forKey: "accountUrl")
updateUrl()
}
/// Updates the url of the api client
private func updateUrl() {
if let u = UserDefaults.standard.string(forKey: "accountUrl") {
OpenAPIClientAPI.basePath = u
}
}
// Resets the device completely.
public func reset() {
device = nil
terms = 0
development = false
token = ""
device = ""
}
private init() {
self.keyChain = KeyChain(server: "www.mowesta.com")
updateUrl()
if let data = UserDefaults.standard.object(forKey: "device") as? Data,
let value = try? JSONDecoder().decode(Device.self, from: data) {
loadedDevice = value
}
}
}
private struct AppStateKey: EnvironmentKey {
static let defaultValue: AppState = AppState()
}
extension EnvironmentValues {
var appState: AppState {
get { self[AppStateKey.self] }
set { self[AppStateKey.self] = newValue }
}
}
+174 -8
View File
@@ -6,24 +6,190 @@
//
import Foundation
import SwiftUI
import MoWeStaApi
public enum UnitSystem {
case SI
case IM
case BOTH
public enum UnitSystem: Codable {
case si
case imperial
case both
}
public enum TemperatureUnit: Codable {
case celsius
case fahrenheit
case both
}
public class DataBindings {
public static func getTemperature(_ value: Double, _ system: UnitSystem) -> String {
return "";
public static func getTemperature(_ value: Double, _ unit: TemperatureUnit) -> LocalizedStringKey {
switch unit {
case .celsius:
return "format_temperature_celsius \(value)"
case .fahrenheit:
return "format_temperature_fahrenheit \(UnitConverter.celsiusToFahrenheit(value))"
case .both:
return "format_temperature_both \(value) \(UnitConverter.celsiusToFahrenheit(value))"
}
}
public static func getPressure(_ value: Double, _ system: UnitSystem) -> LocalizedStringKey {
switch system {
case .si:
return "format_pressure_si \(value)"
case .imperial:
return "format_pressure_imperial \(UnitConverter.hpaToPsi(value))"
case .both:
return "format_pressure_both \(value) \(UnitConverter.hpaToPsi(value))"
}
}
public static func getHumidity(_ value: Double) -> LocalizedStringKey {
return "format_humidity \(value)"
}
public static func getCloudCoverage(_ value: Double) -> LocalizedStringKey {
return "format_cloud_coverage \(value * 100)"
}
public static func getWindSpeed(_ value: Double, _ system: UnitSystem) -> LocalizedStringKey {
switch system {
case .si:
return "format_wind_speed_si \(UnitConverter.mpsToKmph(value)) \(UnitConverter.mpsToBFT(value))"
case .imperial:
return "format_wind_speed_imperial \(UnitConverter.mpsToMph(value)) \(UnitConverter.mpsToBFT(value))"
case .both:
return "format_wind_speed_both \(UnitConverter.mpsToKmph(value)) \(UnitConverter.mpsToMph(value))"
}
}
public static func getPrecipitation(_ value: Double, _ system: UnitSystem) -> LocalizedStringKey {
switch system {
case .si:
return "format_precipitation_si \(value)"
case .imperial:
return "format_precipitation_imperial \(UnitConverter.mmToIn(value))"
case .both:
return "format_precipitation_both \(value) \(UnitConverter.mmToIn(value))"
}
}
public static func getSnow(_ value: Double, _ system: UnitSystem) -> LocalizedStringKey {
switch system {
case .si:
return "format_snow_si \(value)"
case .imperial:
return "format_snow_imperial \(UnitConverter.mToFt(value))"
case .both:
return "format_snow_both \(value) \(UnitConverter.mToFt(value))"
}
}
public static func getAltitude(_ value: Double, _ system: UnitSystem) -> LocalizedStringKey {
switch system {
case .si:
return "format_altitude_si \(value)"
case .imperial:
return "format_altitude_imperial \(UnitConverter.mToFt(value))"
case .both:
return "format_altitude_both \(value) \(UnitConverter.mToFt(value))"
}
}
public static func getWindDirection(_ value: WeatherCondition.WindDirection) -> Angle {
switch value {
case .unknown, .north:
return Angle(degrees: 0)
case .northEast:
return Angle(degrees: 45)
case .east:
return Angle(degrees: 90)
case .southEast:
return Angle(degrees: 135)
case .south:
return Angle(degrees: 180)
case .southWest:
return Angle(degrees: -135)
case .west:
return Angle(degrees: -90)
case .northWest:
return Angle(degrees: -45)
}
}
public static func getDate(_ timestamp: Int64, _ timezone: String?) -> String {
let time = Double(timestamp) / 1000.0
let formatter = DateFormatter()
let format = NSLocalizedString("format_date", comment: "")
formatter.locale = Locale.current
formatter.dateFormat = format.stringValue
if let tz = timezone, let zone = TimeZone(identifier: tz) {
formatter.timeZone = zone
}
return formatter.string(from: Date(timeIntervalSince1970: time))
}
public static func getTime(_ timestamp: Int64, _ timezone: String?) -> String {
let time = Double(timestamp) / 1000.0
let formatter = DateFormatter()
let format = NSLocalizedString("format_time", comment: "")
formatter.locale = Locale.current
formatter.dateFormat = format.stringValue
if let tz = timezone, let zone = TimeZone(identifier: tz) {
formatter.timeZone = zone
}
return formatter.string(from: Date(timeIntervalSince1970: time))
}
public static func getHour(_ timestamp: Int64, _ timezone: String?) -> Int {
let time = Double(timestamp) / 1000.0
let formatter = DateFormatter()
formatter.locale = Locale(identifier: "de_DE")
formatter.dateFormat = "HH"
if let tz = timezone, let zone = TimeZone(identifier: tz) {
formatter.timeZone = zone
}
return Int(formatter.string(from: Date(timeIntervalSince1970: time)))!
}
public static func getWeekday(_ timestamp: Int64, _ timezone: String?) -> String {
let now = Date()
let tomorrow = getDate(Int64(Calendar.current.date(byAdding: .day, value: 1, to: now)!.timeIntervalSince1970 * 1000), nil)
let yesterday = getDate(Int64(Calendar.current.date(byAdding: .day, value: -1, to: now)!.timeIntervalSince1970 * 1000), nil)
let today = getDate(Int64(now.timeIntervalSince1970 * 1000), nil)
let date = getDate(timestamp, timezone)
if date == tomorrow {
return NSLocalizedString("date_tomorrow", comment: "")
} else if date == today {
return NSLocalizedString("date_today", comment: "")
} else if date == yesterday {
return NSLocalizedString("date_yesterday", comment: "")
} else {
let formatter = DateFormatter()
formatter.locale = Locale.current
formatter.dateFormat = "EEEE"
if let tz = timezone, let zone = TimeZone(identifier: tz) {
formatter.timeZone = zone
}
return formatter.string(from: Date(timeIntervalSince1970: Double(timestamp) / 1000))
}
}
public static func getInterval(_ timestamp: Int64, _ timezone: String?) -> String {
let hour = getHour(timestamp, timezone)
if hour < 6 {
return NSLocalizedString("label_night", comment: "")
} else if hour < 12 {
return NSLocalizedString("label_morning", comment: "")
} else if hour < 18 {
return NSLocalizedString("label_afternoon", comment: "")
} else {
return NSLocalizedString("label_evening", comment: "")
}
}
}
+165
View File
@@ -0,0 +1,165 @@
//
// ColorScheme.swift - Color schemes for rendering data
//
// Created by Marcus Handte on 23.07.22.
//
import Foundation
import SwiftUI
/// Base class for color schemes
public class DataColorScheme {
public func getColor(_ data: Double) -> UInt32 {
return 0xFFFFFFFF
}
public func color(_ data: Double) -> Color {
let color = getColor(data)
let alpha = Double((color >> 24) & 0xFF) / 255
let red = Double((color >> 16) & 0xFF) / 255
let green = Double((color >> 8) & 0xFF) / 255
let blue = Double(color & 0xFF) / 255
return Color(red: red, green: green, blue: blue, opacity: alpha)
}
}
/// Color support at a particular value
public struct ColorSupport {
let value: Double
let red: UInt8
let green: UInt8
let blue: UInt8
let alpha: UInt8
let color: UInt32
public init(value: Double, color: UInt32) {
self.value = value
self.alpha = UInt8((color >> 24) & 0xFF)
self.red = UInt8((color >> 16) & 0xFF)
self.green = UInt8((color >> 8) & 0xFF)
self.blue = UInt8(color & 0xFF)
self.color = color
}
}
/// A color scheme that perform interpolation at given support points
public class InterpolatedColorScheme: DataColorScheme {
let supports: [ColorSupport]
let interpolation: Interpolation
public init(supports: [ColorSupport], interpolation: Interpolation) {
self.supports = supports.sorted(by: { a, b in return a.value <= b.value })
self.interpolation = interpolation
}
public override func getColor(_ data: Double) -> UInt32 {
if let first = supports.first {
if data < first.value {
return first.color
}
for i in 1..<supports.count {
if supports[i].value > data {
return getColor(supports[i - 1], supports[i], data)
}
}
return supports[supports.count - 1].color
} else {
return super.getColor(data)
}
}
func getColor(_ from: ColorSupport, _ to: ColorSupport, _ at: Double) -> UInt32 {
let fraction = (at - from.value) / (to.value - from.value)
let alpha = getColor(from.alpha, to.alpha, fraction)
let red = getColor(from.red, to.red, fraction)
let green = getColor(from.green, to.green, fraction)
let blue = getColor(from.blue, to.blue, fraction)
return (UInt32(alpha) << 24) | (UInt32(red) << 16) | (UInt32(green) << 8) | UInt32(blue)
}
func getColor(_ from: UInt8, _ to: UInt8, _ at: Double) -> UInt8 {
return UInt8(min(255, max(0, interpolation.interpolate(from: Double(from), to: Double(to), at: at))))
}
}
/// MoWeSta specific color schemes
public struct DataColorSchemes {
/// scheme for cloud cover
let whiteCloud = InterpolatedColorScheme(supports: [
ColorSupport(value: 0, color: 0x00FFFFFF),
ColorSupport(value: 1, color: 0xFFFFFFFF)
], interpolation: LinearInterpolation())
// scheme for temperature
let scientificTemperature = InterpolatedColorScheme(supports: [
ColorSupport(value: -35, color: 0xFF0000FB),
ColorSupport(value: -30, color: 0xFF2E46FF),
ColorSupport(value: -25, color: 0xFF3974FF),
ColorSupport(value: -20, color: 0xFF39A9FF),
ColorSupport(value: -15, color: 0xFF29DBFF),
ColorSupport(value: -10, color: 0xFF30FFEF),
ColorSupport(value: -5, color: 0xFF88FFBE),
ColorSupport(value: 0, color: 0xFFB6FE8E),
ColorSupport(value: 0, color: 0xFFFFFF00),
ColorSupport(value: 5, color: 0xFFDAFF61),
ColorSupport(value: 10, color: 0xFFF8FF26),
ColorSupport(value: 15, color: 0xFFFEE100),
ColorSupport(value: 20, color: 0xFFFFB200),
ColorSupport(value: 25, color: 0xFFFE8500),
ColorSupport(value: 30, color: 0xFFFF5100),
ColorSupport(value: 35, color: 0xFFB30000)
], interpolation: LinearInterpolation())
/// dynamic scheme for pressure
public func pressure(min: Double, max: Double, avg: Double) -> InterpolatedColorScheme {
return InterpolatedColorScheme(supports: [
ColorSupport(value: min, color: 0xFF000000),
ColorSupport(value: avg, color: 0xFF0000FF),
ColorSupport(value: max, color: 0xFFFF00FF)
], interpolation: LinearInterpolation())
}
/// scheme for precipitation
let precipitation = InterpolatedColorScheme(supports: [
ColorSupport(value: 0, color: 0x0000000),
ColorSupport(value: 0.1, color: 0x88008800),
ColorSupport(value: 1, color: 0xFF00FF00), // Nieselregen (<1)
ColorSupport(value: 10, color: 0xFF00FFFF),
ColorSupport(value: 20, color: 0xFF0000FF), // Starkregen (>20)
ColorSupport(value: 20, color: 0xFF880000),
ColorSupport(value: 35, color: 0xFFFF0000), // Unwetter (>35)
], interpolation: LinearInterpolation())
/// scheme for humidity
let humidity = InterpolatedColorScheme(supports: [
ColorSupport(value: 0, color: 0x0042BAD0),
ColorSupport(value: 100, color: 0xFF42BAD0)
], interpolation: LinearInterpolation())
/// scheme for depth
let cloudDepth = InterpolatedColorScheme(supports: [
ColorSupport(value: 0, color: 0x00FFFFFF),
ColorSupport(value: 1, color: 0xFF999999)
], interpolation: LinearInterpolation())
/// windspeed
let windSpeed = InterpolatedColorScheme(supports: [
ColorSupport(value: 0.5, color: 0xff7ec1d9),
ColorSupport(value: 1.5, color: 0xff8ed1d9),
ColorSupport(value: 3.3, color: 0xff8ed1d9),
ColorSupport(value: 5.5, color: 0xff8ed1d9),
ColorSupport(value: 7.9, color: 0xff8ed1d9),
ColorSupport(value: 10.7, color: 0xff8ed1d9),
ColorSupport(value: 13.8, color: 0xff8ed1d9),
ColorSupport(value: 17.1, color: 0xff8ed1d9),
ColorSupport(value: 20.7, color: 0xff8ed1d9),
ColorSupport(value: 24.4, color: 0xff8ed1d9),
ColorSupport(value: 28.4, color: 0xff8ed1d9),
ColorSupport(value: 32.6, color: 0xff8ed1d9),
ColorSupport(value: 32.7, color: 0xff8ed1d9)
], interpolation: Interpolation())
}
+195
View File
@@ -0,0 +1,195 @@
//
// Favorite.swift
// App
//
// Created by Marcus Handte on 15.07.22.
//
import Foundation
import MoWeStaApi
import AnyCodable
/// Extends the favorite entity generated by core data with additional properties (implemented via associated objects)
/// to simplify the access to json encoded data stored in the database and to avoid repeated loading and unloading.
extension Favorite {
/// The location which should be a city, state or country
public var locationValue: Any? {
get {
if let loc = location, let data = loc.data(using: .utf8) {
switch getLocationType() {
case .city:
return try? JSONDecoder().decode(City.self, from: data)
case .country:
return try? JSONDecoder().decode(Country.self, from: data)
case .state:
return try? JSONDecoder().decode(State.self, from: data)
}
}
return nil
}
set {
if let nv = newValue as? City {
if let data = try? JSONEncoder().encode(nv) {
location = String(decoding: data, as: UTF8.self)
} else {
location = nil
}
} else if let nv = newValue as? State {
if let data = try? JSONEncoder().encode(nv) {
location = String(decoding: data, as: UTF8.self)
} else {
location = nil
}
} else if let nv = newValue as? Country {
if let data = try? JSONEncoder().encode(nv) {
location = String(decoding: data, as: UTF8.self)
} else {
location = nil
}
} else {
location = nil
}
}
}
/// The city
public var cityValue: City? {
get {
if let c = city, let data = c.data(using: .utf8) {
return try? JSONDecoder().decode(City.self, from: data)
}
return nil
}
set {
if let v = newValue, let data = try? JSONEncoder().encode(v) {
city = String(decoding: data, as: UTF8.self)
} else {
city = nil
}
}
}
/// The weather condition.
public var conditionValue: WeatherCondition? {
get {
if let c = condition, let data = c.data(using: .utf8) {
return try? JSONDecoder().decode(WeatherCondition.self, from: data)
} else {
return nil
}
}
set {
if let v = newValue, let data = try? JSONEncoder().encode(v) {
condition = String(decoding: data, as: UTF8.self)
} else {
condition = nil
}
}
}
/// The weather forecast.
public var forecastValue: WeatherForecast? {
get {
if let f = forecast, let data = f.data(using: .utf8) {
return try? JSONDecoder().decode(WeatherForecast.self, from: data)
}
return nil
}
set {
if let v = newValue, let data = try? JSONEncoder().encode(v) {
forecast = String(decoding: data, as: UTF8.self)
} else {
forecast = nil
}
}
}
/// The weatehr station
public var stationValue: WeatherStation? {
get {
if let s = station, let data = s.data(using: .utf8) {
return try? JSONDecoder().decode(WeatherStation.self, from: data)
}
return nil
}
set {
if let v = newValue, let data = try? JSONEncoder().encode(v) {
station = String(decoding: data, as: UTF8.self)
} else {
station = nil
}
}
}
/// The boundary
public var boundaryValue: Geometry? {
get {
if let b = boundary, let data = b.data(using: .utf8) {
return try? JSONDecoder().decode(Geometry.self, from: data)
}
return nil
}
set {
if let v = newValue, let data = try? JSONEncoder().encode(v) {
boundary = String(decoding: data, as: UTF8.self)
} else {
boundary = nil
}
}
}
/// Returns the loation type
public func getLocationType() -> LocationHierarchy.ModelType {
if (self.locationType == 2) {
return .country
} else if (self.locationType == 1) {
return .state
} else {
return .city
}
}
/// Sets the location type.
public func setLocationType(type: LocationHierarchy.ModelType) {
switch (type) {
case .city:
locationType = 0
case .state:
locationType = 1
case .country:
locationType = 2
}
}
/// Returns the loation type
public func getLocationReferenceType() -> LocationReference.ModelType {
if (self.locationType == 2) {
return .country
} else if (self.locationType == 1) {
return .state
} else {
return .city
}
}
/// Sets the location type.
public func setLocationReferenceType(type: LocationReference.ModelType) {
switch (type) {
case .city:
locationType = 0
case .state:
locationType = 1
case .country:
locationType = 2
}
}
}
+82
View File
@@ -0,0 +1,82 @@
//
// Favorites.swift
// App
//
// Created by Marcus Handte on 23.07.22.
//
import Foundation
import CoreData
struct Favorites {
public static func canDelete(_ favorite: Favorite?) -> Bool {
if let f = favorite {
return !f.removed && !f.isDeleted
}
return false
}
public static func delete(_ context: NSManagedObjectContext, _ favorite: Favorite?) {
if let f = favorite {
if f.added {
f.removed = true
} else {
context.delete(f)
}
do {
try context.save()
} catch {
context.reset()
}
}
BaseTask.execute(all: [SyncTask()]) { success in
print("Successful update: \(success)")
}
}
public static func add(_ context: NSManagedObjectContext, _ favorite: Favorite?, values: (Favorite)->Void) {
var fav: Favorite
if let f = favorite {
if f.isDeleted {
f.removed = false
fav = f
} else {
fav = Favorite(context: context)
context.insert(fav)
}
} else {
fav = Favorite(context: context)
context.insert(fav)
}
values(fav)
fav.position = Favorites.position(context) + 1
do {
try context.save()
} catch {
context.reset()
}
BaseTask.execute(all: [SyncTask(), RefreshTask()]) { success in
print("Successful update: \(success)")
}
}
private static func position(_ context: NSManagedObjectContext) -> Int16 {
let request = NSFetchRequest<NSFetchRequestResult>()
request.entity = Favorite.entity()
request.resultType = .dictionaryResultType
let expression = NSExpressionDescription()
expression.name = "maxpos"
expression.expression = NSExpression(forFunction: "max:", arguments: [NSExpression(forKeyPath: "position")])
expression.expressionResultType = .integer16AttributeType
request.propertiesToFetch = [ expression]
request.resultType = .dictionaryResultType
if let result = try? context.fetch(request) as? [[String:Int16]], let r = result.first, let res = r["maxpos"] {
return res
} else {
return 0
}
}
}
+13 -1
View File
@@ -9,6 +9,7 @@ import Foundation
import class MoWeStaApi.LocationHierarchy
import class MoWeStaApi.WeatherCondition
import class MoWeStaApi.Device
public class ImageBindings {
@@ -50,7 +51,7 @@ public class ImageBindings {
case .rainShowerSlight:
return alternate ? "icon_night_showers" : "icon_day_showers"
case .rainShowerModerateHeavy:
return "icon_showers"
return "icon_day_showers"
case .rainShowerViolent:
return "icon_storm_showers"
case .snowShowerSlight:
@@ -66,4 +67,15 @@ public class ImageBindings {
}
}
public static func getDeviceIcon(_ os: Device.Os) -> String {
switch os {
case .android:
return "icon_android"
case .arduino:
return "icon_arduino"
case .ios:
return "icon_ios"
}
}
}
+30
View File
@@ -0,0 +1,30 @@
//
// Interpolations.swift
// App
//
// Created by Marcus Handte on 23.07.22.
//
import Foundation
/// Base class for interpolations that implements a step function
public class Interpolation {
/// Performs step interpolation with a breakpoint set to 0.5
public func interpolate(from x: Double, to y: Double, at: Double) -> Double {
return at < 0.5 ? x : y
}
}
/// A linear interpolation betwen x and y.
public class LinearInterpolation: Interpolation {
/// Performs a linear interpolation between x (at 0) and y (at 1)
public override func interpolate(from x: Double, to y: Double, at: Double) -> Double {
return x + (y - x) * min(1, max(0, at));
}
}
+109 -1
View File
@@ -11,6 +11,11 @@ import SwiftUI
import class MoWeStaApi.City
import class MoWeStaApi.LocationHierarchy
import class MoWeStaApi.WeatherCondition
import class MoWeStaApi.WeatherVideo
import class MoWeStaApi.WeatherStation
import class MoWeStaApi.State
import class MoWeStaApi.Country
import class MoWeStaApi.Device
public class TextBindings {
@@ -31,6 +36,24 @@ public class TextBindings {
}
}
public static func getName(_ state: State?, _ country: Country?) -> String? {
var strings: [String] = [ ];
if let s = state, let stateName = getName(s.names, true) {
strings.append(stateName)
}
if let c = country, let countryName = getName(c.names, true) {
strings.append(countryName)
}
if strings.count == 1 {
return strings.first!
} else if strings.count == 2 {
return "\(strings[0]), \(strings[1])"
} else {
return nil
}
}
public static func getLocationName(_ hierarchy: LocationHierarchy) -> String {
if let name = getName(hierarchy.names, false) {
return name
@@ -54,6 +77,15 @@ public class TextBindings {
}
return string
}
public static func getRegionName(_ city: City) -> String {
let name = getName(city.country.names, false)!
if let s = city.state {
return "\(getName(s.names, true)!), \(name)"
} else {
return name
}
}
public static func getCityType(_ city: City) -> LocalizedStringKey {
switch (city.type) {
@@ -68,7 +100,7 @@ public class TextBindings {
}
}
public static func getWeatherSource(_ condition: WeatherCondition) -> LocalizedStringKey {
public static func getWeatherSource(_ condition: WeatherCondition) -> String {
switch (condition.source) {
case WeatherCondition.Source.cosmoEurope:
return "source_cosmo_europe"
@@ -143,5 +175,81 @@ public class TextBindings {
}
}
public static func getWindDirection(_ value: WeatherCondition.WindDirection) -> LocalizedStringKey {
switch value {
case .unknown, .north:
return "direction_north"
case .northEast:
return "direction_north_east"
case .east:
return "direction_east"
case .southEast:
return "direction_south_east"
case .south:
return "direction_south"
case .southWest:
return "direction_south_west"
case .west:
return "direction_west"
case .northWest:
return "direction_north_west"
}
}
public static func getUnitSystem(_ value: UnitSystem) -> LocalizedStringKey {
switch (value) {
case .imperial:
return "customize_system_imperial"
case .si:
return "customize_system_standard"
case .both:
return "customize_system_both"
}
}
public static func getTemperatureUnit(_ value: TemperatureUnit) -> LocalizedStringKey {
switch (value) {
case .celsius:
return "customize_temperature_celsius"
case .fahrenheit:
return "customize_temperature_fahrenheit"
case .both:
return "customize_temperature_both"
}
}
public static func getVideoType(_ value: WeatherVideo.ModelType) -> LocalizedStringKey {
switch value {
case .pressure:
return "video_type_pressure"
case .precipitation:
return "video_type_precipitation"
case .cloud:
return "video_type_cloud"
case .temperature:
return "video_type_temperature"
case .wind:
return "video_type_wind"
}
}
public static func getOperatorName(_ value: WeatherStation.Operator) -> LocalizedStringKey{
switch value {
case .dwd:
return "operator_dwd"
}
}
public static func getDeviceOs(_ value: Device.Os) -> LocalizedStringKey {
switch value {
case .ios:
return "label_device_type_ios"
case .arduino:
return "label_device_type_arduino"
case .android:
return "label_device_type_android"
}
}
}
+331
View File
@@ -0,0 +1,331 @@
//
// WeatherAggregates.swift
// App
//
// Created by Marcus Handte on 17.07.22.
//
import Foundation
import SwiftUI
import class MoWeStaApi.WeatherCondition
import class MoWeStaApi.WeatherForecast
struct WeatherSummary: Identifiable {
let id = UUID()
let title: LocalizedStringKey
let subtitle: LocalizedStringKey
let min: WeatherCondition
let max: WeatherCondition
init?(title: LocalizedStringKey, subtitle: LocalizedStringKey, conditions: [WeatherCondition]) {
self.title = title
self.subtitle = subtitle
if let f = conditions.first {
min = f.copy()
max = f.copy()
for c in conditions {
min.cloudCoverage = Swift.min(min.cloudCoverage, c.cloudCoverage)
min.windSpeed = Swift.min(min.windSpeed, c.windSpeed)
if (min.windSpeed == c.windSpeed) {
min.windDirection = c.windDirection
}
min.temperature = Swift.min(min.temperature, c.temperature)
min.snowDepth = Swift.min(min.snowDepth, c.snowDepth)
min.pressure = Swift.min(min.pressure, c.pressure)
min.precipitation = Swift.min(min.precipitation, c.precipitation)
min.humidity = Swift.min(min.humidity, c.humidity)
min.cloudDepth = Swift.min(min.cloudDepth, c.cloudDepth)
min.type = mini(min.type, c.type)
min.source = mini(min.source, c.source)
max.cloudCoverage = Swift.max(max.cloudCoverage, c.cloudCoverage)
max.windSpeed = Swift.max(max.windSpeed, c.windSpeed)
if (max.windSpeed == c.windSpeed) {
max.windDirection = c.windDirection
}
max.temperature = Swift.max(max.temperature, c.temperature)
max.snowDepth = Swift.max(max.snowDepth, c.snowDepth)
max.pressure = Swift.max(max.pressure, c.pressure)
max.precipitation = Swift.max(max.precipitation, c.precipitation)
max.humidity = Swift.max(max.humidity, c.humidity)
max.cloudDepth = Swift.max(max.cloudDepth, c.cloudDepth)
max.type = maxi(max.type, c.type)
max.source = maxi(max.source, c.source)
}
} else {
return nil
}
}
private func mini(_ a: WeatherCondition.Source, _ b: WeatherCondition.Source) -> WeatherCondition.Source {
let ra = getRank(a)
let rb = getRank(b)
if ra < 0 {
return b
}
if rb < 0 {
return a
}
return (ra < rb) ? a : b
}
private func maxi(_ a: WeatherCondition.Source, _ b: WeatherCondition.Source) -> WeatherCondition.Source {
let ra = getRank(a)
let rb = getRank(b)
if ra < 0 {
return b
}
if rb < 0 {
return a
}
return (ra > rb) ? a : b
}
private func mini(_ a: WeatherCondition.ModelType, _ b: WeatherCondition.ModelType) -> WeatherCondition.ModelType {
let ra = getRank(a)
let rb = getRank(b)
if ra < 0 {
return b
}
if rb < 0 {
return a
}
return (ra < rb) ? a : b
}
private func maxi(_ a: WeatherCondition.ModelType, _ b: WeatherCondition.ModelType) -> WeatherCondition.ModelType {
let ra = getRank(a)
let rb = getRank(b)
if ra < 0 {
return b
}
if rb < 0 {
return a
}
return (ra > rb) ? a : b
}
private func getRank(_ source: WeatherCondition.Source) -> Int {
switch (source) {
case .iconGlobal:
return 2;
case .iconEurope:
return 1;
case .cosmoEurope:
return 0;
case .weatherStation:
return -1;
}
}
private func getRank(_ type: WeatherCondition.ModelType) -> Int {
switch (type) {
case .clearSky:
return 0
case .mainlyClear:
return 1
case .partlyCloudy:
return 2
case .cloudy:
return 3
case .fog:
return 4
case .fogDepositingRime:
return 5
case .slightDrizzle:
return 6
case .slightRainNotFreezing:
return 7
case .rainShowerSlight:
return 8
case .drizzleFreezingSlight:
return 9
case .rainFreezingSlight:
return 10
case .slightFallOfSnowflakes:
return 11
case .snowShowerSlight:
return 12
case .moderateDrizzle:
return 13
case .heavyDrizzle:
return 14
case .moderateRainNotFreezing:
return 15
case .snowGrains:
return 16
case .moderateFallOfSnowflakes:
return 17
case .heavyRainNotFreezing:
return 18
case .drizzleFreezingModerateHeavy:
return 19
case .heavyFallOfSnowflakes:
return 20
case .rainShowerModerateHeavy:
return 21
case .rainFreezingModerateHeavy:
return 22
case .snowShowerModerateHeavy:
return 23
case .rainShowerViolent:
return 24
case .thunderstormSlightModerate:
return 25
case .thunderstormHailHeavy:
return 26
default:
return -1
}
}
}
extension WeatherCondition {
func copy() -> WeatherCondition {
return WeatherCondition(cloudCoverage: cloudCoverage, cloudDepth: cloudDepth, duration: duration, hour: hour, humidity: humidity, precipitation: precipitation, pressure: pressure, snowDepth: snowDepth, source: source, temperature: temperature, time: time, type: type, windDirection: windDirection, windSpeed: windSpeed)
}
}
struct WeatherEntry: Identifiable {
let id = UUID()
let title: LocalizedStringKey
let subtitle: LocalizedStringKey
let condition: WeatherCondition
}
public class WeatherAggregate {
var hours: [WeatherEntry] = []
var times: [WeatherSummary] = []
var days: [WeatherSummary] = []
init(_ conditions: [WeatherCondition], _ timezone: String?) {
let input = conditions.sorted { a, b in
return a.time < b.time
}
var times: [[WeatherCondition]] = []
var days: [[WeatherCondition]] = []
var currentDay: [WeatherCondition] = []
var currentTime: [WeatherCondition] = []
for w in input {
let title = LocalizedStringKey("format_title \(DataBindings.getWeekday(w.time, timezone))")
let subtitle = LocalizedStringKey("format_title \(DataBindings.getTime(w.time, timezone)) \(DataBindings.getDate(w.time, timezone))")
hours.append(WeatherEntry(title: title, subtitle: subtitle , condition: w))
if let c = currentDay.first {
if DataBindings.getDate(c.time, timezone) == DataBindings.getDate(w.time, timezone) {
currentDay.append(w)
} else {
days.append(currentDay)
currentDay = [ w ]
times.append(currentTime)
currentTime = []
}
} else {
currentDay.append(w)
}
if let c = currentTime.first {
if DataBindings.getInterval(c.time, timezone) == DataBindings.getInterval(w.time, timezone) {
currentTime.append(w)
} else {
times.append(currentTime)
currentTime = [ w ]
}
} else {
currentTime.append(w)
}
}
if (!currentDay.isEmpty) {
days.append(currentDay)
}
if (!currentTime.isEmpty) {
times.append(currentTime)
}
for d in days {
if let first = d.first {
let title = LocalizedStringKey("format_title \(DataBindings.getWeekday(first.time, timezone))")
let subtitle = LocalizedStringKey("label_full_day")
self.days.append(WeatherSummary(title: title, subtitle: subtitle, conditions: d)!)
}
}
for t in times {
if let first = t.first {
let title = LocalizedStringKey("format_title \(DataBindings.getWeekday(first.time, timezone))")
let subtitle = LocalizedStringKey("format_title \(DataBindings.getInterval(first.time, timezone))")
self.times.append(WeatherSummary(title: title, subtitle: subtitle, conditions: t)!)
}
}
}
}
public class WeatherGradientData {
let hours: [Int64]
let temp: [Double]
let cloudDepth: [Double]
let cloudCoverage: [Double]
let windSpeed: [Double]
let humidity: [Double]
let precipitation: [Double]
let pressure: [Double]
let averagePressure: Double
let minimumPressure: Double
let maximumPressure: Double
init(_ forecast: WeatherForecast) {
var hours: [Int64] = []
var temp: [Double] = []
var cloudDepth: [Double] = []
var cloudCoverage: [Double] = []
var windSpeed: [Double] = []
var humidity: [Double] = []
var precipitation: [Double] = []
var pressure: [Double] = []
for c in forecast.conditions.sorted(by: { a, b in return a.time <= b.time }) {
for i in 0..<c.duration {
hours.append(c.time + Int64(i) * 3600000)
temp.append(c.temperature)
cloudDepth.append(c.cloudDepth)
cloudCoverage.append(c.cloudCoverage)
windSpeed.append(c.windSpeed)
humidity.append(c.humidity)
precipitation.append(c.precipitation)
pressure.append(c.pressure)
}
}
self.hours = hours
self.temp = temp
self.cloudDepth = cloudDepth
self.cloudCoverage = cloudCoverage
self.windSpeed = windSpeed
self.humidity = humidity
self.precipitation = precipitation
self.pressure = pressure
self.averagePressure = 1013.25 * pow(1 - 6.5 * forecast.surfaceHeight / 288150.0, 5.255);
self.minimumPressure = averagePressure - 20
self.maximumPressure = averagePressure + 10
}
private func getIndex(selection: Double) -> Int? {
if hours.count == 0 {
return nil
} else {
let idx = max(0, min(selection, 1)) * Double(hours.count - 1)
return max(0, min(hours.count - 1, Int(round(idx))))
}
}
public func getValue<T>(values: [T], at: Double) -> T? {
if let idx = getIndex(selection: at) {
if idx > 0 && idx < values.count {
return values[idx]
}
}
return nil
}
}
+2 -1
View File
@@ -13,6 +13,7 @@ struct PersistenceController {
static var preview: PersistenceController = {
let result = PersistenceController(inMemory: true)
let viewContext = result.container.viewContext
/*
for _ in 0..<10 {
let newItem = Item(context: viewContext)
newItem.timestamp = Date()
@@ -24,7 +25,7 @@ struct PersistenceController {
// fatalError() causes the application to generate a crash log and terminate. You should not use this function in a shipping application, although it may be useful during development.
let nsError = error as NSError
fatalError("Unresolved error \(nsError), \(nsError.userInfo)")
}
}*/
return result
}()
+93
View File
@@ -0,0 +1,93 @@
//
// Task.swift
// App
//
// Created by Marcus Handte on 22.07.22.
//
import Foundation
public class BaseTask {
/// A dispatch queue to ensure that tasks are executed sequentially
public static let queue = DispatchQueue(label: "tasks")
/// A flag to indicate whether the operation is cancelled.
private var canceled = false
/// A lock to guard the cancelled flag.
private let lock = NSLock()
/// Creates the operation.
public init() { }
/// Determines whether the operation should be canceled.
///
/// - returns: True if the operation is canceled, false otherwise.
public func isCanceled() -> Bool {
lock.lock()
let result = canceled
lock.unlock()
return result
}
/// Cancels the upload operation.
public func cancel() {
lock.lock()
canceled = true
lock.unlock()
}
/// Executes a task an informs the completion handler on the main thread.
public func execute(completion: @escaping (Bool) -> Void) {
BaseTask.queue.async {
let result = self.executeAsync()
DispatchQueue.main.async {
completion(result)
}
}
}
/// Executes the task logic. Multiple classes
func executeAsync() -> Bool {
return true
}
/// Cancels all tasks.
public static func cancel(all tasks: [BaseTask]) {
for t in tasks {
t.cancel()
}
}
/// Executes a series of tasks until one of them fails or all complete
public static func execute(all tasks: [BaseTask], completion: @escaping (Bool) -> Void) {
if tasks.count > 0 {
var t = tasks
BaseTask.execute(current: t.removeFirst(), next: t, completion: completion)
} else {
DispatchQueue.main.async {
completion(true)
}
}
}
/// Executes the current task and continues with the next tasks, if the task is successful.
private static func execute(current: BaseTask, next: [BaseTask], completion: @escaping (Bool) -> Void) {
BaseTask.queue.async {
let result = current.executeAsync()
if !result || next.count == 0 {
DispatchQueue.main.async {
completion(result)
}
} else {
var t = next
BaseTask.execute(current: t.removeFirst(), next: t, completion: completion)
}
}
}
}
+248
View File
@@ -0,0 +1,248 @@
//
// RefreshTask.swift
// App
//
// Created by Marcus Handte on 22.07.22.
//
import Foundation
import class MoWeStaApi.DefaultAPI
import class MoWeStaApi.City
import class MoWeStaApi.State
import class MoWeStaApi.Country
import class MoWeStaApi.WeatherCondition
import class MoWeStaApi.WeatherForecast
import class MoWeStaApi.WeatherStation
import class MoWeStaApi.Geometry
/// Loads the location and weather info for all favorites.
public class RefreshTask: BaseTask {
// The timeout to prevent frequent location downloads
public static let LOCATION_TIMEOUT = 24 * 60 * 60 * 1000
// The timeout to prevent too frequent weather downloads
public static let WEATHER_TIMEOUT = 5 * 60 * 1000
/// The persistence context
let context = PersistenceController.shared.container.newBackgroundContext()
override func executeAsync() -> Bool {
context.performAndWait {
let fetch = Favorite.fetchRequest()
if let favorites = try? fetch.execute() {
print("Syncing \(favorites.count) favorites.")
let group = DispatchGroup()
let queue = DispatchQueue(label: "refresh", attributes: .concurrent)
let semaphore = DispatchSemaphore(value: 3)
for fav in favorites {
if isCanceled() {
print("Sync was cancelled.")
break
} else {
print("Refresh start: \(fav.identifier)")
if !fav.removed {
semaphore.wait()
group.enter()
queue.async {
let favref = FavoriteRefresher(self, fav)
favref.refresh {
print("Refresh complete: \(fav.identifier)")
semaphore.signal()
group.leave()
}
}
}
}
}
group.wait()
print("Saving refreshed context.")
try? context.save()
}
}
return !isCanceled()
}
}
/// A utility class to download the data for a favorite
class FavoriteRefresher {
let task: RefreshTask
let favorite: Favorite
let now = Int64(NSDate().timeIntervalSince1970 * 1000)
var remaining = 0
var lock = NSRecursiveLock()
var city: City? = nil
var location: Any? = nil
var boundary: Geometry? = nil
var forecast: WeatherForecast? = nil
var condition: WeatherCondition? = nil
var station: WeatherStation? = nil
init(_ task: RefreshTask, _ favorite: Favorite) {
self.favorite = favorite
self.task = task
}
private func isLocationIncomplete() -> Bool {
return favorite.location == nil || favorite.forecast == nil
}
private func isWeatherIncomplete() -> Bool {
return favorite.condition == nil || favorite.forecast == nil
}
public func refresh(completion: @escaping () -> Void) {
lock.lock()
if !task.isCanceled() {
if now - favorite.locationTime > RefreshTask.LOCATION_TIMEOUT || isLocationIncomplete() {
switch favorite.getLocationType() {
case .country:
remaining += 2
DefaultAPI.getCountry(id: favorite.identifier) {
response, error in
if let r = response {
self.location = r
}
self.complete(completion: completion)
}
DefaultAPI.getCountryCities(id: favorite.identifier, pageOffset: 0, pageSize: 1) {
response, error in
if let r = response, let f = r.elements.first {
self.city = f
self.refresh(f, true, completion)
}
self.complete(completion: completion)
}
/** This is too much data.
DefaultAPI.getCountryBoundary(id: favorite.identifier) {
response, error in
if let r = response {
self.boundary = r
}
self.complete(completion: completion)
}
*/
case .state:
remaining += 3
DefaultAPI.getState(id: favorite.identifier) {
response, error in
if let r = response {
self.location = r
}
self.complete(completion: completion)
}
DefaultAPI.getStateCities(id: favorite.identifier, pageOffset: 0, pageSize: 1) {
response, error in
if let r = response, let f = r.elements.first {
self.city = f
self.refresh(f, true, completion)
}
self.complete(completion: completion)
}
DefaultAPI.getStateBoundary(id: favorite.identifier) {
response, error in
if let r = response {
self.boundary = r
}
self.complete(completion: completion)
}
case .city:
remaining += 2
DefaultAPI.getCity(id: favorite.identifier) {
response, error in
if let r = response {
self.city = r
self.location = r
self.refresh(r, true, completion)
}
self.complete(completion: completion)
}
DefaultAPI.getCityBoundary(id: favorite.identifier) {
response, error in
if let r = response {
self.boundary = r
}
self.complete(completion: completion)
}
}
} else if now - favorite.weatherTime > RefreshTask.WEATHER_TIMEOUT || isWeatherIncomplete() {
if let c = favorite.cityValue {
refresh(c, false, completion)
}
}
}
if remaining == 0 {
DispatchQueue.main.async {
completion()
}
}
lock.unlock()
}
/// refreshes the weather for a city, optionally with location
func refresh(_ city: City, _ full: Bool, _ completion: @escaping () -> Void) {
if !task.isCanceled() {
lock.lock()
if full {
remaining += 3
} else {
remaining += 2
}
lock.unlock()
if full {
DefaultAPI.getCityStation(id: city.id!) {
response, error in
if let r = response {
self.station = r
}
self.complete(completion: completion)
}
}
DefaultAPI.getCityForecast(id: city.id!) {
response, error in
if let r = response {
self.forecast = r
}
self.complete(completion: completion)
}
DefaultAPI.getCityCondition(id: city.id!) {
response, error in
if let r = response {
self.condition = r
}
self.complete(completion: completion)
}
}
}
/// complete the task and sets the variables
func complete(completion: @escaping () -> Void) {
lock.lock()
remaining -= 1
if remaining == 0 {
if let c = city, let l = location {
if let b = boundary {
favorite.boundaryValue = b
}
if let s = station {
favorite.stationValue = s
}
favorite.locationValue = l
favorite.cityValue = c
favorite.locationTime = now
}
if let f = forecast, let c = condition {
favorite.forecastValue = f
favorite.conditionValue = c
favorite.weatherTime = now
}
DispatchQueue.main.async {
completion()
}
}
lock.unlock()
}
}
+188
View File
@@ -0,0 +1,188 @@
//
// SyncTask.swift
// App
//
// Created by Marcus Handte on 22.07.22.
//
import Foundation
import class MoWeStaApi.DefaultAPI
import class MoWeStaApi.Settings
import class MoWeStaApi.LocationReference
public class SyncTask: BaseTask {
/// The persistence context
let context = PersistenceController.shared.container.newBackgroundContext()
/// The app state
let state = AppState.shared
/// The user credentials
let credential = AppState.shared.credentials
override func executeAsync() -> Bool {
print("Performing favorite synchronization.")
if let cs = credential {
if let settings = SettingDownloader(cs).getSettings() {
context.performAndWait {
let fetch = Favorite.fetchRequest()
if let favorites = try? fetch.execute() {
/// create a diff
var localOnlyFavorites = favorites
var localAndServerFavorites: [LocationReference:Favorite] = [:]
var remoteOnlyFavorites = settings.locations
ref: for ref in settings.locations {
for idx in localOnlyFavorites.indices {
let fav = localOnlyFavorites[idx]
if (fav.identifier == ref.id && fav.getLocationReferenceType() == ref.type) {
localAndServerFavorites.updateValue(fav, forKey: ref)
localOnlyFavorites.remove(at: idx)
remoteOnlyFavorites.removeAll() { r in
return ref.id == r.id && ref.type == r.type
}
continue ref
}
}
}
// handle favorites available remotely
var newFavorties: [Favorite] = []
var deletedFavorites: [Favorite] = []
var changedFavorites: [Favorite] = []
var newState = settings.locations
var deleted = 0
for idx in settings.locations.indices {
let i = idx - deleted
let ref = newState[i]
if let fav = localAndServerFavorites[ref] {
if fav.removed {
newState.remove(at: i)
deletedFavorites.append(fav)
context.delete(fav)
deleted += 1
} else {
fav.position = Int16(i)
fav.added = true
changedFavorites.append(fav)
}
} else {
let fav = Favorite(context: context)
fav.setLocationReferenceType(type: ref.type)
fav.added = true
fav.identifier = ref.id!
fav.position = Int16(i)
context.insert(fav)
newFavorties.append(fav)
}
}
/// handle local only favorties
for fav in localOnlyFavorites {
if fav.removed || fav.added {
context.delete(fav)
deletedFavorites.append(fav)
} else {
let ref = LocationReference(id: fav.identifier, type: fav.getLocationReferenceType())
fav.position = Int16(newState.count)
fav.added = true
newState.append(ref)
changedFavorites.append(fav)
}
}
/// apply the state to the server
let newSettings = Settings(creationTime: settings.creationTime, deleted: false, id: settings.id, locations: newState, modificationTime: settings.modificationTime)
if SettingUploader(cs, newSettings).setSettings() {
print("Saving local favorite changes since upload completed.")
try? context.save()
} else {
print("Resetting local favorite changes since upload failed.")
context.reset()
}
}
}
} else {
return false
}
return !isCanceled()
} else {
print("Skipping sync since user is not logged in.")
return true
}
}
}
/// A class to perform a blocking download of the settings
class SettingDownloader {
let credential: UserCredentials
var settings: Settings? = nil
init(_ credential: UserCredentials) {
self.credential = credential
}
public func getSettings() -> Settings? {
print("Loading user settings.")
let group = DispatchGroup()
group.enter()
let rb = DefaultAPI.getCurrentUserSettingsWithRequestBuilder()
rb.addHeaders(ApiHeader.create(credential))
rb.execute() { result in
switch result {
case let .success(response):
print("Loaded user setttings.")
self.settings = response.body
case let .failure(.error(code, _, _, _)):
print("Failed to load user settings.")
if code == 403 {
DispatchQueue.main.async {
AppState.shared.credentialFailure = true
}
}
}
group.leave()
}
group.wait()
print("Returning user settings: \(settings == nil)")
return settings
}
}
/// A class to perform a blocking upload of the settings
class SettingUploader {
let credential: UserCredentials
let settings: Settings
var success = false
init(_ credential: UserCredentials, _ settings: Settings) {
self.credential = credential
self.settings = settings
}
public func setSettings() -> Bool {
print("Uploading user settings.")
let group = DispatchGroup()
group.enter()
let rb = DefaultAPI.setCurrentUserSettingsWithRequestBuilder(body: settings)
rb.addHeaders(ApiHeader.create(credential))
rb.execute() { result in
switch result {
case .success:
print("Uploaded user setttings.")
self.success = true
case let .failure(.error(code, _, _, _)):
print("Failed to upload user settings.")
if code == 403 {
DispatchQueue.main.async {
AppState.shared.credentialFailure = true
}
}
}
group.leave()
}
group.wait()
print("Returning upload settings: \(success)")
return success
}
}

Some files were not shown because too many files have changed in this diff Show More