Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
4d21dea4cd | ||
|
|
e4603a231e | ||
|
|
316df58af6 | ||
|
|
35516af52b | ||
|
|
3bded2af7a | ||
|
|
2c788e3329 | ||
|
|
af2409a16d | ||
|
|
7e390ed56f | ||
|
|
756a816abb | ||
|
|
1e174f77f7 |
@@ -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 27
|
||||
targetSdkVersion 33
|
||||
versionCode 29
|
||||
versionName "${versionApp}"
|
||||
buildConfigField "long", "BUILD_TIME", System.currentTimeMillis() + "L"
|
||||
testInstrumentationRunner "androidx.test.runner.AndroidJUnitRunner"
|
||||
|
||||
@@ -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)
|
||||
|
||||
+24
-19
@@ -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());
|
||||
}
|
||||
|
||||
|
||||
}
|
||||
|
||||
+39
-43
@@ -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());
|
||||
}
|
||||
}
|
||||
|
||||
@@ -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;
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
@@ -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
-5
@@ -5,7 +5,7 @@ apply plugin: 'maven-publish'
|
||||
|
||||
buildscript {
|
||||
dependencies {
|
||||
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"
|
||||
@@ -24,7 +24,7 @@ allprojects {
|
||||
|
||||
// set version for our project
|
||||
group = 'com.mowesta'
|
||||
version = '1.0.27'
|
||||
version = '1.0.29'
|
||||
|
||||
// set versions for our libraries
|
||||
ext {
|
||||
@@ -54,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'
|
||||
|
||||
@@ -0,0 +1,64 @@
|
||||
|
||||
|
||||

|
||||
|
||||
# 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).
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||

|
||||
Binary file not shown.
Binary file not shown.
|
After Width: | Height: | Size: 190 KiB |
Binary file not shown.
|
After Width: | Height: | Size: 19 KiB |
@@ -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
@@ -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
|
||||
|
||||
@@ -46,6 +46,9 @@
|
||||
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 */; };
|
||||
@@ -71,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 */
|
||||
@@ -135,6 +140,10 @@
|
||||
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>"; };
|
||||
@@ -160,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 */
|
||||
@@ -215,9 +226,11 @@
|
||||
2C163309283A27D300F78CEE /* App */ = {
|
||||
isa = PBXGroup;
|
||||
children = (
|
||||
2CC38B082912463F002E4DB0 /* App.entitlements */,
|
||||
2CB84A33288AFD3400DB8F41 /* Info.plist */,
|
||||
2CEB027F283EB09B00DF3151 /* Database.xcdatamodeld */,
|
||||
2CFC0F132841201E00E597DC /* Html */,
|
||||
2CC38B032911A706002E4DB0 /* Arduino */,
|
||||
2CEB028C2840C96D00DF3151 /* Ui */,
|
||||
2CA281FD283E1D1300D4A05A /* Model */,
|
||||
2CA281FC283E1D0400D4A05A /* View */,
|
||||
@@ -306,6 +319,7 @@
|
||||
2C369C6B2889719C00B5AFB2 /* MeasurementView.swift */,
|
||||
2C369C6F2889D44100B5AFB2 /* DeviceView.swift */,
|
||||
2C369C6D2889D42700B5AFB2 /* DevicesView.swift */,
|
||||
2CC38B0929128196002E4DB0 /* SetupView.swift */,
|
||||
);
|
||||
path = View;
|
||||
sourceTree = "<group>";
|
||||
@@ -336,6 +350,17 @@
|
||||
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 = (
|
||||
@@ -434,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;
|
||||
@@ -498,10 +523,12 @@
|
||||
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 */,
|
||||
@@ -514,10 +541,13 @@
|
||||
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 */,
|
||||
@@ -712,13 +742,16 @@
|
||||
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 = 2;
|
||||
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;
|
||||
@@ -731,7 +764,7 @@
|
||||
"$(inherited)",
|
||||
"@executable_path/Frameworks",
|
||||
);
|
||||
MARKETING_VERSION = 1.0;
|
||||
MARKETING_VERSION = 1.2;
|
||||
PRODUCT_BUNDLE_IDENTIFIER = com.mowesta.app;
|
||||
PRODUCT_NAME = MoWeSta;
|
||||
SWIFT_EMIT_LOC_STRINGS = YES;
|
||||
@@ -745,13 +778,16 @@
|
||||
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 = 2;
|
||||
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;
|
||||
@@ -764,7 +800,7 @@
|
||||
"$(inherited)",
|
||||
"@executable_path/Frameworks",
|
||||
);
|
||||
MARKETING_VERSION = 1.0;
|
||||
MARKETING_VERSION = 1.2;
|
||||
PRODUCT_BUNDLE_IDENTIFIER = com.mowesta.app;
|
||||
PRODUCT_NAME = MoWeSta;
|
||||
SWIFT_EMIT_LOC_STRINGS = YES;
|
||||
@@ -852,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 */,
|
||||
|
||||
@@ -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>
|
||||
@@ -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"
|
||||
}
|
||||
@@ -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
|
||||
}
|
||||
|
||||
}
|
||||
@@ -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
|
||||
}
|
||||
|
||||
@@ -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()
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
@@ -6,6 +6,8 @@
|
||||
<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>
|
||||
|
||||
@@ -52,7 +52,7 @@ public class DataBindings {
|
||||
}
|
||||
|
||||
public static func getCloudCoverage(_ value: Double) -> LocalizedStringKey {
|
||||
return "format_cloud_coverage \(value)"
|
||||
return "format_cloud_coverage \(value * 100)"
|
||||
}
|
||||
|
||||
|
||||
|
||||
@@ -40,7 +40,7 @@ struct MaterialButtonStyle: ButtonStyle {
|
||||
.foregroundColor(disabled ? .white : foreground)
|
||||
.frame(maxWidth:.infinity)
|
||||
.padding(8)
|
||||
.background(color.opacity(configuration.isPressed ? 0.7 : 1))
|
||||
.background(disabled ? .gray : color.opacity(configuration.isPressed ? 0.7 : 1))
|
||||
.cornerRadius(6)
|
||||
}
|
||||
|
||||
|
||||
@@ -1,6 +1,5 @@
|
||||
//
|
||||
// ErrorView.swift
|
||||
// App
|
||||
// ErrorView.swift - The view to display a communciation error.
|
||||
//
|
||||
// Created by Marcus Handte on 20.07.22.
|
||||
//
|
||||
|
||||
@@ -1,6 +1,5 @@
|
||||
//
|
||||
// GradientViews.swift
|
||||
// App
|
||||
// GradientViews.swift - A set of smaller views to implement the visual forecast.
|
||||
//
|
||||
// Created by Marcus Handte on 23.07.22.
|
||||
//
|
||||
|
||||
@@ -1,6 +1,5 @@
|
||||
//
|
||||
// PagedView.swift
|
||||
// App
|
||||
// PagedView.swift - A view to display a set of pages.
|
||||
//
|
||||
// Created by Marcus Handte on 18.07.22.
|
||||
//
|
||||
@@ -27,33 +26,35 @@ struct PageView: View {
|
||||
} else {
|
||||
pages[current].builder()
|
||||
}
|
||||
Divider()
|
||||
HStack(spacing: 0) {
|
||||
ForEach(pages, id: \PageItem.id) { page in
|
||||
Button(action: {
|
||||
current = page.id
|
||||
}) {
|
||||
let t = Text(page.text)
|
||||
.frame(alignment: .center)
|
||||
.frame(maxWidth: .infinity)
|
||||
.frame(minHeight: 40)
|
||||
.lineLimit(1)
|
||||
if page.id == current {
|
||||
t
|
||||
.font(.caption.bold())
|
||||
.background(
|
||||
RoundedRectangle(cornerRadius: 4)
|
||||
.foregroundColor(Color("PrimaryColor")))
|
||||
.foregroundColor(Color.accentColor)
|
||||
} else {
|
||||
t.font(.caption)
|
||||
if !pages.isEmpty {
|
||||
Divider()
|
||||
HStack(spacing: 0) {
|
||||
ForEach(pages, id: \PageItem.id) { page in
|
||||
Button(action: {
|
||||
current = page.id
|
||||
}) {
|
||||
let t = Text(page.text)
|
||||
.frame(alignment: .center)
|
||||
.frame(maxWidth: .infinity)
|
||||
.frame(minHeight: 40)
|
||||
.lineLimit(1)
|
||||
if page.id == current {
|
||||
t
|
||||
.font(.caption.bold())
|
||||
.background(
|
||||
RoundedRectangle(cornerRadius: 4)
|
||||
.foregroundColor(Color("PrimaryColor")))
|
||||
.foregroundColor(Color.accentColor)
|
||||
} else {
|
||||
t.font(.caption)
|
||||
}
|
||||
}
|
||||
.frame(minHeight: 44)
|
||||
.buttonStyle(NullButtonStyle())
|
||||
}
|
||||
.frame(minHeight: 44)
|
||||
.buttonStyle(NullButtonStyle())
|
||||
}
|
||||
}.padding([.trailing, .leading], 2)
|
||||
}
|
||||
}.padding([.trailing, .leading], 2)
|
||||
}
|
||||
}.frame(maxHeight: .infinity)
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -1,6 +1,5 @@
|
||||
//
|
||||
// ProgressBar.swift
|
||||
// App
|
||||
// ProgressViews.swift - A view for a progress spinner and a progress bar.
|
||||
//
|
||||
// Created by Marcus Handte on 13.07.22.
|
||||
//
|
||||
@@ -15,7 +14,21 @@ struct ProgressSpinnerView: View {
|
||||
@State private var trim: CGFloat = CGFloat(0)
|
||||
/// The rotation of the circle animating from 90 to 450 degrees.
|
||||
@State private var rotation: Double = 90
|
||||
|
||||
/// The frame size of the circle.
|
||||
private let frameSize: CGFloat;
|
||||
/// The line width of the circle.
|
||||
private let lineWidth: CGFloat;
|
||||
|
||||
init() {
|
||||
frameSize = 150
|
||||
lineWidth = 8
|
||||
}
|
||||
|
||||
init(_ frameSize: CGFloat, _ lineWidth: CGFloat) {
|
||||
self.frameSize = frameSize;
|
||||
self.lineWidth = lineWidth;
|
||||
}
|
||||
|
||||
/// Creates the progress bar.
|
||||
var body: some View {
|
||||
VStack {
|
||||
@@ -23,10 +36,10 @@ struct ProgressSpinnerView: View {
|
||||
Circle()
|
||||
.trim(from: 0.0, to: trim)
|
||||
.stroke(style: StrokeStyle(
|
||||
lineWidth: 8, lineCap: .round
|
||||
lineWidth: lineWidth, lineCap: .round
|
||||
))
|
||||
.foregroundColor(.accentColor)
|
||||
.frame(width: 150, alignment: .center)
|
||||
.frame(width: frameSize, alignment: .center)
|
||||
.rotationEffect(Angle(degrees: rotation), anchor: .center)
|
||||
Spacer()
|
||||
}
|
||||
|
||||
@@ -1,6 +1,5 @@
|
||||
//
|
||||
// RemoteImageView.swift
|
||||
// App
|
||||
// RemoteImageView.swift - A view to display an image loaded from a server.
|
||||
//
|
||||
// Created by Marcus Handte on 18.07.22.
|
||||
//
|
||||
|
||||
@@ -1,6 +1,5 @@
|
||||
//
|
||||
// CityForecastView.swift
|
||||
// App
|
||||
// CityForecastView.swift - The view to display the city forecast.
|
||||
//
|
||||
// Created by Marcus Handte on 17.07.22.
|
||||
//
|
||||
|
||||
@@ -1,6 +1,5 @@
|
||||
//
|
||||
// CityGradientView.swift
|
||||
// App
|
||||
// CityGradientView.swift - The view to display a visual forecast.
|
||||
//
|
||||
// Created by Marcus Handte on 24.07.22.
|
||||
//
|
||||
|
||||
@@ -1,6 +1,5 @@
|
||||
//
|
||||
// CityInfoView.swift
|
||||
// App
|
||||
// CityInfoView.swift - The view to display the current weather for a city.
|
||||
//
|
||||
// Created by Marcus Handte on 29.05.22.
|
||||
//
|
||||
|
||||
@@ -1,6 +1,5 @@
|
||||
//
|
||||
// CityVideoView.swift
|
||||
// App
|
||||
// CityVideoView.swift - The views to display the weather videos.
|
||||
//
|
||||
// Created by Marcus Handte on 18.07.22.
|
||||
//
|
||||
@@ -24,6 +23,7 @@ struct CityVideoView: View {
|
||||
self.videos = videos
|
||||
self.page = page
|
||||
var id = 0
|
||||
|
||||
if !videos.cosmoEurope.isEmpty {
|
||||
pages.append(PageItem(id: id, text: "video_source_cosmo_europe") {
|
||||
AnyView(
|
||||
|
||||
@@ -1,6 +1,5 @@
|
||||
//
|
||||
// CityView.swift
|
||||
// App
|
||||
// CityView.swift - The base pager view for cities.
|
||||
//
|
||||
// Created by Marcus Handte on 28.05.22.
|
||||
//
|
||||
|
||||
@@ -1,6 +1,5 @@
|
||||
//
|
||||
// CollectionView.swift
|
||||
// App
|
||||
// CollectionView.swift - The onboarding view for data collection.
|
||||
//
|
||||
// Created by Marcus Handte on 13.07.22.
|
||||
//
|
||||
|
||||
@@ -1,6 +1,5 @@
|
||||
//
|
||||
// CountryView.swift
|
||||
// App
|
||||
// CountryView.swift - The view to display a city list for a country.
|
||||
//
|
||||
// Created by Marcus Handte on 20.07.22.
|
||||
//
|
||||
|
||||
@@ -1,6 +1,5 @@
|
||||
//
|
||||
// CustomizeView.swift
|
||||
// App
|
||||
// CustomizeView.swift - The view to customize the data shown in forecast views.
|
||||
//
|
||||
// Created by Marcus Handte on 18.07.22.
|
||||
//
|
||||
|
||||
@@ -1,6 +1,5 @@
|
||||
//
|
||||
// DeviceView.swift
|
||||
// App
|
||||
// DeviceView.swift - The view to display the data of a single device.
|
||||
//
|
||||
// Created by Marcus Handte on 21.07.22.
|
||||
//
|
||||
|
||||
@@ -1,6 +1,5 @@
|
||||
//
|
||||
// DevicesView.swift
|
||||
// App
|
||||
// DevicesView.swift - The view with the list of the user's devices.
|
||||
//
|
||||
// Created by Marcus Handte on 21.07.22.
|
||||
//
|
||||
@@ -20,13 +19,36 @@ struct DevicesView: View {
|
||||
var body: some View {
|
||||
VStack(spacing: 0) {
|
||||
if let devs = devices {
|
||||
List(devs, id: \Device.id) { device in
|
||||
NavigationLink(destination: {
|
||||
DeviceView(device: device)
|
||||
}) {
|
||||
DeviceEntryView(device: device)
|
||||
ZStack {
|
||||
List(devs, id: \Device.id) { device in
|
||||
NavigationLink(destination: {
|
||||
DeviceView(device: device)
|
||||
}) {
|
||||
DeviceEntryView(device: device)
|
||||
}
|
||||
}.listStyle(PlainListStyle())
|
||||
VStack {
|
||||
Spacer()
|
||||
HStack {
|
||||
Spacer()
|
||||
NavigationLink(destination: {
|
||||
SetupView()
|
||||
}, label: {
|
||||
Image(systemName: "plus")
|
||||
.font(.title)
|
||||
.frame(width: 60, height: 60)
|
||||
.foregroundColor(Color.black)
|
||||
.background(
|
||||
Circle()
|
||||
.fill(Color.accentColor)
|
||||
.shadow(color: .gray, radius: 5)
|
||||
)
|
||||
|
||||
})
|
||||
.padding()
|
||||
}
|
||||
}
|
||||
}.listStyle(PlainListStyle())
|
||||
}
|
||||
}
|
||||
if loading {
|
||||
Spacer()
|
||||
|
||||
@@ -1,6 +1,5 @@
|
||||
//
|
||||
// FavoritesView.swift
|
||||
// App
|
||||
// FavoritesView.swift - The view to display the favorites.
|
||||
//
|
||||
// Created by Marcus Handte on 28.05.22.
|
||||
//
|
||||
|
||||
@@ -1,6 +1,5 @@
|
||||
//
|
||||
// LoginView.swift
|
||||
// App
|
||||
// LoginView.swift - The view to login a user or to link the device.
|
||||
//
|
||||
// Created by Marcus Handte on 28.05.22.
|
||||
//
|
||||
|
||||
@@ -1,6 +1,5 @@
|
||||
//
|
||||
// MeasurementView.swift
|
||||
// App
|
||||
// MeasurementView.swift - The view to display a measurement.
|
||||
//
|
||||
// Created by Marcus Handte on 21.07.22.
|
||||
//
|
||||
|
||||
@@ -1,6 +1,5 @@
|
||||
//
|
||||
// MapView.swift
|
||||
// App
|
||||
// PlaceMapView.swift - The view to display a map of a place.
|
||||
//
|
||||
// Created by Marcus Handte on 20.07.22.
|
||||
//
|
||||
|
||||
@@ -1,6 +1,5 @@
|
||||
//
|
||||
// SearchView.swift
|
||||
// App
|
||||
// SearchView.swift - The view to execute searches and display the results.
|
||||
//
|
||||
// Created by Marcus Handte on 28.05.22.
|
||||
//
|
||||
|
||||
@@ -0,0 +1,275 @@
|
||||
//
|
||||
// SetupView.swift - The view used to configure an arduino.
|
||||
//
|
||||
// Created by Marcus Handte on 02.11.22.
|
||||
//
|
||||
|
||||
import SwiftUI
|
||||
|
||||
struct SetupView: View {
|
||||
|
||||
@ObservedObject var state = ArduinoState()
|
||||
@State var locator = ArduinoLocator()
|
||||
|
||||
var body: some View {
|
||||
GeometryReader { proxy in
|
||||
ScrollView {
|
||||
if state.phase == .configure {
|
||||
ConfigureView(state: state, locator: locator)
|
||||
} else {
|
||||
ConnectView(state: state)
|
||||
.frame(minHeight: proxy.size.height)
|
||||
.frame(width: proxy.size.width)
|
||||
}
|
||||
}.navigationTitle("setup_title")
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
struct ConfigureView: View {
|
||||
|
||||
@ObservedObject var state: ArduinoState
|
||||
@ObservedObject var locator: ArduinoLocator
|
||||
@State var manual = false
|
||||
|
||||
var body: some View {
|
||||
VStack {
|
||||
Text("setup_explain")
|
||||
Link("setup_link", destination: URL(string: "https://www.mowesta.com/weatherstation/")!)
|
||||
.foregroundColor(Color("PrimaryColor"))
|
||||
.padding([.leading, .trailing], 2)
|
||||
.padding([.top], 5)
|
||||
.padding([.bottom], 15)
|
||||
|
||||
HStack {
|
||||
Button(action: {
|
||||
if locator.disabled {
|
||||
UIApplication.shared.open(URL(string:UIApplication.openSettingsURLString)!)
|
||||
} else {
|
||||
locator.setListener({ longitude, latitude in
|
||||
state.latitude = String(format: "%.6f", latitude)
|
||||
state.longitude = String(format: "%.6f", longitude)
|
||||
state.updateNetwork()
|
||||
})
|
||||
}
|
||||
}) {
|
||||
HStack {
|
||||
if locator.localizing {
|
||||
ProgressSpinnerView(20, 3)
|
||||
.padding([.leading, .trailing], 3)
|
||||
} else {
|
||||
Image(systemName: locator.disabled ? "location.slash" : "location")
|
||||
.padding([.leading, .trailing], 3)
|
||||
}
|
||||
Text("setup_button_gps")
|
||||
.frame(alignment: .center)
|
||||
.multilineTextAlignment(.center)
|
||||
}.frame(minHeight: 36)
|
||||
}
|
||||
.disabled(manual || locator.localizing)
|
||||
.buttonStyle(MaterialButtonStyle(color: Color("PrimaryColor"), disabled: manual || locator.localizing))
|
||||
.frame(maxWidth: .infinity)
|
||||
|
||||
Toggle(isOn: $manual) {
|
||||
Text("setup_button_manual")
|
||||
.frame(maxWidth: .infinity, alignment: .trailing)
|
||||
}.frame(maxWidth: .infinity)
|
||||
|
||||
}.frame(maxWidth: 400)
|
||||
.padding([.bottom], 5)
|
||||
|
||||
|
||||
|
||||
HStack(alignment: .top) {
|
||||
ConfigureTextField(image: "arrow.left.arrow.right", hint: "setup_hint_longitude", text: $state.longitude, disabled: !manual, error: manual && state.lon == nil ? "setup_error_longitude" : nil, secure: false)
|
||||
ConfigureTextField(image: "arrow.up.arrow.down", hint: "setup_hint_latitude", text: $state.latitude, disabled: !manual, error: manual && state.lat == nil ? "setup_error_latitude" : nil, secure: false)
|
||||
}.frame(maxWidth: 400)
|
||||
|
||||
ConfigureTextField(image: "wifi", hint: "setup_hint_wlan_name", text: $state.network, disabled: false, error: state.network.count > 0 ? nil : "setup_error_wlan_name_too_short", secure: false)
|
||||
|
||||
ConfigureTextField(image: "lock", hint: "setup_hint_wlan_password", text: $state.password, disabled: false, error: state.password.count < 8 ? ( state.password.count == 0 ? "setup_error_wlan_password_none": "setup_error_wlan_password_too_short") : nil, secure: true)
|
||||
|
||||
ConfigureTextField(image: "cpu", hint: "setup_hint_device_name", text: $state.model, disabled: false, error: state.model.count > 0 ? nil : "setup_error_device_name_too_short", secure: false)
|
||||
|
||||
Text("setup_prepare")
|
||||
.frame(maxWidth: 400)
|
||||
.padding([.bottom], 10)
|
||||
Button("setup_button_ready", action: {
|
||||
ArduinoTask(taskState: state).execute()
|
||||
|
||||
}).disabled(!state.isExecutable())
|
||||
.buttonStyle(MaterialButtonStyle(disabled: !state.isExecutable()))
|
||||
.frame(maxWidth: 400)
|
||||
}.padding()
|
||||
.onChange(of: manual) { v in
|
||||
if v {
|
||||
locator.clearListener()
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
struct ConfigureTextField: View {
|
||||
|
||||
let image: String
|
||||
let hint: LocalizedStringKey
|
||||
let text: Binding<String>
|
||||
let disabled: Bool
|
||||
let error: LocalizedStringKey?
|
||||
let secure: Bool
|
||||
@State var hidden = true
|
||||
|
||||
var body: some View {
|
||||
VStack(alignment: .leading, spacing: 1) {
|
||||
HStack {
|
||||
Image(systemName: image)
|
||||
if (secure && hidden) {
|
||||
SecureField(hint, text: text)
|
||||
.frame(maxWidth: .infinity, minHeight: 24)
|
||||
.autocapitalization(.none)
|
||||
.disableAutocorrection(true)
|
||||
.disabled(disabled)
|
||||
} else {
|
||||
TextField(hint, text: text)
|
||||
.frame(maxWidth: .infinity, minHeight: 24)
|
||||
.autocapitalization(.none)
|
||||
.disableAutocorrection(true)
|
||||
.disabled(disabled)
|
||||
}
|
||||
if (secure) {
|
||||
Button(action: { hidden.toggle() }, label: {
|
||||
Image(systemName: hidden ? "eye" : "eye.slash")
|
||||
})
|
||||
.buttonStyle(NullButtonStyle())
|
||||
}
|
||||
}
|
||||
.padding([.top], 14)
|
||||
.padding(8)
|
||||
.frame(maxWidth: 400)
|
||||
.overlay(
|
||||
ZStack(alignment: .topLeading) {
|
||||
RoundedRectangle(cornerRadius: 6)
|
||||
.stroke(error == nil ? .gray : .red, lineWidth: 2)
|
||||
.padding([.top], 10)
|
||||
Text(hint)
|
||||
.foregroundColor(error == nil ? .gray : .red)
|
||||
.padding([.leading, .trailing], 5)
|
||||
.background(Color(UIColor.systemBackground))
|
||||
.font(.system(size: 14))
|
||||
.padding([.leading], 10)
|
||||
}
|
||||
)
|
||||
Text(error == nil ? LocalizedStringKey("") : error!)
|
||||
.font(.caption)
|
||||
.foregroundColor(.red)
|
||||
.padding([.leading], 8)
|
||||
.padding([.bottom], 4)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
|
||||
struct ConnectView: View {
|
||||
|
||||
@ObservedObject var state: ArduinoState
|
||||
@Environment(\.presentationMode) var mode: Binding<PresentationMode>
|
||||
|
||||
var body: some View {
|
||||
VStack {
|
||||
Group {
|
||||
if state.phase == .success {
|
||||
Image(systemName: "checkmark.circle")
|
||||
.resizable()
|
||||
} else if state.phase == .failure {
|
||||
Image(systemName: "exclamationmark.circle")
|
||||
.resizable()
|
||||
} else {
|
||||
ProgressSpinnerView(100, 8)
|
||||
}
|
||||
}.frame(width: 100, height: 100)
|
||||
.padding()
|
||||
|
||||
HStack {
|
||||
Image(systemName: "plus.circle")
|
||||
.foregroundColor(state.phase == .register ? .accentColor : .primary)
|
||||
.padding()
|
||||
Image(systemName: "link.circle")
|
||||
.foregroundColor(state.phase == .connect ? .accentColor : .primary)
|
||||
.padding()
|
||||
Image(systemName: "paperplane.circle")
|
||||
.foregroundColor(state.phase == .transfer ? .accentColor : .primary)
|
||||
.padding()
|
||||
|
||||
|
||||
}.font(.largeTitle)
|
||||
|
||||
if let text = getPhase() {
|
||||
Text(text)
|
||||
.font(.headline)
|
||||
}
|
||||
if state.phase == .failure {
|
||||
if let text = getFailure() {
|
||||
Text(text)
|
||||
.frame(maxWidth: 300)
|
||||
.multilineTextAlignment(.center)
|
||||
}
|
||||
Button(action: {
|
||||
state.reset()
|
||||
}) {
|
||||
Text("connect_button_try_again")
|
||||
}
|
||||
.buttonStyle(MaterialButtonStyle(disabled: false))
|
||||
.frame(maxWidth: 200)
|
||||
.padding()
|
||||
|
||||
}
|
||||
}
|
||||
.padding()
|
||||
.onChange(of: state.phase) { s in
|
||||
if s == .success {
|
||||
DispatchQueue.main.asyncAfter(deadline: .now() + 5) {
|
||||
self.mode.wrappedValue.dismiss()
|
||||
state.reset()
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func getPhase() -> LocalizedStringKey? {
|
||||
if state.phase == .register {
|
||||
return "connect_message_creating"
|
||||
} else if state.phase == .connect {
|
||||
return "connect_message_searching"
|
||||
} else if state.phase == .transfer {
|
||||
return "connect_message_transfering"
|
||||
} else if state.phase == .success {
|
||||
return "connect_message_success"
|
||||
} else {
|
||||
return nil;
|
||||
}
|
||||
}
|
||||
|
||||
func getFailure() -> LocalizedStringKey? {
|
||||
if state.failure == .register {
|
||||
return "connect_message_create_failed"
|
||||
} else if state.failure == .connect {
|
||||
return "connect_message_search_failed"
|
||||
} else if state.failure == .transfer {
|
||||
return "connect_message_transfer_failed"
|
||||
} else {
|
||||
return nil
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
|
||||
|
||||
struct SetupView_Previews: PreviewProvider {
|
||||
static var previews: some View {
|
||||
NavigationView {
|
||||
SetupView()
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,6 +1,5 @@
|
||||
//
|
||||
// StateView.swift
|
||||
// App
|
||||
// StateView.swift - The view to display a city list for a state.
|
||||
//
|
||||
// Created by Marcus Handte on 20.07.22.
|
||||
//
|
||||
|
||||
@@ -1,6 +1,5 @@
|
||||
//
|
||||
// StationView.swift
|
||||
// App
|
||||
// StationView.swift - The view to display a single weather station.
|
||||
//
|
||||
// Created by Marcus Handte on 20.07.22.
|
||||
//
|
||||
|
||||
@@ -1,6 +1,5 @@
|
||||
//
|
||||
// StationsView.swift
|
||||
// App
|
||||
// StationsView.swift - The view to display the list of weather stations.
|
||||
//
|
||||
// Created by Marcus Handte on 21.07.22.
|
||||
//
|
||||
|
||||
@@ -1,6 +1,5 @@
|
||||
//
|
||||
// WeatherConditionView.swift
|
||||
// App
|
||||
// WeatherViews.swift - A set of helper views to display weather infos.
|
||||
//
|
||||
// Created by Marcus Handte on 17.07.22.
|
||||
//
|
||||
|
||||
@@ -127,10 +127,10 @@
|
||||
"setting_about_build_title"="Version";
|
||||
"setting_about_build_summary %@ %@ %@" = "%@ | %@ @ %@";
|
||||
"setting_category_development"="Entwicklung";
|
||||
"setting_development_device"="Geräteinfos";
|
||||
"setting_development_token"="Geräteschlüssel";
|
||||
"setting_mowesta_url_title"="Dienstadresse";
|
||||
"setting_mowesta_url_summary"="Konfiguriert die URL der MoWeSta API, die vom HTTP Client der App verwendet wird.";
|
||||
"setting_development_device_title"="Geräteinfos";
|
||||
"setting_development_token_title"="Geräteschlüssel";
|
||||
"setting_development_url_title"="Dienstadresse";
|
||||
"setting_development_url_summary"="Konfiguriert die URL der MoWeSta API, die vom HTTP Client der App verwendet wird.";
|
||||
"setting_development_clear_title"="Cache löschen";
|
||||
"setting_development_clear_summary"="Löscht alle gecachten Standortdaten vom Gerät.";
|
||||
"setting_development_clear_message"="Der Cache wurde gelöscht.";
|
||||
@@ -360,3 +360,36 @@
|
||||
"format_measure_humidity %lf"="%.0lf";
|
||||
"format_measure_temperature %lf"="%.1lf";
|
||||
"format_measure_pressure %lf"="%.0lf";
|
||||
|
||||
// setup weather station
|
||||
"setup_title"="Arduinoeinrichtung";
|
||||
"setup_explain"="Für den Fall, dass Du eine Arduino-basierte Wetterstation mit unseren Anleitungen und unserem Code bei Github gebastelt hast, kannst Du sie hier einrichten. Dafür brauchen wir Deinen Standort, Deine Wifieinstellungen und einen Gerätenamen.";
|
||||
"setup_prepare"="Bitte schalte Deine Wetterstation ein und halte den Knopf lange gedrückt, um in den Einrichtungsmodus zu wechseln, bevor Du fortfährst.";
|
||||
"setup_link"="Du hast keine Ahnung worum es hier geht? Hier findest Du weitere Informationen.";
|
||||
"setup_hint_wlan_name"="Netzwerkname";
|
||||
"setup_hint_wlan_password"="Netzwerkpasswort";
|
||||
"setup_hint_device_name"="Gerätename";
|
||||
"setup_device_manufacturer"="MoWeSta";
|
||||
"setup_device_name_default"="Arduino";
|
||||
"setup_hint_longitude"="Längengrad";
|
||||
"setup_hint_latitude"="Breitengrad";
|
||||
"setup_button_manual"="Manuelle Eingabe";
|
||||
"setup_button_gps"="Standort bestimmen";
|
||||
"setup_error_longitude"="Ungültiger Längengrad.";
|
||||
"setup_error_latitude"="Ungültiger Breitengrad.";
|
||||
"setup_button_ready"="Fortfahren";
|
||||
"setup_error_wlan_name_too_short"="Der Netzwerkname ist erforderlich.";
|
||||
"setup_error_wlan_password_none"="Das Netzwerkpasswort ist erforderlich.";
|
||||
"setup_error_wlan_password_too_short"="Das Netzwerkpasswort ist zu kurz.";
|
||||
"setup_error_device_name_too_short"="Ein Gerätename ist erforderlich.";
|
||||
"setup_error_gps_disabled"="GPS ist derzeit deaktiviert.";
|
||||
|
||||
"connect_message_creating"="Erstelle MoWeSta Gerät";
|
||||
"connect_message_create_failed"="Das Gerät konnte nicht erstellt werden. Stell sicher, dass Du mit dem Internet verbunden bist und versuch\'s nochmal.";
|
||||
"connect_message_searching"="Suche nach WiFi Netzwerken";
|
||||
"connect_message_search_failed"="Die Verbindung mit dem Netzwerk ist fehlgeschlagen. Stell sicher, dass sich Dein Arduino im Einrichtungsmodus befindet und versuch\'s nochmal.";
|
||||
"connect_message_transfering"="Wetterstation wird eingerichtet";
|
||||
"connect_message_transfer_failed"="Die Einrichtung ist fehlgeschlagen. Stell sicher, dass sich Dein Arduino im Einrichtungsmodus befindet und versuch\'s nochmal.";
|
||||
|
||||
"connect_message_success"="Einrichtung erfolgreich";
|
||||
"connect_button_try_again"="Weiter";
|
||||
|
||||
@@ -131,10 +131,10 @@
|
||||
"setting_about_build_title"="Version";
|
||||
"setting_about_build_summary %@ %@ %@" = "%@ | %@ @ %@";
|
||||
"setting_category_development"="Development";
|
||||
"setting_development_device"="Device Info";
|
||||
"setting_development_token"="Device Key";
|
||||
"setting_mowesta_url_title"="Service Address";
|
||||
"setting_mowesta_url_summary"="Sets the URL to the MoWeSta API that is used by the app's HTTP client.";
|
||||
"setting_development_device_title"="Device Info";
|
||||
"setting_development_token_title"="Device Key";
|
||||
"setting_development_url_title"="Service Address";
|
||||
"setting_development_url_summary"="Sets the URL to the MoWeSta API that is used by the app's HTTP client.";
|
||||
"setting_development_clear_title"="Clear Cache";
|
||||
"setting_development_clear_summary"="Clears all cached location information from the device.";
|
||||
"setting_development_clear_message"="Location cache cleared.";
|
||||
@@ -366,24 +366,35 @@
|
||||
"format_title %@"="%1$@";
|
||||
"format_title %@ %@"="%1$@ | %2$@";
|
||||
|
||||
// setup weather station
|
||||
"setup_title"="Arduino Setup";
|
||||
"setup_explain"="If you assembled an Arduino-based weather station using our tutorials and code on Github, you can set it up here. To configure your weather station, we need your location and your Wifi network settings as well as a device name.";
|
||||
"setup_prepare"="Please turn on your weather station and long press the button to enter setup mode before you continue.";
|
||||
"setup_link"="You don't know what this is? Here you can get more information.";
|
||||
"setup_hint_wlan_name"="Network name";
|
||||
"setup_hint_wlan_password"="Network password";
|
||||
"setup_hint_device_name"="Device name";
|
||||
"setup_device_manufacturer"="MoWeSta";
|
||||
"setup_device_name_default"="Arduino";
|
||||
"setup_hint_longitude"="Longitude";
|
||||
"setup_hint_latitude"="Latitude";
|
||||
"setup_button_manual"="Enter manually";
|
||||
"setup_button_gps"="Get GPS position";
|
||||
"setup_error_longitude"="Invalid longitude.";
|
||||
"setup_error_latitude"="Invalid latitude.";
|
||||
"setup_button_ready"="Ready";
|
||||
"setup_error_wlan_name_too_short"="The network name is required.";
|
||||
"setup_error_wlan_password_none"="The network password is required.";
|
||||
"setup_error_wlan_password_too_short"="The network password is too short.";
|
||||
"setup_error_device_name_too_short"="A device name is required.";
|
||||
"setup_error_gps_disabled"="GPS is currently disabled.";
|
||||
|
||||
/*
|
||||
<string name="format_temperature_both" translatable="false">%.1f<small>\u00A0°C</small> / %.1f<small>\u00A0°F</small></string>
|
||||
<string name="format_temperature_celsius" translatable="false">%.1f<small> °C</small></string>
|
||||
<string name="format_temperature_fahrenheit" translatable="false">%.1f<small> °F</small></string>
|
||||
<string name="format_pressure_both" translatable="false"><span>%.1f<small>\u00A0hPa</small></span> / <span>%.3f<small>\u00A0psi</small></span></string>
|
||||
<string name="format_pressure_si" translatable="false">%.1f<small> hPa</small></string>
|
||||
<string name="format_pressure_im" translatable="false">%.3f<small> psi</small></string>
|
||||
<string name="format_wind_speed_both" translatable="false">%d<small>\u00A0km\u2215h</small> / %d<small>\u00A0mph</small></string>
|
||||
<string name="format_wind_speed_si" translatable="false">%d<small> km\u2215h</small> (<small>BFT</small> %d)</string>
|
||||
<string name="format_wind_speed_im" translatable="false">%d<small> mph</small> (<small>BFT</small> %d)</string>
|
||||
<string name="format_precipitation_both" translatable="false">%.1f<small>\u00A0mm\u2215h</small> / %.2f<small>\u00A0in\u2215h</small></string>
|
||||
<string name="format_precipitation_si" translatable="false">%.1f<small> mm\u2215h</small></string>
|
||||
<string name="format_precipitation_im" translatable="false">%.2f<small> in\u2215h</small></string>
|
||||
<string name="format_snow_both" translatable="false">%.2f<small>\u00A0m</small> / %.2f<small>\u00A0ft</small></string>
|
||||
<string name="format_snow_si" translatable="false">%.2f<small> m</small></string>
|
||||
<string name="format_snow_im" translatable="false">%.2f<small> ft</small></string>
|
||||
<string name="format_altitude_both" translatable="false">%.0f<small>\u00A0m</small> / %.0f<small>\u00A0ft</small></string>
|
||||
<string name="format_altitude_si" translatable="false">%.0f<small> m</small></string>
|
||||
<string name="format_altitude_im" translatable="false">%.0f<small> ft</small></string>
|
||||
*/
|
||||
"connect_message_creating"="Creating MoWeSta device";
|
||||
"connect_message_create_failed"="Failed to create the device. Please make sure that you are connected to the Internet and try again.";
|
||||
"connect_message_searching"="Searching for WiFi networks";
|
||||
"connect_message_search_failed"="Unable to connect to WiFi network. Please make sure that your Arduino is in setup mode and try again.";
|
||||
"connect_message_transfering"="Configuring weather station";
|
||||
"connect_message_transfer_failed"="Failed to configure the device. Please make sure that your Arduino is in setup mode and try again.";
|
||||
|
||||
"connect_message_success"="Setup complete";
|
||||
"connect_button_try_again"="Continue";
|
||||
|
||||
@@ -6,6 +6,7 @@ description = 'MoWeSta Service Alexa'
|
||||
|
||||
dependencies {
|
||||
|
||||
compileOnly project(':common-api')
|
||||
compileOnly project(':service-ejb')
|
||||
api "com.amazon.alexa:ask-sdk:2.37.1"
|
||||
|
||||
|
||||
+18
-1
@@ -69,10 +69,15 @@ public class LinearRegression {
|
||||
private double rSquared;
|
||||
|
||||
/**
|
||||
* The standard error.
|
||||
* The standard error (rmse of residuals).
|
||||
*/
|
||||
private double error;
|
||||
|
||||
/**
|
||||
* The mean average error (of residuals).
|
||||
*/
|
||||
private double mae;
|
||||
|
||||
/**
|
||||
* Performs linear regression on the given values. Of course,
|
||||
* we need at least 2 values at different x positions for this
|
||||
@@ -111,6 +116,7 @@ public class LinearRegression {
|
||||
// analyze results
|
||||
double rss = 0.0; // residual sum of squares
|
||||
double ssr = 0.0; // regression sum of squares
|
||||
mae = 0.0; // mean average error
|
||||
itx = x.iterator();
|
||||
ity = y.iterator();
|
||||
for (int i = 0; i < n; i++) {
|
||||
@@ -119,10 +125,21 @@ public class LinearRegression {
|
||||
double fit = slope*vx + intercept;
|
||||
rss += (fit - vy) * (fit - vy);
|
||||
ssr += (fit - ybar) * (fit - ybar);
|
||||
mae += Math.abs(fit - vy);
|
||||
}
|
||||
rSquared = ssr / yybar;
|
||||
error = Math.sqrt(rss / (n - 2));
|
||||
mae /= n;
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns the mean average error.
|
||||
*
|
||||
* @return The mean average error.
|
||||
*/
|
||||
public double getMae() {
|
||||
return mae;
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns the R² value.
|
||||
|
||||
@@ -12,6 +12,7 @@ dependencies {
|
||||
implementation "org.jboss.resteasy:resteasy-client:${versionResteasy}"
|
||||
implementation 'postgresql:postgresql:8.4-701.jdbc3'
|
||||
implementation 'net.iakovlev:timeshape:2019b.7'
|
||||
implementation 'org.apache.commons:commons-math3:3.6.1'
|
||||
|
||||
// dependencies required for analysis tools
|
||||
implementation 'commons-cli:commons-cli:1.4'
|
||||
@@ -20,6 +21,9 @@ dependencies {
|
||||
|
||||
compileOnly "io.swagger:swagger-annotations:${versionSwagger}"
|
||||
|
||||
implementation 'nz.ac.waikato.cms.weka:weka-stable:3.8.6'
|
||||
|
||||
|
||||
|
||||
|
||||
// builds a jar with all dependencies for the nominatim exporter so
|
||||
|
||||
@@ -0,0 +1,337 @@
|
||||
package com.mowesta.tool.mobilithek;
|
||||
|
||||
import java.io.BufferedReader;
|
||||
import java.io.BufferedWriter;
|
||||
import java.io.File;
|
||||
import java.io.FileReader;
|
||||
import java.io.FileWriter;
|
||||
import java.io.IOException;
|
||||
import java.nio.charset.StandardCharsets;
|
||||
import java.text.ParseException;
|
||||
import java.text.SimpleDateFormat;
|
||||
import java.util.ArrayList;
|
||||
import java.util.Calendar;
|
||||
import java.util.Collections;
|
||||
import java.util.Date;
|
||||
import java.util.HashSet;
|
||||
import java.util.List;
|
||||
import java.util.Set;
|
||||
import java.util.stream.Collectors;
|
||||
|
||||
import com.fasterxml.jackson.databind.ObjectMapper;
|
||||
import com.locoslab.library.geometry.wgs.Coordinates;
|
||||
import com.locoslab.library.geometry.wgs.MapTile;
|
||||
import com.mowesta.api.device.Device;
|
||||
import com.mowesta.api.device.OperatingSystem;
|
||||
import com.mowesta.api.measurement.Measurement;
|
||||
import com.mowesta.tool.paper.LocationClassifier;
|
||||
import com.mowesta.tool.paper.LocationClassifier.TripResult;
|
||||
import com.mowesta.tool.paper.Mse;
|
||||
|
||||
/**
|
||||
* A hack to obfuscate the data for the public release in the Mobilithek.
|
||||
*
|
||||
* @author marcus
|
||||
*/
|
||||
public class DataObfuscator {
|
||||
|
||||
public static final File folder = new File("mowesta-dump");
|
||||
|
||||
public static final int OBFUSCATION_ZOOM = 10;
|
||||
public static final String SEPARATOR = ";";
|
||||
|
||||
public static void main(String[] args) throws Exception {
|
||||
Set<MapTile> tiles = new HashSet<>();
|
||||
Long tmin = null;
|
||||
Long tmax = null;
|
||||
Double minLat = null;
|
||||
Double maxLat = null;
|
||||
Double minLon = null;
|
||||
Double maxLon = null;
|
||||
|
||||
|
||||
BufferedWriter writer = new BufferedWriter(new FileWriter(new File("obfuscated.csv")));
|
||||
writer.write("Geraet" + SEPARATOR);
|
||||
writer.write("Hersteller" + SEPARATOR);
|
||||
writer.write("Model" + SEPARATOR);
|
||||
writer.write("Monat" + SEPARATOR);
|
||||
writer.write("Temperatur in °C (DWD)" + SEPARATOR);
|
||||
writer.write("Latitude (WGS84)" + SEPARATOR);
|
||||
writer.write("Longitude (WGS84)" + SEPARATOR);
|
||||
writer.write("Verschleierung (m)" + SEPARATOR);
|
||||
|
||||
writer.write("Aufenthaltsdauer im Freien (ms)" + SEPARATOR);
|
||||
writer.write("Batterietemperatur in °C" + SEPARATOR);
|
||||
writer.write("Geraet aktiv" + SEPARATOR);
|
||||
|
||||
writer.write("Aufenthaltsdauer im Freien (ms)" + SEPARATOR);
|
||||
writer.write("Batterietemperatur in °C" + SEPARATOR);
|
||||
writer.write("Geraet aktiv" + SEPARATOR);
|
||||
|
||||
writer.write("..." + SEPARATOR);
|
||||
writer.newLine();
|
||||
|
||||
long start = getDate("2019-01-01 0:00");
|
||||
long end = getDate("2023-01-01 00:00");
|
||||
int id = 0;
|
||||
int count = 0;
|
||||
|
||||
List<Device> devices = readFile(new File(folder, "devices.json"), Device.class);
|
||||
for (Device d: devices) {
|
||||
if (d.getId() == 24963415l) continue; // stationary tablet (will cause out-of-memory)
|
||||
// if (d.getId() == 20488695l) {
|
||||
// System.out.println("Dev: " + d.getManufacturer() + " " + d.getModel());
|
||||
// }
|
||||
// if (d.getId() == 20488695l) continue; // device with 1 degree precision
|
||||
// if (d.getId() == 35723568l) continue; // t: 0.9 - 9.5
|
||||
// if (d.getId() == 40549928l) continue; // one of our test devices
|
||||
|
||||
|
||||
//if (d.getId() != 11626535l) continue;
|
||||
|
||||
|
||||
if (d.getOs() == OperatingSystem.ANDROID) {
|
||||
List<Measurement> ms = readFile(new File(folder, "measurement-" + d.getId() + ".json" ), Measurement.class);
|
||||
ms = ms.stream().filter(m->m.getTime() > start && m.getTime() < end).collect(Collectors.toList());
|
||||
Collections.sort(ms, (a, b) -> Long.compare(a.getTime(), b.getTime()));
|
||||
List<TripResult> trips = getTrips(ms, System.currentTimeMillis());
|
||||
List<TripResult> walking = trips.stream().filter(t -> t.getDistance() > 300 && t.getSpeed() < 2 && t.getDuration() > 5 * 60 * 1000).collect(Collectors.toList());
|
||||
List<TripResult> walkingWithTruth = walking.stream().filter(t -> getStationTemperature(t) != null).collect(Collectors.toList());
|
||||
List<String> output = new ArrayList<>();
|
||||
if (walkingWithTruth.size() > 0) {
|
||||
id += 1;
|
||||
for (TripResult r: walkingWithTruth) {
|
||||
tmin = (tmin == null || tmin > r.origin.getTime())?r.origin.getTime():tmin;
|
||||
tmax = (tmax == null || tmax < r.origin.getTime())?r.origin.getTime():tmax;
|
||||
StringBuilder b = new StringBuilder();
|
||||
double truth = getStationTemperature(r);
|
||||
double latitude = r.origin.getCoordinate().getLatitude();
|
||||
double longitude = r.origin.getCoordinate().getLongitude();
|
||||
MapTile t = MapTile.getMapTile(longitude, latitude, OBFUSCATION_ZOOM);
|
||||
tiles.add(t);
|
||||
double olatitude = (t.getNorthWest().getLatitude() + t.getSouthEast().getLatitude()) / 2;
|
||||
double olongitude = (t.getNorthWest().getLongitude() + t.getSouthEast().getLongitude()) / 2;
|
||||
double oaccuracy = Coordinates.DISTANCE.getDistance(t.getNorthWest(), t.getSouthEast()) / 2;
|
||||
int month = getMonth(r);
|
||||
minLat = (minLat == null || minLat > olatitude)?olatitude:minLat;
|
||||
maxLat = (maxLat == null || maxLat < olatitude)?olatitude:maxLat;
|
||||
minLon = (minLon == null || minLon > olongitude)?olongitude:minLon;
|
||||
maxLon = (maxLon == null || maxLon < olongitude)?olongitude:maxLon;
|
||||
|
||||
b.append(id + SEPARATOR);
|
||||
b.append(d.getManufacturer() + SEPARATOR);
|
||||
b.append(d.getModel() + SEPARATOR);
|
||||
b.append(month + SEPARATOR);
|
||||
b.append(String.format("%.1f", truth) + SEPARATOR);
|
||||
b.append(String.format("%.5f", olatitude) + SEPARATOR);
|
||||
b.append(String.format("%.5f", olongitude) + SEPARATOR);
|
||||
b.append(String.format("%.0f", oaccuracy) + SEPARATOR);
|
||||
|
||||
b.append("0" + SEPARATOR);
|
||||
b.append(String.format("%.1f", Mse.getDeviceTemperature(r.origin)) + SEPARATOR);
|
||||
b.append((Mse.isActive(r.origin)?"Ja":"Nein") + SEPARATOR);
|
||||
count += 1;
|
||||
|
||||
for (Measurement m: r.motion) {
|
||||
if (m.getTime() - r.origin.getTime() == 0) continue;
|
||||
b.append(String.format("%d", m.getTime() - r.origin.getTime()) + SEPARATOR);
|
||||
b.append(String.format("%.1f", Mse.getDeviceTemperature(m)) + SEPARATOR);
|
||||
b.append((Mse.isActive(m)?"Ja":"Nein") + SEPARATOR);
|
||||
count += 1;
|
||||
}
|
||||
|
||||
|
||||
if (r.destination != r.motion.get(r.motion.size() - 1)) {
|
||||
b.append(String.format("%d", r.destination.getTime() - r.origin.getTime()) + SEPARATOR);
|
||||
b.append(String.format("%.1f", Mse.getDeviceTemperature(r.destination)) + SEPARATOR);
|
||||
b.append((Mse.isActive(r.destination)?"Ja":"Nein") + SEPARATOR);
|
||||
count += 1;
|
||||
}
|
||||
|
||||
output.add(b.toString());
|
||||
}
|
||||
}
|
||||
Collections.sort(output);
|
||||
for (String s: output) {
|
||||
writer.append(s);
|
||||
writer.newLine();
|
||||
}
|
||||
}
|
||||
}
|
||||
writer.flush();
|
||||
writer.close();
|
||||
System.out.println("Tiles: " + tiles.size());
|
||||
System.out.println("Tmin: " + new Date(tmin));
|
||||
System.out.println("Tmax: " + new Date(tmax));
|
||||
System.out.println("Count: " + count);
|
||||
System.out.println("MinLat: " + minLat);
|
||||
System.out.println("MaxLat: " + maxLat);
|
||||
System.out.println("MinLon: " + minLon);
|
||||
System.out.println("MaxLon: " + maxLon);
|
||||
|
||||
}
|
||||
|
||||
|
||||
public static void append(StringBuilder b, double value) {
|
||||
b.append(("" + value).replace(".", ",") + ";");
|
||||
}
|
||||
|
||||
public static List<double[]> getAllPairs(List<Measurement> ms) {
|
||||
List<double[]> result = new ArrayList<>();
|
||||
for (Measurement m: ms) {
|
||||
Double station = Mse.getStationTemperature(m);
|
||||
Double device = Mse.getDeviceTemperature(m);
|
||||
if (station != null && device != null) {
|
||||
result.add(new double[] { device, station });
|
||||
}
|
||||
}
|
||||
return result;
|
||||
}
|
||||
|
||||
public static List<double[]> getTripPairs(List<TripResult> trips) {
|
||||
List<double[]> result = new ArrayList<>();
|
||||
for (TripResult r: trips) {
|
||||
for (Measurement m: r.motion) {
|
||||
Double station = Mse.getStationTemperature(m);
|
||||
Double device = Mse.getDeviceTemperature(m);
|
||||
if (station != null && device != null) {
|
||||
result.add(new double[] { device, station });
|
||||
}
|
||||
}
|
||||
}
|
||||
return result;
|
||||
}
|
||||
|
||||
public static int getMonth(TripResult r) {
|
||||
Calendar c = Calendar.getInstance();
|
||||
c.setTimeInMillis(r.origin.getTime());
|
||||
return c.get(Calendar.MONTH) + 1;
|
||||
}
|
||||
|
||||
|
||||
|
||||
|
||||
public static List<double[]> getPairs(List<TripResult> walking, double time, boolean noActive) {
|
||||
List<double[]> outside = new ArrayList<>();
|
||||
walking.forEach(t -> {
|
||||
double station = getStationTemperature(t);
|
||||
Double temperature = getDeviceTemperatureAt(t, time, noActive);
|
||||
if (temperature != null) {
|
||||
outside.add(new double[] { temperature, station });
|
||||
}
|
||||
});
|
||||
return outside;
|
||||
}
|
||||
|
||||
|
||||
public static Double getDeviceTemperatureAt(TripResult t, double minute, boolean noActive) {
|
||||
Measurement first = t.origin;
|
||||
double firstMinute = 0;
|
||||
Measurement last = t.destination;
|
||||
double lastMinute = getMinuteForMeasurement(t.origin, last);
|
||||
if (minute > lastMinute) {
|
||||
return null;
|
||||
}
|
||||
for (Measurement m: t.motion) {
|
||||
double curr = getMinuteForMeasurement(t.origin, m);
|
||||
if (curr <= minute) {
|
||||
if (minute - curr < minute - firstMinute) {
|
||||
first = m;
|
||||
firstMinute = curr;
|
||||
}
|
||||
} else {
|
||||
if (curr - minute < lastMinute - minute) {
|
||||
last = m;
|
||||
lastMinute = curr;
|
||||
}
|
||||
}
|
||||
}
|
||||
if (noActive) {
|
||||
// filter trips with active measurements
|
||||
if (Mse.isActive(last) || Mse.isActive(first)) return null;
|
||||
int count = 1;
|
||||
for (Measurement m: t.motion) {
|
||||
if (Mse.isActive(m)) {
|
||||
count -= 1;
|
||||
if (count == 0)
|
||||
return null;
|
||||
}
|
||||
if (m == last) break;
|
||||
}
|
||||
}
|
||||
// linear interpolation
|
||||
double ft = Mse.getDeviceTemperature(first);
|
||||
double lt = Mse.getDeviceTemperature(last);
|
||||
if (lastMinute == firstMinute) return ft;
|
||||
double percent = (minute - firstMinute) / (lastMinute - firstMinute);
|
||||
//System.out.println("perc: " + percent);
|
||||
double res = percent * lt + (1 - percent) * ft;
|
||||
//System.out.println("FT: " + ft + " LT: " + lt + " Timing: " + firstMinute + " " + lastMinute + " " + minute + " = " + res);
|
||||
return res;
|
||||
}
|
||||
|
||||
public static double getMinuteForMeasurement(Measurement origin, Measurement m) {
|
||||
return (m.getTime() - origin.getTime()) / 60000d;
|
||||
}
|
||||
|
||||
public static Double getStationTemperature(TripResult t) {
|
||||
Double r = Mse.getStationTemperature(t.origin);
|
||||
if (r == null) {
|
||||
for (Measurement m: t.motion) {
|
||||
r = Mse.getStationTemperature(m);
|
||||
if (r != null) break;
|
||||
}
|
||||
if (r == null) {
|
||||
//r = Mse.getStationTemperature(t.destination);
|
||||
}
|
||||
}
|
||||
return r;
|
||||
}
|
||||
|
||||
|
||||
public static List<TripResult> getTrips(List<Measurement> ms, long now) {
|
||||
List<TripResult> results = new ArrayList<>();
|
||||
TripResult result;
|
||||
while ((result = LocationClassifier.computeNextTrip(ms, now)) != null) {
|
||||
results.add(result);
|
||||
ms = result.remainder;
|
||||
}
|
||||
return results;
|
||||
}
|
||||
|
||||
public static Measurement getMeasurement(TripResult result, double minute, double threshold) {
|
||||
List<Measurement> candidates = result.motion.stream().filter(m -> {
|
||||
double min = (m.getTime() - result.origin.getTime()) / 60000d;
|
||||
return min > minute - 0.5 * threshold && min <= minute + 0.5 * threshold;
|
||||
}).collect(Collectors.toList());
|
||||
if (candidates.isEmpty()) return null;
|
||||
else return candidates.get(0);
|
||||
}
|
||||
|
||||
|
||||
public static String toString(Date date) {
|
||||
SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm");
|
||||
return df.format(date);
|
||||
}
|
||||
|
||||
public static long getDate(String string) throws ParseException {
|
||||
SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm");
|
||||
Date date = df.parse(string);
|
||||
return date.getTime();
|
||||
}
|
||||
|
||||
|
||||
public static <T> List<T> readFile(File file, Class<T> type) throws Exception {
|
||||
ObjectMapper mapper = new ObjectMapper();
|
||||
List<T> result = new ArrayList<>();
|
||||
try (BufferedReader reader = new BufferedReader(new FileReader(file, StandardCharsets.UTF_8))) {
|
||||
String line = null;
|
||||
while ((line = reader.readLine()) != null) {
|
||||
result.add(mapper.readValue(line, type));
|
||||
}
|
||||
}
|
||||
return result;
|
||||
}
|
||||
|
||||
|
||||
}
|
||||
@@ -8,9 +8,11 @@ import java.util.Date;
|
||||
import java.util.List;
|
||||
import java.util.stream.Collectors;
|
||||
|
||||
import com.mowesta.api.Coordinate;
|
||||
import com.mowesta.api.TimeRange;
|
||||
import com.mowesta.api.measurement.Measurement;
|
||||
import com.mowesta.api.measurement.MeasurementType;
|
||||
import com.mowesta.data.process.algorithm.LinearRegression;
|
||||
|
||||
public class FAIRKarlsruhe {
|
||||
|
||||
@@ -18,56 +20,61 @@ public class FAIRKarlsruhe {
|
||||
|
||||
File out = new File("karlsruhe");
|
||||
out.mkdirs();
|
||||
|
||||
TimeRange range = new TimeRange(1638572400000l, 24 * 60 * 60000 * 55l);
|
||||
|
||||
|
||||
List<Long> devices = new ArrayList<>();
|
||||
// devices.add(41306043l);
|
||||
// devices.add(41306077l);
|
||||
// devices.add(41306087l);
|
||||
TimeRange range = new TimeRange(1629410400000l, 3888000000l);
|
||||
// TimeRange range = new TimeRange(1629410400000l, 3888000000l);
|
||||
//
|
||||
// 8-15 sept
|
||||
// TimeRange range = new TimeRange(1631052000000l, 691200000l);
|
||||
|
||||
|
||||
devices.add(40549928l); // hmd
|
||||
// devices.add(40549928l); // hmd
|
||||
devices.add(41236816l); // hmd
|
||||
devices.add(41238320l); // hmd
|
||||
|
||||
devices.add(41306043l); // esp 0
|
||||
devices.add(41306071l); // esp 1
|
||||
devices.add(41306077l); // esp 2
|
||||
devices.add(41306083l); // esp 3
|
||||
devices.add(41306087l); // esp 4
|
||||
devices.add(41306092l); // esp 5
|
||||
|
||||
|
||||
devices.add(41307981l); // markt
|
||||
devices.add(41310835l); // laser
|
||||
devices.add(41325252l); // schloss
|
||||
devices.add(42044973l); // schloss2
|
||||
|
||||
|
||||
// devices
|
||||
devices.add(41744821l); // Nexus 4
|
||||
devices.add(41744849l); // Nexus 4
|
||||
devices.add(41744861l); // Nexus 4
|
||||
devices.add(41751505l); // Nexus 5
|
||||
devices.add(41905035l); // HMD
|
||||
// devices.add(41238320l); // hmd
|
||||
|
||||
// devices.add(41306043l); // esp 0
|
||||
// devices.add(41306071l); // esp 1
|
||||
// devices.add(41306077l); // esp 2
|
||||
// devices.add(41306083l); // esp 3
|
||||
// devices.add(41306087l); // esp 4
|
||||
// devices.add(41306092l); // esp 5
|
||||
//
|
||||
//
|
||||
// devices.add(41307981l); // markt
|
||||
// devices.add(41310835l); // laser
|
||||
// devices.add(41325252l); // schloss
|
||||
// devices.add(42044973l); // schloss2
|
||||
//
|
||||
//
|
||||
// // devices
|
||||
// devices.add(41744821l); // Nexus 4
|
||||
// devices.add(41744849l); // Nexus 4
|
||||
// devices.add(41744861l); // Nexus 4
|
||||
// devices.add(41751505l); // Nexus 5
|
||||
// devices.add(41905035l); // HMD
|
||||
|
||||
|
||||
devices.add(49610081l); // eisenbahn (winter)
|
||||
|
||||
|
||||
MeasurementDownloader downloader = new MeasurementDownloader("nesexperiments", "nespass!!!", out, devices);
|
||||
downloader.download(range);
|
||||
|
||||
|
||||
LinearRegression.Builder<Double> builder = new LinearRegression.Builder<>();
|
||||
System.out.println("here");
|
||||
|
||||
List<List<Measurement>> data = new ArrayList<>();
|
||||
devices.forEach((dev)-> data.add(MeasurementAnalyzer.loadMeasurements(new File(out, "measurement-" + dev + ".json"))));
|
||||
|
||||
data.forEach((dt)-> Collections.sort(dt, (a, b) -> Long.compare(a.getTime(), b.getTime())));
|
||||
final int[] counters = new int[devices.size()];
|
||||
long interval = 30 * 60 * 1000;
|
||||
long interval = 10 * 60 * 1000;
|
||||
long current = range.getStart();
|
||||
while (current < range.getEnd()) {
|
||||
System.out.print(new Date(current) + "; ");
|
||||
@@ -75,11 +82,15 @@ public class FAIRKarlsruhe {
|
||||
final long stop = current + interval;
|
||||
data.forEach((dt) -> {
|
||||
List<Measurement> ms = dt.stream().filter(m -> m.getTime() >= start && m.getTime() < stop).collect(Collectors.toList());
|
||||
if (ms.size() > 0 && (ms.get(0).getData().get(MeasurementType.BATTERY_CHARGING) == null || ms.get(0).getData().get(MeasurementType.BATTERY_CHARGING).equals("false"))) {
|
||||
double temp = ms.get(0).getTemperature();
|
||||
if (ms.size() > 0) { // && (ms.get(0).getData().get(MeasurementType.BATTERY_CHARGING) == null || ms.get(0).getData().get(MeasurementType.BATTERY_CHARGING).equals("false"))) {
|
||||
Coordinate c = ms.get(0).getCoordinate();
|
||||
|
||||
double temp = ms.get(0).getTemperature();
|
||||
double station = Double.valueOf(ms.get(0).getData().get(MeasurementType.STATION_TEMPERATURE));
|
||||
counters[data.indexOf(dt)] += 1;
|
||||
System.out.print(temp + "; ");
|
||||
// System.out.print(ms.get(0).getData().get(MeasurementType.STATION_TEMPERATURE) + "; ");
|
||||
System.out.print(c + ";" + temp + "; ");
|
||||
System.out.print(station + "; ");
|
||||
builder.add(temp, station);
|
||||
} else {
|
||||
System.out.print("; ");
|
||||
}
|
||||
@@ -89,7 +100,8 @@ public class FAIRKarlsruhe {
|
||||
current += interval;
|
||||
}
|
||||
System.out.println(Arrays.toString(counters));
|
||||
|
||||
LinearRegression r = builder.build();
|
||||
System.out.println(r.getIntercept() + " " + r.getSlope() + " " + r.getRSquared() + " " + r.getError());
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
@@ -0,0 +1,118 @@
|
||||
package com.mowesta.tool.paper;
|
||||
|
||||
import java.util.ArrayList;
|
||||
import java.util.Arrays;
|
||||
import java.util.Collections;
|
||||
import java.util.List;
|
||||
|
||||
import com.mowesta.data.process.algorithm.LinearRegression;
|
||||
|
||||
public class Algo {
|
||||
|
||||
|
||||
public static double correlate(List<double[]> data) {
|
||||
double[] mean = new double[2];
|
||||
for (double[] values: data) {
|
||||
mean[0] += values[0];
|
||||
mean[1] += values[1];
|
||||
}
|
||||
mean[0] /= data.size();
|
||||
mean[1] /= data.size();
|
||||
double product = 0;
|
||||
double var1 = 0;
|
||||
double var2 = 0;
|
||||
for (double[] values: data) {
|
||||
double v1 = values[0] - mean[0];
|
||||
double v2 = values[1] - mean[1];
|
||||
product += v1 * v2;
|
||||
var1 += v1 * v1;
|
||||
var2 += v2 * v2;
|
||||
}
|
||||
return product / (Math.sqrt(var1) * Math.sqrt(var2));
|
||||
}
|
||||
|
||||
public static ErrorSummary errors(LinearRegression reg, List<double[]> data) {
|
||||
List<Double> errors = new ArrayList<>();
|
||||
for (double[] pair: data) {
|
||||
double res = reg.getSlope() * pair[0] + reg.getIntercept();
|
||||
errors.add(Math.abs(res - pair[1]));
|
||||
}
|
||||
ErrorSummary s = new ErrorSummary();
|
||||
s.mae = average(errors);
|
||||
s.max = max(errors);
|
||||
s.rms = rms(errors);
|
||||
s.distribution = new double[11];
|
||||
for (int i = 0; i < s.distribution.length; i++) {
|
||||
s.distribution[i] = percentile(errors, i * 0.1);
|
||||
}
|
||||
return s;
|
||||
}
|
||||
|
||||
public static ErrorSummary errors(List<double[]> data) {
|
||||
LinearRegression.Builder<Double> b = new LinearRegression.Builder<>();
|
||||
for (double[] d: data) {
|
||||
b.add(d[0], d[1]);
|
||||
}
|
||||
return errors(b.build(), data);
|
||||
}
|
||||
|
||||
public static double percentile(List<Double> values, double percentile) {
|
||||
Collections.sort(values);
|
||||
if (values.isEmpty()) return 0;
|
||||
int idx = (int)((values.size() - 1) * percentile);
|
||||
idx = Math.max(0, Math.min(values.size() - 1, idx));
|
||||
return values.get(idx);
|
||||
|
||||
}
|
||||
|
||||
public static double max(List<Double> values) {
|
||||
if (values.isEmpty()) return 0;
|
||||
double v = values.get(0);
|
||||
for (Double d: values) {
|
||||
v = Math.max(v, d);
|
||||
}
|
||||
return v;
|
||||
}
|
||||
|
||||
public static double rms(List<Double> values) {
|
||||
double v = 0;
|
||||
for (Double d: values) {
|
||||
v += d * d;
|
||||
}
|
||||
if (values.size() > 0) return Math.sqrt(v / values.size());
|
||||
else return 0;
|
||||
}
|
||||
|
||||
public static double average(List<Double> values) {
|
||||
double v = 0;
|
||||
for (Double d: values) {
|
||||
v += d;
|
||||
}
|
||||
if (values.size() > 0) return v / values.size();
|
||||
else return 0;
|
||||
}
|
||||
|
||||
public static double variance(List<Double> values) {
|
||||
double avg = average(values);
|
||||
double sum = 0;
|
||||
for (Double d: values) {
|
||||
double dx = d - avg;
|
||||
sum += dx * dx;
|
||||
}
|
||||
return Math.sqrt(sum / values.size());
|
||||
}
|
||||
|
||||
|
||||
public static class ErrorSummary {
|
||||
public double[] distribution;
|
||||
public double mae;
|
||||
public double rms;
|
||||
public double max;
|
||||
|
||||
@Override
|
||||
public String toString() {
|
||||
return "MAE: " + mae + " RMS: " + rms + " MAX: " + max + " DIST: " + Arrays.toString(distribution);
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,150 @@
|
||||
package com.mowesta.tool.paper;
|
||||
|
||||
import java.util.Arrays;
|
||||
import java.util.List;
|
||||
|
||||
import com.mowesta.api.measurement.Measurement;
|
||||
import com.mowesta.api.measurement.MeasurementType;
|
||||
|
||||
public class CPULoadModel {
|
||||
|
||||
int cores;
|
||||
double[] min;
|
||||
double[] max;
|
||||
double[] avgIdle;
|
||||
double[] avgActive;
|
||||
double coreAboveMinIdle;
|
||||
double coreAboveMinActive;
|
||||
double coreAboveAvgIdle;
|
||||
double coreAboveAvgActive;
|
||||
|
||||
private CPULoadModel(int cores) {
|
||||
this.cores = cores;
|
||||
this.min = new double[cores];
|
||||
this.max = new double[cores];
|
||||
this.avgIdle = new double[cores];
|
||||
this.avgActive = new double[cores];
|
||||
}
|
||||
|
||||
public boolean isHot(Measurement m) {
|
||||
double[] f = Mse.getCpuFreq(m);
|
||||
if (f != null) {
|
||||
boolean active = Mse.isActive(m);
|
||||
int aboveMin = 0;
|
||||
int aboveAvg = 0;
|
||||
double[] avg = active?avgActive:avgActive;
|
||||
for (int i = 0; i < f.length; i++) {
|
||||
if (f[i] > min[i]) aboveMin += 1;
|
||||
if (f[i] > avg[i]) aboveAvg += 1;
|
||||
}
|
||||
if (active) {
|
||||
return //aboveMin > coreAboveMinActive + 1 ||
|
||||
aboveAvg > coreAboveAvgActive + 2;
|
||||
} else {
|
||||
return //aboveMin > coreAboveMinIdle + 1 ||
|
||||
aboveAvg > coreAboveAvgActive + 1;
|
||||
}
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
public Double load(Measurement m) {
|
||||
double[] f = Mse.getCpuFreq(m);
|
||||
if (f != null) {
|
||||
double result = 0;
|
||||
for (int i = 0; i < f.length; i++) {
|
||||
if ((max[i] - min[i]) == 0) {
|
||||
result += 0.5;
|
||||
} else {
|
||||
result += (f[i] - min[i]) / (max[i] - min[i]);
|
||||
}
|
||||
}
|
||||
return result / f.length;
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
|
||||
public static CPULoadModel create(List<Measurement> measurement) {
|
||||
if (measurement.isEmpty()) return null;
|
||||
CPULoadModel model = null;
|
||||
int activeCount = 0;
|
||||
int idleCount = 0;
|
||||
for (Measurement m: measurement) {
|
||||
double[] f = Mse.getCpuFreq(m);
|
||||
if (f != null) {
|
||||
if (model == null) {
|
||||
model = new CPULoadModel(f.length);
|
||||
System.arraycopy(f, 0, model.min, 0, f.length);
|
||||
System.arraycopy(f, 0, model.max, 0, f.length);
|
||||
} else {
|
||||
for (int i = 0; i < f.length; i++) {
|
||||
model.max[i] = Math.max(model.max[i], f[i]);
|
||||
model.min[i] = Math.min(model.min[i], f[i]);
|
||||
}
|
||||
}
|
||||
if (Mse.isActive(m)) {
|
||||
for (int i = 0; i < f.length; i++) {
|
||||
model.avgActive[i] += f[i];
|
||||
}
|
||||
activeCount += 1;
|
||||
} else {
|
||||
for (int i = 0; i < f.length; i++) {
|
||||
model.avgIdle[i] += f[i];
|
||||
}
|
||||
idleCount += 1;
|
||||
}
|
||||
}
|
||||
}
|
||||
if (model == null) return null;
|
||||
for (int i = 0; i < model.cores; i++) {
|
||||
model.avgActive[i] /= activeCount;
|
||||
model.avgIdle[i] /= idleCount;
|
||||
}
|
||||
for (Measurement m: measurement) {
|
||||
double[] f = Mse.getCpuFreq(m);
|
||||
if (f != null) {
|
||||
if (Mse.isActive(m)) {
|
||||
for (int i = 0; i < f.length; i++) {
|
||||
if (f[i] > model.min[i]) {
|
||||
model.coreAboveMinActive += 1;
|
||||
if (f[i] > model.avgActive[i]) {
|
||||
model.coreAboveAvgActive += 1;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
} else {
|
||||
for (int i = 0; i < f.length; i++) {
|
||||
if (f[i] > model.min[i]) {
|
||||
model.coreAboveMinIdle += 1;
|
||||
if (f[i] > model.avgIdle[i]) {
|
||||
model.coreAboveAvgIdle += 1;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
model.coreAboveAvgActive /= activeCount;
|
||||
model.coreAboveMinActive /= activeCount;
|
||||
model.coreAboveAvgIdle /= idleCount;
|
||||
model.coreAboveMinIdle /= idleCount;
|
||||
return model;
|
||||
}
|
||||
|
||||
@Override
|
||||
public String toString() {
|
||||
StringBuilder b = new StringBuilder();
|
||||
b.append("Min: " + Arrays.toString(min) + "\n");
|
||||
b.append("Max: " + Arrays.toString(max) + "\n");
|
||||
b.append("Avg (Idle): " + Arrays.toString(avgIdle) + "\n");
|
||||
b.append("AVg (Active): " + Arrays.toString(avgActive) + "\n");
|
||||
b.append("Core (Idle): " + coreAboveMinIdle + " min " + coreAboveAvgIdle + " avg\n" );
|
||||
b.append("Core (Active): " + coreAboveMinActive + " min " + coreAboveAvgActive + " avg\n" );
|
||||
return b.toString();
|
||||
}
|
||||
|
||||
|
||||
|
||||
}
|
||||
@@ -0,0 +1,243 @@
|
||||
package com.mowesta.tool.paper;
|
||||
|
||||
import java.io.BufferedReader;
|
||||
import java.io.File;
|
||||
import java.io.FileReader;
|
||||
import java.io.IOException;
|
||||
import java.nio.charset.StandardCharsets;
|
||||
import java.text.ParseException;
|
||||
import java.text.SimpleDateFormat;
|
||||
import java.util.ArrayList;
|
||||
import java.util.Collections;
|
||||
import java.util.Date;
|
||||
import java.util.HashMap;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.stream.Collectors;
|
||||
|
||||
import com.fasterxml.jackson.databind.ObjectMapper;
|
||||
import com.locoslab.library.geometry.wgs.HaversineDistance;
|
||||
import com.mowesta.api.Coordinate;
|
||||
import com.mowesta.api.device.Device;
|
||||
import com.mowesta.api.device.OperatingSystem;
|
||||
import com.mowesta.api.measurement.Measurement;
|
||||
import com.mowesta.tool.paper.LocationClassifier.TripResult;
|
||||
|
||||
public class DeviceAnalyzer {
|
||||
|
||||
public static final File folder = new File("mowesta-dump");
|
||||
|
||||
public static void main(String[] args) throws Exception {
|
||||
// hunga tonga vulcano
|
||||
long start = getDate("2021-12-01 0:00");
|
||||
long end = getDate("2022-02-01 00:00");
|
||||
|
||||
List<Device> devices = readFile(new File(folder, "devices.json"), Device.class);
|
||||
List<List<Measurement>> data = new ArrayList<>();
|
||||
List<Device> psd = new ArrayList<>();
|
||||
for (Device d: devices) {
|
||||
if (d.getOs() == OperatingSystem.ANDROID) {
|
||||
List<Measurement> ms = readFile(new File(folder, "measurement-" + d.getId() + ".json" ), Measurement.class);
|
||||
ms = ms.stream().filter(m->m.getTime() > start && m.getTime() < end).collect(Collectors.toList());
|
||||
Collections.sort(ms, (a, b) -> Long.compare(a.getTime(), b.getTime()));
|
||||
boolean hasPressure = false;
|
||||
for (Measurement m: ms) {
|
||||
try {
|
||||
Double p = Mse.getDevicePressure(m);
|
||||
if (p != null && p > 500) hasPressure = true;
|
||||
} catch (NumberFormatException e) {
|
||||
// ignore
|
||||
}
|
||||
}
|
||||
if (hasPressure && ms.size() > 10000) {
|
||||
//System.out.println("Device: " + d.getId() + " " + d.getManufacturer() + "/" + d.getModel() + " Measurements: " + ms.size() + " First: " + new Date(ms.get(ms.size() - 1).getTime()) + " Last: " + new Date(ms.get(0).getTime()));
|
||||
data.add(ms);
|
||||
psd.add(d);
|
||||
}
|
||||
}
|
||||
}
|
||||
long now = System.currentTimeMillis();
|
||||
for (int i = 0; i < data.size(); i++) {
|
||||
List<Measurement> ms = data.get(i);
|
||||
Device d = psd.get(i);
|
||||
|
||||
System.out.println("MS: " + ms.size() + " Dev: " + d.getManufacturer() + " - " + d.getModel());
|
||||
Map<Coordinate, List<Measurement>> locations = new HashMap<>();
|
||||
TripResult result;
|
||||
while ((result = LocationClassifier.computeNextTrip(ms, now)) != null) {
|
||||
if (result.start.isEmpty()) continue;
|
||||
Coordinate c = result.start.get(0).getCoordinate();
|
||||
Coordinate target = null;
|
||||
for (Coordinate can: locations.keySet()) {
|
||||
if (HaversineDistance.getDistance(c.getLongitude(), c.getLatitude(), can.getLongitude(), can.getLatitude()) < 150) {
|
||||
target = can;
|
||||
}
|
||||
}
|
||||
if (target != null) {
|
||||
locations.get(target).addAll(filterL(result.start));
|
||||
} else {
|
||||
locations.put(c, new ArrayList<>(filterL(result.start)));
|
||||
}
|
||||
ms = result.remainder;
|
||||
}
|
||||
|
||||
int max = 0;
|
||||
for (Map.Entry<Coordinate, List<Measurement>> entry: locations.entrySet()) {
|
||||
max = Math.max(max, entry.getValue().size());
|
||||
}
|
||||
|
||||
for (Map.Entry<Coordinate, List<Measurement>> entry: locations.entrySet()) {
|
||||
if (entry.getValue().size() != max) continue;
|
||||
data.remove(i);
|
||||
data.add(i, entry.getValue());
|
||||
List<double[]> map = new ArrayList<>();
|
||||
Double prev = null;
|
||||
for (Measurement m: entry.getValue()) {
|
||||
Double v = Mse.getDevicePressure(m);
|
||||
Double s = Mse.getStationPressure(m);
|
||||
if (v != null && s != null && !Double.isNaN(v) && !Double.isNaN(v)) {
|
||||
map.add(new double[] { v, s });
|
||||
}
|
||||
}
|
||||
filter(map);
|
||||
|
||||
if (map.size() > 10) {
|
||||
double corel = correlate(map);
|
||||
|
||||
System.out.println(map.size() + ":" + corel);
|
||||
System.out.println(entry.getKey());
|
||||
|
||||
// if (corel < 0.57) {
|
||||
// for (double[] dv: map) {
|
||||
// System.out.println(dv[0] + ";" + dv[1]);
|
||||
// }
|
||||
// System.exit(0);
|
||||
// }
|
||||
|
||||
}
|
||||
|
||||
}
|
||||
System.out.println();
|
||||
}
|
||||
|
||||
long next = start;
|
||||
while (next < end) {
|
||||
long from = next;
|
||||
long to = next + 10 * 60 * 1000;
|
||||
System.out.print(toString(new Date(from)));
|
||||
System.out.print(";");
|
||||
for (int i = 0; i < data.size(); i++) {
|
||||
List<Measurement> set = data.get(i).stream().filter(m -> m.getTime() >= from && m.getTime() < to).collect(Collectors.toList());
|
||||
for (Measurement m: set) {
|
||||
System.out.print(m.getCoordinate().getLatitude() + "," + m.getCoordinate().getLongitude());
|
||||
break;
|
||||
}
|
||||
System.out.print(";");
|
||||
for (Measurement m: set) {
|
||||
Double p = Mse.getDevicePressure(m);
|
||||
if (p != null) {
|
||||
System.out.print(p.toString().replace(".", ","));
|
||||
break;
|
||||
}
|
||||
}
|
||||
System.out.print(";");
|
||||
for (Measurement m: set) {
|
||||
Double s = Mse.getStationPressure(m);
|
||||
if (s != null) {
|
||||
System.out.print(s.toString().replace(".", ","));
|
||||
break;
|
||||
}
|
||||
}
|
||||
System.out.print(";");
|
||||
|
||||
}
|
||||
System.out.println();
|
||||
next = to;
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
public static String toString(Date date) {
|
||||
SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm");
|
||||
return df.format(date);
|
||||
}
|
||||
|
||||
public static long getDate(String string) throws ParseException {
|
||||
SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm");
|
||||
Date date = df.parse(string);
|
||||
return date.getTime();
|
||||
}
|
||||
|
||||
|
||||
public static <T> List<T> readFile(File file, Class<T> type) throws Exception {
|
||||
ObjectMapper mapper = new ObjectMapper();
|
||||
List<T> result = new ArrayList<>();
|
||||
try (BufferedReader reader = new BufferedReader(new FileReader(file, StandardCharsets.UTF_8))) {
|
||||
String line = null;
|
||||
while ((line = reader.readLine()) != null) {
|
||||
result.add(mapper.readValue(line, type));
|
||||
}
|
||||
}
|
||||
return result;
|
||||
}
|
||||
|
||||
public static double correlate(List<double[]> data) {
|
||||
double[] mean = new double[2];
|
||||
for (double[] values: data) {
|
||||
mean[0] += values[0];
|
||||
mean[1] += values[1];
|
||||
}
|
||||
mean[0] /= data.size();
|
||||
mean[1] /= data.size();
|
||||
double product = 0;
|
||||
double var1 = 0;
|
||||
double var2 = 0;
|
||||
for (double[] values: data) {
|
||||
double v1 = values[0] - mean[0];
|
||||
double v2 = values[1] - mean[1];
|
||||
product += v1 * v2;
|
||||
var1 += v1 * v1;
|
||||
var2 += v2 * v2;
|
||||
}
|
||||
//System.out.println("prod: " + product + " v1: " + var1 + " v2: " + var2);
|
||||
|
||||
return product / (Math.sqrt(var1) * Math.sqrt(var2));
|
||||
}
|
||||
|
||||
public static void filter(List<double[]> map) {
|
||||
double sum = 0;
|
||||
for (double[] v: map) {
|
||||
sum += v[0];
|
||||
}
|
||||
sum = sum / map.size();
|
||||
for (int i = map.size() - 1; i >= 0; i--) {
|
||||
if (Math.abs(map.get(i)[0] - sum) > 50) {
|
||||
map.remove(i);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
public static List<Measurement> filterL(List<Measurement> ms) {
|
||||
// return ms;
|
||||
List<Measurement> r = new ArrayList<>();
|
||||
r.add(ms.get(0));
|
||||
for (int i = 1; i < ms.size() - 1; i++) {
|
||||
Double a = Mse.getDevicePressure(ms.get(i - 1));
|
||||
Double b = Mse.getDevicePressure(ms.get(i));
|
||||
Double c = Mse.getDevicePressure(ms.get(i + 1));
|
||||
|
||||
if (a != null && b != null && c != null) {
|
||||
if (Math.abs(a - b) < 10 && Math.abs(b - c) < 10) {
|
||||
r.add(ms.get(i));
|
||||
} else {
|
||||
System.out.println("Filter");
|
||||
}
|
||||
}
|
||||
}
|
||||
r.add(ms.get(ms.size() - 1));
|
||||
return r;
|
||||
|
||||
}
|
||||
|
||||
|
||||
}
|
||||
@@ -0,0 +1,117 @@
|
||||
package com.mowesta.tool.paper;
|
||||
|
||||
import java.io.BufferedReader;
|
||||
import java.io.File;
|
||||
import java.io.FileReader;
|
||||
import java.io.IOException;
|
||||
import java.nio.charset.StandardCharsets;
|
||||
import java.text.ParseException;
|
||||
import java.text.SimpleDateFormat;
|
||||
import java.util.ArrayList;
|
||||
import java.util.Collections;
|
||||
import java.util.Date;
|
||||
import java.util.List;
|
||||
import java.util.stream.Collectors;
|
||||
|
||||
import com.fasterxml.jackson.databind.ObjectMapper;
|
||||
import com.mowesta.api.device.Device;
|
||||
import com.mowesta.api.device.OperatingSystem;
|
||||
import com.mowesta.api.measurement.Measurement;
|
||||
|
||||
public class DeviceAnalyzer2 {
|
||||
|
||||
public static final File folder = new File("mowesta-dump");
|
||||
|
||||
public static void main(String[] args) throws Exception {
|
||||
// hunga tonga vulcano
|
||||
long start = getDate("2022-06-30 15:30");
|
||||
long end = getDate("2022-07-01 01:20");
|
||||
|
||||
List<Device> devices = readFile(new File(folder, "devices.json"), Device.class);
|
||||
List<List<Measurement>> data = new ArrayList<>();
|
||||
for (Device d: devices) {
|
||||
if (d.getOs() == OperatingSystem.ANDROID) {
|
||||
List<Measurement> ms = readFile(new File(folder, "measurement-" + d.getId() + ".json" ), Measurement.class);
|
||||
ms = ms.stream().filter(m->m.getTime() > start && m.getTime() < end).collect(Collectors.toList());
|
||||
Collections.sort(ms, (a, b) -> Long.compare(a.getTime(), b.getTime()));
|
||||
boolean hasPressure = false;
|
||||
for (Measurement m: ms) {
|
||||
try {
|
||||
Double p = Mse.getDevicePressure(m);
|
||||
if (p != null && p > 500) hasPressure = true;
|
||||
} catch (NumberFormatException e) {
|
||||
// ignore
|
||||
}
|
||||
}
|
||||
if (hasPressure && ms.size() > 0) {
|
||||
System.out.println("Device: " + d.getId() + " " + d.getManufacturer() + "/" + d.getModel() + " Measurements: " + ms.size() + " First: " + new Date(ms.get(ms.size() - 1).getTime()) + " Last: " + new Date(ms.get(0).getTime()));
|
||||
data.add(ms);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
long next = start;
|
||||
while (next < end) {
|
||||
long from = next;
|
||||
long to = next + 10 * 60 * 1000;
|
||||
System.out.print(toString(new Date(from)));
|
||||
System.out.print(";");
|
||||
for (int i = 0; i < data.size(); i++) {
|
||||
List<Measurement> set = data.get(i).stream().filter(m -> m.getTime() >= from && m.getTime() < to).collect(Collectors.toList());
|
||||
for (Measurement m: set) {
|
||||
System.out.print(m.getCoordinate().getLatitude() + "," + m.getCoordinate().getLongitude());
|
||||
break;
|
||||
}
|
||||
System.out.print(";");
|
||||
for (Measurement m: set) {
|
||||
Double p = Mse.getDevicePressure(m);
|
||||
if (p != null) {
|
||||
System.out.print(p.toString().replace(".", ","));
|
||||
break;
|
||||
}
|
||||
}
|
||||
System.out.print(";");
|
||||
for (Measurement m: set) {
|
||||
Double s = Mse.getStationPressure(m);
|
||||
if (s != null) {
|
||||
System.out.print(s.toString().replace(".", ","));
|
||||
break;
|
||||
}
|
||||
}
|
||||
System.out.print(";");
|
||||
|
||||
}
|
||||
System.out.println();
|
||||
next = to;
|
||||
}
|
||||
}
|
||||
|
||||
public static String toString(Date date) {
|
||||
SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm");
|
||||
return df.format(date);
|
||||
}
|
||||
|
||||
public static long getDate(String string) throws ParseException {
|
||||
SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm");
|
||||
Date date = df.parse(string);
|
||||
return date.getTime();
|
||||
}
|
||||
|
||||
|
||||
public static <T> List<T> readFile(File file, Class<T> type) throws Exception {
|
||||
ObjectMapper mapper = new ObjectMapper();
|
||||
List<T> result = new ArrayList<>();
|
||||
try (BufferedReader reader = new BufferedReader(new FileReader(file, StandardCharsets.UTF_8))) {
|
||||
String line = null;
|
||||
while ((line = reader.readLine()) != null) {
|
||||
result.add(mapper.readValue(line, type));
|
||||
}
|
||||
}
|
||||
return result;
|
||||
}
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
}
|
||||
@@ -0,0 +1,100 @@
|
||||
package com.mowesta.tool.paper;
|
||||
|
||||
import java.io.BufferedReader;
|
||||
import java.io.File;
|
||||
import java.io.FileReader;
|
||||
import java.io.IOException;
|
||||
import java.nio.charset.StandardCharsets;
|
||||
import java.text.ParseException;
|
||||
import java.text.SimpleDateFormat;
|
||||
import java.util.ArrayList;
|
||||
import java.util.Collections;
|
||||
import java.util.Date;
|
||||
import java.util.HashSet;
|
||||
import java.util.List;
|
||||
import java.util.Set;
|
||||
import java.util.stream.Collectors;
|
||||
|
||||
import com.fasterxml.jackson.databind.ObjectMapper;
|
||||
import com.mowesta.api.device.Device;
|
||||
import com.mowesta.api.device.OperatingSystem;
|
||||
import com.mowesta.api.measurement.Measurement;
|
||||
|
||||
public class DeviceStats {
|
||||
|
||||
public static final File folder = new File("mowesta-dump");
|
||||
|
||||
public static void main(String[] args) throws Exception {
|
||||
long start = getDate("2019-01-01 00:00");
|
||||
long end = getDate("2023-01-01 00:00");
|
||||
int count = 0;
|
||||
Set<String> types = new HashSet<>();
|
||||
Set<String> manuf = new HashSet<>();
|
||||
|
||||
List<Device> devices = readFile(new File(folder, "devices.json"), Device.class);
|
||||
List<List<Measurement>> data = new ArrayList<>();
|
||||
for (Device d: devices) {
|
||||
if (d.getOs() == OperatingSystem.ANDROID) {
|
||||
List<Measurement> ms = readFile(new File(folder, "measurement-" + d.getId() + ".json" ), Measurement.class);
|
||||
ms = ms.stream().filter(m->m.getTime() > start && m.getTime() < end).collect(Collectors.toList());
|
||||
Collections.sort(ms, (a, b) -> Long.compare(a.getTime(), b.getTime()));
|
||||
boolean hasPressure = false;
|
||||
for (Measurement m: ms) {
|
||||
try {
|
||||
Double p = Mse.getDevicePressure(m);
|
||||
if (p != null && p > 500) hasPressure = true;
|
||||
} catch (NumberFormatException e) {
|
||||
// ignore
|
||||
}
|
||||
}
|
||||
if (hasPressure && ms.size() > 0) {
|
||||
//System.out.println("Device: " + d.getId() + " " + d.getManufacturer() + "/" + d.getModel() + " Measurements: " + ms.size() + " First: " + new Date(ms.get(ms.size() - 1).getTime()) + " Last: " + new Date(ms.get(0).getTime()));
|
||||
data.add(ms);
|
||||
}
|
||||
System.out.println(ms.size() + ";" + (hasPressure?ms.size():0));
|
||||
if (ms.size() > 0 && hasPressure) {
|
||||
types.add(d.getManufacturer() + "-" + d.getModel());
|
||||
manuf.add(d.getManufacturer());
|
||||
count += 1;
|
||||
}
|
||||
|
||||
}
|
||||
}
|
||||
System.out.println();
|
||||
for (String n: manuf) {
|
||||
System.out.println(n);
|
||||
}
|
||||
System.out.println("Manu:" + manuf.size());
|
||||
System.out.println("Types: " + types.size());
|
||||
System.out.println("Count: " + count);
|
||||
}
|
||||
|
||||
public static String toString(Date date) {
|
||||
SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm");
|
||||
return df.format(date);
|
||||
}
|
||||
|
||||
public static long getDate(String string) throws ParseException {
|
||||
SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm");
|
||||
Date date = df.parse(string);
|
||||
return date.getTime();
|
||||
}
|
||||
|
||||
|
||||
public static <T> List<T> readFile(File file, Class<T> type) throws Exception {
|
||||
ObjectMapper mapper = new ObjectMapper();
|
||||
List<T> result = new ArrayList<>();
|
||||
try (BufferedReader reader = new BufferedReader(new FileReader(file, StandardCharsets.UTF_8))) {
|
||||
String line = null;
|
||||
while ((line = reader.readLine()) != null) {
|
||||
result.add(mapper.readValue(line, type));
|
||||
}
|
||||
}
|
||||
return result;
|
||||
}
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
}
|
||||
@@ -0,0 +1,178 @@
|
||||
package com.mowesta.tool.paper;
|
||||
|
||||
import java.io.BufferedReader;
|
||||
import java.io.File;
|
||||
import java.io.FileReader;
|
||||
import java.io.IOException;
|
||||
import java.nio.charset.StandardCharsets;
|
||||
import java.text.ParseException;
|
||||
import java.text.SimpleDateFormat;
|
||||
import java.util.ArrayList;
|
||||
import java.util.Collections;
|
||||
import java.util.Date;
|
||||
import java.util.HashMap;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.stream.Collectors;
|
||||
|
||||
import com.fasterxml.jackson.databind.ObjectMapper;
|
||||
import com.locoslab.library.geometry.wgs.HaversineDistance;
|
||||
import com.mowesta.api.Coordinate;
|
||||
import com.mowesta.api.device.Device;
|
||||
import com.mowesta.api.device.OperatingSystem;
|
||||
import com.mowesta.api.measurement.Measurement;
|
||||
import com.mowesta.tool.analysis.WeatherResolver;
|
||||
import com.mowesta.tool.analysis.WeatherResolver.DataType;
|
||||
import com.mowesta.tool.analysis.WeatherResolver.Resolution;
|
||||
import com.mowesta.tool.paper.Algo.ErrorSummary;
|
||||
import com.mowesta.tool.paper.LocationClassifier.TripResult;
|
||||
|
||||
public class DeviceTemperature {
|
||||
|
||||
public static final File folder = new File("mowesta-dump");
|
||||
|
||||
public static void main(String[] args) throws Exception {
|
||||
// hunga tonga vulcano
|
||||
long start = getDate("2019-01-01 0:00");
|
||||
long end = getDate("2023-01-01 00:00");
|
||||
|
||||
double csum = 0;
|
||||
int ccount = 0;
|
||||
double msum = 0;
|
||||
int mcount = 0;
|
||||
List<Device> devices = readFile(new File(folder, "devices.json"), Device.class);
|
||||
for (Device d: devices) {
|
||||
if (d.getId() == 24963415l) continue; // stationary tablet
|
||||
if (d.getId() == 20488695l) continue; // device with 1 degree precision
|
||||
|
||||
|
||||
//if (d.getId() != 11626535l) continue;
|
||||
|
||||
|
||||
if (d.getOs() == OperatingSystem.ANDROID) {
|
||||
List<Measurement> ms = readFile(new File(folder, "measurement-" + d.getId() + ".json" ), Measurement.class);
|
||||
ms = ms.stream().filter(m->m.getTime() > start && m.getTime() < end).collect(Collectors.toList());
|
||||
Collections.sort(ms, (a, b) -> Long.compare(a.getTime(), b.getTime()));
|
||||
List<TripResult> trips = getTrips(ms, System.currentTimeMillis());
|
||||
List<TripResult> walking = trips.stream().filter(t -> t.getDistance() > 300 && t.getSpeed() < 1.5 && t.getDuration() > 5 * 60 * 1000).collect(Collectors.toList());
|
||||
if (walking.size() > 100) {
|
||||
//CPULoadModel model = CPULoadModel.create(ms);
|
||||
List<double[]> outside = new ArrayList<>();
|
||||
int[] missing = new int[1];
|
||||
walking.forEach(t -> {
|
||||
List<double[]> current = new ArrayList<>();
|
||||
boolean[] valid = new boolean[] { true };
|
||||
Measurement[] base = new Measurement[] { t.origin };
|
||||
Double[] stat = new Double[] { Mse.getStationTemperature(t.origin) };
|
||||
if (stat[0] == null) {
|
||||
for (int i = 0; i < t.motion.size(); i++) {
|
||||
stat[0] = Mse.getStationTemperature(t.motion.get(i));
|
||||
if (stat[0] != null) {
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
if (stat[0] == null) {
|
||||
missing[0] += 1;
|
||||
return;
|
||||
}
|
||||
t.motion.add(t.destination);
|
||||
t.motion.forEach(m -> {
|
||||
Double temp = Mse.getDeviceTemperature(m);
|
||||
//System.out.print(temp + " ");
|
||||
//valid[0] = valid[0] & !Mse.isActive(m);
|
||||
//valid[0] = valid[0] & !Mse.isCharging(m);
|
||||
if (! valid[0]) return;
|
||||
if (base[0] == null && Math.abs(Mse.getDeviceTemperature(t.origin) - Mse.getDeviceTemperature(m)) > 0) {
|
||||
base[0] = m;
|
||||
}
|
||||
if (base[0] == null && (m.getTime() - t.origin.getTime()) / 60000d > 11) {
|
||||
if (temp != null) {
|
||||
outside.add(new double[] { temp, stat[0] });
|
||||
valid[0] = false;
|
||||
}
|
||||
}
|
||||
|
||||
if (base[0] == null) return;
|
||||
double minutes = (m.getTime() - base[0].getTime()) / 60000d;
|
||||
if (minutes < 4 || minutes > 6) return;
|
||||
if (temp != null && stat[0] != null) {
|
||||
current.clear();
|
||||
current.add(new double[] { temp, stat[0] });
|
||||
//System.out.println((temp + ";"+ stat).replace(".", ","));
|
||||
} else {
|
||||
System.out.println("What=");
|
||||
}
|
||||
});
|
||||
outside.addAll(current);
|
||||
//System.out.println();
|
||||
if (! current.isEmpty()) {
|
||||
//System.out.println((current.get(0)[0] + ";"+ current.get(0)[1]).replace(".", ","));
|
||||
}
|
||||
|
||||
});
|
||||
if (outside.size() > 3) {
|
||||
double c = Algo.correlate(outside);
|
||||
ErrorSummary e = Algo.errors(outside);
|
||||
System.out.println(d.getId() + " Walks: " + (walking.size() - missing[0]) + " Outside: " + c + " " + outside.size() + " Mae: " + e.mae + " RMS: " + e.rms + " Max: " + e.max);
|
||||
if (c > 0.5) {
|
||||
csum += c;
|
||||
ccount += 1;
|
||||
mcount += 1;
|
||||
msum += e.mae;
|
||||
}
|
||||
//System.out.println(model.toString());
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
System.out.println("Count: " + ccount + " Avg: " + csum / ccount + " Err: " + msum / mcount);
|
||||
}
|
||||
|
||||
public static List<TripResult> getTrips(List<Measurement> ms, long now) {
|
||||
List<TripResult> results = new ArrayList<>();
|
||||
TripResult result;
|
||||
while ((result = LocationClassifier.computeNextTrip(ms, now)) != null) {
|
||||
results.add(result);
|
||||
ms = result.remainder;
|
||||
}
|
||||
return results;
|
||||
}
|
||||
|
||||
public static Measurement getMeasurement(TripResult result, double minute, double threshold) {
|
||||
List<Measurement> candidates = result.motion.stream().filter(m -> {
|
||||
double min = (m.getTime() - result.origin.getTime()) / 60000d;
|
||||
return min > minute - 0.5 * threshold && min <= minute + 0.5 * threshold;
|
||||
}).collect(Collectors.toList());
|
||||
if (candidates.isEmpty()) return null;
|
||||
else return candidates.get(0);
|
||||
}
|
||||
|
||||
|
||||
public static String toString(Date date) {
|
||||
SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm");
|
||||
return df.format(date);
|
||||
}
|
||||
|
||||
public static long getDate(String string) throws ParseException {
|
||||
SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm");
|
||||
Date date = df.parse(string);
|
||||
return date.getTime();
|
||||
}
|
||||
|
||||
|
||||
public static <T> List<T> readFile(File file, Class<T> type) throws Exception {
|
||||
ObjectMapper mapper = new ObjectMapper();
|
||||
List<T> result = new ArrayList<>();
|
||||
try (BufferedReader reader = new BufferedReader(new FileReader(file, StandardCharsets.UTF_8))) {
|
||||
String line = null;
|
||||
while ((line = reader.readLine()) != null) {
|
||||
result.add(mapper.readValue(line, type));
|
||||
}
|
||||
}
|
||||
return result;
|
||||
}
|
||||
|
||||
|
||||
}
|
||||
@@ -0,0 +1,317 @@
|
||||
package com.mowesta.tool.paper;
|
||||
|
||||
import java.io.BufferedReader;
|
||||
import java.io.File;
|
||||
import java.io.FileReader;
|
||||
import java.io.IOException;
|
||||
import java.nio.charset.StandardCharsets;
|
||||
import java.text.ParseException;
|
||||
import java.text.SimpleDateFormat;
|
||||
import java.util.ArrayList;
|
||||
import java.util.Collections;
|
||||
import java.util.Date;
|
||||
import java.util.HashMap;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.stream.Collectors;
|
||||
|
||||
import com.fasterxml.jackson.databind.ObjectMapper;
|
||||
import com.locoslab.library.geometry.wgs.HaversineDistance;
|
||||
import com.mowesta.api.Coordinate;
|
||||
import com.mowesta.api.device.Device;
|
||||
import com.mowesta.api.device.OperatingSystem;
|
||||
import com.mowesta.api.measurement.Measurement;
|
||||
import com.mowesta.tool.analysis.WeatherResolver;
|
||||
import com.mowesta.tool.analysis.WeatherResolver.DataType;
|
||||
import com.mowesta.tool.analysis.WeatherResolver.Resolution;
|
||||
import com.mowesta.tool.paper.Algo.ErrorSummary;
|
||||
import com.mowesta.tool.paper.LocationClassifier.TripResult;
|
||||
|
||||
public class DeviceTemperatureEval {
|
||||
|
||||
public static final File folder = new File("mowesta-dump");
|
||||
|
||||
public static void main(String[] args) throws Exception {
|
||||
// hunga tonga vulcano
|
||||
long start = getDate("2019-01-01 0:00");
|
||||
long end = getDate("2023-01-01 00:00");
|
||||
|
||||
StringBuilder cBuilder = new StringBuilder();
|
||||
StringBuilder minMax = new StringBuilder();
|
||||
StringBuilder volume = new StringBuilder();
|
||||
|
||||
StringBuilder error = new StringBuilder();
|
||||
|
||||
List<Device> devices = readFile(new File(folder, "devices.json"), Device.class);
|
||||
for (Device d: devices) {
|
||||
if (d.getId() == 24963415l) continue; // stationary tablet (will cause out-of-memory)
|
||||
if (d.getId() == 20488695l) {
|
||||
System.out.println("Dev: " + d.getManufacturer() + " " + d.getModel());
|
||||
}
|
||||
// if (d.getId() == 20488695l) continue; // device with 1 degree precision
|
||||
if (d.getId() == 35723568l) continue; // t: 0.9 - 9.5
|
||||
if (d.getId() == 40549928l) continue; // one of our test devices
|
||||
|
||||
|
||||
//if (d.getId() != 11626535l) continue;
|
||||
if (d.getOs() == OperatingSystem.ANDROID) {
|
||||
List<Measurement> ms = readFile(new File(folder, "measurement-" + d.getId() + ".json" ), Measurement.class);
|
||||
ms = ms.stream().filter(m->m.getTime() > start && m.getTime() < end).collect(Collectors.toList());
|
||||
Collections.sort(ms, (a, b) -> Long.compare(a.getTime(), b.getTime()));
|
||||
List<TripResult> trips = getTrips(ms, System.currentTimeMillis());
|
||||
List<TripResult> walking = trips.stream().filter(t -> t.getDistance() > 300 && t.getSpeed() < 2 && t.getDuration() > 5 * 60 * 1000).collect(Collectors.toList());
|
||||
List<TripResult> walkingWithTruth = walking.stream().filter(t -> getStationTemperature(t) != null).collect(Collectors.toList());
|
||||
if (walking.size() > 100 && walkingWithTruth.size() > 0) {
|
||||
CPULoadModel cpu = CPULoadModel.create(ms);
|
||||
cBuilder.append(d.getModel() + ";");
|
||||
minMax.append(d.getModel() + ";");
|
||||
volume.append(d.getModel() + ";");
|
||||
error.append(d.getModel() + ";");
|
||||
List<double[]> allMap = getAllPairs(ms);
|
||||
append(cBuilder, Algo.correlate(allMap));
|
||||
append(volume, allMap.size());
|
||||
appendError(error, allMap);
|
||||
List<double[]> allTripspMap = getTripPairs(trips);
|
||||
append(cBuilder, Algo.correlate(allTripspMap));
|
||||
append(volume, allTripspMap.size());
|
||||
appendError(error, allTripspMap);
|
||||
List<double[]> allWalking = getTripPairs(walking);
|
||||
append(cBuilder, Algo.correlate(allWalking));
|
||||
append(volume, allWalking.size());
|
||||
appendError(error, allWalking);
|
||||
|
||||
List<Double> loads = new ArrayList<>();
|
||||
int count = 0;
|
||||
int total = 0;
|
||||
for (TripResult r: walking) {
|
||||
int c = 3;
|
||||
j: for (Measurement mx: r.motion) {
|
||||
if (Mse.isActive(mx)) {
|
||||
c -= 1;
|
||||
if (c == 0) {
|
||||
count += 1;
|
||||
break j;
|
||||
}
|
||||
}
|
||||
}
|
||||
total += 1;
|
||||
}
|
||||
System.out.println(d.getModel() + " " + count + " " + total + " " + (count / (double)total));
|
||||
|
||||
|
||||
|
||||
for (double minutes: new double[] { 5, 10, 15, 20 }) {
|
||||
List<double[]> map = getPairs(walkingWithTruth, minutes, true);
|
||||
double c = Algo.correlate(map);
|
||||
if (Double.isNaN(c)) {
|
||||
for (double[] xx: map) {
|
||||
System.out.println(xx[0] + " " + xx[1]);
|
||||
}
|
||||
|
||||
}
|
||||
append(cBuilder, Algo.correlate(map));
|
||||
append(volume, map.size());
|
||||
appendError(error, map);
|
||||
double min = 0;
|
||||
double max = 0;
|
||||
if (map.size() > 0) {
|
||||
min = map.get(0)[1];
|
||||
max = map.get(0)[1];
|
||||
for (double[] vx: map) {
|
||||
min = Math.min(min, vx[1]);
|
||||
max = Math.max(max, vx[1]);
|
||||
}
|
||||
}
|
||||
append(minMax, min);
|
||||
append(minMax, max);
|
||||
}
|
||||
List<double[]> mapActive = getPairs(walkingWithTruth, 20, false);
|
||||
append(cBuilder, Algo.correlate(mapActive));
|
||||
append(volume, mapActive.size());
|
||||
appendError(error, mapActive);
|
||||
|
||||
cBuilder.append("\n");
|
||||
minMax.append("\n");
|
||||
volume.append("\n");
|
||||
error.append("\n");
|
||||
|
||||
}
|
||||
}
|
||||
}
|
||||
System.out.println("Correlations");
|
||||
System.out.println(cBuilder);
|
||||
System.out.println("Min/Max");
|
||||
System.out.println(minMax);
|
||||
System.out.println("Volume");
|
||||
System.out.println(volume);
|
||||
System.out.println("Errors");
|
||||
System.out.println(error);
|
||||
}
|
||||
|
||||
public static void appendError(StringBuilder b, List<double[]> map) {
|
||||
ErrorSummary s = Algo.errors(map);
|
||||
append(b, s.mae);
|
||||
append(b, s.rms);
|
||||
append(b, s.max);
|
||||
for (int i = 0; i< s.distribution.length; i++) {
|
||||
//append(b, s.distribution[i]);
|
||||
}
|
||||
}
|
||||
|
||||
public static void append(StringBuilder b, double value) {
|
||||
b.append(("" + value).replace(".", ",") + ";");
|
||||
}
|
||||
|
||||
public static List<double[]> getAllPairs(List<Measurement> ms) {
|
||||
List<double[]> result = new ArrayList<>();
|
||||
for (Measurement m: ms) {
|
||||
Double station = Mse.getStationTemperature(m);
|
||||
Double device = Mse.getDeviceTemperature(m);
|
||||
if (station != null && device != null) {
|
||||
result.add(new double[] { device, station });
|
||||
}
|
||||
}
|
||||
return result;
|
||||
}
|
||||
|
||||
public static List<double[]> getTripPairs(List<TripResult> trips) {
|
||||
List<double[]> result = new ArrayList<>();
|
||||
for (TripResult r: trips) {
|
||||
for (Measurement m: r.motion) {
|
||||
Double station = Mse.getStationTemperature(m);
|
||||
Double device = Mse.getDeviceTemperature(m);
|
||||
if (station != null && device != null) {
|
||||
result.add(new double[] { device, station });
|
||||
}
|
||||
}
|
||||
}
|
||||
return result;
|
||||
}
|
||||
|
||||
|
||||
|
||||
|
||||
public static List<double[]> getPairs(List<TripResult> walking, double time, boolean noActive) {
|
||||
List<double[]> outside = new ArrayList<>();
|
||||
walking.forEach(t -> {
|
||||
double station = getStationTemperature(t);
|
||||
Double temperature = getDeviceTemperatureAt(t, time, noActive);
|
||||
if (temperature != null) {
|
||||
outside.add(new double[] { temperature, station });
|
||||
}
|
||||
});
|
||||
return outside;
|
||||
}
|
||||
|
||||
|
||||
public static Double getDeviceTemperatureAt(TripResult t, double minute, boolean noActive) {
|
||||
Measurement first = t.origin;
|
||||
double firstMinute = 0;
|
||||
Measurement last = t.destination;
|
||||
double lastMinute = getMinuteForMeasurement(t.origin, last);
|
||||
if (minute > lastMinute) {
|
||||
return null;
|
||||
}
|
||||
for (Measurement m: t.motion) {
|
||||
double curr = getMinuteForMeasurement(t.origin, m);
|
||||
if (curr <= minute) {
|
||||
if (minute - curr < minute - firstMinute) {
|
||||
first = m;
|
||||
firstMinute = curr;
|
||||
}
|
||||
} else {
|
||||
if (curr - minute < lastMinute - minute) {
|
||||
last = m;
|
||||
lastMinute = curr;
|
||||
}
|
||||
}
|
||||
}
|
||||
if (noActive) {
|
||||
// filter trips with active measurements
|
||||
if (Mse.isActive(last) || Mse.isActive(first)) return null;
|
||||
int count = 1;
|
||||
for (Measurement m: t.motion) {
|
||||
if (Mse.isActive(m)) {
|
||||
count -= 1;
|
||||
if (count == 0)
|
||||
return null;
|
||||
}
|
||||
if (m == last) break;
|
||||
}
|
||||
}
|
||||
// linear interpolation
|
||||
double ft = Mse.getDeviceTemperature(first);
|
||||
double lt = Mse.getDeviceTemperature(last);
|
||||
if (lastMinute == firstMinute) return ft;
|
||||
double percent = (minute - firstMinute) / (lastMinute - firstMinute);
|
||||
//System.out.println("perc: " + percent);
|
||||
double res = percent * lt + (1 - percent) * ft;
|
||||
//System.out.println("FT: " + ft + " LT: " + lt + " Timing: " + firstMinute + " " + lastMinute + " " + minute + " = " + res);
|
||||
return res;
|
||||
}
|
||||
|
||||
public static double getMinuteForMeasurement(Measurement origin, Measurement m) {
|
||||
return (m.getTime() - origin.getTime()) / 60000d;
|
||||
}
|
||||
|
||||
public static Double getStationTemperature(TripResult t) {
|
||||
Double r = Mse.getStationTemperature(t.origin);
|
||||
if (r == null) {
|
||||
for (Measurement m: t.motion) {
|
||||
r = Mse.getStationTemperature(m);
|
||||
if (r != null) break;
|
||||
}
|
||||
if (r == null) {
|
||||
//r = Mse.getStationTemperature(t.destination);
|
||||
}
|
||||
}
|
||||
return r;
|
||||
}
|
||||
|
||||
|
||||
public static List<TripResult> getTrips(List<Measurement> ms, long now) {
|
||||
List<TripResult> results = new ArrayList<>();
|
||||
TripResult result;
|
||||
while ((result = LocationClassifier.computeNextTrip(ms, now)) != null) {
|
||||
results.add(result);
|
||||
ms = result.remainder;
|
||||
}
|
||||
return results;
|
||||
}
|
||||
|
||||
public static Measurement getMeasurement(TripResult result, double minute, double threshold) {
|
||||
List<Measurement> candidates = result.motion.stream().filter(m -> {
|
||||
double min = (m.getTime() - result.origin.getTime()) / 60000d;
|
||||
return min > minute - 0.5 * threshold && min <= minute + 0.5 * threshold;
|
||||
}).collect(Collectors.toList());
|
||||
if (candidates.isEmpty()) return null;
|
||||
else return candidates.get(0);
|
||||
}
|
||||
|
||||
|
||||
public static String toString(Date date) {
|
||||
SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm");
|
||||
return df.format(date);
|
||||
}
|
||||
|
||||
public static long getDate(String string) throws ParseException {
|
||||
SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm");
|
||||
Date date = df.parse(string);
|
||||
return date.getTime();
|
||||
}
|
||||
|
||||
|
||||
public static <T> List<T> readFile(File file, Class<T> type) throws Exception {
|
||||
ObjectMapper mapper = new ObjectMapper();
|
||||
List<T> result = new ArrayList<>();
|
||||
try (BufferedReader reader = new BufferedReader(new FileReader(file, StandardCharsets.UTF_8))) {
|
||||
String line = null;
|
||||
while ((line = reader.readLine()) != null) {
|
||||
result.add(mapper.readValue(line, type));
|
||||
}
|
||||
}
|
||||
return result;
|
||||
}
|
||||
|
||||
|
||||
}
|
||||
@@ -0,0 +1,136 @@
|
||||
package com.mowesta.tool.paper;
|
||||
|
||||
import java.io.File;
|
||||
import java.text.DateFormat;
|
||||
import java.text.SimpleDateFormat;
|
||||
import java.util.ArrayList;
|
||||
import java.util.Collections;
|
||||
import java.util.Date;
|
||||
import java.util.HashMap;
|
||||
import java.util.List;
|
||||
import java.util.Locale;
|
||||
import java.util.Map;
|
||||
import java.util.stream.Collectors;
|
||||
|
||||
import com.mowesta.api.Coordinate;
|
||||
import com.mowesta.api.TimeRange;
|
||||
import com.mowesta.api.measurement.Measurement;
|
||||
import com.mowesta.api.measurement.MeasurementType;
|
||||
import com.mowesta.tool.paper.FairExperimentEvaluation.Sample;
|
||||
|
||||
public class FairDeviceEvaluation {
|
||||
|
||||
|
||||
// 9732599 samsung s10e
|
||||
|
||||
public static void main(String[] args) {
|
||||
List<Long> devices = new ArrayList<>();
|
||||
|
||||
|
||||
TimeRange range = new TimeRange(1622498400000l, 12*30 * 24 * 60 * 60000l);
|
||||
|
||||
//TimeRange range = new TimeRange(1654034400000l, 30 * 24 * 60 * 60000l);
|
||||
devices.add(9732599l); // hmd
|
||||
|
||||
List<Sample> samples = createSamples(FairExperimentEvaluation.loadDevices(new File("mowesta-dump"), devices), range);
|
||||
for (Sample s: samples) {
|
||||
if (s.isOutside(devices.get(0)))
|
||||
System.out.println(s.toString(devices));
|
||||
}
|
||||
|
||||
|
||||
}
|
||||
|
||||
public static List<Sample> createSamples(List<List<Measurement>> data, TimeRange range) {
|
||||
List<Sample> samples = new ArrayList<>();
|
||||
data.forEach((dt)-> Collections.sort(dt, (a, b) -> Long.compare(a.getTime(), b.getTime())));
|
||||
long interval = 10 * 60 * 1000;
|
||||
long current = range.getStart();
|
||||
while (current < range.getEnd()) {
|
||||
final long start = current;
|
||||
final long stop = current + interval;
|
||||
Sample sample = new Sample();
|
||||
sample.date = new Date(start);
|
||||
samples.add(sample);
|
||||
data.forEach((dt) -> {
|
||||
List<Measurement> ms = dt.stream().filter(m -> m.getTime() >= start && m.getTime() < stop).collect(Collectors.toList());
|
||||
if (ms.size() > 0 && ms.get(0).getData().get(MeasurementType.STATION_TEMPERATURE) != null) {
|
||||
Coordinate c = ms.get(0).getCoordinate();
|
||||
double temp = ms.get(0).getTemperature();
|
||||
double station = Double.valueOf(ms.get(0).getData().get(MeasurementType.STATION_TEMPERATURE));
|
||||
boolean charging = Boolean.parseBoolean(ms.get(0).getData().get(MeasurementType.BATTERY_CHARGING));
|
||||
boolean outside = Boolean.parseBoolean(ms.get(0).getData().get(MeasurementType.OUTSIDE_INDICATOR));
|
||||
boolean active = false;
|
||||
for (Measurement m: ms) {
|
||||
active |= Boolean.parseBoolean(ms.get(0).getData().get(MeasurementType.SCREEN_ENABLED));
|
||||
}
|
||||
sample.station = station;
|
||||
sample.addValue(ms.get(0).getDevice(), temp, charging, outside, active);
|
||||
}
|
||||
});
|
||||
current += interval;
|
||||
}
|
||||
return samples;
|
||||
}
|
||||
|
||||
public static class Sample {
|
||||
|
||||
static DateFormat format = new SimpleDateFormat("YYYY-MM-dd HH:mm");
|
||||
|
||||
Date date;
|
||||
Double station;
|
||||
Map<Long, Double> values = new HashMap<>();
|
||||
Map<Long, Boolean> outside = new HashMap<>();
|
||||
Map<Long, Boolean> charging = new HashMap<>();
|
||||
Map<Long, Boolean> active = new HashMap<>();
|
||||
|
||||
public void addValue(Long device, Double value, boolean c, boolean o, boolean a) {
|
||||
values.put(device, value);
|
||||
outside.put(device, o);
|
||||
charging.put(device, c);
|
||||
active.put(device, a);
|
||||
}
|
||||
|
||||
public boolean isComplete(List<Long> devices) {
|
||||
for (Long d: devices) {
|
||||
if (values.get(d) == null)
|
||||
return false;
|
||||
}
|
||||
return station != null;
|
||||
}
|
||||
|
||||
public String toString(List<Long> devices) {
|
||||
StringBuilder b = new StringBuilder();
|
||||
b.append(format.format(date) + ";");
|
||||
b.append(toString(station) + ";");
|
||||
for (Long d: devices) {
|
||||
b.append(toString(values.get(d)) + ";");
|
||||
b.append(toString(charging.get(d))+ ";");
|
||||
b.append(toString(outside.get(d))+ ";");
|
||||
b.append(toString(active.get(d))+ ";");
|
||||
|
||||
}
|
||||
return b.toString();
|
||||
}
|
||||
|
||||
public boolean isOutside(Long device) {
|
||||
if (values.get(device) != null) {
|
||||
return outside.get(device) && !active.get(device);
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
public String toString(Double value) {
|
||||
if (value == null) return "";
|
||||
else return String.format(Locale.GERMANY, "%f", value);
|
||||
}
|
||||
|
||||
public String toString(Boolean value) {
|
||||
if (value == null) return "";
|
||||
if (value) return "1";
|
||||
else return "0";
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,289 @@
|
||||
package com.mowesta.tool.paper;
|
||||
|
||||
import java.io.File;
|
||||
import java.util.ArrayList;
|
||||
import java.util.Collections;
|
||||
import java.util.List;
|
||||
|
||||
import com.mowesta.api.Coordinate;
|
||||
import com.locoslab.library.geometry.wgs.HaversineDistance;
|
||||
import com.mowesta.api.TimeRange;
|
||||
import com.mowesta.api.measurement.Measurement;
|
||||
import com.mowesta.api.measurement.MeasurementType;
|
||||
import com.mowesta.data.process.algorithm.LinearRegression;
|
||||
import com.mowesta.tool.paper.LocationClassifier.TripResult;
|
||||
|
||||
public class FairDeviceTripEval {
|
||||
|
||||
public static void main(String[] args) throws Exception {
|
||||
List<Long> devices = new ArrayList<>();
|
||||
/*
|
||||
devices.add(9732599l); // marcus
|
||||
devices.add(35723568l); // bijan
|
||||
devices.add(50170543l); // peter
|
||||
devices.add(10255524l); // alex
|
||||
devices.add(51013123l); // sepehr
|
||||
devices.add(55854857l); // xiaomi
|
||||
devices.add(51013123l); // pixel 0.4
|
||||
devices.add(10312353l); // 0.58
|
||||
devices.add(11893063l);
|
||||
*/
|
||||
|
||||
|
||||
// devices.add(9934728l);
|
||||
//devices.add(12608296l);
|
||||
//devices.add(24963415l);
|
||||
//devices.add(40130654l);
|
||||
// devices.add(41900131l);
|
||||
|
||||
|
||||
devices.add( 9732599l); // Device: 9732599 Trips: 471 Correl: 0.8355684509263944
|
||||
devices.add(40549928l); // Device: 40549928 Trips: 53 Correl: 0.7988629288657759
|
||||
devices.add(11626535l); // Device: 11626535 Trips: 224 Correl: 0.7426799691965503
|
||||
devices.add(31479035l); // Device: 31479035 Trips: 67 Correl: 0.7612317117391304
|
||||
devices.add(55854857l); // Device: 55854857 Trips: 30 Correl: 0.7145562853663179
|
||||
devices.add(47842381l); // Device: 47842381 Trips: 120 Correl: 0.6722217646360276
|
||||
|
||||
|
||||
// devices.add(41823691l); // Device: 41823691 Trips: 40 Correl: 0.5741950189675636
|
||||
// devices.add(11654165l); // Device: 11654165 Trips: 58 Correl: 0.31734328728812855
|
||||
// devices.add(41238320l); // Device: 41238320 Trips: 12 Correl: 0.696438727443019
|
||||
// devices.add(38984801l); // Device: 38984801 Trips: 3 Correl: 0.9054858781022361
|
||||
devices.add(20488695l); // Device: 20488695 Trips: 87 Correl: 0.4721600781064517
|
||||
devices.add(41905496l); // Device: 41905496 Trips: 180 Correl: 0.44761841722539353
|
||||
devices.add(49508917l); // Device: 49508917 Trips: 73 Correl: 0.045661193319880354
|
||||
// devices.add(41236816l); // Device: 41236816 Trips: 18 Correl: 0.2921384178694328
|
||||
// devices.add(36029354l); // Device: 36029354 Trips: 27 Correl: 0.3124698214249411
|
||||
// devices.add(20136895l); // Device: 20136895 Trips: 14 Correl: 0.6373958660006969
|
||||
devices.add(12071766l); // Device: 12071766 Trips: 174 Correl: 0.08542554887412529
|
||||
devices.add(51013123l); // Device: 51013123 Trips: 98 Correl: 0.39772235864194727
|
||||
devices.add(11629870l); // Device: 11629870 Trips: 129 Correl: 0.571784843448459
|
||||
// devices.add(65670031l); // Device: 65670031 Trips: 9 Correl: 0.7214039104943657
|
||||
// devices.add(42160931l); // Device: 42160931 Trips: 38 Correl: 0.5168320598452678
|
||||
// devices.add(10255524l); // Device: 10255524 Trips: 30 Correl: 0.41287414438595815
|
||||
// devices.add(39455128l); // Device: 39455128 Trips: 0 Correl: NaN
|
||||
devices.add(10312353l); // Device: 10312353 Trips: 73 Correl: 0.5894331880031445
|
||||
|
||||
|
||||
/*
|
||||
devices.add(50400745l);
|
||||
devices.add(35723568l);
|
||||
devices.add(51646778l);
|
||||
devices.add(11641609l);
|
||||
devices.add(12314824l);
|
||||
devices.add(11597879l);
|
||||
devices.add(11624766l);
|
||||
devices.add(41900866l);
|
||||
devices.add(66018865l);
|
||||
devices.add(9939081l);
|
||||
*/
|
||||
|
||||
/*
|
||||
-rw-r--r-- 1 marcus staff 18251970 18 Sep 16:29 measurement-21277893
|
||||
-rw-r--r-- 1 marcus staff 17266713 18 Sep 12:30 measurement-51197483
|
||||
-rw-r--r-- 1 marcus staff 16941433 18 Sep 16:28 measurement-22800085
|
||||
-rw-r--r-- 1 marcus staff 16855883 18 Sep 20:23 measurement-9770329
|
||||
-rw-r--r-- 1 marcus staff 16186053 18 Sep 18:54 measurement-10108047
|
||||
-rw-r--r-- 1 marcus staff 15802230 18 Sep 12:22 measurement-56848775
|
||||
-rw-r--r-- 1 marcus staff 15326568 18 Sep 12:48 measurement-48185381
|
||||
-rw-r--r-- 1 marcus staff 14729402 18 Sep 12:38 measurement-50172370
|
||||
-rw-r--r-- 1 marcus staff 14632959 18 Sep 12:47 measurement-49051541
|
||||
-rw-r--r-- 1 marcus staff 13756161 18 Sep 13:49 measurement-41549718
|
||||
-rw-r--r-- 1 marcus staff 13484829 18 Sep 16:44 measurement-20046489
|
||||
-rw-r--r-- 1 marcus staff 13305160 18 Sep 16:46 measurement-14316440
|
||||
-rw-r--r-- 1 marcus staff 12164951 18 Sep 12:36 measurement-50190362
|
||||
-rw-r--r-- 1 marcus staff 11377951 18 Sep 12:37 measurement-50172394
|
||||
-rw-r--r-- 1 marcus staff 10527735 18 Sep 16:45 measurement-16492044
|
||||
-rw-r--r-- 1 marcus staff 10229763 18 Sep 12:20 measurement-62945978
|
||||
-rw-r--r-- 1 marcus staff 10129874 18 Sep 12:59 measurement-42482498
|
||||
-rw-r--r-- 1 marcus staff 10068332 18 Sep 18:06 measurement-11893063
|
||||
*/
|
||||
|
||||
|
||||
System.out.println("load");
|
||||
List<List<Measurement>> data = FairExperimentEvaluation.loadDevices(new File("mowesta-dump"), devices);
|
||||
System.out.println("sort");
|
||||
data.forEach((dt)-> Collections.sort(dt, (a, b) -> Long.compare(a.getTime(), b.getTime())));
|
||||
long now = System.currentTimeMillis();
|
||||
System.out.println("compute");
|
||||
for (int i = 0; i < data.size(); i++) {
|
||||
process(devices.get(i), data.get(i), now);
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
public static void process(Long device, List<Measurement> input, long now) {
|
||||
int readings = 0;
|
||||
double avg = 0;
|
||||
double freq = 0;
|
||||
int freqR = 0;
|
||||
double fmax = 0;
|
||||
for (Measurement m: input) {
|
||||
Double v = Mse.getDeviceTemperature(m);
|
||||
Double s = Mse.getStationTemperature(m);
|
||||
Double f = Mse.getAverageCpuFreq(m);
|
||||
Boolean active = Mse.isActive(m);
|
||||
if (v != null && s != null && !active) {
|
||||
avg += v;
|
||||
readings += 1;
|
||||
}
|
||||
if (!active && f != null) {
|
||||
freq += f;
|
||||
freqR += 1;
|
||||
}
|
||||
if (f != null) {
|
||||
fmax = Math.max(fmax, Mse.getMaxCpuFreq(m));
|
||||
}
|
||||
}
|
||||
avg /= readings;
|
||||
freq /= freqR;
|
||||
freq /= fmax;
|
||||
|
||||
LinearRegression.Builder<Double> lrb = new LinearRegression.Builder<>();
|
||||
List<Coordinate> places = new ArrayList<>();
|
||||
List<double[]> mapping = new ArrayList<>();
|
||||
List<Double> starts = new ArrayList<>();
|
||||
int counter = 0;
|
||||
while (true) {
|
||||
TripResult r = LocationClassifier.computeNextTrip(input, now);
|
||||
if (r == null) {
|
||||
break;
|
||||
}
|
||||
input = r.remainder;
|
||||
double duration = ((r.destination.getTime() - r.origin.getTime()) / 60000d);
|
||||
double distance = 0;
|
||||
for (int i = 1; i < r.motion.size(); i++) {
|
||||
Coordinate p = r.motion.get(i - 1).getCoordinate();
|
||||
Coordinate c = r.motion.get(i).getCoordinate();
|
||||
distance += HaversineDistance.getDistance(p.getLongitude(), p.getLatitude(), c.getLongitude(), c.getLatitude());
|
||||
}
|
||||
double speed = (distance / (duration * 60));
|
||||
if (speed < 2 && distance > 300 && duration > 10) {
|
||||
boolean active = false;
|
||||
Measurement ten = null;
|
||||
for (Measurement m: r.motion) {
|
||||
if (Mse.isActive(m)) { // || Mse.getDeviceTemperature(m) > Mse.getDeviceTemperature(r.origin)) {
|
||||
active = true;
|
||||
break;
|
||||
}
|
||||
if (ten == null) {
|
||||
if (m.getTime() - r.origin.getTime() > 60000 * 15) {
|
||||
ten = m;
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
if (!active && ten != null) {
|
||||
|
||||
// if (r.start.isEmpty() || r.origin.getTime() - r.start.get(0).getTime() < 60 * 60 * 1000) {
|
||||
// continue;
|
||||
// }
|
||||
|
||||
|
||||
boolean found = false;
|
||||
for (Coordinate c: places) {
|
||||
if (HaversineDistance.getDistance(c.getLongitude(), c.getLatitude(), r.origin.getCoordinate().getLongitude(), r.origin.getCoordinate().getLatitude()) < 150) {
|
||||
found = true;
|
||||
break;
|
||||
}
|
||||
}
|
||||
if (!found) {
|
||||
//if (places.isEmpty())
|
||||
places.add(r.origin.getCoordinate());
|
||||
//else
|
||||
// continue;
|
||||
}
|
||||
|
||||
|
||||
|
||||
|
||||
Double station = Mse.getStationTemperature(r.origin);
|
||||
Double device0 = Mse.getDeviceTemperature(r.origin);
|
||||
Double device10 = Mse.getDeviceTemperature(ten);
|
||||
double tx = (ten.getTime() - r.origin.getTime()) / (10 * 60000d);
|
||||
double max = 0;
|
||||
for (Measurement m: r.motion) {
|
||||
Double f = Mse.getMaxCpuFreq(m);
|
||||
if (f != null)
|
||||
max = Math.max(f, max);
|
||||
if (m == ten) break;
|
||||
}
|
||||
|
||||
if (station != null) {
|
||||
starts.add(device0);
|
||||
|
||||
double[] map = new double[] {
|
||||
station, //- device0,
|
||||
device10 //(device10 - device0) / tx
|
||||
};
|
||||
|
||||
mapping.add(map);
|
||||
//if (mapping.size() < 40)
|
||||
lrb.add(map[1], map[0]);
|
||||
counter += 1;
|
||||
//System.out.println(station + ";" + (station - device0) + ";" + (device10 - device0) + ";" + max);
|
||||
}
|
||||
// System.out.println(station + " " + device0 + " " + device10);
|
||||
// System.out.println(r.origin.getCoordinate().getLatitude() + ", " + r.origin.getCoordinate().getLongitude());
|
||||
// System.out.println(r.destination.getCoordinate().getLatitude() + ", " + r.destination.getCoordinate().getLongitude());
|
||||
// for (Measurement m: r.motion) {
|
||||
// System.out.println(m.getData().get(MeasurementType.CPU_FREQUENCY));
|
||||
// if (m == ten) break;
|
||||
// }
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
System.out.println("Device: " + device + " Trips: " + counter + " Correl: " + correlate(mapping) + " temp: " + avg + " places: " + places.size() + " IdleF: " + freq);
|
||||
LinearRegression lr = lrb.build();
|
||||
//System.out.println("IC:" + lr.getIntercept() + " Slope: " + lr.getSlope() + " R2:" + lr.getRSquared() + " er: " + lr.getError() + " mae: " + lr.getMae());
|
||||
print(starts);
|
||||
}
|
||||
|
||||
|
||||
|
||||
|
||||
public static double correlate(List<double[]> data) {
|
||||
double[] mean = new double[2];
|
||||
for (double[] values: data) {
|
||||
mean[0] += values[0];
|
||||
mean[1] += values[1];
|
||||
}
|
||||
mean[0] /= data.size();
|
||||
mean[1] /= data.size();
|
||||
double product = 0;
|
||||
double var1 = 0;
|
||||
double var2 = 0;
|
||||
for (double[] values: data) {
|
||||
double v1 = values[0] - mean[0];
|
||||
double v2 = values[1] - mean[1];
|
||||
product += v1 * v2;
|
||||
var1 += v1 * v1;
|
||||
var2 += v2 * v2;
|
||||
}
|
||||
//System.out.println("prod: " + product + " v1: " + var1 + " v2: " + var2);
|
||||
|
||||
return product / (Math.sqrt(var1) * Math.sqrt(var2));
|
||||
}
|
||||
|
||||
|
||||
public static void print(List<Double> starts) {
|
||||
double mean = 0;
|
||||
for (Double d: starts) {
|
||||
mean += d;
|
||||
}
|
||||
mean /= starts.size();
|
||||
double dev = 0;
|
||||
for (Double d: starts) {
|
||||
double x = d - mean;
|
||||
dev += x*x;
|
||||
}
|
||||
System.out.println("mean:" + mean + "Dev: " + Math.sqrt(dev / starts.size()));
|
||||
|
||||
}
|
||||
|
||||
|
||||
|
||||
|
||||
}
|
||||
@@ -0,0 +1,475 @@
|
||||
package com.mowesta.tool.paper;
|
||||
|
||||
import java.io.File;
|
||||
import java.util.ArrayList;
|
||||
import java.util.Arrays;
|
||||
import java.util.Collections;
|
||||
import java.util.HashMap;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.Map.Entry;
|
||||
|
||||
import org.apache.commons.math3.stat.regression.OLSMultipleLinearRegression;
|
||||
|
||||
import com.mowesta.api.Coordinate;
|
||||
import com.locoslab.library.geometry.wgs.HaversineDistance;
|
||||
import com.mowesta.api.TimeRange;
|
||||
import com.mowesta.api.measurement.Measurement;
|
||||
import com.mowesta.api.measurement.MeasurementType;
|
||||
import com.mowesta.data.process.algorithm.LinearRegression;
|
||||
import com.mowesta.tool.paper.LocationClassifier.TripResult;
|
||||
|
||||
public class FairDeviceTripEval2 {
|
||||
|
||||
public static void main(String[] args) throws Exception {
|
||||
List<Long> devices = new ArrayList<>();
|
||||
/*
|
||||
devices.add(9732599l); // marcus
|
||||
devices.add(35723568l); // bijan
|
||||
devices.add(50170543l); // peter
|
||||
devices.add(10255524l); // alex
|
||||
devices.add(51013123l); // sepehr
|
||||
devices.add(55854857l); // xiaomi
|
||||
devices.add(51013123l); // pixel 0.4
|
||||
devices.add(10312353l); // 0.58
|
||||
devices.add(11893063l);
|
||||
*/
|
||||
|
||||
|
||||
// devices.add(9934728l);
|
||||
//devices.add(12608296l);
|
||||
//devices.add(24963415l);
|
||||
//devices.add(40130654l);
|
||||
// devices.add(41900131l);
|
||||
|
||||
|
||||
devices.add( 9732599l); // Device: 9732599 Trips: 471 Correl: 0.8355684509263944
|
||||
devices.add(40549928l); // Device: 40549928 Trips: 53 Correl: 0.7988629288657759
|
||||
devices.add(11626535l); // Device: 11626535 Trips: 224 Correl: 0.7426799691965503
|
||||
devices.add(31479035l); // Device: 31479035 Trips: 67 Correl: 0.7612317117391304
|
||||
devices.add(55854857l); // Device: 55854857 Trips: 30 Correl: 0.7145562853663179
|
||||
devices.add(47842381l); // Device: 47842381 Trips: 120 Correl: 0.6722217646360276
|
||||
|
||||
|
||||
// devices.add(41823691l); // Device: 41823691 Trips: 40 Correl: 0.5741950189675636
|
||||
// devices.add(11654165l); // Device: 11654165 Trips: 58 Correl: 0.31734328728812855
|
||||
// devices.add(41238320l); // Device: 41238320 Trips: 12 Correl: 0.696438727443019
|
||||
// devices.add(38984801l); // Device: 38984801 Trips: 3 Correl: 0.9054858781022361
|
||||
devices.add(20488695l); // Device: 20488695 Trips: 87 Correl: 0.4721600781064517
|
||||
devices.add(41905496l); // Device: 41905496 Trips: 180 Correl: 0.44761841722539353
|
||||
devices.add(49508917l); // Device: 49508917 Trips: 73 Correl: 0.045661193319880354
|
||||
// devices.add(41236816l); // Device: 41236816 Trips: 18 Correl: 0.2921384178694328
|
||||
// devices.add(36029354l); // Device: 36029354 Trips: 27 Correl: 0.3124698214249411
|
||||
// devices.add(20136895l); // Device: 20136895 Trips: 14 Correl: 0.6373958660006969
|
||||
devices.add(12071766l); // Device: 12071766 Trips: 174 Correl: 0.08542554887412529
|
||||
devices.add(51013123l); // Device: 51013123 Trips: 98 Correl: 0.39772235864194727
|
||||
devices.add(11629870l); // Device: 11629870 Trips: 129 Correl: 0.571784843448459
|
||||
// devices.add(65670031l); // Device: 65670031 Trips: 9 Correl: 0.7214039104943657
|
||||
// devices.add(42160931l); // Device: 42160931 Trips: 38 Correl: 0.5168320598452678
|
||||
// devices.add(10255524l); // Device: 10255524 Trips: 30 Correl: 0.41287414438595815
|
||||
// devices.add(39455128l); // Device: 39455128 Trips: 0 Correl: NaN
|
||||
devices.add(10312353l); // Device: 10312353 Trips: 73 Correl: 0.5894331880031445
|
||||
|
||||
|
||||
/*
|
||||
devices.add(50400745l);
|
||||
devices.add(35723568l);
|
||||
devices.add(51646778l);
|
||||
devices.add(11641609l);
|
||||
devices.add(12314824l);
|
||||
devices.add(11597879l);
|
||||
devices.add(11624766l);
|
||||
devices.add(41900866l);
|
||||
devices.add(66018865l);
|
||||
devices.add(9939081l);
|
||||
*/
|
||||
|
||||
/*
|
||||
-rw-r--r-- 1 marcus staff 18251970 18 Sep 16:29 measurement-21277893
|
||||
-rw-r--r-- 1 marcus staff 17266713 18 Sep 12:30 measurement-51197483
|
||||
-rw-r--r-- 1 marcus staff 16941433 18 Sep 16:28 measurement-22800085
|
||||
-rw-r--r-- 1 marcus staff 16855883 18 Sep 20:23 measurement-9770329
|
||||
-rw-r--r-- 1 marcus staff 16186053 18 Sep 18:54 measurement-10108047
|
||||
-rw-r--r-- 1 marcus staff 15802230 18 Sep 12:22 measurement-56848775
|
||||
-rw-r--r-- 1 marcus staff 15326568 18 Sep 12:48 measurement-48185381
|
||||
-rw-r--r-- 1 marcus staff 14729402 18 Sep 12:38 measurement-50172370
|
||||
-rw-r--r-- 1 marcus staff 14632959 18 Sep 12:47 measurement-49051541
|
||||
-rw-r--r-- 1 marcus staff 13756161 18 Sep 13:49 measurement-41549718
|
||||
-rw-r--r-- 1 marcus staff 13484829 18 Sep 16:44 measurement-20046489
|
||||
-rw-r--r-- 1 marcus staff 13305160 18 Sep 16:46 measurement-14316440
|
||||
-rw-r--r-- 1 marcus staff 12164951 18 Sep 12:36 measurement-50190362
|
||||
-rw-r--r-- 1 marcus staff 11377951 18 Sep 12:37 measurement-50172394
|
||||
-rw-r--r-- 1 marcus staff 10527735 18 Sep 16:45 measurement-16492044
|
||||
-rw-r--r-- 1 marcus staff 10229763 18 Sep 12:20 measurement-62945978
|
||||
-rw-r--r-- 1 marcus staff 10129874 18 Sep 12:59 measurement-42482498
|
||||
-rw-r--r-- 1 marcus staff 10068332 18 Sep 18:06 measurement-11893063
|
||||
*/
|
||||
|
||||
|
||||
System.out.println("load");
|
||||
List<List<Measurement>> data = FairExperimentEvaluation.loadDevices(new File("mowesta-dump"), devices);
|
||||
System.out.println("sort");
|
||||
data.forEach((dt)-> Collections.sort(dt, (a, b) -> Long.compare(a.getTime(), b.getTime())));
|
||||
long now = System.currentTimeMillis();
|
||||
System.out.println("compute");
|
||||
for (int i = 0; i < data.size(); i++) {
|
||||
process(devices.get(i), data.get(i), now);
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
public static void process(Long device, List<Measurement> input, long now) {
|
||||
CPULoadModel model = CPULoadModel.create(input);
|
||||
//System.out.println(model);
|
||||
|
||||
double stationMin = Double.MAX_VALUE;
|
||||
double stationMax = Double.MIN_VALUE;
|
||||
|
||||
int readings = 0;
|
||||
double avg = 0;
|
||||
double freq = 0;
|
||||
int freqR = 0;
|
||||
double fmax = 0;
|
||||
double fmin = Double.MAX_VALUE;
|
||||
for (Measurement m: input) {
|
||||
Double v = Mse.getDeviceTemperature(m);
|
||||
Double s = Mse.getStationTemperature(m);
|
||||
Double f = Mse.getAverageCpuFreq(m);
|
||||
Boolean active = Mse.isActive(m);
|
||||
if (v != null && s != null && !active) {
|
||||
avg += v;
|
||||
readings += 1;
|
||||
}
|
||||
if (!active && f != null) {
|
||||
freq += f;
|
||||
freqR += 1;
|
||||
}
|
||||
if (f != null) {
|
||||
fmax = Math.max(fmax, Mse.getMaxCpuFreq(m));
|
||||
fmin = Math.min(fmin, Mse.getMinCpuFreq(m));
|
||||
}
|
||||
}
|
||||
avg /= readings;
|
||||
freq /= freqR;
|
||||
freq -= fmin;
|
||||
freq /= fmax - fmin;
|
||||
|
||||
LinearRegression.Builder<Double> lrb = new LinearRegression.Builder<>();
|
||||
List<Coordinate> places = new ArrayList<>();
|
||||
List<double[]> mapping = new ArrayList<>();
|
||||
List<Double> starts = new ArrayList<>();
|
||||
List<List<double[]>> placeMappings = new ArrayList<>();
|
||||
int counter = 0;
|
||||
int tripReadings = 0;
|
||||
|
||||
List<Double> stationValues = new ArrayList<>();
|
||||
List<double[]> modelValues = new ArrayList<>();
|
||||
List<Double> loadValues = new ArrayList<>();
|
||||
List<Double> tempVariability = new ArrayList<>();
|
||||
|
||||
while (true) {
|
||||
TripResult r = LocationClassifier.computeNextTrip(input, now);
|
||||
if (r == null) {
|
||||
break;
|
||||
}
|
||||
input = r.remainder;
|
||||
double duration = ((r.destination.getTime() - r.origin.getTime()) / 60000d);
|
||||
double distance = 0;
|
||||
for (int i = 1; i < r.motion.size(); i++) {
|
||||
Coordinate p = r.motion.get(i - 1).getCoordinate();
|
||||
Coordinate c = r.motion.get(i).getCoordinate();
|
||||
distance += HaversineDistance.getDistance(p.getLongitude(), p.getLatitude(), c.getLongitude(), c.getLatitude());
|
||||
}
|
||||
|
||||
double timing = 10;
|
||||
|
||||
double speed = (distance / (duration * 60));
|
||||
if (speed < 2 && distance > 300 && duration > timing) {
|
||||
Double station = Mse.getStationTemperature(r.origin);
|
||||
Double device0 = Mse.getDeviceTemperature(r.origin);
|
||||
|
||||
if (station == null) continue;
|
||||
|
||||
stationMax = Math.max(station, stationMax);
|
||||
stationMin = Math.min(station, stationMin);
|
||||
|
||||
boolean active = false;
|
||||
List<Double> deltaTs = new ArrayList<>();
|
||||
Measurement prev = r.origin;
|
||||
double load = 0;
|
||||
int loadCount = 0;
|
||||
for (Measurement m: r.motion) {
|
||||
double minuteStart = (m.getTime() - r.origin.getTime()) / 60000d;
|
||||
if (minuteStart > timing) break;
|
||||
if (Mse.isActive(m)) active = true;
|
||||
double minutePrev = (m.getTime() - prev.getTime()) / 60000d;
|
||||
double valueCurr = Mse.getDeviceTemperature(m);
|
||||
double valuePrev = Mse.getDeviceTemperature(prev);
|
||||
|
||||
// if (valueCurr > valuePrev) {
|
||||
// active = true;
|
||||
// break;
|
||||
// }
|
||||
|
||||
double changePrev = (valueCurr - valuePrev) / minutePrev;
|
||||
deltaTs.add(changePrev);
|
||||
load += model.load(m);
|
||||
loadCount += 1;
|
||||
prev = m;
|
||||
|
||||
}
|
||||
// System.out.println("Load: " + (load / loadCount));
|
||||
|
||||
if (active) continue;
|
||||
if (deltaTs.isEmpty()) continue;
|
||||
|
||||
double temp = 0;
|
||||
for (Double v: deltaTs) {
|
||||
temp += v;
|
||||
}
|
||||
temp /= deltaTs.size();
|
||||
|
||||
double tempVar = 0;
|
||||
for (double v: deltaTs) {
|
||||
tempVar += (v - temp) * (v - temp);
|
||||
}
|
||||
tempVar = Math.sqrt(tempVar / deltaTs.size());
|
||||
tempVariability.add(tempVar);
|
||||
|
||||
|
||||
stationValues.add(station);
|
||||
|
||||
double dx = Mse.getDeviceTemperature(prev) - Mse.getDeviceTemperature(r.origin);
|
||||
double tx = (60 * timing * 1000d) / (prev.getTime() - r.origin.getTime());
|
||||
|
||||
modelValues.add(new double[] {
|
||||
Mse.getDeviceTemperature(prev),
|
||||
// Mse.getDeviceTemperature(r.origin) + dx * tx
|
||||
//, tempVar
|
||||
//, dx
|
||||
//, load / loadCount
|
||||
});
|
||||
loadValues.add(load / loadCount);
|
||||
|
||||
|
||||
int index = -1;
|
||||
boolean found = false;
|
||||
for (Coordinate c: places) {
|
||||
index += 1;
|
||||
if (HaversineDistance.getDistance(c.getLongitude(), c.getLatitude(), r.origin.getCoordinate().getLongitude(), r.origin.getCoordinate().getLatitude()) < 150) {
|
||||
found = true;
|
||||
break;
|
||||
}
|
||||
}
|
||||
if (!found) {
|
||||
index += 1;
|
||||
places.add(r.origin.getCoordinate());
|
||||
placeMappings.add(new ArrayList<>());
|
||||
}
|
||||
|
||||
|
||||
double[] map = new double[] {
|
||||
station, // - device0,
|
||||
//temp
|
||||
// Mse.getDeviceTemperature(r.origin) + dx * tx
|
||||
Mse.getDeviceTemperature(prev)
|
||||
};
|
||||
|
||||
mapping.add(map);
|
||||
|
||||
// System.out.println((index + ";" + station + ";" + device0 + ";" + (station - device0) + ";" + temp).replace(".", ","));
|
||||
|
||||
|
||||
|
||||
placeMappings.get(index).add(map);
|
||||
lrb.add(map[1], map[0]);
|
||||
counter += 1;
|
||||
//System.out.println(station + ";" + (station - device0) + ";" + (device10 - device0) + ";" + max);
|
||||
// System.out.println(station + " " + device0 + " " + device10);
|
||||
// System.out.println(r.origin.getCoordinate().getLatitude() + ", " + r.origin.getCoordinate().getLongitude());
|
||||
// System.out.println(r.destination.getCoordinate().getLatitude() + ", " + r.destination.getCoordinate().getLongitude());
|
||||
// for (Measurement m: r.motion) {
|
||||
// System.out.println(m.getData().get(MeasurementType.CPU_FREQUENCY));
|
||||
// if (m == ten) break;
|
||||
// }
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
|
||||
|
||||
if (modelValues.size() < 5) return;
|
||||
|
||||
int maxValues = 1000;
|
||||
int offset = 0;
|
||||
|
||||
|
||||
double[] ys = new double[Math.min(stationValues.size(), maxValues)];
|
||||
for (int i = 0; i < ys.length; i++) {
|
||||
ys[i] = stationValues.get(i + offset);
|
||||
}
|
||||
|
||||
double ysmin = ys[0];
|
||||
double ysmax = ys[1];
|
||||
double ysavg = 0;
|
||||
for (int i = 0; i < ys.length; i++) {
|
||||
ysmin = Math.min(ysmin, ys[i]);
|
||||
ysmax = Math.max(ysmax, ys[i]);
|
||||
ysavg = ys[i];
|
||||
}
|
||||
System.out.println("YS: " + ysmin + " " + ysmax + " " + ysavg);
|
||||
|
||||
|
||||
|
||||
|
||||
double[][] xs = new double[ys.length][];
|
||||
for (int i = 0; i < xs.length; i++) {
|
||||
xs[i] = modelValues.get(i + offset);
|
||||
}
|
||||
|
||||
LinearRegression lr = lrb.build();
|
||||
//System.out.println("Device: " + device + " Trips: " + counter + " Correl: " + correlate(mapping) + " temp: " + avg + " places: " + places.size() + " Mae: " + lr.getMae() + " Rmae: " + lr.getMae() / (stationMax - stationMin));
|
||||
|
||||
OLSMultipleLinearRegression regression = new OLSMultipleLinearRegression();
|
||||
regression.newSampleData(ys, xs);
|
||||
System.out.println("Regression params: " + Arrays.toString(regression.estimateRegressionParameters()));
|
||||
double[] residuals = regression.estimateResiduals();
|
||||
double meanError = 0;
|
||||
double rmsError = 0;
|
||||
double maxError = 0;
|
||||
for (int i = 0; i < residuals.length; i++) {
|
||||
meanError += Math.abs(residuals[i]);
|
||||
rmsError += residuals[i] * residuals[i];
|
||||
maxError = Math.max(maxError, Math.abs(residuals[i]));
|
||||
}
|
||||
rmsError = Math.sqrt(rmsError / residuals.length);
|
||||
meanError /= residuals.length;
|
||||
System.out.println("Device: " + device + " Places: " + places.size() + " Trips: " + counter + " Cor: " + correlate(mapping) + " Mae: " + meanError + " Rms: " + rmsError + " Max: " + maxError + " RMae: " + (meanError / (stationMax - stationMin)));
|
||||
int maxPlaces = 0;
|
||||
for (int i = 0; i < placeMappings.size(); i++) {
|
||||
maxPlaces = Math.max(placeMappings.get(i).size(), maxPlaces);
|
||||
}
|
||||
System.out.println("maxplaces: " + maxPlaces);
|
||||
|
||||
List<double[]> resload = new ArrayList<>();
|
||||
for (int i = 0; i < residuals.length; i++) {
|
||||
resload.add(new double[] {
|
||||
residuals[i],
|
||||
loadValues.get(i)
|
||||
});
|
||||
}
|
||||
// System.out.println("Residual load correlation: " + correlate(resload));
|
||||
//
|
||||
// for (int i = 0; i < residuals.length; i++) {
|
||||
// System.out.println((
|
||||
// ys[i] + ";" +
|
||||
// xs[i][0] + ";" +
|
||||
// xs[i][1] + ";" +
|
||||
// residuals[i] + ";" +
|
||||
// loadValues.get(i) + ";" +
|
||||
// tempVariability.get(i)
|
||||
// ).replace(".",","));
|
||||
// }
|
||||
|
||||
|
||||
/*
|
||||
|
||||
int trainCount = 30;
|
||||
int evalCountMin = 20;
|
||||
|
||||
if (mapping.size() > trainCount + evalCountMin) {
|
||||
|
||||
System.out.println("Device: " + device + " Trips: " + counter + " Correl: " + correlate(mapping) + " temp: " + avg + " places: " + places.size() + " Mae: " + lr.getMae() + " Rmae: " + lr.getMae() / (stationMax - stationMin));
|
||||
System.out.println("IC:" + lr.getIntercept() + " Slope: " + lr.getSlope() + " R2:" + lr.getRSquared() + " er: " + lr.getError() + " mae: " + lr.getMae());
|
||||
System.out.println("Smin: " + stationMin + " Smax: " + stationMax);
|
||||
|
||||
LinearRegression.Builder<Double> train = new LinearRegression.Builder<>();
|
||||
for (int i = 0; i < trainCount; i++) {
|
||||
train.add(mapping.get(i)[1], mapping.get(i)[0]);
|
||||
}
|
||||
LinearRegression eval = train.build();
|
||||
double maxError = 0;
|
||||
double maeError = 0;
|
||||
for (int i = trainCount; i < mapping.size(); i++) {
|
||||
double[] v = mapping.get(i);
|
||||
double pred = v[1] * eval.getSlope() + eval.getIntercept();
|
||||
double error = Math.abs(pred - v[0]);
|
||||
maxError = Math.max(error, maxError);
|
||||
maeError += error;
|
||||
}
|
||||
maeError /= mapping.size() - trainCount;
|
||||
System.out.println("Count: " + (mapping.size() - trainCount) + " Mae: " + maeError + " Max: " + maxError);
|
||||
|
||||
|
||||
double guess = 0;
|
||||
for (int i = 0; i < trainCount; i++) {
|
||||
guess += mapping.get(i)[0];
|
||||
}
|
||||
guess /= trainCount;
|
||||
|
||||
double guessMax = 0;
|
||||
double guessMae = 0;
|
||||
for (int i = trainCount; i < mapping.size(); i++) {
|
||||
double[] v = mapping.get(i);
|
||||
double error = Math.abs(guess - v[0]);
|
||||
guessMax = Math.max(error, guessMax);
|
||||
guessMae += error;
|
||||
}
|
||||
guessMae /= mapping.size() - trainCount;
|
||||
System.out.println("Count: " + (mapping.size() - trainCount) + " Mae: " + guessMae + " Max: " + guessMax);
|
||||
|
||||
|
||||
}
|
||||
|
||||
*/
|
||||
|
||||
|
||||
|
||||
}
|
||||
|
||||
|
||||
|
||||
|
||||
public static double correlate(List<double[]> data) {
|
||||
double[] mean = new double[2];
|
||||
for (double[] values: data) {
|
||||
mean[0] += values[0];
|
||||
mean[1] += values[1];
|
||||
}
|
||||
mean[0] /= data.size();
|
||||
mean[1] /= data.size();
|
||||
double product = 0;
|
||||
double var1 = 0;
|
||||
double var2 = 0;
|
||||
for (double[] values: data) {
|
||||
double v1 = values[0] - mean[0];
|
||||
double v2 = values[1] - mean[1];
|
||||
product += v1 * v2;
|
||||
var1 += v1 * v1;
|
||||
var2 += v2 * v2;
|
||||
}
|
||||
//System.out.println("prod: " + product + " v1: " + var1 + " v2: " + var2);
|
||||
|
||||
return product / (Math.sqrt(var1) * Math.sqrt(var2));
|
||||
}
|
||||
|
||||
|
||||
public static void print(List<Double> starts) {
|
||||
double mean = 0;
|
||||
for (Double d: starts) {
|
||||
mean += d;
|
||||
}
|
||||
mean /= starts.size();
|
||||
double dev = 0;
|
||||
for (Double d: starts) {
|
||||
double x = d - mean;
|
||||
dev += x*x;
|
||||
}
|
||||
System.out.println("mean:" + mean + "Dev: " + Math.sqrt(dev / starts.size()));
|
||||
|
||||
}
|
||||
|
||||
|
||||
|
||||
|
||||
}
|
||||
@@ -0,0 +1,228 @@
|
||||
package com.mowesta.tool.paper;
|
||||
|
||||
import java.io.File;
|
||||
import java.text.DateFormat;
|
||||
import java.text.SimpleDateFormat;
|
||||
import java.util.ArrayList;
|
||||
import java.util.Arrays;
|
||||
import java.util.Collections;
|
||||
import java.util.Date;
|
||||
import java.util.HashMap;
|
||||
import java.util.List;
|
||||
import java.util.Locale;
|
||||
import java.util.Map;
|
||||
import java.util.stream.Collectors;
|
||||
|
||||
import com.mowesta.api.Coordinate;
|
||||
import com.mowesta.api.TimeRange;
|
||||
import com.mowesta.api.measurement.Measurement;
|
||||
import com.mowesta.api.measurement.MeasurementType;
|
||||
import com.mowesta.data.process.algorithm.LinearRegression;
|
||||
import com.mowesta.tool.model.MeasurementAnalyzer;
|
||||
|
||||
public class FairExperimentEvaluation {
|
||||
|
||||
|
||||
|
||||
|
||||
public static void main(String[] args) throws Exception {
|
||||
Evaluation eze = new Evaluation();
|
||||
List<Triple> ez = Eiszeit();
|
||||
eze.data.addAll(ez);
|
||||
Evaluation sse = new Evaluation();
|
||||
List<Triple> ss = Schlosslichtspiele();
|
||||
sse.data.addAll(ss);
|
||||
System.out.println("Summer:");
|
||||
sse.print();
|
||||
System.out.println("");
|
||||
System.out.println("Winter:");
|
||||
eze.print();
|
||||
System.out.println("");
|
||||
Evaluation all = new Evaluation();
|
||||
all.data.addAll(ez);
|
||||
all.data.addAll(ss);
|
||||
System.out.println("Combined:");
|
||||
all.print();
|
||||
|
||||
|
||||
|
||||
}
|
||||
|
||||
private static List<Triple> Eiszeit() {
|
||||
List<Triple> result = new ArrayList<>();
|
||||
List<Long> devices = new ArrayList<>();
|
||||
//TimeRange range = new TimeRange(1638572400000l, 24 * 60 * 60000 * 55l);
|
||||
TimeRange range = new TimeRange(1639954800000l, 24 * 60 * 60000 * 14l);
|
||||
|
||||
|
||||
|
||||
//
|
||||
// 8-15 sept
|
||||
// TimeRange range = new TimeRange(1631052000000l, 691200000l);
|
||||
devices.add(41236816l); //hmd
|
||||
devices.add(49610081l); // eisenbahn (winter)
|
||||
|
||||
List<Sample> samples = createSamples(loadDevices(new File("karlsruhe"), devices), range);
|
||||
int incomplete = 0;
|
||||
LinearRegression.Builder<Double> b = new LinearRegression.Builder<>();
|
||||
for (Sample s: samples) {
|
||||
if (s.isComplete(devices)) {
|
||||
System.out.println(s.toString(devices));
|
||||
b.add(s.values.get(41236816l), s.station);//s.values.get(49610081l));
|
||||
Triple t = new Triple();
|
||||
t.station = s.station;
|
||||
t.phone = s.values.get(41236816l);
|
||||
t.sensor = s.values.get(49610081l);
|
||||
result.add(t);
|
||||
|
||||
} else {
|
||||
incomplete += 1;
|
||||
}
|
||||
}
|
||||
System.out.println("Total samples: " + samples.size() + " Incomplete: " + incomplete);
|
||||
LinearRegression r = b.build();
|
||||
System.out.println(r.getIntercept() + " " + r.getSlope() + " " + r.getRSquared() + " " + r.getError() + " MAE: " + r.getMae());
|
||||
return result;
|
||||
}
|
||||
|
||||
|
||||
private static List<Triple> Schlosslichtspiele() {
|
||||
List<Triple> result = new ArrayList<>();
|
||||
List<Long> devices = new ArrayList<>();
|
||||
// TimeRange range = new TimeRange(1629410400000l, 3888000000l);
|
||||
TimeRange range = new TimeRange(1631052000000l, 24 * 60 * 60000 * 14l);
|
||||
//
|
||||
// 8-15 sept
|
||||
// TimeRange range = new TimeRange(1631052000000l, 691200000l);
|
||||
devices.add(41238320l); // hmd
|
||||
devices.add(41307981l); // markt
|
||||
|
||||
List<Sample> samples = createSamples(loadDevices(new File("schlosslichtspiele"), devices), range);
|
||||
int incomplete = 0;
|
||||
LinearRegression.Builder<Double> b = new LinearRegression.Builder<>();
|
||||
for (Sample s: samples) {
|
||||
if (s.isComplete(devices)) {
|
||||
System.out.println(s.toString(devices));
|
||||
b.add(s.values.get(41238320l), s.station); //s.values.get(41307981l));
|
||||
Triple t = new Triple();
|
||||
t.station = s.station;
|
||||
t.phone = s.values.get(41238320l);
|
||||
t.sensor = s.values.get(41307981l);
|
||||
result.add(t);
|
||||
} else {
|
||||
incomplete += 1;
|
||||
}
|
||||
}
|
||||
System.out.println("Total samples: " + samples.size() + " Incomplete: " + incomplete);
|
||||
LinearRegression r = b.build();
|
||||
System.out.println(r.getIntercept() + " " + r.getSlope() + " " + r.getRSquared() + " " + r.getError() + " MAE: " + r.getMae());
|
||||
return result;
|
||||
}
|
||||
|
||||
public static List<List<Measurement>> loadDevices(File folder, List<Long> devices) {
|
||||
List<List<Measurement>> data = new ArrayList<>();
|
||||
devices.forEach((dev)-> data.add(MeasurementAnalyzer.loadMeasurements(new File(folder, "measurement-" + dev + ".json"))));
|
||||
return data;
|
||||
}
|
||||
|
||||
|
||||
public static List<Sample> createSamples(List<List<Measurement>> data, TimeRange range) {
|
||||
List<Sample> samples = new ArrayList<>();
|
||||
data.forEach((dt)-> Collections.sort(dt, (a, b) -> Long.compare(a.getTime(), b.getTime())));
|
||||
long interval = 10 * 60 * 1000;
|
||||
long current = range.getStart();
|
||||
while (current < range.getEnd()) {
|
||||
final long start = current;
|
||||
final long stop = current + interval;
|
||||
Sample sample = new Sample();
|
||||
sample.date = new Date(start);
|
||||
samples.add(sample);
|
||||
data.forEach((dt) -> {
|
||||
List<Measurement> ms = dt.stream().filter(m -> m.getTime() >= start && m.getTime() < stop).collect(Collectors.toList());
|
||||
if (ms.size() > 0) {
|
||||
Coordinate c = ms.get(0).getCoordinate();
|
||||
double temp = ms.get(0).getTemperature();
|
||||
double station = Double.valueOf(ms.get(0).getData().get(MeasurementType.STATION_TEMPERATURE));
|
||||
sample.station = station;
|
||||
sample.addValue(ms.get(0).getDevice(), temp);
|
||||
}
|
||||
});
|
||||
current += interval;
|
||||
}
|
||||
return samples;
|
||||
}
|
||||
|
||||
public static class Sample {
|
||||
|
||||
static DateFormat format = new SimpleDateFormat("YYYY-MM-dd HH:mm");
|
||||
|
||||
Date date;
|
||||
Double station;
|
||||
Map<Long, Double> values = new HashMap<>();
|
||||
|
||||
public void addValue(Long device, Double value) {
|
||||
values.put(device, value);
|
||||
}
|
||||
|
||||
public boolean isComplete(List<Long> devices) {
|
||||
for (Long d: devices) {
|
||||
if (values.get(d) == null)
|
||||
return false;
|
||||
}
|
||||
return station != null;
|
||||
}
|
||||
|
||||
public String toString(List<Long> devices) {
|
||||
StringBuilder b = new StringBuilder();
|
||||
b.append(format.format(date) + ";");
|
||||
b.append(toString(station) + ";");
|
||||
for (Long d: devices) {
|
||||
b.append(toString(values.get(d)) + ";");
|
||||
}
|
||||
return b.toString();
|
||||
}
|
||||
|
||||
public String toString(Double value) {
|
||||
if (value == null) return "";
|
||||
else return String.format(Locale.GERMANY, "%f", value);
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
public static class Triple {
|
||||
public double station;
|
||||
public double sensor;
|
||||
public double phone;
|
||||
}
|
||||
|
||||
public static class Evaluation {
|
||||
public List<Triple> data = new ArrayList<>();
|
||||
|
||||
public void print() {
|
||||
List<double[]> stationVsPhone = new ArrayList<>();
|
||||
List<double[]> stationVsSensor = new ArrayList<>();
|
||||
List<double[]> sensorVsPhone = new ArrayList<>();
|
||||
for (Triple t: data) {
|
||||
stationVsPhone.add(new double[] { t.phone, t.station });
|
||||
stationVsSensor.add(new double[] { t.sensor, t.station });
|
||||
sensorVsPhone.add(new double[] { t.phone, t.sensor });
|
||||
}
|
||||
print("Station vs Phone:", stationVsPhone);
|
||||
print("Station vs Sensor:", stationVsSensor);
|
||||
print("Sensor vs Phone:", sensorVsPhone);
|
||||
}
|
||||
|
||||
public void print(String label, List<double[]> mapping) {
|
||||
System.out.println(label);
|
||||
System.out.println(("Correlation: " + Algo.correlate(mapping)).replace(".", ","));
|
||||
LinearRegression.Builder<Double> builder = new LinearRegression.Builder<>();
|
||||
for (double[] d: mapping) {
|
||||
builder.add(d[0], d[1]);
|
||||
}
|
||||
LinearRegression regression = builder.build();
|
||||
System.out.println(("Regression slope: " + regression.getIntercept() + " Intercept: " + regression.getIntercept() + " R2: " + regression.getRSquared()).replace(".", ","));
|
||||
System.out.println("Errors: " + (Algo.errors(regression, mapping).toString()).replace(".", ","));
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,269 @@
|
||||
package com.mowesta.tool.paper;
|
||||
|
||||
import com.locoslab.library.geometry.wgs.Coordinate;
|
||||
import com.locoslab.library.geometry.wgs.HaversineDistance;
|
||||
import com.locoslab.library.geometry.wgs.MapTile;
|
||||
import com.mowesta.api.measurement.Measurement;
|
||||
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
|
||||
/**
|
||||
* A utility to create trips from sequences of coordinates.
|
||||
*
|
||||
* @author Marcus
|
||||
*/
|
||||
public class LocationClassifier {
|
||||
|
||||
/**
|
||||
* The zoom level for obfuscation.
|
||||
*/
|
||||
public static final int OBFUSCATION_ZOOM_LEVEL = 17;
|
||||
|
||||
/** The duration after which we consider trips with null coordinates to be complete. */
|
||||
public static final double DURATION_BREAK = 1000 * 60 * 60;
|
||||
|
||||
/** The duration after which we detect staying at a particular place (in milliseconds). */
|
||||
public static final double DURATION_VISIT = 1000 * 60 * 10;
|
||||
|
||||
/** The distance at which we consider the user to be at the same place (in meters). */
|
||||
public static final double DISTANCE_VISIT = 150;
|
||||
|
||||
/** The maximum time between the trip origin and the motion used to detect breaks due to privacy mode. */
|
||||
public static final double DURATION_ENDPOINTS = 1000 * 60 * 10;
|
||||
|
||||
/**
|
||||
* Computes the next sequence that constitutes a complete trip. A
|
||||
* complete trip must end at a particular location for the visit
|
||||
* duration.
|
||||
*
|
||||
* @param updates The updates that we want to classify. The updates must
|
||||
* be sorted by time.
|
||||
* @param currentTime The time that we have currently, which is used to identify
|
||||
* trips that have ended, even if we do not have any new coordinates
|
||||
* in the mean time.
|
||||
* @return The next trip.
|
||||
*/
|
||||
public static TripResult computeNextTrip(List<Measurement> updates, long currentTime) {
|
||||
TripResult result = new TripResult();
|
||||
int pos;
|
||||
// find the trip start
|
||||
for (pos = 0; pos < updates.size(); pos++) {
|
||||
Measurement update = updates.get(pos);
|
||||
if (result.origin == null && update.getCoordinate() != null) {
|
||||
result.origin = update;
|
||||
result.start.add(update);
|
||||
} else if (update.getCoordinate() != null) {
|
||||
double distance = HaversineDistance.getDistance(
|
||||
result.origin.getCoordinate().getLongitude(), result.origin.getCoordinate().getLatitude(),
|
||||
update.getCoordinate().getLongitude(), update.getCoordinate().getLatitude());
|
||||
if (distance >= DISTANCE_VISIT) {
|
||||
// pos is now the first coordinate with > 150m distance
|
||||
break;
|
||||
} else {
|
||||
result.start.add(update);
|
||||
}
|
||||
} else {
|
||||
result.start.add(update);
|
||||
}
|
||||
}
|
||||
// find the trip end
|
||||
pos: for (; pos < updates.size(); pos++) {
|
||||
Measurement update = updates.get(pos);
|
||||
if (update.getCoordinate() == null) {
|
||||
result.motion.add(update);
|
||||
} else {
|
||||
for (int i = pos + 1; i < updates.size(); i++) {
|
||||
Measurement next = updates.get(i);
|
||||
if (next.getCoordinate() != null) {
|
||||
double distance = HaversineDistance.getDistance(
|
||||
update.getCoordinate().getLongitude(), update.getCoordinate().getLatitude(),
|
||||
next.getCoordinate().getLongitude(), next.getCoordinate().getLatitude());
|
||||
if (next.getTime() - update.getTime() >= DURATION_VISIT) {
|
||||
// we found a final destination, set the destination
|
||||
// and add the remaining updates to the remainder
|
||||
result.destination = update;
|
||||
result.motion.add(update);
|
||||
for (int j = pos + 1; j < updates.size(); j++) {
|
||||
result.remainder.add(updates.get(j));
|
||||
}
|
||||
return findEndpoints(result);
|
||||
} else if (distance >= DISTANCE_VISIT) {
|
||||
// this is another step that the user made
|
||||
result.motion.add(update);
|
||||
continue pos;
|
||||
}
|
||||
} else if (next.getTime() - update.getTime() >= DURATION_BREAK) {
|
||||
// we break the trip, since there are too many null updates
|
||||
result.destination = update;
|
||||
result.motion.add(update);
|
||||
for (int j = pos + 1; j < updates.size(); j++) {
|
||||
result.remainder.add(updates.get(j));
|
||||
}
|
||||
return findEndpoints(result);
|
||||
}
|
||||
}
|
||||
// we have checked all remaining coordinates and the user stayed here
|
||||
if (currentTime - update.getTime() >= DURATION_VISIT) {
|
||||
// if the current time minus the arrival time is larger than the visit
|
||||
// duration, we can end the trip, even if we do not have any further
|
||||
// coordinates
|
||||
result.destination = update;
|
||||
result.motion.add(update);
|
||||
for (int j = pos + 1; j < updates.size(); j++) {
|
||||
result.remainder.add(updates.get(j));
|
||||
}
|
||||
return findEndpoints(result);
|
||||
} else {
|
||||
// update cannot be classified, we need more data
|
||||
return null;
|
||||
}
|
||||
}
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
/**
|
||||
* Finds the best origin for the trip. This is either the last
|
||||
* coordinate of the start or the first coordinate of the motion,
|
||||
* if the time between the origin and the motion is too high.
|
||||
*
|
||||
* @param result The result to correct.
|
||||
* @return The trip result.
|
||||
*/
|
||||
private static TripResult findEndpoints(TripResult result) {
|
||||
// the first motion exists an has a coordinate
|
||||
Measurement motion = result.motion.get(0);
|
||||
Measurement originCandidate = null;
|
||||
double originDistance = 0;
|
||||
for (int i = result.start.size() - 1; i >= 0; i--) {
|
||||
Measurement u = result.start.get(i);
|
||||
// go back at most 5 minutes in time
|
||||
if (motion.getTime() - u.getTime() > DURATION_ENDPOINTS) {
|
||||
break;
|
||||
}
|
||||
// allow greedy movement that gets closer to origin
|
||||
if (u.getCoordinate() != null) {
|
||||
double d = HaversineDistance.getDistance(u.getCoordinate().getLongitude(), u.getCoordinate().getLatitude(),
|
||||
result.origin.getCoordinate().getLongitude(), result.origin.getCoordinate().getLongitude());
|
||||
if (originCandidate == null || d < originDistance) {
|
||||
originCandidate = u;
|
||||
originDistance = d;
|
||||
} else {
|
||||
// greedy search
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
if (originCandidate != null) {
|
||||
// use the candidate as origin
|
||||
result.origin = originCandidate;
|
||||
} else {
|
||||
// use the first motion as origin
|
||||
result.origin = motion;
|
||||
result.start.add(motion);
|
||||
result.motion.remove(0);
|
||||
}
|
||||
// move the destination to the farest point
|
||||
double destinationDistance = 0;
|
||||
Measurement destinationCandidate = null;
|
||||
for (int i = 0; i < result.remainder.size(); i++) {
|
||||
Measurement u = result.remainder.get(i);
|
||||
// go forward at most 5 minutes in time
|
||||
if (u.getTime() - result.destination.getTime() > DURATION_ENDPOINTS) {
|
||||
break;
|
||||
}
|
||||
// allow greedy movements that move further away
|
||||
if (u.getCoordinate() != null) {
|
||||
double d = HaversineDistance.getDistance(
|
||||
u.getCoordinate().getLongitude(), u.getCoordinate().getLatitude(),
|
||||
result.destination.getCoordinate().getLongitude(),
|
||||
result.destination.getCoordinate().getLatitude()
|
||||
);
|
||||
if (destinationCandidate == null || d > destinationDistance) {
|
||||
destinationCandidate = u;
|
||||
destinationDistance = d;
|
||||
} else {
|
||||
// greedy condition
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
if (destinationCandidate != null) {
|
||||
result.destination = destinationCandidate;
|
||||
while (true) {
|
||||
Measurement u = result.remainder.remove(0);
|
||||
result.motion.add(u);
|
||||
if (u == destinationCandidate) {
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
return result;
|
||||
}
|
||||
|
||||
|
||||
public static class TripResult {
|
||||
/** The device update representing the first origin coordinate. */
|
||||
public Measurement origin = null;
|
||||
/** The device update representing the first destination coordinate. */
|
||||
public Measurement destination = null;
|
||||
/** The coordinate at the origin or null. */
|
||||
public List<Measurement> start = new ArrayList<>();
|
||||
/** The coordinates that are in motion. */
|
||||
public List<Measurement> motion = new ArrayList<>();
|
||||
/** The unclassified remainder. */
|
||||
public List<Measurement> remainder = new ArrayList<>();
|
||||
|
||||
public double getDistance() {
|
||||
double result = 0;
|
||||
Measurement p = origin;
|
||||
for (Measurement m: motion) {
|
||||
result += HaversineDistance.getDistance(p.getCoordinate().getLongitude(), p.getCoordinate().getLatitude(),
|
||||
m.getCoordinate().getLongitude(), m.getCoordinate().getLatitude());
|
||||
p = m;
|
||||
}
|
||||
result += HaversineDistance.getDistance(p.getCoordinate().getLongitude(), p.getCoordinate().getLatitude(),
|
||||
destination.getCoordinate().getLongitude(), destination.getCoordinate().getLatitude());
|
||||
return result;
|
||||
}
|
||||
|
||||
public long getDuration() {
|
||||
return destination.getTime() - origin.getTime();
|
||||
}
|
||||
|
||||
public double getSpeed() {
|
||||
long duration = getDuration();
|
||||
if (duration == 0) return 0;
|
||||
return getDistance() / (duration / 1000d);
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
|
||||
/**
|
||||
* Returns the map tile for the update.
|
||||
*
|
||||
* @param u The update.
|
||||
* @return The map tile
|
||||
*/
|
||||
public static MapTile getMapTile(Measurement u) {
|
||||
return MapTile.getMapTile(u.getCoordinate().getLongitude(), u.getCoordinate().getLatitude(), OBFUSCATION_ZOOM_LEVEL);
|
||||
}
|
||||
|
||||
/**
|
||||
* Determines whether the coordinate of the update is on the tile.
|
||||
* If the update has no coordinate, we consider this to be true.
|
||||
*
|
||||
* @param u The update.
|
||||
* @param tile The tile.
|
||||
* @return True if the update is on the tile.
|
||||
*/
|
||||
public static boolean isOnTile(Measurement u, MapTile tile) {
|
||||
if (u.getCoordinate() == null) return true;
|
||||
else return getMapTile(u).equals(tile);
|
||||
}
|
||||
|
||||
|
||||
|
||||
}
|
||||
@@ -0,0 +1,95 @@
|
||||
package com.mowesta.tool.paper;
|
||||
|
||||
import com.mowesta.api.measurement.Measurement;
|
||||
import com.mowesta.api.measurement.MeasurementType;
|
||||
|
||||
public class Mse {
|
||||
|
||||
|
||||
public static Double getDeviceTemperature(Measurement m) {
|
||||
String v = m.getData().get(MeasurementType.BATTERY_TEMPERATURE);
|
||||
if (v == null) return null;
|
||||
return Double.valueOf(v);
|
||||
}
|
||||
|
||||
public static Double getStationTemperature(Measurement m) {
|
||||
String v = m.getData().get(MeasurementType.STATION_TEMPERATURE);
|
||||
if (v == null) return null;
|
||||
return Double.valueOf(v);
|
||||
|
||||
}
|
||||
|
||||
public static Double getDevicePressure(Measurement m) {
|
||||
String v = m.getData().get(MeasurementType.SENSOR_PRESSURE);
|
||||
if (v == null) return null;
|
||||
return Double.valueOf(v);
|
||||
}
|
||||
|
||||
public static Double getStationPressure(Measurement m) {
|
||||
String v = m.getData().get(MeasurementType.STATION_PRESSURE);
|
||||
if (v == null) return null;
|
||||
return Double.valueOf(v);
|
||||
}
|
||||
|
||||
public static Boolean isActive(Measurement m) {
|
||||
String v = m.getData().get(MeasurementType.SCREEN_ENABLED);
|
||||
if (v == null) return null;
|
||||
return Boolean.valueOf(v);
|
||||
}
|
||||
|
||||
public static Boolean isCharging(Measurement m) {
|
||||
String v = m.getData().get(MeasurementType.BATTERY_CHARGING);
|
||||
if (v == null) return null;
|
||||
return Boolean.valueOf(v);
|
||||
}
|
||||
|
||||
public static Double getMaxCpuFreq(Measurement m) {
|
||||
String v = m.getData().get(MeasurementType.CPU_FREQUENCY);
|
||||
if (v == null) return null;
|
||||
String[] tokens = v.split(",");
|
||||
double max = 0;
|
||||
for (String t: tokens) {
|
||||
max = Math.max(max, Double.valueOf(t));
|
||||
}
|
||||
return max;
|
||||
}
|
||||
|
||||
public static Double getMinCpuFreq(Measurement m) {
|
||||
String v = m.getData().get(MeasurementType.CPU_FREQUENCY);
|
||||
if (v == null) return null;
|
||||
String[] tokens = v.split(",");
|
||||
double min = Double.MAX_VALUE;
|
||||
for (String t: tokens) {
|
||||
min = Math.min(min, Double.valueOf(t));
|
||||
}
|
||||
return min;
|
||||
}
|
||||
|
||||
public static double[] getCpuFreq(Measurement m) {
|
||||
String v = m.getData().get(MeasurementType.CPU_FREQUENCY);
|
||||
if (v == null) return null;
|
||||
String[] tokens = v.split(",");
|
||||
double[] result = new double[tokens.length];
|
||||
for (int i = 0; i < tokens.length; i++)
|
||||
result[i] = Double.valueOf(tokens[i]);
|
||||
return result;
|
||||
}
|
||||
|
||||
public static Double getAverageCpuFreq(Measurement m) {
|
||||
String v = m.getData().get(MeasurementType.CPU_FREQUENCY);
|
||||
if (v == null) return null;
|
||||
String[] tokens = v.split(",");
|
||||
double sum = 0;
|
||||
for (String t: tokens) {
|
||||
sum += Double.valueOf(t);
|
||||
}
|
||||
return sum / tokens.length;
|
||||
}
|
||||
|
||||
public static Double getBuildingDistance(Measurement m) {
|
||||
String v = m.getData().get(MeasurementType.BUILDING_DISTANCE);
|
||||
if (v == null) return null;
|
||||
return Double.valueOf(v);
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,83 @@
|
||||
package com.mowesta.tool.paper;
|
||||
|
||||
import java.io.IOException;
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
|
||||
import weka.classifiers.Classifier;
|
||||
import weka.classifiers.Evaluation;
|
||||
import weka.classifiers.trees.J48;
|
||||
import weka.classifiers.trees.REPTree;
|
||||
import weka.core.Attribute;
|
||||
import weka.core.DenseInstance;
|
||||
import weka.core.Instance;
|
||||
import weka.core.Instances;
|
||||
|
||||
public class WekaTester {
|
||||
|
||||
public static void evaluate(List<double[]> values, int split) throws Exception {
|
||||
if (values.isEmpty() || values.size() < split) return;
|
||||
int count = values.get(0).length;
|
||||
ArrayList<Attribute> list = new ArrayList<>();
|
||||
for (int i = 0; i < count; i++) {
|
||||
list.add(new Attribute("A" + i));
|
||||
}
|
||||
Instances trainingDataSet = new Instances("Temperature", list, 0);
|
||||
trainingDataSet.setClassIndex(0);
|
||||
|
||||
for (int j = 0; j < (split>0?split:values.size()); j++) {
|
||||
double[] v = values.get(j);
|
||||
Instance instance = new DenseInstance(count);
|
||||
for (int i = 0; i < count; i++) {
|
||||
instance.setValue(list.get(i), v[i]);
|
||||
}
|
||||
trainingDataSet.add(instance);
|
||||
}
|
||||
|
||||
Instances testingDataSet = new Instances("Temperature", list, 0);
|
||||
testingDataSet.setClassIndex(0);
|
||||
|
||||
if (split > 0) {
|
||||
for (int j = split; j < values.size();j++) {
|
||||
double[] v = values.get(j);
|
||||
Instance instance = new DenseInstance(count);
|
||||
for (int i = 0; i < count; i++) {
|
||||
instance.setValue(list.get(i), v[i]);
|
||||
}
|
||||
testingDataSet.add(instance);
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
/** Classifier here is Linear Regression */
|
||||
Classifier classifier = new REPTree();
|
||||
|
||||
//J48,Id3
|
||||
/** */
|
||||
classifier.buildClassifier(trainingDataSet);
|
||||
/**
|
||||
* train the alogorithm with the training data and evaluate the
|
||||
* algorithm with testing data
|
||||
*/
|
||||
Evaluation eval = new Evaluation(split>0?testingDataSet:trainingDataSet);
|
||||
if (split > 0) {
|
||||
eval.evaluateModel(classifier, testingDataSet);
|
||||
} else {
|
||||
eval.evaluateModel(classifier, trainingDataSet);
|
||||
}
|
||||
/** Print the algorithm summary */
|
||||
System.out.println("** Decision Tress Evaluation with Datasets **");
|
||||
System.out.println(eval.toSummaryString());
|
||||
//System.out.print(" the expression for the input data as per alogorithm is ");
|
||||
//System.out.println(classifier);
|
||||
//System.out.println(eval.toMatrixString());
|
||||
//System.out.println(eval.toClassDetailsString());
|
||||
|
||||
|
||||
}
|
||||
|
||||
|
||||
}
|
||||
@@ -10,8 +10,8 @@ dependencies {
|
||||
}
|
||||
|
||||
node {
|
||||
version = '10.16.0'
|
||||
npmVersion = '6.9.0'
|
||||
version = '16.16.0'
|
||||
npmVersion = '8.11.0'
|
||||
download = true
|
||||
}
|
||||
|
||||
|
||||
@@ -35,7 +35,7 @@
|
||||
"document-register-element": "^1.7.2",
|
||||
"jszip": "^3.2.2",
|
||||
"leaflet": "1.6.0",
|
||||
"ngx-gauge": "^1.1.0",
|
||||
"ngx-gauge": "^3.0.0",
|
||||
"rxjs": "^6.6.3",
|
||||
"tslib": "^2.0.0",
|
||||
"zone.js": "~0.10.3"
|
||||
|
||||
Reference in New Issue
Block a user