ThreatMapFragment.java 8.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291
  1. package de.tudarmstadt.informatik.hostage.ui2.fragment;
  2. import android.app.Fragment;
  3. import android.graphics.Color;
  4. import android.location.Location;
  5. import android.os.Bundle;
  6. import android.view.InflateException;
  7. import android.view.LayoutInflater;
  8. import android.view.View;
  9. import android.view.ViewGroup;
  10. import com.google.android.gms.common.ConnectionResult;
  11. import com.google.android.gms.common.GooglePlayServicesClient;
  12. import com.google.android.gms.location.LocationClient;
  13. import com.google.android.gms.location.LocationListener;
  14. import com.google.android.gms.location.LocationRequest;
  15. import com.google.android.gms.maps.CameraUpdateFactory;
  16. import com.google.android.gms.maps.GoogleMap;
  17. import com.google.android.gms.maps.MapFragment;
  18. import com.google.android.gms.maps.model.CircleOptions;
  19. import com.google.android.gms.maps.model.LatLng;
  20. import com.google.android.gms.maps.model.Marker;
  21. import com.google.android.gms.maps.model.MarkerOptions;
  22. import java.util.ArrayList;
  23. import java.util.HashMap;
  24. import java.util.Map;
  25. import de.tudarmstadt.informatik.hostage.R;
  26. import de.tudarmstadt.informatik.hostage.logging.Record;
  27. import de.tudarmstadt.informatik.hostage.logging.UglyDbHelper;
  28. import de.tudarmstadt.informatik.hostage.ui2.activity.MainActivity;
  29. import static com.google.android.gms.common.GooglePlayServicesUtil.*;
  30. /**
  31. * ThreatMapFragment
  32. *
  33. * Created by Fabio Arnold on 10.02.14.
  34. */
  35. public class ThreatMapFragment extends Fragment implements GoogleMap.OnInfoWindowClickListener,
  36. GooglePlayServicesClient.ConnectionCallbacks,
  37. GooglePlayServicesClient.OnConnectionFailedListener,
  38. LocationListener {
  39. private static GoogleMap sMap = null;
  40. private static View sView = null;
  41. private static HashMap<String, String> sMarkerIDToSSID = new HashMap<String, String>();
  42. private LocationClient mLocationClient;
  43. private static final LocationRequest REQUEST = LocationRequest.create()
  44. .setExpirationDuration(5000) // 5 seconds
  45. .setInterval(5000) // 5 seconds
  46. .setFastestInterval(16) // 16ms = 60fps
  47. .setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY);
  48. /**
  49. * if google play services aren't available an error notification will be displayed
  50. *
  51. * @return true if the google play services are available
  52. */
  53. private boolean isGooglePlay() {
  54. int status = isGooglePlayServicesAvailable(getActivity());
  55. boolean result = status == ConnectionResult.SUCCESS;
  56. if (!result) {
  57. getErrorDialog(status, getActivity(), 10).show();
  58. }
  59. return result;
  60. }
  61. /**
  62. * callback for when the info window of a marker gets clicked
  63. * open the RecordOverviewFragment and display all records belonging to an SSID
  64. *
  65. * @param marker this info window belongs to
  66. */
  67. @Override
  68. public void onInfoWindowClick(Marker marker) {
  69. MainActivity.getInstance().displayView(MainActivity.MainMenuItem.RECORDS.getValue());
  70. RecordOverviewFragment recordOverviewFragment = (RecordOverviewFragment)MainActivity.getInstance().getCurrentFragment();
  71. if (recordOverviewFragment != null) {
  72. String ssid = sMarkerIDToSSID.get(marker.getId());
  73. recordOverviewFragment.showDetailsForSSID(getActivity(), ssid);
  74. }
  75. }
  76. /**
  77. * callbacks from LocationClient
  78. */
  79. @Override
  80. public void onConnected(Bundle bundle) {
  81. mLocationClient.requestLocationUpdates(REQUEST, this);
  82. }
  83. @Override
  84. public void onDisconnected() {
  85. }
  86. @Override
  87. public void onConnectionFailed(ConnectionResult connectionResult) {
  88. }
  89. @Override
  90. public void onLocationChanged(Location location) {
  91. sMap.animateCamera(CameraUpdateFactory.newLatLng(
  92. new LatLng(location.getLatitude(), location.getLongitude())));
  93. }
  94. /**
  95. * helper class
  96. * easier to use than LatLng
  97. */
  98. private class Point {
  99. public double x, y;
  100. public Point(double sx, double sy) {
  101. x = sx;
  102. y = sy;
  103. }
  104. }
  105. /**
  106. * helper class
  107. * contains heuristic to split SSIDs by location
  108. * see MAX_DISTANCE
  109. */
  110. private class SSIDArea {
  111. private Point mMinimum, mMaximum;
  112. public int numPoints;
  113. public static final int MAX_NUM_ATTACKS = 20;
  114. public static final float MAX_DISTANCE = 1000.0f; // 1km
  115. public SSIDArea(LatLng initialLocation) {
  116. //mMinimum = new Point(360.0, 360.0);
  117. //mMaximum = new Point(-360.0, -360.0);
  118. mMinimum = new Point(initialLocation.latitude, initialLocation.longitude);
  119. mMaximum = new Point(initialLocation.latitude, initialLocation.longitude);
  120. numPoints = 1;
  121. }
  122. public boolean doesLocationBelongToArea(LatLng location) {
  123. LatLng center = calculateCenterLocation();
  124. float[] result = new float[1];
  125. Location.distanceBetween(center.latitude, center.longitude, location.latitude, location.longitude, result);
  126. return result[0] < MAX_DISTANCE;
  127. }
  128. public void addLocation(LatLng location) {
  129. Point point = new Point(location.latitude, location.longitude);
  130. if (point.x < mMinimum.x) mMinimum.x = point.x;
  131. if (point.x > mMaximum.x) mMaximum.x = point.x;
  132. if (point.y < mMinimum.y) mMinimum.y = point.y;
  133. if (point.y > mMaximum.y) mMaximum.y = point.y;
  134. numPoints++;
  135. }
  136. public LatLng calculateCenterLocation() {
  137. return new LatLng(0.5 * (mMinimum.x + mMaximum.x), 0.5 * (mMinimum.y + mMaximum.y));
  138. }
  139. public float calculateRadius() {
  140. float[] result = new float[1];
  141. Location.distanceBetween(mMinimum.x, mMinimum.y, mMaximum.x, mMaximum.y, result);
  142. return 0.5f * result[0];
  143. }
  144. public int calculateColor() {
  145. int threatLevel = numPoints;
  146. if (threatLevel > MAX_NUM_ATTACKS) threatLevel = MAX_NUM_ATTACKS;
  147. float alpha = 1.0f - (float)(threatLevel-1) / (float)(MAX_NUM_ATTACKS-1);
  148. return Color.argb(127, (int) (240.0 + 15.0 * alpha), (int) (80.0 + 175.0 * alpha), 60);
  149. }
  150. }
  151. /**
  152. * fills the map with markers and circle representing SSIDs
  153. */
  154. private void populateMap() {
  155. UglyDbHelper dbh = new UglyDbHelper(getActivity());
  156. ArrayList<Record> records = dbh.getAllRecords();
  157. HashMap<String, ArrayList<SSIDArea>> threadAreas = new HashMap<String, ArrayList<SSIDArea>>();
  158. for (Record record : records) {
  159. LatLng location = new LatLng(record.getLatitude(), record.getLongitude());
  160. ArrayList<SSIDArea> areas;
  161. if (threadAreas.containsKey(record.getSsid())) {
  162. areas = threadAreas.get(record.getSsid());
  163. boolean foundArea = false;
  164. for (SSIDArea area : areas) {
  165. if (area.doesLocationBelongToArea(location)) {
  166. area.addLocation(location);
  167. foundArea = true;
  168. break;
  169. }
  170. }
  171. if (!foundArea) {
  172. areas.add(new SSIDArea(location));
  173. }
  174. } else {
  175. areas = new ArrayList<SSIDArea>();
  176. areas.add(new SSIDArea(location));
  177. threadAreas.put(record.getSsid(), areas);
  178. }
  179. }
  180. CircleOptions circleOptions = new CircleOptions().radius(200.0).fillColor(Color.argb(127, 240, 80, 60)).strokeWidth(0.0f);
  181. for (Map.Entry<String, ArrayList<SSIDArea>> entry : threadAreas.entrySet()) {
  182. String ssid = entry.getKey();
  183. ArrayList<SSIDArea> areas = entry.getValue();
  184. for (SSIDArea area : areas) {
  185. int color = area.calculateColor();
  186. LatLng center = area.calculateCenterLocation();
  187. float radius = area.calculateRadius();
  188. sMap.addCircle(circleOptions.center(center).radius(100.0 + radius).fillColor(color));
  189. Marker marker = sMap.addMarker(new MarkerOptions()
  190. .title(ssid + ": " + area.numPoints + (area.numPoints == 1 ? " attack"
  191. : " attacks")).position(
  192. center));
  193. sMarkerIDToSSID.put(marker.getId(), ssid);
  194. }
  195. }
  196. sMap.setMyLocationEnabled(true);
  197. LatLng tudarmstadt = new LatLng(49.86923, 8.6632768); // default location
  198. sMap.moveCamera(CameraUpdateFactory.newLatLngZoom(tudarmstadt, 13));
  199. }
  200. /**
  201. * performs initialization
  202. * checks if google play services are supported
  203. * view must be removed if this object has been created once before
  204. * that is why view is static
  205. *
  206. * @param inflater
  207. * @param container
  208. * @param savedInstanceState
  209. * @return the view
  210. */
  211. @Override
  212. public View onCreateView(LayoutInflater inflater, ViewGroup container,
  213. Bundle savedInstanceState) {
  214. super.onCreateView(inflater, container, savedInstanceState);
  215. if (sView != null) {
  216. ViewGroup parent = (ViewGroup) sView.getParent();
  217. if (parent != null)
  218. parent.removeView(sView);
  219. }
  220. try {
  221. sView = inflater.inflate(R.layout.fragment_threatmap, container, false);
  222. if (isGooglePlay()) {
  223. sMap = ((MapFragment) getFragmentManager()
  224. .findFragmentById(R.id.threatmapfragment)).getMap();
  225. populateMap();
  226. }
  227. } catch (InflateException e) {
  228. // map already exists
  229. //e.printStackTrace();
  230. }
  231. if (sMap != null) {
  232. sMap.setOnInfoWindowClickListener(this);
  233. }
  234. return sView;
  235. }
  236. @Override
  237. public void onResume() {
  238. super.onResume();
  239. if (mLocationClient == null) {
  240. mLocationClient = new LocationClient(MainActivity.getInstance().getApplicationContext(), this, this);
  241. }
  242. mLocationClient.connect();
  243. }
  244. @Override
  245. public void onPause() {
  246. super.onPause();
  247. if (mLocationClient != null) {
  248. mLocationClient.disconnect();
  249. }
  250. }
  251. }