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 30KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659
  1. package de.edotzlaff.schockwelle;
  2. import android.Manifest;
  3. import android.content.Context;
  4. import android.content.Intent;
  5. import android.content.pm.PackageManager;
  6. import android.location.Location;
  7. import android.net.wifi.WifiManager;
  8. import android.os.Build;
  9. import android.os.Bundle;
  10. import android.os.CountDownTimer;
  11. import android.os.VibrationEffect;
  12. import android.os.Vibrator;
  13. import android.provider.Settings;
  14. import android.util.Log;
  15. import android.widget.TextView;
  16. import android.widget.Toast;
  17. import androidx.annotation.NonNull;
  18. import androidx.annotation.RequiresApi;
  19. import androidx.core.app.ActivityCompat;
  20. import androidx.core.content.ContextCompat;
  21. import androidx.fragment.app.FragmentActivity;
  22. import com.google.android.gms.location.FusedLocationProviderClient;
  23. import com.google.android.gms.location.LocationServices;
  24. import com.google.android.gms.maps.CameraUpdateFactory;
  25. import com.google.android.gms.maps.GoogleMap;
  26. import com.google.android.gms.maps.OnMapReadyCallback;
  27. import com.google.android.gms.maps.SupportMapFragment;
  28. import com.google.android.gms.maps.model.LatLng;
  29. import com.google.android.gms.maps.model.MarkerOptions;
  30. import com.google.android.gms.tasks.OnCompleteListener;
  31. import com.google.android.gms.tasks.Task;
  32. import com.google.firebase.database.DataSnapshot;
  33. import com.google.firebase.database.DatabaseError;
  34. import com.google.firebase.database.DatabaseReference;
  35. import com.google.firebase.database.FirebaseDatabase;
  36. import com.google.firebase.database.ValueEventListener;
  37. import java.time.LocalDateTime;
  38. import java.time.ZoneOffset;
  39. import java.util.Calendar;
  40. import java.util.Date;
  41. public class SensorMapsActivity extends FragmentActivity implements OnMapReadyCallback {
  42. private static final String TAG = "MainActivity";
  43. private static final String FINE_LOCATION = Manifest.permission.ACCESS_FINE_LOCATION;
  44. private static final int LOCATION_PERMISSION_REQUEST_CODE = 1234;
  45. private static final double EARTHQUAKE_VELOCITY = 1; // 1 Meter pro Sekunde Erdbebengeschwindigkeit
  46. Datenbank db = new Datenbank();
  47. //vars
  48. private Boolean mLocationPermissionsGranted = false;
  49. private GoogleMap mMap;
  50. private FusedLocationProviderClient mFusedLocationProviderClient;
  51. //Date currentTime;
  52. Location currentLocation;
  53. Long currentTime;
  54. private double breitengrad;
  55. private double laengengrad;
  56. private double sensorGPSbreitengrad;
  57. private double sensorGPSlaengengrad;
  58. private boolean useOwnGPS;
  59. private boolean takeGPSfromDB = true;
  60. private boolean tookOwnGPS = false;
  61. private boolean globalShit = true;
  62. private boolean permissionToWriteToDataBase = true;
  63. private DataSnapshot datenBankSnapShot;
  64. boolean vibrationTrigger = true;
  65. boolean grabGPSandID = true;
  66. private DatabaseReference mDatenbank;
  67. private String breitengradQuellVibration;
  68. private String laengengradQuellVibration;
  69. private Boolean mDeviceCanVibrate = false;
  70. @Override
  71. protected void onCreate(Bundle savedInstanceState) {
  72. super.onCreate(savedInstanceState);
  73. setContentView(R.layout.activity_sensor_maps);
  74. //Database Init
  75. db.setMyWaveSpeed(2000);
  76. db.setMyAndroidID(Settings.Secure.getString(this.getContentResolver(), Settings.Secure.ANDROID_ID));
  77. WifiManager wm = (WifiManager) getApplicationContext().getSystemService(WIFI_SERVICE);
  78. int ip = wm.getConnectionInfo().getIpAddress();
  79. db.setMyIPadress(String.format("%d.%d.%d.%d",(ip & 0xff),(ip >> 8 & 0xff),(ip >> 16 & 0xff), (ip >> 24 & 0xff)));
  80. /*
  81. db.getDatafromDBnoListener();
  82. db.getDataBaseValuesWithListener();
  83. */
  84. getDataBaseValuesWithListener();
  85. TextView tv= (TextView) findViewById(R.id.txtSensor);
  86. getLocationPermission(); //Zuerst werden die aktuellen Standortdaten ermittelt
  87. getVibrationAbility();
  88. }
  89. //#####################################################################################################################################################################
  90. //################################################################## vvv ShakeCode vvv ##############################################################################
  91. private void getVibrationAbility()
  92. {
  93. // Get instance of Vibrator from current Context
  94. Vibrator v = (Vibrator) getSystemService(Context.VIBRATOR_SERVICE);
  95. // Output yes if can vibrate, no otherwise
  96. if (v.hasVibrator()) {
  97. Log.v("Can Vibrate", "YES");
  98. // Log.v("Can Control Amplitude", v.hasAmplitudeControl() ? "YES" : "NO");
  99. mDeviceCanVibrate = true;
  100. }
  101. else
  102. {
  103. Log.v("Can Vibrate", "NO");
  104. mDeviceCanVibrate = false;
  105. }
  106. }
  107. private void setVibrationTimer(long msDelay, int duration, int amplitude, int index)
  108. {
  109. new CountDownTimer(msDelay, 1000) {
  110. public void onTick(long millisUntilFinished) {
  111. ((TextView) findViewById(R.id.txtSensor)).setText("Earthquake hits in " + millisUntilFinished / 1000 + " s");
  112. }
  113. @RequiresApi(api = Build.VERSION_CODES.O)
  114. public void onFinish() {
  115. Toast.makeText(getApplicationContext(), "The Ground is shaking!", Toast.LENGTH_SHORT).show();
  116. performVibration(duration, amplitude);
  117. ( (TextView) findViewById(R.id.txtSensor)).setText("No Earthquake upcoming");
  118. //Hier wird in DB geschrieben
  119. setVibrationInDataBase(index); //TODO Aron
  120. }
  121. }.start();
  122. }
  123. public void performVibration(int duration, int amplitude) {
  124. if(!mDeviceCanVibrate)
  125. return;
  126. Vibrator v = (Vibrator) getSystemService(Context.VIBRATOR_SERVICE);
  127. if (Build.VERSION.SDK_INT >= 26) {
  128. if(amplitude > 255 || amplitude < 1)
  129. amplitude = VibrationEffect.DEFAULT_AMPLITUDE;
  130. if(duration == 0)
  131. {
  132. v.cancel(); //stop vibration if still running
  133. Toast.makeText(this, "Vibration has been stopped", Toast.LENGTH_SHORT).show();
  134. return;
  135. }
  136. //Toast.makeText(this, "Ampl: " + amplitude + ", Dur: " + duration, Toast.LENGTH_SHORT).show();
  137. v.vibrate(VibrationEffect.createOneShot(duration,amplitude));
  138. } else {
  139. if(duration == 0)
  140. {
  141. v.cancel(); //stop vibration if still running
  142. return;
  143. }
  144. v.vibrate(duration);
  145. }
  146. }
  147. //################################################################## ^^^^ ShakeCode ^^^^ ############################################################################
  148. //#####################################################################################################################################################################
  149. //#####################################################################################################################################################################
  150. //################################################################## vvv GPS Code vvv ###############################################################################
  151. private void getLocationPermission() {
  152. String[] permissions = {Manifest.permission.ACCESS_FINE_LOCATION};
  153. if (ContextCompat.checkSelfPermission(this.getApplicationContext(), FINE_LOCATION) == PackageManager.PERMISSION_GRANTED) {
  154. mLocationPermissionsGranted = true;
  155. initMap();
  156. } else {
  157. ActivityCompat.requestPermissions(this, permissions, LOCATION_PERMISSION_REQUEST_CODE);
  158. }
  159. }
  160. @Override
  161. public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
  162. super.onRequestPermissionsResult(requestCode, permissions, grantResults);
  163. mLocationPermissionsGranted = false;
  164. switch (requestCode) {
  165. case LOCATION_PERMISSION_REQUEST_CODE: {
  166. if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
  167. mLocationPermissionsGranted = true;
  168. //initalize or map
  169. initMap();
  170. }
  171. }
  172. }
  173. }
  174. void initMap(){
  175. // Obtain the SupportMapFragment and get notified when the map is ready to be used.
  176. SupportMapFragment mapFragment = (SupportMapFragment) getSupportFragmentManager()
  177. .findFragmentById(R.id.map);
  178. mapFragment.getMapAsync(this);
  179. }
  180. @Override
  181. public void onMapReady(GoogleMap googleMap) {
  182. Toast.makeText(this, "Map is ready", Toast.LENGTH_SHORT).show();
  183. mMap = googleMap;
  184. if (mLocationPermissionsGranted) {
  185. getDeviceLocation();
  186. if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION)
  187. != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(this,
  188. Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
  189. return;
  190. }
  191. mMap.setMyLocationEnabled(true);
  192. }
  193. //TODO @ Eddy: Ich denke diesen Code brauchst du noch, oder? :D
  194. //Add a marker in Sydney and move the camera
  195. //LatLng sydney = new LatLng(-34, 151);
  196. //mMap.addMarker(new MarkerOptions().position(sydney).title("Marker in Sydney"));
  197. //mMap.moveCamera(CameraUpdateFactory.newLatLng(sydney));
  198. }
  199. private void getDeviceLocation(){
  200. mFusedLocationProviderClient = LocationServices.getFusedLocationProviderClient(this);
  201. try {
  202. if (mLocationPermissionsGranted){
  203. final Task location = mFusedLocationProviderClient.getLastLocation();
  204. location.addOnCompleteListener(new OnCompleteListener() {
  205. @Override
  206. public void onComplete(@NonNull Task task) {
  207. if (task.isSuccessful()){
  208. currentLocation = (Location) task.getResult();
  209. currentTime = Calendar.getInstance().getTimeInMillis();
  210. /*
  211. if(!db.getNativeGPScaseInDB())
  212. {
  213. System.out.println("---Fremde GPS Daten werden verwendet");
  214. currentLocation.setLatitude(breitengrad);
  215. currentLocation.setLongitude(laengengrad);
  216. }
  217. */
  218. if (!useOwnGPS)
  219. {
  220. currentLocation.setLatitude(breitengrad);
  221. currentLocation.setLongitude(laengengrad);
  222. }
  223. //Toast.makeText(SensorMapsActivity.this, currentTime.toString(), Toast.LENGTH_SHORT).show();
  224. moveCamera(new LatLng(currentLocation.getLatitude(), currentLocation.getLongitude()),15f);
  225. }
  226. else{
  227. Toast.makeText(SensorMapsActivity.this, "Current Location unavailable", Toast.LENGTH_SHORT).show();
  228. }
  229. }
  230. });
  231. }
  232. }catch (SecurityException e){
  233. Log.e(TAG,"Device Location not found" + e.getMessage());
  234. }
  235. }
  236. private void moveCamera(LatLng latlng, float zoom){
  237. Log.d(TAG,"Latitude: "+latlng.latitude+"Longitude: "+latlng.longitude);
  238. mMap.moveCamera(CameraUpdateFactory.newLatLngZoom(latlng, zoom));
  239. }
  240. //################################################################## ^^^^ GPS Code ^^^^ #############################################################################
  241. //#####################################################################################################################################################################
  242. //#####################################################################################################################################################################
  243. //################################################################## vvv DB Code vvv ###############################################################################
  244. //Datenbank auslesen mit Listener. D.h. es werden Daten (snapshot) ausgelesen und gleichzeitig ein Listener hinterlegt.
  245. //Sollten sich danach Daten zu einem beliebigen Zeitpunkt in der DB ändern, wird die Funktion "onDataChange" erneut ausgelöst und wieder Daten (snapshot) ausgelesen.
  246. public void getDataBaseValuesWithListener()
  247. {
  248. mDatenbank = FirebaseDatabase.getInstance().getReference();
  249. mDatenbank.addValueEventListener(new ValueEventListener() {
  250. @Override
  251. public void onDataChange(@NonNull DataSnapshot snapshot) {
  252. processDataBaseUpdate(snapshot);
  253. datenBankSnapShot = snapshot;
  254. }
  255. @Override
  256. public void onCancelled(@NonNull DatabaseError error) {
  257. getDataBaseFailure(error);
  258. }
  259. });
  260. }
  261. public void processDataBaseUpdate (DataSnapshot data)
  262. {
  263. int indexMax = (int) data.child("overviewnodes").getChildrenCount();
  264. //Festellen ob DB oder eigene GPS-Daten verwendet werden sollen
  265. if(analyzeForUseOfOwnGPS(data))
  266. {
  267. useOwnGPS = true;
  268. }
  269. else
  270. {
  271. useOwnGPS = false;
  272. }
  273. //Wichtig zur Verwendung von GPS-Daten explizit aus der Datenbank
  274. if(!useOwnGPS && grabGPSandID)
  275. {
  276. for (int f = 1; f<=indexMax; f++)
  277. {
  278. if(f>=2 && f<=indexMax)
  279. {
  280. if(analyzeIfAnroidIdIsEmpty(data,f))
  281. {
  282. String breitengradString = data.child("overviewnodes").child("IDG" + f).child("d_breitengrad").getValue().toString();
  283. String laengengradString = data.child("overviewnodes").child("IDG" + f).child("e_laengengrad").getValue().toString();
  284. breitengrad = Double.parseDouble(breitengradString);
  285. laengengrad = Double.parseDouble(laengengradString);
  286. allocateIDtoDatabaseSlot(f);
  287. grabGPSandID = false;
  288. break;
  289. }
  290. }
  291. }
  292. }
  293. //Hier sind die Schreibregeln für die DB definiert wenn Sensor aktiviert ist
  294. for (int f = 1; f<=indexMax; f++)
  295. {
  296. if((!analyzeIfAnroidIdIsEmpty(data,f) && !analyzeForOwnAndroidID(data,f) && analyzeForStateOfVibration(data,f) && analyzeForExisitingGPSvalues(data,f) && permissionToWriteToDataBase))
  297. {
  298. System.out.println("Index: " + f + ": Eintrittskriterien erfüllt.");
  299. //Nehme Quelle GPS Daten
  300. String breitengradString = data.child("overviewnodes").child("IDG" + f).child("d_breitengrad").getValue().toString();
  301. String laengengradString = data.child("overviewnodes").child("IDG" + f).child("e_laengengrad").getValue().toString();
  302. breitengradQuellVibration = breitengradString;
  303. laengengradQuellVibration = laengengradString;
  304. f=1;
  305. if(analyzeForOwnAndroidID(data,f))
  306. {
  307. System.out.println("Index: " + f + ": Eigene ID vorhanden.");
  308. if (!analyzeForStateOfVibration(data,f))
  309. {
  310. System.out.println("Index: " + f + ": Vibration is false.");
  311. if(analyzeForExisitingGPSvalues(data,f) && permissionToWriteToDataBase)
  312. {
  313. //System.out.println("Index: " + f + ": Beide GPS Daten vorhanden. Ich reserviere mir diesen Platz und schreibe hier demnächst rein.");
  314. //hier sofort ID eintragen
  315. //mDatenbank = FirebaseDatabase.getInstance().getReference();
  316. //mDatenbank.child("overviewnodes").child("IDG" + f).child("a_androidid").setValue(getandroidid());
  317. float distanceToEarthquake;
  318. distanceToEarthquake = distance(currentLocation.getLatitude(), currentLocation.getLongitude(), Double.parseDouble(breitengradQuellVibration), Double.parseDouble(laengengradQuellVibration));
  319. long wellenAusbreitungsGeschwindigkeit = (long) db.getMyWaveSpeed(); //Meter die Sekunde
  320. long delayInSeconds = (long) distanceToEarthquake/wellenAusbreitungsGeschwindigkeit; //s
  321. long delayInMilliSeconds = delayInSeconds*1000;
  322. setVibrationTimer(delayInMilliSeconds,1500,255,f);
  323. permissionToWriteToDataBase = false;
  324. break;
  325. }
  326. else{
  327. System.out.println("Index: " + f + ": Habe keine GPS Daten");
  328. }
  329. }else{
  330. System.out.println("Index: " + f + ": Meine Vibration ist bereits true.");
  331. break;
  332. }
  333. }
  334. else
  335. {
  336. System.out.println("Index: " + f + ": Eigene ID nicht vorhanden");
  337. for(f = f; f<=indexMax; f++)
  338. {
  339. if((analyzeIfAnroidIdIsEmpty(data,f) || analyzeForOwnAndroidID(data,f)) && permissionToWriteToDataBase)
  340. {
  341. //System.out.println("Index: " + f + ": Diese Slot war leer oder es ist meine eigene ID. Ich schreibe hier rein");
  342. //mDatenbank = FirebaseDatabase.getInstance().getReference();
  343. //mDatenbank.child("overviewnodes").child("IDG" + f).child("a_androidid").setValue(getandroidid());
  344. float distanceToEarthquake;
  345. distanceToEarthquake = distance(currentLocation.getLatitude(), currentLocation.getLongitude(), Double.parseDouble(breitengradQuellVibration), Double.parseDouble(laengengradQuellVibration));
  346. long wellenAusbreitungsGeschwindigkeit = (long) db.getMyWaveSpeed(); //Meter die Sekunde
  347. long delayInSeconds = (long) distanceToEarthquake/wellenAusbreitungsGeschwindigkeit; //s
  348. long delayInMilliSeconds = delayInSeconds*1000;
  349. setVibrationTimer(delayInMilliSeconds,1500,255,f);
  350. permissionToWriteToDataBase = false;
  351. break;
  352. }
  353. if(f == indexMax && !analyzeIfAnroidIdIsEmpty(data,f))
  354. {
  355. System.out.println(">>>Index " + f + " >>>Konnte keine freien Slot finden");
  356. }
  357. }
  358. }
  359. }
  360. }
  361. }
  362. public boolean analyzeForUseOfOwnGPS(DataSnapshot data)
  363. {
  364. String nativeGPSString;
  365. boolean nativeGPS;
  366. int amountNativeGPSisTrue = 0;
  367. int indexMax = (int) data.child("overviewnodes").getChildrenCount();
  368. for (int i = 1; i <= indexMax; i++)
  369. {
  370. nativeGPSString = data.child("overviewnodes").child("IDG" + i).child("f_nativegps").getValue().toString();
  371. if(nativeGPSString.equals("true"))
  372. {
  373. amountNativeGPSisTrue++;
  374. }else
  375. {
  376. amountNativeGPSisTrue--;
  377. }
  378. }
  379. if(amountNativeGPSisTrue == indexMax)
  380. {
  381. nativeGPS = true;
  382. }else{
  383. nativeGPS = false;
  384. }
  385. return nativeGPS;
  386. }
  387. public boolean analyzeIfAnroidIdIsEmpty(DataSnapshot data, int k)
  388. {
  389. String androidid;
  390. int indexMax = (int) data.child("overviewnodes").getChildrenCount();
  391. boolean androididempty = false;
  392. for (int i = k; i <= k; i++)
  393. {
  394. androidid = data.child("overviewnodes").child("IDG" + i).child("a_androidid").getValue().toString();
  395. if(androidid.isEmpty())
  396. {
  397. androididempty = true;
  398. }else
  399. {
  400. androididempty = false;
  401. }
  402. }
  403. return androididempty;
  404. }
  405. public boolean analyzeForOwnAndroidID(DataSnapshot data, int k)
  406. {
  407. String androididString;
  408. boolean ownAndroidID = false;
  409. int indexMax = (int) data.child("overviewnodes").getChildrenCount();
  410. for (int i = k; i <= k; i++)
  411. {
  412. androididString = data.child("overviewnodes").child("IDG" + i).child("a_androidid").getValue().toString();
  413. if(androididString.equals(getandroidid()))
  414. {
  415. ownAndroidID = true;
  416. }else
  417. {
  418. ownAndroidID = false;
  419. }
  420. }
  421. return ownAndroidID;
  422. }
  423. public boolean analyzeForStateOfVibration(DataSnapshot data, int k)
  424. {
  425. String vibrationString;
  426. boolean stateOfVibration = false;
  427. int indexMax = (int) data.child("overviewnodes").getChildrenCount();
  428. for (int i = k; i <= k; i++)
  429. {
  430. vibrationString = data.child("overviewnodes").child("IDG" + i).child("g_vibration").getValue().toString();
  431. if(vibrationString.equals("true"))
  432. {
  433. stateOfVibration = true;
  434. }else
  435. {
  436. stateOfVibration = false;
  437. }
  438. }
  439. return stateOfVibration;
  440. }
  441. public boolean analyzeForExisitingGPSvalues(DataSnapshot data, int k)
  442. {
  443. String breitengradString;
  444. String laengengradString;
  445. boolean bothGPSvaluesExist = false;
  446. int indexMax = (int) data.child("overviewnodes").getChildrenCount();
  447. for (int i = k; i <= k; i++)
  448. {
  449. breitengradString = data.child("overviewnodes").child("IDG" + i).child("d_breitengrad").getValue().toString();
  450. laengengradString = data.child("overviewnodes").child("IDG" + i).child("e_laengengrad").getValue().toString();
  451. if(!breitengradString.isEmpty() && !laengengradString.isEmpty())
  452. {
  453. bothGPSvaluesExist = true;
  454. }else
  455. {
  456. bothGPSvaluesExist = false;
  457. }
  458. }
  459. return bothGPSvaluesExist;
  460. }
  461. public void allocateIDtoDatabaseSlot(int k)
  462. {
  463. mDatenbank = FirebaseDatabase.getInstance().getReference();
  464. mDatenbank.child("overviewnodes").child("IDG" + k).child("a_androidid").setValue(getandroidid());
  465. }
  466. @RequiresApi(api = Build.VERSION_CODES.O)
  467. public void setVibrationInDataBase(int k)
  468. {
  469. System.out.println("Es wird versucht in DB zu schreiben....");
  470. for(k =k; k<=datenBankSnapShot.child("overviewnodes").getChildrenCount();k++)
  471. {
  472. System.out.println("Index...." + k);
  473. System.out.println("analyzeIfAnroidIdIsEmpty(datenBankSnapShot,k)" + k + "___" + analyzeIfAnroidIdIsEmpty(datenBankSnapShot,k));
  474. System.out.println("analyzeForOwnAndroidID(datenBankSnapShot,k)" + k + "___" + analyzeForOwnAndroidID(datenBankSnapShot,k));
  475. System.out.println("analyzeForStateOfVibration(datenBankSnapShot,k)" + k + "___" + analyzeForStateOfVibration(datenBankSnapShot,k));
  476. //Wenn Leer ODER eigene ID und Vibration = false;
  477. if((analyzeIfAnroidIdIsEmpty(datenBankSnapShot,k) || analyzeForOwnAndroidID(datenBankSnapShot,k) && !analyzeForStateOfVibration(datenBankSnapShot,k) ))
  478. {
  479. System.out.println("Android ID war leer oder es war eigene ID mit Vibration = false. SChreibe in DB...... " + k);
  480. //Reinschreieben
  481. mDatenbank = FirebaseDatabase.getInstance().getReference();
  482. mDatenbank.child("overviewnodes").child("IDG" + k).child("a_androidid").setValue(getandroidid());
  483. if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
  484. //mDatenbank.child("overviewnodes").child("IDG" + k).child("b_localdatetime").setValue(LocalDateTime.now().toString());
  485. mDatenbank.child("overviewnodes").child("IDG" + k).child("b_localdatetime").setValue(LocalDateTime.now(ZoneOffset.UTC).toString());
  486. }
  487. mDatenbank.child("overviewnodes").child("IDG" + k).child("c_ip").setValue(getDeviceIpAdress());
  488. if (useOwnGPS)
  489. {
  490. mDatenbank.child("overviewnodes").child("IDG" + k).child("f_nativegps").setValue(true);
  491. mDatenbank.child("overviewnodes").child("IDG" + k).child("d_breitengrad").setValue(currentLocation.getLatitude()); //aktueller Breitengrad
  492. mDatenbank.child("overviewnodes").child("IDG" + k).child("e_laengengrad").setValue(currentLocation.getLongitude()); //aktueller Längergrad
  493. }else{
  494. mDatenbank.child("overviewnodes").child("IDG" + k).child("d_breitengrad").setValue(breitengrad); //aktueller Breitengrad
  495. mDatenbank.child("overviewnodes").child("IDG" + k).child("e_laengengrad").setValue(laengengrad); //aktueller Längergrad
  496. mDatenbank.child("overviewnodes").child("IDG" + k).child("f_nativegps").setValue(false);
  497. }
  498. mDatenbank.child("overviewnodes").child("IDG" + k).child("g_vibration").setValue(true);
  499. mDatenbank.child("overviewnodes").child("IDG" + k).child("h_timestamp").setValue(Calendar.getInstance().getTimeInMillis()); //aktueller Zeitstempel wird in Datenbank eingetragen
  500. mDatenbank.child("overviewnodes").child("IDG" + k).child("i_amplitude").setValue(1000);
  501. mDatenbank.child("overviewnodes").child("IDG" + k).child("w_wellengeschwindigkeit").setValue(db.getMyWaveSpeed());
  502. break;
  503. }else
  504. {
  505. System.out.println("Erhöhe Index weil nicht durchgekommen" + k);
  506. //k erhöhen solange leerer Slot ist oder abbruch weil zu voll
  507. if(k ==(int) datenBankSnapShot.child("overviewnodes").getChildrenCount())
  508. {
  509. System.out.println("Kein freier Slot mehr vorhanden");
  510. break;
  511. }
  512. }
  513. }
  514. }
  515. public String getDeviceIpAdress ()
  516. {
  517. WifiManager wm = (WifiManager) getApplicationContext().getSystemService(WIFI_SERVICE);
  518. int ip = wm.getConnectionInfo().getIpAddress();
  519. String ipAddress = String.format("%d.%d.%d.%d",(ip & 0xff),(ip >> 8 & 0xff),(ip >> 16 & 0xff), (ip >> 24 & 0xff));
  520. return ipAddress;
  521. }
  522. public String getandroidid ()
  523. {
  524. return Settings.Secure.getString(this.getContentResolver(), Settings.Secure.ANDROID_ID);
  525. }
  526. public void getDataBaseFailure (DatabaseError error)
  527. {
  528. System.out.println("Fehler");
  529. Log.w("Datenbankfehler", error.toException());
  530. }
  531. private float distance(double currentlatitude, double currentlongitude, double originLat, double originLon) {
  532. float[] results = new float[1];
  533. Location.distanceBetween(currentlatitude, currentlongitude, originLat, originLon, results);
  534. float distanceInMeters = results[0];
  535. return distanceInMeters;
  536. }
  537. //################################################################## ^^^^ DB Code ^^^^ #############################################################################
  538. //#####################################################################################################################################################################
  539. //TODO @Patrick: Ist backupVonAltemCode noch relevanter Code wenn Viration und das Schreiben in die Datenbank passt und synchron abläuft? Falls nichts relevant, können wir das ja löschen ;)
  540. public void backupVonAltemCode (DataSnapshot data)
  541. {
  542. /*
  543. //####### Auslesen für boolean-Werte #######:
  544. int i = 1;
  545. String vibrationString = data.child("overviewnodes").child("IDG").child("vibration").getValue().toString();
  546. String amplitudeString = data.child("overviewnodes").child("IDG").child("amplitude").getValue().toString();
  547. boolean vibration;
  548. if(vibrationString.equals("true")){
  549. vibration = true;
  550. }else{
  551. vibration = false;
  552. }
  553. int amplitude = Integer.parseInt(amplitudeString);
  554. // Workaround beseiteigen: hier wird immer davon ausgegangen, dass auslösendes Gerät die ID 1 besitzt
  555. if(vibration == true && i == 1)
  556. {
  557. float distance = distance(currentLocation.getLatitude(), currentLocation.getLongitude(),breitengrad,laengengrad);
  558. long delay = getTimeStampDifference(distance);
  559. setVibrationTimer(delay,1000,amplitude);
  560. }
  561. */
  562. }
  563. //TODO @Patrick: Ist getTimeStampDifference noch relevanter Code wenn Viration und das Schreiben in die Datenbank passt und synchron abläuft? Falls nichts relevant, können wir das ja löschen ;)
  564. private long getTimeStampDifference(float distance)
  565. {
  566. long diff= 0;
  567. if (distance>0)
  568. {
  569. diff = (long)Math.round(1/(EARTHQUAKE_VELOCITY/distance));
  570. }
  571. return diff;
  572. }
  573. }