Projektarbeit
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

SensorMapsActivity.java 20KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452
  1. package de.edotzlaff.schockwelle;
  2. import android.Manifest;
  3. import android.content.Context;
  4. import android.content.pm.PackageManager;
  5. import android.location.Location;
  6. import android.os.Build;
  7. import android.os.Bundle;
  8. import android.os.CountDownTimer;
  9. import android.os.VibrationEffect;
  10. import android.os.Vibrator;
  11. import android.provider.Settings;
  12. import android.util.Log;
  13. import android.widget.TextView;
  14. import android.widget.Toast;
  15. import androidx.annotation.NonNull;
  16. import androidx.core.app.ActivityCompat;
  17. import androidx.core.content.ContextCompat;
  18. import androidx.fragment.app.FragmentActivity;
  19. import com.google.android.gms.location.FusedLocationProviderClient;
  20. import com.google.android.gms.location.LocationServices;
  21. import com.google.android.gms.maps.CameraUpdateFactory;
  22. import com.google.android.gms.maps.GoogleMap;
  23. import com.google.android.gms.maps.OnMapReadyCallback;
  24. import com.google.android.gms.maps.SupportMapFragment;
  25. import com.google.android.gms.maps.model.LatLng;
  26. import com.google.android.gms.maps.model.MarkerOptions;
  27. import com.google.android.gms.tasks.OnCompleteListener;
  28. import com.google.android.gms.tasks.Task;
  29. import com.google.firebase.database.DataSnapshot;
  30. import com.google.firebase.database.DatabaseError;
  31. import com.google.firebase.database.DatabaseReference;
  32. import com.google.firebase.database.FirebaseDatabase;
  33. import com.google.firebase.database.ValueEventListener;
  34. import java.time.LocalDateTime;
  35. import java.util.Calendar;
  36. import java.util.Date;
  37. public class SensorMapsActivity extends FragmentActivity implements OnMapReadyCallback {
  38. private static final String TAG = "MainActivity";
  39. private static final String FINE_LOCATION = Manifest.permission.ACCESS_FINE_LOCATION;
  40. private static final int LOCATION_PERMISSION_REQUEST_CODE = 1234;
  41. private static final double EARTHQUAKE_VELOCITY = 1; // 1 Meter pro Sekunde Erdbebengeschwindigkeit
  42. //vars
  43. private Boolean mLocationPermissionsGranted = false;
  44. private GoogleMap mMap;
  45. private FusedLocationProviderClient mFusedLocationProviderClient;
  46. //Date currentTime;
  47. Location currentLocation;
  48. Long currentTime;
  49. private double breitengrad;
  50. private double laengengrad;
  51. private double sensorGPSbreitengrad;
  52. private double sensorGPSlaengengrad;
  53. private boolean useOwnGPS;
  54. private boolean takeGPSfromDB = true;
  55. private boolean tookOwnGPS = false;
  56. boolean vibrationTrigger = true;
  57. private DatabaseReference mDatenbank;
  58. private String breitengradQuellVibration;
  59. private String laengengradQuellVibration;
  60. private Boolean mDeviceCanVibrate = false;
  61. @Override
  62. protected void onCreate(Bundle savedInstanceState) {
  63. super.onCreate(savedInstanceState);
  64. setContentView(R.layout.activity_sensor_maps);
  65. getDataBaseValuesWithListener();
  66. TextView tv= (TextView) findViewById(R.id.txtSensor);
  67. getLocationPermission(); //Zuerst werden die aktuellen Standortdaten ermittelt
  68. getVibrationAbility();
  69. }
  70. //#####################################################################################################################################################################
  71. //################################################################## vvv ShakeCode vvv ##############################################################################
  72. private void getVibrationAbility()
  73. {
  74. // Get instance of Vibrator from current Context
  75. Vibrator v = (Vibrator) getSystemService(Context.VIBRATOR_SERVICE);
  76. // Output yes if can vibrate, no otherwise
  77. if (v.hasVibrator()) {
  78. Log.v("Can Vibrate", "YES");
  79. // Log.v("Can Control Amplitude", v.hasAmplitudeControl() ? "YES" : "NO");
  80. mDeviceCanVibrate = true;
  81. }
  82. else
  83. {
  84. Log.v("Can Vibrate", "NO");
  85. mDeviceCanVibrate = false;
  86. }
  87. }
  88. private long getTimeStampDifference(float distance)
  89. {
  90. long diff= 0;
  91. //TODO Zeitdifferenz in Millisekunden zwischen aktuellen Uhrzeit und Vibratonszeitstempel berechnen
  92. if (distance>0)
  93. {
  94. diff = (long)Math.round(1/(EARTHQUAKE_VELOCITY/distance));
  95. }
  96. return diff;
  97. }
  98. private void setVibrationTimer(long msDelay, int duration, int amplitude, int index)
  99. {
  100. new CountDownTimer(msDelay, 1000) {
  101. public void onTick(long millisUntilFinished) {
  102. ((TextView) findViewById(R.id.txtSensor)).setText("Earthquake hits in " + millisUntilFinished / 1000 + " s");
  103. }
  104. public void onFinish() {
  105. Toast.makeText(getApplicationContext(), "The Ground is shaking!", Toast.LENGTH_SHORT).show();
  106. performVibration(duration, amplitude);
  107. ( (TextView) findViewById(R.id.txtSensor)).setText("No Earthquake upcoming");
  108. //In DB schreiben!
  109. setVibrationInDataBase(index);
  110. }
  111. }.start();
  112. }
  113. public void performVibration(int duration, int amplitude) {
  114. if(!mDeviceCanVibrate)
  115. return;
  116. Vibrator v = (Vibrator) getSystemService(Context.VIBRATOR_SERVICE);
  117. if (Build.VERSION.SDK_INT >= 26) {
  118. if(duration == 0)
  119. {
  120. v.cancel(); //stop vibration if still running
  121. Toast.makeText(this, "Vibration has been stopped", Toast.LENGTH_SHORT).show();
  122. return;
  123. }
  124. Toast.makeText(this, "Ampl: " + amplitude + ", Dur: " + duration, Toast.LENGTH_SHORT).show();
  125. v.vibrate(VibrationEffect.createOneShot(duration,amplitude));
  126. } else {
  127. if(duration == 0)
  128. {
  129. v.cancel(); //stop vibration if still running
  130. return;
  131. }
  132. v.vibrate(duration);
  133. }
  134. }
  135. //################################################################## ^^^^ ShakeCode ^^^^ ############################################################################
  136. //#####################################################################################################################################################################
  137. //#####################################################################################################################################################################
  138. //################################################################## vvv GPS Code vvv ###############################################################################
  139. private void getLocationPermission() {
  140. String[] permissions = {Manifest.permission.ACCESS_FINE_LOCATION};
  141. if (ContextCompat.checkSelfPermission(this.getApplicationContext(), FINE_LOCATION) == PackageManager.PERMISSION_GRANTED) {
  142. mLocationPermissionsGranted = true;
  143. initMap();
  144. } else {
  145. ActivityCompat.requestPermissions(this, permissions, LOCATION_PERMISSION_REQUEST_CODE);
  146. }
  147. }
  148. @Override
  149. public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
  150. super.onRequestPermissionsResult(requestCode, permissions, grantResults);
  151. mLocationPermissionsGranted = false;
  152. switch (requestCode) {
  153. case LOCATION_PERMISSION_REQUEST_CODE: {
  154. if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
  155. mLocationPermissionsGranted = true;
  156. //initalize or map
  157. initMap();
  158. }
  159. }
  160. }
  161. }
  162. void initMap(){
  163. // Obtain the SupportMapFragment and get notified when the map is ready to be used.
  164. SupportMapFragment mapFragment = (SupportMapFragment) getSupportFragmentManager()
  165. .findFragmentById(R.id.map);
  166. mapFragment.getMapAsync(this);
  167. }
  168. @Override
  169. public void onMapReady(GoogleMap googleMap) {
  170. Toast.makeText(this, "Map is ready", Toast.LENGTH_SHORT).show();
  171. mMap = googleMap;
  172. if (mLocationPermissionsGranted) {
  173. getDeviceLocation();
  174. if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION)
  175. != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(this,
  176. Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
  177. return;
  178. }
  179. mMap.setMyLocationEnabled(true);
  180. }
  181. // Add a marker in Sydney and move the camera
  182. //LatLng sydney = new LatLng(-34, 151);
  183. //mMap.addMarker(new MarkerOptions().position(sydney).title("Marker in Sydney"));
  184. //mMap.moveCamera(CameraUpdateFactory.newLatLng(sydney));
  185. }
  186. private void getDeviceLocation(){
  187. mFusedLocationProviderClient = LocationServices.getFusedLocationProviderClient(this);
  188. try {
  189. if (mLocationPermissionsGranted){
  190. final Task location = mFusedLocationProviderClient.getLastLocation();
  191. location.addOnCompleteListener(new OnCompleteListener() {
  192. @Override
  193. public void onComplete(@NonNull Task task) {
  194. if (task.isSuccessful()){
  195. currentLocation = (Location) task.getResult();
  196. currentTime = Calendar.getInstance().getTimeInMillis();
  197. if (!useOwnGPS)
  198. {
  199. currentLocation.setLatitude(breitengrad);
  200. currentLocation.setLongitude(laengengrad);
  201. }
  202. Toast.makeText(SensorMapsActivity.this, currentTime.toString(), Toast.LENGTH_SHORT).show();
  203. moveCamera(new LatLng(currentLocation.getLatitude(), currentLocation.getLongitude()),15f);
  204. }
  205. else{
  206. Toast.makeText(SensorMapsActivity.this, "Current Location unavailable", Toast.LENGTH_SHORT).show();
  207. }
  208. }
  209. });
  210. }
  211. }catch (SecurityException e){
  212. Log.e(TAG,"Device Location not found" + e.getMessage());
  213. }
  214. }
  215. private void moveCamera(LatLng latlng, float zoom){
  216. Log.d(TAG,"Latitude: "+latlng.latitude+"Longitude: "+latlng.longitude);
  217. mMap.moveCamera(CameraUpdateFactory.newLatLngZoom(latlng, zoom));
  218. }
  219. //################################################################## ^^^^ GPS Code ^^^^ #############################################################################
  220. //#####################################################################################################################################################################
  221. //Datenbank auslesen mit Listener. D.h. es werden Daten (snapshot) ausgelesen und gleichzeitig ein Listener hinterlegt.
  222. //Sollten sich danach Daten zu einem beliebigen Zeitpunkt in der DB ändern, wird die Funktion "onDataChange" erneut ausgelöst und wieder Daten (snapshot) ausgelesen.
  223. public void getDataBaseValuesWithListener()
  224. {
  225. mDatenbank = FirebaseDatabase.getInstance().getReference();
  226. mDatenbank.addValueEventListener(new ValueEventListener() {
  227. @Override
  228. public void onDataChange(@NonNull DataSnapshot snapshot) {
  229. processDataBaseUpdate(snapshot);
  230. }
  231. @Override
  232. public void onCancelled(@NonNull DatabaseError error) {
  233. getDataBaseFailure(error);
  234. }
  235. });
  236. }
  237. public void processDataBaseUpdate (DataSnapshot data)
  238. {
  239. String breitengradString;
  240. String laengengradString;
  241. String vibrationString;
  242. String androidid;
  243. int vibratingDevices = 0;
  244. for (int i = 1; i<=4; i++)
  245. {
  246. breitengradString = data.child("overviewAronTestetInDiesemAbschnitt").child("IDG" + i).child("breitengrad").getValue().toString();
  247. laengengradString = data.child("overviewAronTestetInDiesemAbschnitt").child("IDG" + i).child("laengengrad").getValue().toString();
  248. androidid = data.child("overviewAronTestetInDiesemAbschnitt").child("IDG" + i).child("androidid").getValue().toString();
  249. vibrationString = data.child("overviewAronTestetInDiesemAbschnitt").child("IDG" + i).child("vibration").getValue().toString();
  250. if(!androidid.isEmpty())
  251. {
  252. //System.out.println("Index " + i + " ist nicht leer");
  253. if(vibrationString == "false")
  254. {
  255. //System.out.println("Index " + i + " Vibration ist false");
  256. continue;
  257. }
  258. else
  259. {
  260. //System.out.println("Index " + i + " Vibration ist true");
  261. if(androidid.equals(getandroidid()))
  262. {
  263. //System.out.println("Index " + i + " Vibration ist von mir. Falscher Alarm");
  264. vibrationTrigger = false;
  265. break;
  266. }
  267. else
  268. {
  269. //System.out.println("Index " + i + " Vibration ist nicht von mir. Breitengrad und Laegengrad von Vibrationsquelle bestimmen.");
  270. breitengradQuellVibration = breitengradString;
  271. laengengradQuellVibration = laengengradString;
  272. vibratingDevices++;
  273. continue;
  274. }
  275. }
  276. }
  277. else
  278. {
  279. //System.out.println("Index " + i + " ist leer");
  280. if(androidid.isEmpty() && !breitengradString.isEmpty() && !laengengradString.isEmpty() && vibrationString.equals("false") && takeGPSfromDB)
  281. {
  282. System.out.println("Index " + i +" -> Leere AdnroidID. Breitengrad und Laengengrad sind belegt. Vibration ist false. Kann als eigenes Gerät beansprucht werden.");
  283. System.out.println("Index " + i +" -> Übernehme Breitengrad: " + breitengradString + " und Laengengrad: " + laengengradString + " als eigene Position.");
  284. breitengrad = Double.parseDouble(breitengradString);
  285. laengengrad = Double.parseDouble(laengengradString);
  286. useOwnGPS = false;
  287. takeGPSfromDB = false;
  288. }else
  289. {
  290. if(!tookOwnGPS && takeGPSfromDB)
  291. {
  292. //System.out.println("Nutze eigene DB. Bin bei Index " + i + " ++++++++++++++++++++++++++++++++++++++++++++");
  293. tookOwnGPS = true;
  294. useOwnGPS = true;
  295. }
  296. }
  297. if(vibrationTrigger == true && (vibratingDevices == 1))
  298. {
  299. //System.out.println("#########Freigabe zum Schreiben in DB mit Index " + i + " liegt vor. Schreibe nun... !!!!!#####################");
  300. /*
  301. System.out.println("currentLocation.getLatitude(): " + currentLocation.getLatitude());
  302. System.out.println("currentLocation.getLongitude(): " + currentLocation.getLongitude());
  303. System.out.println("Double.parseDouble(breitengradQuellVibration): " + Double.parseDouble(breitengradQuellVibration));
  304. System.out.println("Double.parseDouble(laengengradQuellVibration): " + Double.parseDouble(laengengradQuellVibration));
  305. System.out.println("######################################################################################################################################################################");
  306. */
  307. vibrationTrigger = false;
  308. float distanceToEarthquake;
  309. distanceToEarthquake = distance(currentLocation.getLatitude(), currentLocation.getLongitude(), Double.parseDouble(breitengradQuellVibration), Double.parseDouble(laengengradQuellVibration));
  310. System.out.println("Distance to Earthquake: " + distanceToEarthquake);
  311. long wellenAusbreitungsGeschwindigkeit = 4500; //Meter die Sekunde
  312. long delayInSeconds = (long) distanceToEarthquake/wellenAusbreitungsGeschwindigkeit; //s
  313. long delayInMilliSeconds = delayInSeconds*1000;
  314. setVibrationTimer(delayInMilliSeconds,1500,255,i);
  315. //setVibrationInDataBase(i);
  316. break;
  317. }
  318. }
  319. }
  320. //TODO Weiterer Code von Patrick. @Aron Anschauen ob dieser noch verwendet werden muss da paar Sachen schon in dieser Version umgesetzt worde sind.
  321. /*
  322. //####### Auslesen für boolean-Werte #######:
  323. int i = 1;
  324. String vibrationString = data.child("overview").child("IDG").child("vibration").getValue().toString();
  325. String amplitudeString = data.child("overview").child("IDG").child("amplitude").getValue().toString();
  326. boolean vibration;
  327. if(vibrationString.equals("true")){
  328. vibration = true;
  329. }else{
  330. vibration = false;
  331. }
  332. int amplitude = Integer.parseInt(amplitudeString);
  333. // Workaround beseiteigen: hier wird immer davon ausgegangen, dass auslösendes Gerät die ID 1 besitzt
  334. if(vibration == true && i == 1)
  335. {
  336. float distance = distance(currentLocation.getLatitude(), currentLocation.getLongitude(),breitengrad,laengengrad);
  337. long delay = getTimeStampDifference(distance);
  338. setVibrationTimer(delay,1000,amplitude);
  339. }
  340. */
  341. }
  342. public void setVibrationInDataBase(int k)
  343. {
  344. mDatenbank = FirebaseDatabase.getInstance().getReference();
  345. mDatenbank.child("overviewAronTestetInDiesemAbschnitt").child("IDG" + k).child("ip").setValue(k + "0.00.00.000");
  346. mDatenbank.child("overviewAronTestetInDiesemAbschnitt").child("IDG" + k).child("vibration").setValue(true);
  347. mDatenbank.child("overviewAronTestetInDiesemAbschnitt").child("IDG" + k).child("timestamp").setValue(Calendar.getInstance().getTimeInMillis()); //aktueller Zeitstempel wird in Datenbank eingetragen
  348. if (useOwnGPS)
  349. {
  350. //System.out.println("YYYcurrentLocation.getLatitude(): " + currentLocation.getLatitude());
  351. //System.out.println("YYYcurrentLocation.getLongitude(): " + currentLocation.getLongitude());
  352. mDatenbank.child("overviewAronTestetInDiesemAbschnitt").child("IDG" + k).child("breitengrad").setValue(currentLocation.getLatitude()); //aktueller Breitengrad
  353. mDatenbank.child("overviewAronTestetInDiesemAbschnitt").child("IDG" + k).child("laengengrad").setValue(currentLocation.getLongitude()); //aktueller Längergrad
  354. }else{
  355. //System.out.println("YYYbreitengrad: " + breitengrad);
  356. //System.out.println("YYYlaengengrad: " + laengengrad);
  357. mDatenbank.child("overviewAronTestetInDiesemAbschnitt").child("IDG" + k).child("breitengrad").setValue(breitengrad); //aktueller Breitengrad
  358. mDatenbank.child("overviewAronTestetInDiesemAbschnitt").child("IDG" + k).child("laengengrad").setValue(laengengrad); //aktueller Längergrad
  359. }
  360. mDatenbank.child("overviewAronTestetInDiesemAbschnitt").child("IDG" + k).child("amplitude").setValue(1001);
  361. if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
  362. mDatenbank.child("overviewAronTestetInDiesemAbschnitt").child("IDG" + k).child("localdatetime").setValue(LocalDateTime.now().toString());
  363. }
  364. mDatenbank.child("overviewAronTestetInDiesemAbschnitt").child("IDG" + k).child("androidid").setValue(getandroidid());
  365. }
  366. public String getandroidid ()
  367. {
  368. return Settings.Secure.getString(this.getContentResolver(), Settings.Secure.ANDROID_ID);
  369. }
  370. public void getDataBaseFailure (DatabaseError error)
  371. {
  372. System.out.println("Fehler");
  373. Log.w("Datenbankfehler", error.toException());
  374. }
  375. //TODO Edward Dauer für Timer berechnen bis Smartphone vibriert
  376. private float distance(double currentlatitude, double currentlongitude, double originLat, double originLon) {
  377. float[] results = new float[1];
  378. Location.distanceBetween(currentlatitude, currentlongitude, originLat, originLon, results);
  379. float distanceInMeters = results[0];
  380. return distanceInMeters;
  381. }
  382. }