Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
326e56a24c | ||
|
|
6f388520f5 | ||
|
|
c8a52eec58 | ||
|
|
e568f43dd7 | ||
|
|
22ccdd21ac |
Vendored
+1
-1
@@ -49,7 +49,7 @@ node {
|
||||
if (env.BRANCH_NAME == "master" && release) {
|
||||
echo "Deploying to production server ..."
|
||||
withCredentials([sshUserPrivateKey(credentialsId: "mowesta-server-key", keyFileVariable: "KEYFILE")]) {
|
||||
sh 'scp -i $KEYFILE site-ear/build/libs/site-ear-' + version + '.ear wildfly@apps-pro.nes.uni-due.de:/opt/wildfly-21-mowesta/standalone/deployments/mowesta.ear'
|
||||
// sh 'scp -i $KEYFILE site-ear/build/libs/site-ear-' + version + '.ear wildfly@apps-pro.nes.uni-due.de:/opt/wildfly-21-mowesta/standalone/deployments/mowesta.ear'
|
||||
sh 'scp -i $KEYFILE android-app/build/outputs/apk/prod/release/*.apk wildfly@apps-pro.nes.uni-due.de:/opt/android/mowesta/'
|
||||
}
|
||||
} else if (env.BRANCH_NAME == "master" || env.BRANCH_NAME == "feat/auth") {
|
||||
|
||||
@@ -100,7 +100,7 @@ android {
|
||||
applicationId "com.mowesta.android.app"
|
||||
minSdkVersion 19
|
||||
targetSdkVersion 30
|
||||
versionCode 19
|
||||
versionCode 20
|
||||
versionName "${versionApp}"
|
||||
buildConfigField "long", "BUILD_TIME", System.currentTimeMillis() + "L"
|
||||
testInstrumentationRunner "androidx.test.runner.AndroidJUnitRunner"
|
||||
|
||||
Binary file not shown.
@@ -1,10 +1,15 @@
|
||||
package com.mowesta.android.app;
|
||||
|
||||
import android.Manifest;
|
||||
import android.app.Activity;
|
||||
import android.app.Dialog;
|
||||
import android.content.DialogInterface;
|
||||
import android.content.Intent;
|
||||
import android.content.SharedPreferences.OnSharedPreferenceChangeListener;
|
||||
import android.content.pm.PackageManager;
|
||||
import android.net.Uri;
|
||||
import android.net.http.HttpResponseCache;
|
||||
import android.os.Build;
|
||||
import android.os.Bundle;
|
||||
import android.provider.Settings;
|
||||
import android.util.Log;
|
||||
@@ -14,8 +19,12 @@ import androidx.annotation.NonNull;
|
||||
import androidx.annotation.Nullable;
|
||||
import androidx.appcompat.app.AppCompatActivity;
|
||||
import androidx.core.app.ActivityCompat;
|
||||
import androidx.fragment.app.DialogFragment;
|
||||
import androidx.navigation.NavController;
|
||||
import androidx.navigation.NavDirections;
|
||||
import androidx.navigation.Navigation;
|
||||
|
||||
import com.google.android.material.dialog.MaterialAlertDialogBuilder;
|
||||
import com.google.android.material.snackbar.Snackbar;
|
||||
import com.mowesta.android.app.database.FavoriteDatabase;
|
||||
import com.mowesta.android.app.repository.UserCredentials;
|
||||
@@ -24,6 +33,8 @@ 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.feign.api.DefaultApi;
|
||||
import com.mowesta.android.sdk.SdkRepository;
|
||||
import com.mowesta.android.sdk.task.ClearTask;
|
||||
|
||||
import java.io.File;
|
||||
import java.io.IOException;
|
||||
@@ -48,9 +59,15 @@ public class MowestaActivity extends AppCompatActivity {
|
||||
private static final int DELAY_REFRESH = 15 * 60 * 1000;
|
||||
|
||||
/**
|
||||
* The code used to request the permissions.
|
||||
* The code used to request the permission for localizing in the foreground.
|
||||
*/
|
||||
private static final int CODE_REQUEST_PERMISSIONS = 3334;
|
||||
public static final int CODE_REQUEST_FOREGROUND_PERMISSIONS = 3334;
|
||||
|
||||
/**
|
||||
* The code used to request the permission for localizing in the background.
|
||||
*/
|
||||
private static final int CODE_REQUEST_BACKGROUND_PERMISSIONS = 3335;
|
||||
|
||||
|
||||
/**
|
||||
* The preferences.
|
||||
@@ -121,15 +138,31 @@ public class MowestaActivity extends AppCompatActivity {
|
||||
@Override
|
||||
protected void onNewIntent(Intent intent) {
|
||||
super.onNewIntent(intent);
|
||||
// got to navigation drawer when user presses notification
|
||||
setIntent(intent);
|
||||
Navigation.findNavController(this, R.id.navigation_app).navigate(R.id.action_drawer);
|
||||
|
||||
}
|
||||
|
||||
// got to navigation drawer when user presses notification
|
||||
private void handleNotificationIntent() {
|
||||
Intent intent = getIntent();
|
||||
if (intent.hasExtra(getString(R.string.mowesta_sdk_notification_activity_extra_name))) {
|
||||
String value = intent.getStringExtra(getString(R.string.mowesta_sdk_notification_activity_extra_name));
|
||||
if (value != null && value.equals(getString(R.string.mowesta_sdk_notification_activity_extra_value))) {
|
||||
NavController controller = Navigation.findNavController(this, R.id.navigation_app);
|
||||
if (controller.getGraph().getId() == R.id.navigation_core) {
|
||||
controller.navigate(R.id.action_drawer);
|
||||
} else {
|
||||
controller.navigate(R.id.action_core);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
protected void onResume() {
|
||||
super.onResume();
|
||||
settings.getPreferences().registerOnSharedPreferenceChangeListener(preferenceListener);
|
||||
handleNotificationIntent();
|
||||
}
|
||||
|
||||
@Override
|
||||
@@ -174,16 +207,11 @@ public class MowestaActivity extends AppCompatActivity {
|
||||
*/
|
||||
public void requestPermissions() {
|
||||
Log.d(TAG, "Requesting permissions.");
|
||||
requestPermissions(PermissionUtil.getNonGrantedBackgroundPermissions(this));
|
||||
}
|
||||
|
||||
/**
|
||||
* Requests the permissions.
|
||||
*
|
||||
* @param permissions The permissions to request.
|
||||
*/
|
||||
public void requestPermissions(String[] permissions) {
|
||||
ActivityCompat.requestPermissions(this, permissions, CODE_REQUEST_PERMISSIONS);
|
||||
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);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -197,7 +225,8 @@ 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_PERMISSIONS: {
|
||||
case CODE_REQUEST_BACKGROUND_PERMISSIONS:
|
||||
case CODE_REQUEST_FOREGROUND_PERMISSIONS: {
|
||||
boolean granted = true;
|
||||
StringBuilder b = new StringBuilder();
|
||||
for (int i = 0, s = Math.min(permissions.length, grantResults.length); i < s; i++) {
|
||||
@@ -208,9 +237,10 @@ public class MowestaActivity extends AppCompatActivity {
|
||||
Log.d(TAG, "Permission result: " + b.toString());
|
||||
if (!granted) {
|
||||
settings.setPrivacyMeasure(false);
|
||||
showMissingPermission();
|
||||
} else {
|
||||
MowestaService.startService(this);
|
||||
showMissingPermission(requestCode == CODE_REQUEST_FOREGROUND_PERMISSIONS);
|
||||
} else if (requestCode == CODE_REQUEST_BACKGROUND_PERMISSIONS){
|
||||
if (!PermissionUtil.hasBackgroundPermissions(this)) requestPermissions();
|
||||
else MowestaService.startService(this);
|
||||
}
|
||||
break;
|
||||
}
|
||||
@@ -222,22 +252,61 @@ public class MowestaActivity extends AppCompatActivity {
|
||||
/**
|
||||
* Shows a snackbar indicating a missing permission.
|
||||
*/
|
||||
public void showMissingPermission() {
|
||||
View coordinator = findViewById(R.id.layout_coordinator);
|
||||
Snackbar.make(coordinator, R.string.message_no_permission, Snackbar.LENGTH_LONG )
|
||||
.setAction(R.string.button_configure, (view) -> {
|
||||
// go to app settings
|
||||
public void showMissingPermission(boolean foreground) {
|
||||
PermissionDialogFragment pdf = PermissionDialogFragment.newInstance(foreground);
|
||||
pdf.show(getSupportFragmentManager(), "permissions");
|
||||
}
|
||||
|
||||
|
||||
|
||||
/**
|
||||
* A dialog fragment to explain the need for permissions.
|
||||
*
|
||||
* @author Marcus
|
||||
*/
|
||||
public static class PermissionDialogFragment extends DialogFragment {
|
||||
|
||||
private static final String KEY_FOREGROUND = "foreground";
|
||||
|
||||
public static PermissionDialogFragment newInstance(boolean foreground) {
|
||||
PermissionDialogFragment f = new PermissionDialogFragment();
|
||||
Bundle b = new Bundle();
|
||||
b.putBoolean(KEY_FOREGROUND, foreground);
|
||||
f.setArguments(b);
|
||||
return f;
|
||||
}
|
||||
|
||||
@NonNull
|
||||
@Override
|
||||
public Dialog onCreateDialog(@Nullable Bundle savedInstanceState) {
|
||||
MaterialAlertDialogBuilder b = new MaterialAlertDialogBuilder(getActivity());
|
||||
b.setTitle(R.string.message_permission_title);
|
||||
b.setMessage(isForeground()?R.string.message_permission_foreground:R.string.message_permission_background);
|
||||
b.setIcon(R.drawable.ic_gps_off_normal_24);
|
||||
b.setNeutralButton(R.string.button_configure, new DialogInterface.OnClickListener() {
|
||||
@Override
|
||||
public void onClick(DialogInterface dialog, int which) {
|
||||
Intent intent = new Intent(Settings.ACTION_APPLICATION_DETAILS_SETTINGS);
|
||||
intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
|
||||
Uri uri = Uri.fromParts("package", getPackageName(), null);
|
||||
Uri uri = Uri.fromParts("package", getActivity().getPackageName(), null);
|
||||
intent.setData(uri);
|
||||
try {
|
||||
startActivity(intent);
|
||||
} catch (Exception e) {
|
||||
View coordinator = getActivity().findViewById(R.id.layout_coordinator);
|
||||
Snackbar.make(coordinator, R.string.message_configure_failed,
|
||||
Snackbar.LENGTH_SHORT).show();
|
||||
}
|
||||
}).show();
|
||||
}
|
||||
});
|
||||
return b.show();
|
||||
}
|
||||
|
||||
private boolean isForeground() {
|
||||
Bundle b = getArguments();
|
||||
return b.getBoolean(KEY_FOREGROUND, false);
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
}
|
||||
|
||||
+96
@@ -0,0 +1,96 @@
|
||||
package com.mowesta.android.app.fragment;
|
||||
|
||||
import android.app.Dialog;
|
||||
import android.content.ActivityNotFoundException;
|
||||
import android.content.Context;
|
||||
import android.content.DialogInterface;
|
||||
import android.content.Intent;
|
||||
import android.content.SharedPreferences;
|
||||
import android.net.Uri;
|
||||
import android.os.Bundle;
|
||||
import android.view.LayoutInflater;
|
||||
import android.view.View;
|
||||
import android.view.ViewGroup;
|
||||
import android.widget.FrameLayout;
|
||||
|
||||
import androidx.annotation.NonNull;
|
||||
import androidx.annotation.Nullable;
|
||||
import androidx.databinding.DataBindingUtil;
|
||||
import androidx.fragment.app.Fragment;
|
||||
import androidx.lifecycle.ViewModelProvider;
|
||||
import androidx.preference.PreferenceManager;
|
||||
|
||||
import com.google.android.material.bottomsheet.BottomSheetBehavior;
|
||||
import com.google.android.material.bottomsheet.BottomSheetDialog;
|
||||
import com.google.android.material.bottomsheet.BottomSheetDialogFragment;
|
||||
import com.google.android.material.snackbar.Snackbar;
|
||||
import com.mowesta.android.app.R;
|
||||
import com.mowesta.android.app.databinding.DialogAdvertiseBinding;
|
||||
import com.mowesta.android.app.model.AdvertiseViewModel;
|
||||
|
||||
public class AdvertiseDialogFragment extends BottomSheetDialogFragment {
|
||||
|
||||
public static final String KEY_ADVERTISEMENT = "advertisement";
|
||||
|
||||
@NonNull
|
||||
@Override
|
||||
public Dialog onCreateDialog(@Nullable Bundle savedInstanceState) {
|
||||
Dialog dialog = super.onCreateDialog(savedInstanceState);
|
||||
|
||||
dialog.setOnShowListener(new DialogInterface.OnShowListener() {
|
||||
@Override
|
||||
public void onShow(DialogInterface dialog) {
|
||||
BottomSheetDialog d = (BottomSheetDialog) dialog;
|
||||
FrameLayout bottomSheet = (FrameLayout) d.findViewById(com.google.android.material.R.id.design_bottom_sheet);
|
||||
BottomSheetBehavior.from(bottomSheet).setState(BottomSheetBehavior.STATE_EXPANDED);
|
||||
}
|
||||
});
|
||||
return dialog;
|
||||
}
|
||||
|
||||
@Nullable
|
||||
@Override
|
||||
public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
|
||||
DialogAdvertiseBinding binding = DataBindingUtil.inflate(inflater, R.layout.dialog_advertise, container, false);
|
||||
AdvertiseViewModel model = new ViewModelProvider(this).get(AdvertiseViewModel.class);
|
||||
binding.setModel(model);
|
||||
binding.setLifecycleOwner(getViewLifecycleOwner());
|
||||
binding.videoView.setPlayer(model.getExoPlayer());
|
||||
model.getClose().observe(getViewLifecycleOwner(), (v) -> { if (v) this.dismiss(); } );
|
||||
model.getOpen().observe(getViewLifecycleOwner(), (v) -> {
|
||||
if (v) {
|
||||
String url = "https://www.mowesta.com/2021/08/21/fair-experiment-bei-den-schlosslichtspielen-in-karlsruhe/";
|
||||
Intent i = new Intent(Intent.ACTION_VIEW);
|
||||
i.setData(Uri.parse(url));
|
||||
try {
|
||||
startActivity(i);
|
||||
} catch (ActivityNotFoundException e) {
|
||||
Snackbar.make(getView(), R.string.message_no_browser, Snackbar.LENGTH_SHORT).show();
|
||||
}
|
||||
model.getOpen().setValue(Boolean.FALSE);
|
||||
}
|
||||
});
|
||||
return binding.getRoot();
|
||||
}
|
||||
|
||||
|
||||
public boolean shouldShow(Context context) {
|
||||
long time = System.currentTimeMillis();
|
||||
if (time > 1633298400000l) return false;
|
||||
SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(context);
|
||||
long last = prefs.getLong(KEY_ADVERTISEMENT, 0);
|
||||
return (time - last > 7 * 24* 60 * 60 * 1000);
|
||||
}
|
||||
|
||||
@Override
|
||||
public void onDismiss(@NonNull DialogInterface dialog) {
|
||||
super.onDismiss(dialog);
|
||||
Context context = getActivity();
|
||||
if (context != null) {
|
||||
SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(context);
|
||||
SharedPreferences.Editor e = prefs.edit();
|
||||
e.putLong(KEY_ADVERTISEMENT, System.currentTimeMillis());
|
||||
e.apply();
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -9,6 +9,8 @@ import android.database.AbstractCursor;
|
||||
import android.database.Cursor;
|
||||
import android.net.Uri;
|
||||
import android.os.Bundle;
|
||||
import android.os.Handler;
|
||||
import android.os.Looper;
|
||||
import android.view.LayoutInflater;
|
||||
import android.view.Menu;
|
||||
import android.view.MenuInflater;
|
||||
@@ -85,17 +87,21 @@ public class DrawerFragment extends AbstractNetworkFragment {
|
||||
@Override
|
||||
public void onResume() {
|
||||
super.onResume();
|
||||
preventSplashScreen();
|
||||
handleNotificationIntent();
|
||||
if (!preventSplashScreen()) {
|
||||
handleNotificationIntent();
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Prevent going back to the splash screen if opened through deep link.
|
||||
*/
|
||||
private void preventSplashScreen() {
|
||||
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;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -108,8 +114,8 @@ public class DrawerFragment extends AbstractNetworkFragment {
|
||||
if (intent.hasExtra(getString(R.string.mowesta_sdk_notification_activity_extra_name))) {
|
||||
String value = intent.getStringExtra(getString(R.string.mowesta_sdk_notification_activity_extra_name));
|
||||
if (value != null && value.equals(getString(R.string.mowesta_sdk_notification_activity_extra_value))) {
|
||||
Navigation.findNavController(getView().findViewById(R.id.navigation_drawer)).navigate(R.id.destination_settings);
|
||||
getActivity().setIntent(new Intent());
|
||||
Navigation.findNavController(getView().findViewById(R.id.navigation_drawer)).navigate(R.id.destination_settings);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -44,6 +44,11 @@ public class FavoritesFragment extends Fragment {
|
||||
public void onCreate(@Nullable Bundle savedInstanceState) {
|
||||
super.onCreate(savedInstanceState);
|
||||
setHasOptionsMenu(true);
|
||||
// possibly show the ad for schlosslichtspiele
|
||||
AdvertiseDialogFragment adf = new AdvertiseDialogFragment();
|
||||
if (adf.shouldShow(getContext())) {
|
||||
adf.show(getChildFragmentManager(), "ad");
|
||||
}
|
||||
}
|
||||
|
||||
@Nullable
|
||||
|
||||
@@ -17,6 +17,7 @@ import android.view.animation.OvershootInterpolator;
|
||||
|
||||
import androidx.annotation.NonNull;
|
||||
import androidx.annotation.Nullable;
|
||||
import androidx.core.app.ActivityCompat;
|
||||
import androidx.databinding.DataBindingUtil;
|
||||
import androidx.fragment.app.Fragment;
|
||||
import androidx.lifecycle.ViewModelProvider;
|
||||
@@ -66,7 +67,7 @@ public class SetupFragment extends Fragment {
|
||||
SetupViewModel.GpsStatus status = model.registerGpsReceiver();
|
||||
switch (status) {
|
||||
case PROHIBITED:
|
||||
((MowestaActivity)getActivity()).requestPermissions(PermissionUtil.getForegroundPermissions(getActivity()));
|
||||
ActivityCompat.requestPermissions(getActivity(), PermissionUtil.getForegroundPermissions(getActivity()), MowestaActivity.CODE_REQUEST_FOREGROUND_PERMISSIONS);
|
||||
break;
|
||||
case DISABLED:
|
||||
Snackbar.make(container, R.string.setup_error_gps_disabled, Snackbar.LENGTH_LONG).setAction(R.string.button_configure, (v) -> {
|
||||
|
||||
@@ -0,0 +1,66 @@
|
||||
package com.mowesta.android.app.model;
|
||||
|
||||
import android.app.Application;
|
||||
|
||||
import androidx.lifecycle.AndroidViewModel;
|
||||
import androidx.lifecycle.MutableLiveData;
|
||||
|
||||
import com.google.android.exoplayer2.ExoPlayer;
|
||||
import com.google.android.exoplayer2.MediaItem;
|
||||
import com.google.android.exoplayer2.SimpleExoPlayer;
|
||||
import com.google.android.exoplayer2.source.MediaSource;
|
||||
import com.google.android.exoplayer2.source.ProgressiveMediaSource;
|
||||
import com.google.android.exoplayer2.upstream.AssetDataSource;
|
||||
import com.google.android.exoplayer2.upstream.DataSource;
|
||||
|
||||
public class AdvertiseViewModel extends AndroidViewModel {
|
||||
|
||||
private ExoPlayer exoPlayer;
|
||||
|
||||
private MutableLiveData<Boolean> close = new MutableLiveData<>(Boolean.FALSE);
|
||||
|
||||
private MutableLiveData<Boolean> open = new MutableLiveData<>(Boolean.FALSE);
|
||||
|
||||
public AdvertiseViewModel(Application app) {
|
||||
super(app);
|
||||
SimpleExoPlayer.Builder builder = new SimpleExoPlayer.Builder(app);
|
||||
exoPlayer = builder.build();
|
||||
DataSource.Factory df = new DataSource.Factory() {
|
||||
@Override
|
||||
public DataSource createDataSource() {
|
||||
return new AssetDataSource(app);
|
||||
}
|
||||
};
|
||||
MediaSource videoSource = new ProgressiveMediaSource.Factory(df)
|
||||
.createMediaSource(MediaItem.fromUri("android_assets:///schlosslichtspiele.mp4"));
|
||||
exoPlayer.setRepeatMode(ExoPlayer.REPEAT_MODE_ALL);
|
||||
exoPlayer.setMediaSource(videoSource);
|
||||
exoPlayer.prepare();
|
||||
exoPlayer.setPlayWhenReady(true);
|
||||
}
|
||||
|
||||
public MutableLiveData<Boolean> getClose() {
|
||||
return close;
|
||||
}
|
||||
|
||||
public MutableLiveData<Boolean> getOpen() {
|
||||
return open;
|
||||
}
|
||||
|
||||
public void close() {
|
||||
close.setValue(Boolean.TRUE);
|
||||
}
|
||||
|
||||
public void open() {
|
||||
open.setValue(Boolean.TRUE);
|
||||
}
|
||||
|
||||
public ExoPlayer getExoPlayer() {
|
||||
return exoPlayer;
|
||||
}
|
||||
|
||||
@Override
|
||||
protected void onCleared() {
|
||||
exoPlayer.stop();
|
||||
}
|
||||
}
|
||||
@@ -355,16 +355,22 @@ public class SetupViewModel extends AndroidViewModel {
|
||||
|
||||
private Double parseValue(String value) {
|
||||
if (value == null) return null;
|
||||
value = value.trim();
|
||||
LocaleListCompat c = ConfigurationCompat.getLocales(getApplication().getResources().getConfiguration());
|
||||
for (int i = 0; i < c.size(); i++) {
|
||||
Locale l = c.get(i);
|
||||
NumberFormat f = NumberFormat.getNumberInstance(l);
|
||||
try {
|
||||
return ((Number)f.parseObject(value.trim())).doubleValue();
|
||||
return ((Number)f.parseObject(value)).doubleValue();
|
||||
} catch (ParseException e) {
|
||||
Log.d(TAG, "Failed to parse double from: " + value);
|
||||
}
|
||||
}
|
||||
try {
|
||||
return Double.parseDouble(value.replace(',', '.'));
|
||||
} catch (NumberFormatException e) {
|
||||
Log.d(TAG, "Failed to parse double, giving up: " + value);
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
|
||||
@@ -0,0 +1,10 @@
|
||||
<vector xmlns:android="http://schemas.android.com/apk/res/android"
|
||||
android:width="24dp"
|
||||
android:height="24dp"
|
||||
android:viewportWidth="24"
|
||||
android:viewportHeight="24"
|
||||
android:tint="?attr/colorControlNormal">
|
||||
<path
|
||||
android:fillColor="@android:color/white"
|
||||
android:pathData="M20.94,11c-0.46,-4.17 -3.77,-7.48 -7.94,-7.94L13,1h-2v2.06c-1.13,0.12 -2.19,0.46 -3.16,0.97l1.5,1.5C10.16,5.19 11.06,5 12,5c3.87,0 7,3.13 7,7 0,0.94 -0.19,1.84 -0.52,2.65l1.5,1.5c0.5,-0.96 0.84,-2.02 0.97,-3.15L23,13v-2h-2.06zM3,4.27l2.04,2.04C3.97,7.62 3.25,9.23 3.06,11L1,11v2h2.06c0.46,4.17 3.77,7.48 7.94,7.94L11,23h2v-2.06c1.77,-0.2 3.38,-0.91 4.69,-1.98L19.73,21 21,19.73 4.27,3 3,4.27zM16.27,17.54C15.09,18.45 13.61,19 12,19c-3.87,0 -7,-3.13 -7,-7 0,-1.61 0.55,-3.09 1.46,-4.27l9.81,9.81z"/>
|
||||
</vector>
|
||||
@@ -0,0 +1,10 @@
|
||||
<vector xmlns:android="http://schemas.android.com/apk/res/android"
|
||||
android:width="24dp"
|
||||
android:height="24dp"
|
||||
android:viewportWidth="24"
|
||||
android:viewportHeight="24"
|
||||
android:tint="?attr/colorControlNormal">
|
||||
<path
|
||||
android:fillColor="@android:color/white"
|
||||
android:pathData="M12,2C6.48,2 2,6.48 2,12s4.48,10 10,10 10,-4.48 10,-10S17.52,2 12,2zM13,17h-2v-6h2v6zM13,9h-2L11,7h2v2z"/>
|
||||
</vector>
|
||||
@@ -0,0 +1,108 @@
|
||||
<?xml version="1.0" encoding="utf-8"?>
|
||||
<layout xmlns:app="http://schemas.android.com/apk/res-auto"
|
||||
xmlns:tools="http://schemas.android.com/tools"
|
||||
xmlns:android="http://schemas.android.com/apk/res/android">
|
||||
<data>
|
||||
<variable
|
||||
name="model"
|
||||
type="com.mowesta.android.app.model.AdvertiseViewModel" />
|
||||
</data>
|
||||
<LinearLayout
|
||||
android:orientation="vertical"
|
||||
android:layout_width="match_parent"
|
||||
android:layout_height="wrap_content">
|
||||
|
||||
<LinearLayout
|
||||
android:id="@+id/header"
|
||||
android:background="@color/accent"
|
||||
tools:targetApi="21"
|
||||
android:elevation="4dp"
|
||||
android:layout_width="match_parent"
|
||||
android:layout_height="wrap_content">
|
||||
<Space
|
||||
android:layout_width="@dimen/space_medium"
|
||||
android:layout_height="wrap_content"/>
|
||||
<ImageView
|
||||
android:contentDescription="@null"
|
||||
android:layout_width="48dp"
|
||||
android:layout_gravity="center_vertical"
|
||||
android:layout_height="wrap_content"
|
||||
app:tint="@color/fg_accent"
|
||||
app:srcCompat="@drawable/ic_info_normal_24"/>
|
||||
|
||||
<TextView
|
||||
android:layout_weight="1"
|
||||
android:layout_marginStart="@dimen/space_medium"
|
||||
android:layout_marginEnd="@dimen/space_medium"
|
||||
android:layout_gravity="center_vertical"
|
||||
style="@style/TextAppearance.MaterialComponents.Subtitle1"
|
||||
android:text="@string/advertise_header"
|
||||
android:textColor="@color/fg_accent"
|
||||
android:singleLine="true"
|
||||
android:ellipsize="end"
|
||||
android:layout_width="0dp"
|
||||
android:layout_height="wrap_content"/>
|
||||
<ImageButton
|
||||
android:contentDescription="@string/button_close"
|
||||
android:layout_width="48dp"
|
||||
app:tint="@color/fg_accent"
|
||||
android:layout_height="wrap_content"
|
||||
android:onClick="@{ () -> model.close() }"
|
||||
style="@style/Widget.MaterialComponents.Button.TextButton.Icon"
|
||||
app:srcCompat="@drawable/ic_close_normal_24" />
|
||||
</LinearLayout>
|
||||
|
||||
|
||||
<RelativeLayout
|
||||
android:clickable="true"
|
||||
android:focusable="true"
|
||||
android:onClick="@{ () -> model.open() }"
|
||||
android:layout_width="match_parent"
|
||||
android:layout_height="180dp">
|
||||
|
||||
<com.google.android.exoplayer2.ui.PlayerView
|
||||
android:id="@+id/video_view"
|
||||
android:layout_alignParentBottom="true"
|
||||
app:use_controller="false"
|
||||
app:resize_mode="zoom"
|
||||
android:layout_width="match_parent"
|
||||
android:layout_height="match_parent"/>
|
||||
<TextView
|
||||
android:text="@string/advertise_title"
|
||||
android:id="@+id/ad_title"
|
||||
android:textAppearance="?attr/textAppearanceBody1"
|
||||
android:layout_centerHorizontal="true"
|
||||
android:layout_alignParentTop="true"
|
||||
android:padding="8dp"
|
||||
android:gravity="center"
|
||||
android:textColor="@color/white"
|
||||
android:layout_width="wrap_content"
|
||||
android:layout_height="wrap_content"/>
|
||||
|
||||
<TextView
|
||||
android:text="@string/advertise_more"
|
||||
android:textAppearance="?attr/textAppearanceBody1"
|
||||
android:layout_centerInParent="true"
|
||||
android:paddingTop="50dp"
|
||||
android:gravity="center"
|
||||
android:textStyle="bold"
|
||||
android:textColor="@color/accent"
|
||||
android:layout_width="wrap_content"
|
||||
android:layout_height="wrap_content"/>
|
||||
|
||||
<TextView
|
||||
android:text="@string/advertise_description"
|
||||
android:id="@+id/ad_text"
|
||||
android:layout_centerHorizontal="true"
|
||||
android:layout_alignParentBottom="true"
|
||||
android:textAppearance="?attr/textAppearanceBody2"
|
||||
android:gravity="center"
|
||||
android:padding="8dp"
|
||||
android:textColor="@color/white"
|
||||
android:layout_width="wrap_content"
|
||||
android:layout_height="wrap_content"/>
|
||||
</RelativeLayout>
|
||||
|
||||
</LinearLayout>
|
||||
|
||||
</layout>
|
||||
@@ -87,4 +87,11 @@
|
||||
app:destination="@id/navigation_core" />
|
||||
</fragment>
|
||||
|
||||
<action
|
||||
android:id="@+id/action_core"
|
||||
app:popUpTo="@id/destination_splash"
|
||||
app:popUpToInclusive="true"
|
||||
app:launchSingleTop="true"
|
||||
app:destination="@id/navigation_core" />
|
||||
|
||||
</navigation>
|
||||
@@ -87,6 +87,7 @@
|
||||
android:id="@+id/action_drawer"
|
||||
app:popUpTo="@id/destination_drawer"
|
||||
app:popUpToInclusive="true"
|
||||
app:launchSingleTop="true"
|
||||
app:enterAnim="@anim/slide_in_right"
|
||||
app:exitAnim="@anim/slide_out_left"
|
||||
app:destination="@id/destination_drawer" />
|
||||
|
||||
@@ -16,9 +16,11 @@
|
||||
<string name="button_yes">Ja</string>
|
||||
<string name="button_no">Nein</string>
|
||||
<string name="message_no_browser">Dein Webbrowser konnte nicht geöffnet werden.</string>
|
||||
<string name="message_no_permission">Der App fehlt eine notwendige Berechtigung.</string>
|
||||
<string name="message_permission_title">Fehlende Berechtigung</string>
|
||||
<string name="message_permission_background">Um automatisch Messungen zu erfassen, benötigt MoWeSta die Berechtigung auf den Gerätestandort im Hintergrund zugreifen zu können.</string>
|
||||
<string name="message_permission_foreground">Um den Standort automatisch zu bestimmen, benötigt MoWeSta die Berechtigung auf den Gerätestandort zugreifen zu können.</string>
|
||||
<string name="message_configure_failed">Die Einstellungen konnten nicht geöffnet werden.</string>
|
||||
<string name="button_configure">An-\npassen</string>
|
||||
<string name="button_configure">Einstellungen anpasssen</string>
|
||||
|
||||
<!-- video controls -->
|
||||
<string name="button_fit_screen">Anzeige anpasen</string>
|
||||
@@ -318,4 +320,10 @@
|
||||
<string name="color_dialog_blue">Blau</string>
|
||||
<string name="color_dialog_green">Grün</string>
|
||||
|
||||
<string name="advertise_header">Veranstaltungshinweis</string>
|
||||
<string name="advertise_description">Mach mit beim FAIR Experiment vom 19. August bis zum 3. Oktober in Karlsruhe</string>
|
||||
<string name="advertise_more">Mehr erfahren…</string>
|
||||
<string name="advertise_title">Schlosslichtspiele 2021</string>
|
||||
|
||||
|
||||
</resources>
|
||||
|
||||
@@ -16,9 +16,11 @@
|
||||
<string name="button_yes">Yes</string>
|
||||
<string name="button_no">No</string>
|
||||
<string name="message_no_browser">Unable to open your web browser.</string>
|
||||
<string name="message_no_permission">The app is missing a required permission.</string>
|
||||
<string name="message_permission_title">Missing Permission</string>
|
||||
<string name="message_permission_background">To automatically collect measurements, MoWeSta needs your permission to locate your device in the background.</string>
|
||||
<string name="message_permission_foreground">To automatically set the location, MoWeSta needs your permission to locate your device.</string>
|
||||
<string name="message_configure_failed">Could not open the app settings.</string>
|
||||
<string name="button_configure">Con-\nfigure</string>
|
||||
<string name="button_configure">Configure settings</string>
|
||||
|
||||
<!-- video controls -->
|
||||
<string name="button_fit_screen">Match screen</string>
|
||||
@@ -322,4 +324,9 @@
|
||||
<string name="color_dialog_red">Red</string>
|
||||
<string name="color_dialog_blue">Blue</string>
|
||||
<string name="color_dialog_green">Green</string>
|
||||
|
||||
<string name="advertise_header">Event note</string>
|
||||
<string name="advertise_description">Join the FAIR Experiment from August 19th to October 3rd in Karlsruhe</string>
|
||||
<string name="advertise_more">Read more…</string>
|
||||
<string name="advertise_title">Schlosslichtspiele 2021</string>
|
||||
</resources>
|
||||
|
||||
@@ -0,0 +1,480 @@
|
||||
#define ARDUINOJSON_USE_LONG_LONG 1
|
||||
|
||||
#include <ESP8266WiFi.h>
|
||||
#include <ESP8266HTTPClient.h>
|
||||
#include <WiFiClient.h>
|
||||
#include <WiFiClientSecure.h>
|
||||
#include <EEPROM.h>
|
||||
#include "Adafruit_Sensor.h"
|
||||
#include "Adafruit_BME280.h"
|
||||
#include "ArduinoJson.h"
|
||||
|
||||
// Hardware setup
|
||||
#define BUTTON_PIN D5
|
||||
#define VOLTAGE_PIN A0
|
||||
#define VOLTAGE_MULTIPLIER 11
|
||||
#define VOLTAGE_DIVIDER 255.0
|
||||
#define EEPROM_SIZE 512
|
||||
#define BUTTON_OUT D7
|
||||
#define BME_OUT D6
|
||||
#define VOLTAGE_OUT D8
|
||||
|
||||
//Credentials for the Access Point
|
||||
#define WLAN_AP_SSID "MoWeSta - WiFi"
|
||||
#define WLAN_AP_PASSWORD "mowesta123456wifi"
|
||||
|
||||
// API-URL where measurements will be uploaded to
|
||||
#define MOWESTA_UPLOAD_URL "https://www.mowesta.com/api/devices/current/measurements/now"
|
||||
// #define MOWESTA_UPLOAD_URL "https://beta.mowesta.com/api/devices/current/measurements/now"
|
||||
#define MOWESTA_SOFTWARE_VERSION 2
|
||||
|
||||
// memory for json document
|
||||
#define JSON_BUFFER_SIZE 1000
|
||||
|
||||
// deep sleep period between measurements (us = 1e-6)
|
||||
#define DEEP_SLEEP_PERIOD 600000000
|
||||
// timeout to wait for the wifi connection in ms
|
||||
#define TIMEOUT_WIFI 20000
|
||||
// timeout to wait for the ntp sync in ms
|
||||
#define TIMEOUT_NTP 20000
|
||||
// timeout to wait for the setup data in sec
|
||||
#define TIMEOUT_READ 40
|
||||
|
||||
// Let's encrypt root cert (valid until June 4, 2035)
|
||||
const char certificate_anchors[] PROGMEM = R"EOF(
|
||||
-----BEGIN CERTIFICATE-----
|
||||
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
|
||||
-----END CERTIFICATE-----
|
||||
)EOF";
|
||||
X509List certificates(certificate_anchors);
|
||||
|
||||
// Access point config
|
||||
IPAddress ip_address_local(192, 168, 4, 1);
|
||||
IPAddress ip_address_gateway(192, 168, 4, 1);
|
||||
IPAddress ip_subnet_mask(255, 255, 255, 0);
|
||||
WiFiServer wifi_server(8080);
|
||||
|
||||
// Variables set to data values received from the app
|
||||
String* setting_wlan_ssid;
|
||||
String* setting_wlan_password;
|
||||
String* setting_device_id;
|
||||
String* setting_device_token;
|
||||
String* setting_longitude;
|
||||
String* setting_latitude;
|
||||
|
||||
// Flag to store mode
|
||||
bool mode_setup = false;
|
||||
|
||||
// Store boot time for timeout
|
||||
long time_boot;
|
||||
|
||||
// Sensor to gather measurements
|
||||
Adafruit_BME280 sensor_bme;
|
||||
|
||||
// eeprom reading and writing
|
||||
void eeprom_write_string(int* add, String* data);
|
||||
String* eeprom_read_string(int* add);
|
||||
|
||||
// settings reading, writing, printing and validation
|
||||
void settings_read();
|
||||
void settings_write();
|
||||
void settings_print();
|
||||
bool settings_valid();
|
||||
|
||||
|
||||
// device setup via mobile app or netcat
|
||||
bool setup_process_connection(WiFiClient*);
|
||||
bool setup_process_data(String);
|
||||
|
||||
// measurement and upload
|
||||
void measurement_capture();
|
||||
|
||||
void setup() {
|
||||
//Open serial port to display data and set baudrate
|
||||
Serial.begin(115200);
|
||||
// Wait for serial port to be initialized
|
||||
while (!Serial);
|
||||
Serial.println();
|
||||
|
||||
// power the voltage divider
|
||||
pinMode(VOLTAGE_OUT, OUTPUT);
|
||||
digitalWrite(VOLTAGE_OUT, LOW);
|
||||
// power the bme sensor
|
||||
pinMode(BME_OUT, OUTPUT);
|
||||
digitalWrite(BME_OUT, LOW);
|
||||
// power the button
|
||||
pinMode(BUTTON_OUT, OUTPUT);
|
||||
digitalWrite(BUTTON_OUT, LOW);
|
||||
|
||||
// Initialize EEPROM with complete size
|
||||
// Configure the button to enter setup
|
||||
pinMode(BUTTON_PIN, INPUT_PULLUP);
|
||||
// Configure the LED to indicate setup
|
||||
pinMode(LED_BUILTIN, OUTPUT);
|
||||
// Read the settings from eeprom
|
||||
EEPROM.begin(EEPROM_SIZE);
|
||||
settings_read();
|
||||
// Check if button is pressed to enter setup
|
||||
mode_setup = (digitalRead(BUTTON_PIN) == LOW);
|
||||
time_boot = millis();
|
||||
if (mode_setup) {
|
||||
digitalWrite(LED_BUILTIN, LOW);
|
||||
Serial.println("Entering setup mode.");
|
||||
WiFi.softAPConfig(ip_address_local, ip_address_gateway, ip_subnet_mask);
|
||||
WiFi.softAP(WLAN_AP_SSID, WLAN_AP_PASSWORD);
|
||||
IPAddress ip_address = WiFi.softAPIP();
|
||||
Serial.print("IP address is: '");
|
||||
Serial.print(ip_address);
|
||||
Serial.println("'");
|
||||
wifi_server.begin();
|
||||
} else if (settings_valid()){
|
||||
digitalWrite(LED_BUILTIN, HIGH);
|
||||
Serial.print("Connecting to WiFi network '");
|
||||
Serial.print(*setting_wlan_ssid);
|
||||
Serial.println("'");
|
||||
WiFi.begin(setting_wlan_ssid->c_str(), setting_wlan_password->c_str());
|
||||
} else {
|
||||
Serial.println("Invalid settings, setup required.");
|
||||
settings_print();
|
||||
}
|
||||
}
|
||||
|
||||
void loop() {
|
||||
if (mode_setup) {
|
||||
// setup mode, keeps handling incoming clients until successful setup
|
||||
WiFiClient client = wifi_server.available();
|
||||
if (client) {
|
||||
digitalWrite(LED_BUILTIN, HIGH);
|
||||
if (setup_process_connection(&client)) {
|
||||
WiFi.softAPdisconnect(true);
|
||||
delay(5000);
|
||||
ESP.restart();
|
||||
} else {
|
||||
digitalWrite(LED_BUILTIN, LOW);
|
||||
}
|
||||
}
|
||||
} else if (settings_valid()) {
|
||||
// measurement mode, captures and uploads a measurement when wifi is up
|
||||
if (WiFi.status() == WL_CONNECTED) {
|
||||
if (sensor_bme.begin(0x76)) {
|
||||
measurement_capture();
|
||||
} else {
|
||||
Serial.println("Failed to activate sensor.");
|
||||
}
|
||||
WiFi.disconnect();
|
||||
delay(1000);
|
||||
Serial.end();
|
||||
ESP.deepSleep(DEEP_SLEEP_PERIOD);
|
||||
} else {
|
||||
// check for excessive waiting time
|
||||
long time_now = millis();
|
||||
long time_delta = (time_now > time_boot) ? (time_now - time_boot) : time_boot - time_now;
|
||||
if (time_delta > TIMEOUT_WIFI) {
|
||||
Serial.println("Failed to activate wifi.");
|
||||
WiFi.disconnect();
|
||||
delay(1000);
|
||||
Serial.end();
|
||||
ESP.deepSleep(DEEP_SLEEP_PERIOD);
|
||||
}
|
||||
delay(500);
|
||||
}
|
||||
} else {
|
||||
// blink to indicate missing config
|
||||
for(int i = 0; i < 10; i++){
|
||||
digitalWrite(LED_BUILTIN, LOW);
|
||||
delay(50);
|
||||
digitalWrite(LED_BUILTIN, HIGH);
|
||||
delay(50);
|
||||
}
|
||||
Serial.end();
|
||||
ESP.deepSleep(DEEP_SLEEP_PERIOD);
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
|
||||
/**
|
||||
* Writes a String in EEPROM memory starting at a defined address.
|
||||
*
|
||||
* @param add In/out parameter with the address.
|
||||
* @param data The string to write.
|
||||
*/
|
||||
void eeprom_write_string(int* add, String* data) {
|
||||
int s = data->length();
|
||||
if (*add + s + 1 < EEPROM_SIZE) {
|
||||
for (int i = 0; i < s; i++) {
|
||||
EEPROM.write(*add + i, (*data)[i]);
|
||||
}
|
||||
EEPROM.write(*add + s, '\0');
|
||||
}
|
||||
*add += s + 1;
|
||||
}
|
||||
|
||||
/**
|
||||
* Reads a String from EEPROM memory starting at a defined address.
|
||||
* Reads until a terminating null character.
|
||||
*
|
||||
* @param add In/out parameter with the address.
|
||||
* @return A pointer to the string.
|
||||
*/
|
||||
String* eeprom_read_string(int* add) {
|
||||
char data[EEPROM_SIZE + 1];
|
||||
int limit = EEPROM_SIZE - *add;
|
||||
limit = limit < 0 ? 0 : limit;
|
||||
int len = 0;
|
||||
unsigned char k;
|
||||
if (limit > 0) {
|
||||
k = EEPROM.read(*add);
|
||||
while (k != '\0' && len < limit)
|
||||
{
|
||||
k = EEPROM.read(*add + len);
|
||||
data[len] = k;
|
||||
len++;
|
||||
}
|
||||
}
|
||||
data[len] = '\0';
|
||||
*add += len;
|
||||
return new String(data);
|
||||
}
|
||||
|
||||
/**
|
||||
* Reads the settings from the eeprom to memory.
|
||||
*/
|
||||
void settings_read() {
|
||||
int address = 0;
|
||||
setting_wlan_ssid = eeprom_read_string(&address);
|
||||
setting_wlan_password = eeprom_read_string(&address);
|
||||
setting_device_id = eeprom_read_string(&address);
|
||||
setting_device_token = eeprom_read_string(&address);
|
||||
setting_longitude = eeprom_read_string(&address);
|
||||
setting_latitude = eeprom_read_string(&address);
|
||||
}
|
||||
|
||||
/**
|
||||
* Writes the settings from memory to the eeprom.
|
||||
*/
|
||||
void settings_write() {
|
||||
int address = 0;
|
||||
eeprom_write_string(&address, setting_wlan_ssid);
|
||||
eeprom_write_string(&address, setting_wlan_password);
|
||||
eeprom_write_string(&address, setting_device_id);
|
||||
eeprom_write_string(&address, setting_device_token);
|
||||
eeprom_write_string(&address, setting_longitude);
|
||||
eeprom_write_string(&address, setting_latitude);
|
||||
EEPROM.commit();
|
||||
}
|
||||
|
||||
/**
|
||||
* Prints the settings onto the serial console.
|
||||
*/
|
||||
void settings_print() {
|
||||
Serial.print("WLAN SSID: ");
|
||||
Serial.println(*setting_wlan_ssid);
|
||||
Serial.print("WLAN Password: ");
|
||||
Serial.println(*setting_wlan_password);
|
||||
Serial.print("Device ID: ");
|
||||
Serial.println(*setting_device_id);
|
||||
Serial.print("Device Token: ");
|
||||
Serial.println(*setting_device_token);
|
||||
Serial.print("Longitude: ");
|
||||
Serial.println(*setting_longitude);
|
||||
Serial.print("Latitude: ");
|
||||
Serial.println(*setting_latitude);
|
||||
}
|
||||
|
||||
/**
|
||||
* Determines whether the settings are valid. This is
|
||||
* done by making sure that every string has a non-zero length.
|
||||
*
|
||||
* @return True if the settings are valid, false otherwise.
|
||||
*/
|
||||
bool settings_valid() {
|
||||
return setting_wlan_ssid->length() > 0 &&
|
||||
setting_wlan_password->length() > 0 &&
|
||||
setting_device_id->length() > 0 &&
|
||||
setting_device_token->length() > 0 &&
|
||||
setting_longitude->length() > 0 &&
|
||||
setting_latitude->length() > 0;
|
||||
}
|
||||
|
||||
/**
|
||||
* Parses the client data and stores the relevant information in flash memory.
|
||||
* It is assumed that the client data is in json format.
|
||||
*
|
||||
* @param data The data received from the client.
|
||||
* @return True if the data seems ok and has been stored to flash, false otherwise.
|
||||
*/
|
||||
bool setup_process_data(String data) {
|
||||
StaticJsonDocument<JSON_BUFFER_SIZE> doc; //Memory pool
|
||||
Serial.print("Received settings: ");
|
||||
Serial.println(data);
|
||||
DeserializationError error = deserializeJson(doc, data);
|
||||
if (error) {
|
||||
Serial.print("Deserialization failed with code ");
|
||||
Serial.println(error.c_str());
|
||||
return false;
|
||||
} else {
|
||||
delete setting_wlan_ssid;
|
||||
delete setting_wlan_password;
|
||||
delete setting_device_id;
|
||||
delete setting_device_token;
|
||||
delete setting_longitude;
|
||||
delete setting_latitude;
|
||||
setting_wlan_ssid = new String(doc["ssid"]);
|
||||
setting_wlan_password = new String(doc["password"]);
|
||||
setting_device_id = new String(doc["id"]);
|
||||
setting_device_token = new String(doc["token"]);
|
||||
setting_longitude = new String(doc["longitude"]);
|
||||
setting_latitude = new String(doc["latitude"]);
|
||||
settings_print();
|
||||
if (settings_valid()) {
|
||||
Serial.println("Storing valid settings.");
|
||||
settings_write();
|
||||
return true;
|
||||
} else {
|
||||
Serial.println("Ignoring invalid settings.");
|
||||
return false;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* Performs the setup data exchange with the app and returns
|
||||
* whether the arduino has successfully received a new configuration.
|
||||
*
|
||||
* @param client The wifi client that represents the connection.
|
||||
* @return True if the setup data has been retrieved successfully.
|
||||
*/
|
||||
bool setup_process_connection(WiFiClient *client) {
|
||||
Serial.println("Client connection established.");
|
||||
String data = "";
|
||||
bool didRead = true;
|
||||
client->setTimeout(TIMEOUT_READ);
|
||||
while (client->connected() && didRead) {
|
||||
String chunk = client->readStringUntil('\n');
|
||||
didRead = chunk.length() > 0; // if line is empty, break immediately
|
||||
data += chunk;
|
||||
}
|
||||
if (data.length() > 0) {
|
||||
if(setup_process_data(data)) {
|
||||
client->println("Success\n"); // Notify client
|
||||
client->flush();
|
||||
// Wait for client to close connection, since we will
|
||||
// be disabling the accesspoint directly afterwards
|
||||
while (client->connected());
|
||||
client->stop();
|
||||
Serial.println("Success, client disconnected.");
|
||||
return true;
|
||||
} else {
|
||||
client->println("Error\n"); //Notify client
|
||||
client->flush();
|
||||
client->stop();
|
||||
Serial.println("Error, client disconnected.");
|
||||
return false;
|
||||
}
|
||||
} else {
|
||||
client->println("Timeout\n"); //Notify client
|
||||
client->flush();
|
||||
client->stop();
|
||||
Serial.println("Timeout, client disconnected.");
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* Synchronizes the time with an ntp server, captures a measurement,
|
||||
* generates a json document and uploads it to the mowesta backend.
|
||||
*/
|
||||
void measurement_capture() {
|
||||
WiFiClientSecure wifi;
|
||||
HTTPClient http;
|
||||
StaticJsonDocument<JSON_BUFFER_SIZE> doc;
|
||||
|
||||
// set trusted root certificates and perform ntp time sync for https
|
||||
configTime(0, 0, "time2-1.uni-duisburg-essen.de", "time2-3.uni-duisburg-essen.de", "pool.ntp.org");
|
||||
Serial.print("Waiting for NTP time sync: ");
|
||||
time_t now = time(nullptr);
|
||||
// check that time is after January 1st, 2021
|
||||
int max_wait = TIMEOUT_NTP;
|
||||
while (now < 1606694400) {
|
||||
if (max_wait < 0) {
|
||||
Serial.println("Timeout");
|
||||
return;
|
||||
}
|
||||
delay(500);
|
||||
max_wait -= 500;
|
||||
now = time(nullptr);
|
||||
}
|
||||
Serial.println(now);
|
||||
wifi.setTrustAnchors(&certificates);
|
||||
|
||||
// create json document for upload
|
||||
doc["id"] = 0;
|
||||
doc["creationTime"] = 0;
|
||||
doc["modificationTime"] = 0;
|
||||
doc["deleted"] = "false";
|
||||
JsonObject coordinate = doc.createNestedObject("coordinate");
|
||||
coordinate["latitude"] = setting_latitude->toDouble();
|
||||
coordinate["longitude"] = setting_longitude->toDouble();
|
||||
doc["time"] = now * 1000;
|
||||
doc["device"] = atol(setting_device_id->c_str());
|
||||
doc["version"] = MOWESTA_SOFTWARE_VERSION;
|
||||
doc["temperature"] = (char*)0;
|
||||
doc["pressure"] = (char*)0;
|
||||
doc["humidity"] = (char*)0;
|
||||
JsonObject data = doc.createNestedObject("data");
|
||||
data["SENSOR_TEMPERATURE"] = String(sensor_bme.readTemperature());
|
||||
data["SENSOR_PRESSURE"] = String(sensor_bme.readPressure() / 100);
|
||||
data["SENSOR_HUMIDITY"] = String(sensor_bme.readHumidity());
|
||||
data["BATTERY_VOLTAGE"] = String((analogRead(VOLTAGE_PIN) / VOLTAGE_DIVIDER) * VOLTAGE_MULTIPLIER);
|
||||
|
||||
// print measurement
|
||||
serializeJsonPretty(doc, Serial);
|
||||
Serial.println();
|
||||
|
||||
// upload measurement
|
||||
String body;
|
||||
serializeJson(doc, body);
|
||||
http.begin(wifi, MOWESTA_UPLOAD_URL);
|
||||
http.addHeader("Accept", "application/json");
|
||||
http.addHeader("Authorization", "Bearer " + *setting_device_token);
|
||||
http.addHeader("Content-Type", "application/json");
|
||||
int code = http.POST(body);
|
||||
if (code / 100 == 2) {
|
||||
Serial.println("Upload successful.");
|
||||
} else {
|
||||
Serial.print("Upload failed: ");
|
||||
Serial.println(code);
|
||||
}
|
||||
http.end();
|
||||
}
|
||||
@@ -0,0 +1,482 @@
|
||||
#define ARDUINOJSON_USE_LONG_LONG 1
|
||||
|
||||
#include <ESP8266WiFi.h>
|
||||
#include <ESP8266HTTPClient.h>
|
||||
#include <WiFiClient.h>
|
||||
#include <WiFiClientSecure.h>
|
||||
#include <EEPROM.h>
|
||||
#include <Adafruit_BMP280.h>
|
||||
#include "ArduinoJson.h"
|
||||
|
||||
// Hardware setup
|
||||
#define BUTTON_PIN D5
|
||||
#define VOLTAGE_PIN A0
|
||||
#define VOLTAGE_MULTIPLIER 11
|
||||
#define VOLTAGE_DIVIDER 255.0
|
||||
#define EEPROM_SIZE 512
|
||||
#define BUTTON_OUT D7
|
||||
#define EXTERNAL_OUT D8
|
||||
|
||||
//Credentials for the Access Point
|
||||
#define WLAN_AP_SSID "MoWeSta - WiFi"
|
||||
#define WLAN_AP_PASSWORD "mowesta123456wifi"
|
||||
|
||||
// API-URL where measurements will be uploaded to
|
||||
//#define MOWESTA_UPLOAD_URL "https://www.mowesta.com/api/devices/current/measurements/now"
|
||||
#define MOWESTA_UPLOAD_URL "https://beta.mowesta.com/api/devices/current/measurements/now"
|
||||
#define MOWESTA_SOFTWARE_VERSION 2
|
||||
|
||||
// memory for json document
|
||||
#define JSON_BUFFER_SIZE 1000
|
||||
|
||||
// deep sleep period between measurements (us = 1e-6)
|
||||
#define DEEP_SLEEP_PERIOD 600000000
|
||||
// timeout to wait for the wifi connection in ms
|
||||
#define TIMEOUT_WIFI 20000
|
||||
// timeout to wait for the ntp sync in ms
|
||||
#define TIMEOUT_NTP 20000
|
||||
// timeout to wait for the setup data in sec
|
||||
#define TIMEOUT_READ 40
|
||||
|
||||
// Let's encrypt root cert (valid until June 4, 2035)
|
||||
const char certificate_anchors[] PROGMEM = R"EOF(
|
||||
-----BEGIN CERTIFICATE-----
|
||||
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
|
||||
-----END CERTIFICATE-----
|
||||
)EOF";
|
||||
X509List certificates(certificate_anchors);
|
||||
|
||||
// Access point config
|
||||
IPAddress ip_address_local(192, 168, 4, 1);
|
||||
IPAddress ip_address_gateway(192, 168, 4, 1);
|
||||
IPAddress ip_subnet_mask(255, 255, 255, 0);
|
||||
WiFiServer wifi_server(8080);
|
||||
|
||||
// Variables set to data values received from the app
|
||||
String* setting_wlan_ssid;
|
||||
String* setting_wlan_password;
|
||||
String* setting_device_id;
|
||||
String* setting_device_token;
|
||||
String* setting_longitude;
|
||||
String* setting_latitude;
|
||||
|
||||
// Flag to store mode
|
||||
bool mode_setup = false;
|
||||
|
||||
// Store boot time for timeout
|
||||
long time_boot;
|
||||
|
||||
// Sensor to gather measurements
|
||||
Adafruit_BMP280 sensor_bmp;
|
||||
|
||||
// eeprom reading and writing
|
||||
void eeprom_write_string(int* add, String* data);
|
||||
String* eeprom_read_string(int* add);
|
||||
|
||||
// settings reading, writing, printing and validation
|
||||
void settings_read();
|
||||
void settings_write();
|
||||
void settings_print();
|
||||
bool settings_valid();
|
||||
|
||||
|
||||
// device setup via mobile app or netcat
|
||||
bool setup_process_connection(WiFiClient*);
|
||||
bool setup_process_data(String);
|
||||
|
||||
// measurement and upload
|
||||
void measurement_capture();
|
||||
|
||||
void setup() {
|
||||
//Open serial port to display data and set baudrate
|
||||
Serial.begin(115200);
|
||||
// Wait for serial port to be initialized
|
||||
while (!Serial);
|
||||
Serial.println();
|
||||
// power the button, voltage divider and sensor
|
||||
pinMode(BUTTON_OUT, OUTPUT);
|
||||
digitalWrite(BUTTON_OUT, LOW);
|
||||
pinMode(EXTERNAL_OUT, OUTPUT);
|
||||
digitalWrite(EXTERNAL_OUT, LOW);
|
||||
// Initialize EEPROM with complete size
|
||||
// Configure the button to enter setup
|
||||
pinMode(BUTTON_PIN, INPUT_PULLUP);
|
||||
// Configure the LED to indicate setup
|
||||
pinMode(LED_BUILTIN, OUTPUT);
|
||||
// Read the settings from eeprom
|
||||
EEPROM.begin(EEPROM_SIZE);
|
||||
settings_read();
|
||||
// Check if button is pressed to enter setup
|
||||
mode_setup = (digitalRead(BUTTON_PIN) == LOW);
|
||||
time_boot = millis();
|
||||
if (mode_setup) {
|
||||
digitalWrite(LED_BUILTIN, LOW);
|
||||
Serial.println("Entering setup mode.");
|
||||
WiFi.softAPConfig(ip_address_local, ip_address_gateway, ip_subnet_mask);
|
||||
WiFi.softAP(WLAN_AP_SSID, WLAN_AP_PASSWORD);
|
||||
IPAddress ip_address = WiFi.softAPIP();
|
||||
Serial.print("IP address is: '");
|
||||
Serial.print(ip_address);
|
||||
Serial.println("'");
|
||||
wifi_server.begin();
|
||||
} else if (settings_valid()){
|
||||
digitalWrite(LED_BUILTIN, HIGH);
|
||||
Serial.print("Connecting to WiFi network '");
|
||||
Serial.print(*setting_wlan_ssid);
|
||||
Serial.println("'");
|
||||
WiFi.begin(setting_wlan_ssid->c_str(), setting_wlan_password->c_str());
|
||||
} else {
|
||||
Serial.println("Invalid settings, setup required.");
|
||||
settings_print();
|
||||
}
|
||||
}
|
||||
|
||||
void loop() {
|
||||
if (mode_setup) {
|
||||
// setup mode, keeps handling incoming clients until successful setup
|
||||
WiFiClient client = wifi_server.available();
|
||||
if (client) {
|
||||
digitalWrite(LED_BUILTIN, HIGH);
|
||||
if (setup_process_connection(&client)) {
|
||||
WiFi.softAPdisconnect(true);
|
||||
delay(5000);
|
||||
ESP.restart();
|
||||
} else {
|
||||
digitalWrite(LED_BUILTIN, LOW);
|
||||
}
|
||||
}
|
||||
} else if (settings_valid()) {
|
||||
// measurement mode, captures and uploads a measurement when wifi is up
|
||||
if (WiFi.status() == WL_CONNECTED) {
|
||||
if (sensor_bmp.begin(BMP280_ADDRESS_ALT, BMP280_CHIPID)) {
|
||||
// Setup with default settings from datasheet.
|
||||
sensor_bmp.setSampling(Adafruit_BMP280::MODE_NORMAL, // Operating Mode.
|
||||
Adafruit_BMP280::SAMPLING_X2, // Temp. oversampling
|
||||
Adafruit_BMP280::SAMPLING_X16, // Pressure oversampling
|
||||
Adafruit_BMP280::FILTER_X16, // Filtering.
|
||||
Adafruit_BMP280::STANDBY_MS_500); // Standby time.
|
||||
measurement_capture();
|
||||
} else {
|
||||
Serial.println("Failed to activate sensor.");
|
||||
}
|
||||
WiFi.disconnect();
|
||||
delay(1000);
|
||||
Serial.end();
|
||||
ESP.deepSleep(DEEP_SLEEP_PERIOD);
|
||||
} else {
|
||||
// check for excessive waiting time
|
||||
long time_now = millis();
|
||||
long time_delta = (time_now > time_boot) ? (time_now - time_boot) : time_boot - time_now;
|
||||
if (time_delta > TIMEOUT_WIFI) {
|
||||
Serial.println("Failed to activate wifi.");
|
||||
WiFi.disconnect();
|
||||
delay(1000);
|
||||
Serial.end();
|
||||
ESP.deepSleep(DEEP_SLEEP_PERIOD);
|
||||
}
|
||||
delay(500);
|
||||
}
|
||||
} else {
|
||||
// blink to indicate missing config
|
||||
for(int i = 0; i < 10; i++){
|
||||
digitalWrite(LED_BUILTIN, LOW);
|
||||
delay(50);
|
||||
digitalWrite(LED_BUILTIN, HIGH);
|
||||
delay(50);
|
||||
}
|
||||
Serial.end();
|
||||
ESP.deepSleep(DEEP_SLEEP_PERIOD);
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
|
||||
/**
|
||||
* Writes a String in EEPROM memory starting at a defined address.
|
||||
*
|
||||
* @param add In/out parameter with the address.
|
||||
* @param data The string to write.
|
||||
*/
|
||||
void eeprom_write_string(int* add, String* data) {
|
||||
int s = data->length();
|
||||
if (*add + s + 1 < EEPROM_SIZE) {
|
||||
for (int i = 0; i < s; i++) {
|
||||
EEPROM.write(*add + i, (*data)[i]);
|
||||
}
|
||||
EEPROM.write(*add + s, '\0');
|
||||
}
|
||||
*add += s + 1;
|
||||
}
|
||||
|
||||
/**
|
||||
* Reads a String from EEPROM memory starting at a defined address.
|
||||
* Reads until a terminating null character.
|
||||
*
|
||||
* @param add In/out parameter with the address.
|
||||
* @return A pointer to the string.
|
||||
*/
|
||||
String* eeprom_read_string(int* add) {
|
||||
char data[EEPROM_SIZE + 1];
|
||||
int limit = EEPROM_SIZE - *add;
|
||||
limit = limit < 0 ? 0 : limit;
|
||||
int len = 0;
|
||||
unsigned char k;
|
||||
if (limit > 0) {
|
||||
k = EEPROM.read(*add);
|
||||
while (k != '\0' && len < limit)
|
||||
{
|
||||
k = EEPROM.read(*add + len);
|
||||
data[len] = k;
|
||||
len++;
|
||||
}
|
||||
}
|
||||
data[len] = '\0';
|
||||
*add += len;
|
||||
return new String(data);
|
||||
}
|
||||
|
||||
/**
|
||||
* Reads the settings from the eeprom to memory.
|
||||
*/
|
||||
void settings_read() {
|
||||
int address = 0;
|
||||
setting_wlan_ssid = eeprom_read_string(&address);
|
||||
setting_wlan_password = eeprom_read_string(&address);
|
||||
setting_device_id = eeprom_read_string(&address);
|
||||
setting_device_token = eeprom_read_string(&address);
|
||||
setting_longitude = eeprom_read_string(&address);
|
||||
setting_latitude = eeprom_read_string(&address);
|
||||
}
|
||||
|
||||
/**
|
||||
* Writes the settings from memory to the eeprom.
|
||||
*/
|
||||
void settings_write() {
|
||||
int address = 0;
|
||||
eeprom_write_string(&address, setting_wlan_ssid);
|
||||
eeprom_write_string(&address, setting_wlan_password);
|
||||
eeprom_write_string(&address, setting_device_id);
|
||||
eeprom_write_string(&address, setting_device_token);
|
||||
eeprom_write_string(&address, setting_longitude);
|
||||
eeprom_write_string(&address, setting_latitude);
|
||||
EEPROM.commit();
|
||||
}
|
||||
|
||||
/**
|
||||
* Prints the settings onto the serial console.
|
||||
*/
|
||||
void settings_print() {
|
||||
Serial.print("WLAN SSID: ");
|
||||
Serial.println(*setting_wlan_ssid);
|
||||
Serial.print("WLAN Password: ");
|
||||
Serial.println(*setting_wlan_password);
|
||||
Serial.print("Device ID: ");
|
||||
Serial.println(*setting_device_id);
|
||||
Serial.print("Device Token: ");
|
||||
Serial.println(*setting_device_token);
|
||||
Serial.print("Longitude: ");
|
||||
Serial.println(*setting_longitude);
|
||||
Serial.print("Latitude: ");
|
||||
Serial.println(*setting_latitude);
|
||||
}
|
||||
|
||||
/**
|
||||
* Determines whether the settings are valid. This is
|
||||
* done by making sure that every string has a non-zero length.
|
||||
*
|
||||
* @return True if the settings are valid, false otherwise.
|
||||
*/
|
||||
bool settings_valid() {
|
||||
return setting_wlan_ssid->length() > 0 &&
|
||||
setting_wlan_password->length() > 0 &&
|
||||
setting_device_id->length() > 0 &&
|
||||
setting_device_token->length() > 0 &&
|
||||
setting_longitude->length() > 0 &&
|
||||
setting_latitude->length() > 0;
|
||||
}
|
||||
|
||||
/**
|
||||
* Parses the client data and stores the relevant information in flash memory.
|
||||
* It is assumed that the client data is in json format.
|
||||
*
|
||||
* @param data The data received from the client.
|
||||
* @return True if the data seems ok and has been stored to flash, false otherwise.
|
||||
*/
|
||||
bool setup_process_data(String data) {
|
||||
StaticJsonDocument<JSON_BUFFER_SIZE> doc; //Memory pool
|
||||
Serial.print("Received settings: ");
|
||||
Serial.println(data);
|
||||
DeserializationError error = deserializeJson(doc, data);
|
||||
if (error) {
|
||||
Serial.print("Deserialization failed with code ");
|
||||
Serial.println(error.c_str());
|
||||
return false;
|
||||
} else {
|
||||
delete setting_wlan_ssid;
|
||||
delete setting_wlan_password;
|
||||
delete setting_device_id;
|
||||
delete setting_device_token;
|
||||
delete setting_longitude;
|
||||
delete setting_latitude;
|
||||
setting_wlan_ssid = new String(doc["ssid"]);
|
||||
setting_wlan_password = new String(doc["password"]);
|
||||
setting_device_id = new String(doc["id"]);
|
||||
setting_device_token = new String(doc["token"]);
|
||||
setting_longitude = new String(doc["longitude"]);
|
||||
setting_latitude = new String(doc["latitude"]);
|
||||
settings_print();
|
||||
if (settings_valid()) {
|
||||
Serial.println("Storing valid settings.");
|
||||
settings_write();
|
||||
return true;
|
||||
} else {
|
||||
Serial.println("Ignoring invalid settings.");
|
||||
return false;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* Performs the setup data exchange with the app and returns
|
||||
* whether the arduino has successfully received a new configuration.
|
||||
*
|
||||
* @param client The wifi client that represents the connection.
|
||||
* @return True if the setup data has been retrieved successfully.
|
||||
*/
|
||||
bool setup_process_connection(WiFiClient *client) {
|
||||
Serial.println("Client connection established.");
|
||||
String data = "";
|
||||
bool didRead = true;
|
||||
client->setTimeout(TIMEOUT_READ);
|
||||
while (client->connected() && didRead) {
|
||||
String chunk = client->readStringUntil('\n');
|
||||
didRead = chunk.length() > 0; // if line is empty, break immediately
|
||||
data += chunk;
|
||||
}
|
||||
if (data.length() > 0) {
|
||||
if(setup_process_data(data)) {
|
||||
client->println("Success\n"); // Notify client
|
||||
client->flush();
|
||||
// Wait for client to close connection, since we will
|
||||
// be disabling the accesspoint directly afterwards
|
||||
while (client->connected());
|
||||
client->stop();
|
||||
Serial.println("Success, client disconnected.");
|
||||
return true;
|
||||
} else {
|
||||
client->println("Error\n"); //Notify client
|
||||
client->flush();
|
||||
client->stop();
|
||||
Serial.println("Error, client disconnected.");
|
||||
return false;
|
||||
}
|
||||
} else {
|
||||
client->println("Timeout\n"); //Notify client
|
||||
client->flush();
|
||||
client->stop();
|
||||
Serial.println("Timeout, client disconnected.");
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* Synchronizes the time with an ntp server, captures a measurement,
|
||||
* generates a json document and uploads it to the mowesta backend.
|
||||
*/
|
||||
void measurement_capture() {
|
||||
WiFiClientSecure wifi;
|
||||
HTTPClient http;
|
||||
StaticJsonDocument<JSON_BUFFER_SIZE> doc;
|
||||
sensors_event_t temperature_event, pressure_event;
|
||||
|
||||
// set trusted root certificates and perform ntp time sync for https
|
||||
configTime(0, 0, "time2-1.uni-duisburg-essen.de", "time2-3.uni-duisburg-essen.de", "pool.ntp.org");
|
||||
Serial.print("Waiting for NTP time sync: ");
|
||||
time_t now = time(nullptr);
|
||||
// check that time is after January 1st, 2021
|
||||
int max_wait = TIMEOUT_NTP;
|
||||
while (now < 1606694400) {
|
||||
if (max_wait < 0) {
|
||||
Serial.println("Timeout");
|
||||
return;
|
||||
}
|
||||
delay(500);
|
||||
max_wait -= 500;
|
||||
now = time(nullptr);
|
||||
}
|
||||
Serial.println(now);
|
||||
wifi.setTrustAnchors(&certificates);
|
||||
|
||||
// capture sensor data
|
||||
sensor_bmp.getTemperatureSensor()->getEvent(&temperature_event);
|
||||
sensor_bmp.getPressureSensor()->getEvent(&pressure_event);
|
||||
|
||||
// create json document for upload
|
||||
doc["id"] = 0;
|
||||
doc["creationTime"] = 0;
|
||||
doc["modificationTime"] = 0;
|
||||
doc["deleted"] = "false";
|
||||
JsonObject coordinate = doc.createNestedObject("coordinate");
|
||||
coordinate["latitude"] = setting_latitude->toDouble();
|
||||
coordinate["longitude"] = setting_longitude->toDouble();
|
||||
doc["time"] = now * 1000;
|
||||
doc["device"] = atol(setting_device_id->c_str());
|
||||
doc["version"] = MOWESTA_SOFTWARE_VERSION;
|
||||
doc["temperature"] = (char*)0;
|
||||
doc["pressure"] = (char*)0;
|
||||
doc["humidity"] = (char*)0;
|
||||
JsonObject data = doc.createNestedObject("data");
|
||||
data["SENSOR_TEMPERATURE"] = String(temperature_event.temperature);
|
||||
data["SENSOR_PRESSURE"] = String(pressure_event.pressure);
|
||||
data["BATTERY_VOLTAGE"] = String((analogRead(VOLTAGE_PIN) / VOLTAGE_DIVIDER) * VOLTAGE_MULTIPLIER);
|
||||
|
||||
// print measurement
|
||||
serializeJsonPretty(doc, Serial);
|
||||
Serial.println();
|
||||
|
||||
// upload measurement
|
||||
String body;
|
||||
serializeJson(doc, body);
|
||||
http.begin(wifi, MOWESTA_UPLOAD_URL);
|
||||
http.addHeader("Accept", "application/json");
|
||||
http.addHeader("Authorization", "Bearer " + *setting_device_token);
|
||||
http.addHeader("Content-Type", "application/json");
|
||||
int code = http.POST(body);
|
||||
if (code / 100 == 2) {
|
||||
Serial.println("Upload successful.");
|
||||
} else {
|
||||
Serial.print("Upload failed: ");
|
||||
Serial.println(code);
|
||||
}
|
||||
http.end();
|
||||
}
|
||||
+2
-2
@@ -5,7 +5,7 @@ apply plugin: 'maven-publish'
|
||||
|
||||
buildscript {
|
||||
dependencies {
|
||||
classpath 'com.android.tools.build:gradle:7.0.0'
|
||||
classpath 'com.android.tools.build:gradle:7.0.1'
|
||||
classpath 'com.google.android.gms:oss-licenses-plugin:0.10.4'
|
||||
classpath 'org.handte.gradle:gradle-android-eclipse:1.0.0'
|
||||
classpath "org.openbakery:xcode-plugin:0.19.1"
|
||||
@@ -24,7 +24,7 @@ allprojects {
|
||||
|
||||
// set version for our project
|
||||
group = 'com.mowesta'
|
||||
version = '1.0.19'
|
||||
version = '1.0.20'
|
||||
|
||||
// set versions for our libraries
|
||||
ext {
|
||||
|
||||
@@ -0,0 +1,105 @@
|
||||
package com.mowesta.tool.model;
|
||||
|
||||
import java.io.File;
|
||||
import java.text.SimpleDateFormat;
|
||||
import java.util.Collections;
|
||||
import java.util.Date;
|
||||
import java.util.List;
|
||||
|
||||
import com.mowesta.api.measurement.Measurement;
|
||||
import com.mowesta.api.measurement.MeasurementType;
|
||||
import com.mowesta.data.process.algorithm.LinearRegression;
|
||||
|
||||
public class BuildFAIRModel {
|
||||
|
||||
static int counter = 0;
|
||||
static boolean in = true;
|
||||
static int segments = 0;
|
||||
static long prev = 0;
|
||||
static int five = 0;
|
||||
static Measurement mx = null;
|
||||
|
||||
public static void main(String[] args) {
|
||||
LinearRegression.Builder<Double> builder = new LinearRegression.Builder<Double>();
|
||||
List<Measurement> ms = MeasurementAnalyzer.loadMeasurements(new File("data\\measurement-9732599.json"));
|
||||
Collections.sort(ms, (a, b) -> (int)(a.getTime() - b.getTime()));
|
||||
ms.forEach((m)-> {
|
||||
String outside = m.getData().get(MeasurementType.OUTSIDE_INDICATOR);
|
||||
if (outside != null && outside.equals("true")) {
|
||||
counter += 1;
|
||||
if (in) {
|
||||
in = false;
|
||||
segments += 1;
|
||||
mx = ms.get(ms.indexOf(m) - 1);
|
||||
}
|
||||
long time = getTime(m);
|
||||
if (time > 300_000 && prev < 300_000) {
|
||||
if (mx != null) {
|
||||
boolean used = false;
|
||||
for (int i = ms.indexOf(mx); i <= ms.indexOf(m); i++) {
|
||||
used |= isUsed(ms.get(i));
|
||||
}
|
||||
boolean zone = true;
|
||||
for (int i = ms.indexOf(mx); i <= ms.indexOf(m); i++) {
|
||||
zone &= isInsideZone(ms.get(i));
|
||||
}
|
||||
SimpleDateFormat df = new SimpleDateFormat("y-MM");
|
||||
|
||||
if (zone & !used && time < 390_000) {
|
||||
five += 1;
|
||||
System.out.println(df.format(new Date(m.getTime())) + "; " + (ms.indexOf(m) - ms.indexOf(mx)) + "; " +ms.indexOf(mx) + ":" + ms.indexOf(m) + "; " + getTemp(mx) + "; " + getTemp(m) + "; " + getOutTemp(mx));
|
||||
Double tmx = getTemp(mx);
|
||||
Double tm = getTemp(m);
|
||||
Double ts = getOutTemp(mx);
|
||||
if (tmx != null && tm != null && ts != null && five < 40) {
|
||||
double delta = tmx - ts;
|
||||
double red = tmx - tm;
|
||||
builder.add(red, delta);
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
}
|
||||
} else {
|
||||
in = true;
|
||||
}
|
||||
prev = getTime(m);
|
||||
});
|
||||
System.out.println("Outside: " + counter + " " + segments + " " + five);
|
||||
LinearRegression r = builder.build();
|
||||
System.out.println("Int: " + r.getIntercept());
|
||||
System.out.println("Slop: " + r.getSlope());
|
||||
}
|
||||
|
||||
public static boolean isUsed(Measurement m) {
|
||||
String s = m.getData().get(MeasurementType.SCREEN_ENABLED);
|
||||
return s != null && s.equals("true");
|
||||
}
|
||||
|
||||
public static long getTime(Measurement m) {
|
||||
String s = m.getData().get(MeasurementType.OUTSIDE_DURATION);
|
||||
if (s == null) return 0;
|
||||
return Double.valueOf(s).longValue();
|
||||
}
|
||||
|
||||
public static Double getTemp(Measurement m) {
|
||||
String t = m.getData().get(MeasurementType.BATTERY_TEMPERATURE);
|
||||
if (t == null) return null;
|
||||
return (Double)MeasurementType.BATTERY_TEMPERATURE.getValues(t)[0];
|
||||
}
|
||||
|
||||
public static Double getOutTemp(Measurement m) {
|
||||
String t = m.getData().get(MeasurementType.STATION_TEMPERATURE);
|
||||
if (t == null) return null;
|
||||
return (Double)MeasurementType.STATION_TEMPERATURE.getValues(t)[0];
|
||||
}
|
||||
|
||||
public static boolean isInsideZone(Measurement m) {
|
||||
return m.getCoordinate().getLatitude() > 50.76611968352262
|
||||
&& m.getCoordinate().getLatitude() < 50.780178
|
||||
&& m.getCoordinate().getLongitude() > 7.065301
|
||||
&& m.getCoordinate().getLongitude() < 7.1025515352192;
|
||||
}
|
||||
|
||||
}
|
||||
Reference in New Issue
Block a user