ThreatMapFragment.java 9.1 KB

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