package de.edotzlaff.schockwelle; import android.Manifest; import android.content.Context; import android.content.pm.PackageManager; import android.location.Location; import android.os.Build; import android.os.Bundle; import android.os.CountDownTimer; import android.os.VibrationEffect; import android.os.Vibrator; import android.provider.Settings; import android.util.Log; import android.widget.TextView; import android.widget.Toast; import androidx.annotation.NonNull; import androidx.core.app.ActivityCompat; import androidx.core.content.ContextCompat; import androidx.fragment.app.FragmentActivity; import com.google.android.gms.location.FusedLocationProviderClient; import com.google.android.gms.location.LocationServices; import com.google.android.gms.maps.CameraUpdateFactory; import com.google.android.gms.maps.GoogleMap; import com.google.android.gms.maps.OnMapReadyCallback; import com.google.android.gms.maps.SupportMapFragment; import com.google.android.gms.maps.model.LatLng; import com.google.android.gms.maps.model.MarkerOptions; import com.google.android.gms.tasks.OnCompleteListener; import com.google.android.gms.tasks.Task; import com.google.firebase.database.DataSnapshot; import com.google.firebase.database.DatabaseError; import com.google.firebase.database.DatabaseReference; import com.google.firebase.database.FirebaseDatabase; import com.google.firebase.database.ValueEventListener; import java.time.LocalDateTime; import java.util.Calendar; import java.util.Date; public class SensorMapsActivity extends FragmentActivity implements OnMapReadyCallback { private static final String TAG = "MainActivity"; private static final String FINE_LOCATION = Manifest.permission.ACCESS_FINE_LOCATION; private static final int LOCATION_PERMISSION_REQUEST_CODE = 1234; private static final double EARTHQUAKE_VELOCITY = 1; // 1 Meter pro Sekunde Erdbebengeschwindigkeit //vars private Boolean mLocationPermissionsGranted = false; private GoogleMap mMap; private FusedLocationProviderClient mFusedLocationProviderClient; //Date currentTime; Location currentLocation; Long currentTime; private double breitengrad; private double laengengrad; private double sensorGPSbreitengrad; private double sensorGPSlaengengrad; private boolean useOwnGPS; private boolean takeGPSfromDB = true; private boolean tookOwnGPS = false; boolean vibrationTrigger = true; private DatabaseReference mDatenbank; private String breitengradQuellVibration; private String laengengradQuellVibration; private Boolean mDeviceCanVibrate = false; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_sensor_maps); getDataBaseValuesWithListener(); TextView tv= (TextView) findViewById(R.id.txtSensor); getLocationPermission(); //Zuerst werden die aktuellen Standortdaten ermittelt getVibrationAbility(); } //##################################################################################################################################################################### //################################################################## vvv ShakeCode vvv ############################################################################## private void getVibrationAbility() { // Get instance of Vibrator from current Context Vibrator v = (Vibrator) getSystemService(Context.VIBRATOR_SERVICE); // Output yes if can vibrate, no otherwise if (v.hasVibrator()) { Log.v("Can Vibrate", "YES"); // Log.v("Can Control Amplitude", v.hasAmplitudeControl() ? "YES" : "NO"); mDeviceCanVibrate = true; } else { Log.v("Can Vibrate", "NO"); mDeviceCanVibrate = false; } } private long getTimeStampDifference(float distance) { long diff= 0; //TODO Zeitdifferenz in Millisekunden zwischen aktuellen Uhrzeit und Vibratonszeitstempel berechnen if (distance>0) { diff = (long)Math.round(1/(EARTHQUAKE_VELOCITY/distance)); } return diff; } private void setVibrationTimer(long msDelay, int duration, int amplitude, int index) { new CountDownTimer(msDelay, 1000) { public void onTick(long millisUntilFinished) { ((TextView) findViewById(R.id.txtSensor)).setText("Earthquake hits in " + millisUntilFinished / 1000 + " s"); } public void onFinish() { Toast.makeText(getApplicationContext(), "The Ground is shaking!", Toast.LENGTH_SHORT).show(); performVibration(duration, amplitude); ( (TextView) findViewById(R.id.txtSensor)).setText("No Earthquake upcoming"); //In DB schreiben! setVibrationInDataBase(index); } }.start(); } public void performVibration(int duration, int amplitude) { if(!mDeviceCanVibrate) return; Vibrator v = (Vibrator) getSystemService(Context.VIBRATOR_SERVICE); if (Build.VERSION.SDK_INT >= 26) { if(duration == 0) { v.cancel(); //stop vibration if still running Toast.makeText(this, "Vibration has been stopped", Toast.LENGTH_SHORT).show(); return; } Toast.makeText(this, "Ampl: " + amplitude + ", Dur: " + duration, Toast.LENGTH_SHORT).show(); v.vibrate(VibrationEffect.createOneShot(duration,amplitude)); } else { if(duration == 0) { v.cancel(); //stop vibration if still running return; } v.vibrate(duration); } } //################################################################## ^^^^ ShakeCode ^^^^ ############################################################################ //##################################################################################################################################################################### //##################################################################################################################################################################### //################################################################## vvv GPS Code vvv ############################################################################### private void getLocationPermission() { String[] permissions = {Manifest.permission.ACCESS_FINE_LOCATION}; if (ContextCompat.checkSelfPermission(this.getApplicationContext(), FINE_LOCATION) == PackageManager.PERMISSION_GRANTED) { mLocationPermissionsGranted = true; initMap(); } else { ActivityCompat.requestPermissions(this, permissions, LOCATION_PERMISSION_REQUEST_CODE); } } @Override public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) { super.onRequestPermissionsResult(requestCode, permissions, grantResults); mLocationPermissionsGranted = false; switch (requestCode) { case LOCATION_PERMISSION_REQUEST_CODE: { if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) { mLocationPermissionsGranted = true; //initalize or map initMap(); } } } } void initMap(){ // Obtain the SupportMapFragment and get notified when the map is ready to be used. SupportMapFragment mapFragment = (SupportMapFragment) getSupportFragmentManager() .findFragmentById(R.id.map); mapFragment.getMapAsync(this); } @Override public void onMapReady(GoogleMap googleMap) { Toast.makeText(this, "Map is ready", Toast.LENGTH_SHORT).show(); mMap = googleMap; if (mLocationPermissionsGranted) { getDeviceLocation(); if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) { return; } mMap.setMyLocationEnabled(true); } // Add a marker in Sydney and move the camera //LatLng sydney = new LatLng(-34, 151); //mMap.addMarker(new MarkerOptions().position(sydney).title("Marker in Sydney")); //mMap.moveCamera(CameraUpdateFactory.newLatLng(sydney)); } private void getDeviceLocation(){ mFusedLocationProviderClient = LocationServices.getFusedLocationProviderClient(this); try { if (mLocationPermissionsGranted){ final Task location = mFusedLocationProviderClient.getLastLocation(); location.addOnCompleteListener(new OnCompleteListener() { @Override public void onComplete(@NonNull Task task) { if (task.isSuccessful()){ currentLocation = (Location) task.getResult(); currentTime = Calendar.getInstance().getTimeInMillis(); if (!useOwnGPS) { currentLocation.setLatitude(breitengrad); currentLocation.setLongitude(laengengrad); } Toast.makeText(SensorMapsActivity.this, currentTime.toString(), Toast.LENGTH_SHORT).show(); moveCamera(new LatLng(currentLocation.getLatitude(), currentLocation.getLongitude()),15f); } else{ Toast.makeText(SensorMapsActivity.this, "Current Location unavailable", Toast.LENGTH_SHORT).show(); } } }); } }catch (SecurityException e){ Log.e(TAG,"Device Location not found" + e.getMessage()); } } private void moveCamera(LatLng latlng, float zoom){ Log.d(TAG,"Latitude: "+latlng.latitude+"Longitude: "+latlng.longitude); mMap.moveCamera(CameraUpdateFactory.newLatLngZoom(latlng, zoom)); } //################################################################## ^^^^ GPS Code ^^^^ ############################################################################# //##################################################################################################################################################################### //Datenbank auslesen mit Listener. D.h. es werden Daten (snapshot) ausgelesen und gleichzeitig ein Listener hinterlegt. //Sollten sich danach Daten zu einem beliebigen Zeitpunkt in der DB ändern, wird die Funktion "onDataChange" erneut ausgelöst und wieder Daten (snapshot) ausgelesen. public void getDataBaseValuesWithListener() { mDatenbank = FirebaseDatabase.getInstance().getReference(); mDatenbank.addValueEventListener(new ValueEventListener() { @Override public void onDataChange(@NonNull DataSnapshot snapshot) { processDataBaseUpdate(snapshot); } @Override public void onCancelled(@NonNull DatabaseError error) { getDataBaseFailure(error); } }); } public void processDataBaseUpdate (DataSnapshot data) { String breitengradString; String laengengradString; String vibrationString; String androidid; int vibratingDevices = 0; for (int i = 1; i<=4; i++) { breitengradString = data.child("overviewAronTestetInDiesemAbschnitt").child("IDG" + i).child("breitengrad").getValue().toString(); laengengradString = data.child("overviewAronTestetInDiesemAbschnitt").child("IDG" + i).child("laengengrad").getValue().toString(); androidid = data.child("overviewAronTestetInDiesemAbschnitt").child("IDG" + i).child("androidid").getValue().toString(); vibrationString = data.child("overviewAronTestetInDiesemAbschnitt").child("IDG" + i).child("vibration").getValue().toString(); if(!androidid.isEmpty()) { //System.out.println("Index " + i + " ist nicht leer"); if(vibrationString == "false") { //System.out.println("Index " + i + " Vibration ist false"); continue; } else { //System.out.println("Index " + i + " Vibration ist true"); if(androidid.equals(getandroidid())) { //System.out.println("Index " + i + " Vibration ist von mir. Falscher Alarm"); vibrationTrigger = false; break; } else { //System.out.println("Index " + i + " Vibration ist nicht von mir. Breitengrad und Laegengrad von Vibrationsquelle bestimmen."); breitengradQuellVibration = breitengradString; laengengradQuellVibration = laengengradString; vibratingDevices++; continue; } } } else { //System.out.println("Index " + i + " ist leer"); if(androidid.isEmpty() && !breitengradString.isEmpty() && !laengengradString.isEmpty() && vibrationString.equals("false") && takeGPSfromDB) { System.out.println("Index " + i +" -> Leere AdnroidID. Breitengrad und Laengengrad sind belegt. Vibration ist false. Kann als eigenes Gerät beansprucht werden."); System.out.println("Index " + i +" -> Übernehme Breitengrad: " + breitengradString + " und Laengengrad: " + laengengradString + " als eigene Position."); breitengrad = Double.parseDouble(breitengradString); laengengrad = Double.parseDouble(laengengradString); useOwnGPS = false; takeGPSfromDB = false; }else { if(!tookOwnGPS && takeGPSfromDB) { //System.out.println("Nutze eigene DB. Bin bei Index " + i + " ++++++++++++++++++++++++++++++++++++++++++++"); tookOwnGPS = true; useOwnGPS = true; } } if(vibrationTrigger == true && (vibratingDevices == 1)) { //System.out.println("#########Freigabe zum Schreiben in DB mit Index " + i + " liegt vor. Schreibe nun... !!!!!#####################"); /* System.out.println("currentLocation.getLatitude(): " + currentLocation.getLatitude()); System.out.println("currentLocation.getLongitude(): " + currentLocation.getLongitude()); System.out.println("Double.parseDouble(breitengradQuellVibration): " + Double.parseDouble(breitengradQuellVibration)); System.out.println("Double.parseDouble(laengengradQuellVibration): " + Double.parseDouble(laengengradQuellVibration)); System.out.println("######################################################################################################################################################################"); */ vibrationTrigger = false; float distanceToEarthquake; distanceToEarthquake = distance(currentLocation.getLatitude(), currentLocation.getLongitude(), Double.parseDouble(breitengradQuellVibration), Double.parseDouble(laengengradQuellVibration)); System.out.println("Distance to Earthquake: " + distanceToEarthquake); long wellenAusbreitungsGeschwindigkeit = 4500; //Meter die Sekunde long delayInSeconds = (long) distanceToEarthquake/wellenAusbreitungsGeschwindigkeit; //s long delayInMilliSeconds = delayInSeconds*1000; setVibrationTimer(delayInMilliSeconds,1500,255,i); //setVibrationInDataBase(i); break; } } } //TODO Weiterer Code von Patrick. @Aron Anschauen ob dieser noch verwendet werden muss da paar Sachen schon in dieser Version umgesetzt worde sind. /* //####### Auslesen für boolean-Werte #######: int i = 1; String vibrationString = data.child("overview").child("IDG").child("vibration").getValue().toString(); String amplitudeString = data.child("overview").child("IDG").child("amplitude").getValue().toString(); boolean vibration; if(vibrationString.equals("true")){ vibration = true; }else{ vibration = false; } int amplitude = Integer.parseInt(amplitudeString); // Workaround beseiteigen: hier wird immer davon ausgegangen, dass auslösendes Gerät die ID 1 besitzt if(vibration == true && i == 1) { float distance = distance(currentLocation.getLatitude(), currentLocation.getLongitude(),breitengrad,laengengrad); long delay = getTimeStampDifference(distance); setVibrationTimer(delay,1000,amplitude); } */ } public void setVibrationInDataBase(int k) { mDatenbank = FirebaseDatabase.getInstance().getReference(); mDatenbank.child("overviewAronTestetInDiesemAbschnitt").child("IDG" + k).child("ip").setValue(k + "0.00.00.000"); mDatenbank.child("overviewAronTestetInDiesemAbschnitt").child("IDG" + k).child("vibration").setValue(true); mDatenbank.child("overviewAronTestetInDiesemAbschnitt").child("IDG" + k).child("timestamp").setValue(Calendar.getInstance().getTimeInMillis()); //aktueller Zeitstempel wird in Datenbank eingetragen if (useOwnGPS) { //System.out.println("YYYcurrentLocation.getLatitude(): " + currentLocation.getLatitude()); //System.out.println("YYYcurrentLocation.getLongitude(): " + currentLocation.getLongitude()); mDatenbank.child("overviewAronTestetInDiesemAbschnitt").child("IDG" + k).child("breitengrad").setValue(currentLocation.getLatitude()); //aktueller Breitengrad mDatenbank.child("overviewAronTestetInDiesemAbschnitt").child("IDG" + k).child("laengengrad").setValue(currentLocation.getLongitude()); //aktueller Längergrad }else{ //System.out.println("YYYbreitengrad: " + breitengrad); //System.out.println("YYYlaengengrad: " + laengengrad); mDatenbank.child("overviewAronTestetInDiesemAbschnitt").child("IDG" + k).child("breitengrad").setValue(breitengrad); //aktueller Breitengrad mDatenbank.child("overviewAronTestetInDiesemAbschnitt").child("IDG" + k).child("laengengrad").setValue(laengengrad); //aktueller Längergrad } mDatenbank.child("overviewAronTestetInDiesemAbschnitt").child("IDG" + k).child("amplitude").setValue(1001); if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) { mDatenbank.child("overviewAronTestetInDiesemAbschnitt").child("IDG" + k).child("localdatetime").setValue(LocalDateTime.now().toString()); } mDatenbank.child("overviewAronTestetInDiesemAbschnitt").child("IDG" + k).child("androidid").setValue(getandroidid()); } public String getandroidid () { return Settings.Secure.getString(this.getContentResolver(), Settings.Secure.ANDROID_ID); } public void getDataBaseFailure (DatabaseError error) { System.out.println("Fehler"); Log.w("Datenbankfehler", error.toException()); } //TODO Edward Dauer für Timer berechnen bis Smartphone vibriert private float distance(double currentlatitude, double currentlongitude, double originLat, double originLon) { float[] results = new float[1]; Location.distanceBetween(currentlatitude, currentlongitude, originLat, originLon, results); float distanceInMeters = results[0]; return distanceInMeters; } }